[ DOCS ] /docs/eitri
Eitri language
Eitri is a statically typed scripting language for embedding in Rust. I am writing it; see the project page. Here it is compiled to WebAssembly and runs in your browser. This is a short tour of what the console examples use, written for someone who knows JavaScript or TypeScript. It is not the whole language.
At a glance#
| In TypeScript | In Eitri |
|---|---|
const x = 1 | let x = 1 (cannot be reassigned) |
let x = 1 | var x = 1 |
function f(a: string): string { … } | fn f(a: string) -> string { … } |
e => { … }, () => { … } | the same |
`hello ${name}` | "hello ${name}": ordinary strings interpolate |
a ? b : c | if a { b } else { c }, an expression |
switch | match, an expression, which must cover every case |
for (const x of xs) | for x in xs |
for (let i = 0; i < n; i++) | for i in 0..n |
xs.length | xs.len() |
string | null, x ?? y | ?string, x ?? y |
interface / object literal | struct and Name { field: value } |
Beyond the syntax, the differences are that types are checked before anything runs, there are no semicolons (a newline ends a statement), numbers are integers (i64) or floats (f64) rather than one number, and there is no undefined.
Imports#
A script can only import the modules the host provides. Here those are the SDK modules. The name after import is what you call it in the script, and the string is the module path:
import site from "site", import theme from "site/theme", import card from "card". Members are used with a dot: site.projects, theme.hue(195), card.user. A module's types are qualified the same way: site.Action, theme.Weather, card.Icon.
let, var, functions and lambdas#
let binds a value that cannot be reassigned; var can be. Types are inferred and can be written after a colon. Functions use fn, name their parameter types, and give the return type after -> (leave it out for no value). A lambda is e => … or (a: i64) => …; its body is a single expression or a block, and it can capture and change vars from the scope around it.
import site from "site"
let name = "Eitri"
var count = 0
fn greet(who: string) -> string {
return "hello, ${who}"
}
let shout = (s: string) => s.to_upper()
let report = () => site.print("${count} projects")
for p in site.projects {
count += 1
}
site.print(greet(name))
site.print(shout("done"))
report()
Conditions and loops#
if / else if / else is an expression, so it can be on the right of a let; every branch must give the same type. Conditions must be booleans (if count is an error; write count != 0). Loops are while and for … in, over an array or a range: 0..n excludes n, 0..=n includes it. There is also for i, x in xs for the index and the element.
import site from "site"
let hour = site.time.hour
let part = if hour < 12 {
"morning"
} else if hour < 18 {
"afternoon"
} else {
"evening"
}
var tries = 0
while tries < 3 {
tries += 1
}
var evens = 0
for n in 0..10 {
if n % 2 == 0 {
evens += 1
}
}
site.print("${part}: ${tries} tries, ${evens} even numbers")
Enums and match#
An enum is a closed set of cases, such as theme.Weather with Clear, Rain, Storm and so on. When the compiler already knows the type you can write just the case with a leading dot, .Rain; elsewhere write theme.Weather.Rain. match picks an arm by case (or by value, for strings and numbers), and _ matches everything else. A match that misses a case without _ does not compile.
import site from "site"
import theme from "site/theme"
fn mood(w: theme.Weather) -> string {
return match w {
.Rain => "wet"
.Storm => "very wet"
.Clear => "dry"
_ => "unusual"
}
}
site.print(mood(.Rain))
site.print(mood(.Aurora))
import site from "site"
import theme from "site/theme"
fn mood(w: theme.Weather) -> string {
return match w {
.Rain => "wet"
.Clear => "dry"
}
}
site.print(mood(.Rain))
error[E0301]: non-exhaustive match
╭─ script.eit:5:12
│
5 │ return match w {
│ ╭────────────^
6 │ │ .Rain => "wet"
7 │ │ .Clear => "dry"
8 │ │ }
│ ╰─────^Optionals#
?T is a T or null. Event fields such as e.slug are optional because not every event has one. You cannot use an optional as a plain value: unwrap it with if let name = e.section { … } (with an optional else), or give a fallback with ??.
import site from "site"
site.on("section", e => {
if let name = e.section {
site.print("now reading ${name}")
} else {
site.print("no section")
}
let key = e.key ?? "no key"
site.print(key)
})
Strings and arrays#
Strings use double quotes, and ${expression} inside one inserts a value. Arrays are written [1, 2, 3] and typed []i64. An empty array needs a type: var names: []string = []. The ones the examples use:
xs.len(): the number of elements;xs[i]: the element at an index. An index outside the array is a runtime fault.xs.push(x)appends;xs.insert(i, x)inserts before indexi.xs.contains(x): whether an element equalsx.- Strings have
to_upper()and, for the loop incard.clip,chars().
import site from "site"
var names: []string = []
for p in site.projects {
names.push(p.name)
}
names.insert(0, "first")
let has = names.contains("first")
site.print("${names.len()} names, first is ${names[0]}, has it: ${has}")
Structs#
A struct is a record with named, typed fields. A literal starts with the struct's name and lists the fields as name: value. Structs that come from an SDK module are qualified by the module: site.Action { … }, ui.Pick { … }. In those, every field is required: there are no defaults, so leaving one out is a compile error. A struct can hold a lambda, which is how an action carries its run callback.
import site from "site"
struct Pair {
left: i64
right: i64
}
let pair = Pair { left: 3, right: 4 }
site.action(site.Action {
name: "sum",
title: "Sum a pair",
description: "Prints left + right",
category: "Docs",
keywords: ["add"],
run: () => site.print("${pair.left + pair.right}"),
})
import site from "site"
site.action(site.Action {
name: "hello",
title: "Say hello",
run: () => site.print("hello"),
})
error[E0301]: missing struct field
╭─ script.eit:3:13
│
3 │ site.action(site.Action {
│ ╭─────────────^
4 │ │ name: "hello",
5 │ │ title: "Say hello",
6 │ │ run: () => site.print("hello"),
7 │ │ })
│ ╰─^Integers#
Whole numbers are i64 and decimals f64. The two do not mix implicitly; convert with i64(x) and f64(x). Division of integers truncates. +, - and * on integers are checked: a result that does not fit in 64 bits is a runtime fault, never a silent wrap-around. (The wrapping forms &+, &- and &* exist for when you want that.)
Diagnostics#
When a script is rejected, the report names the error, the line and column, and underlines the code with carets. Runtime faults say where they happened and in which function (<module> is the top level of the script). In the console they appear in the Output tab; in the card studio the report is drawn as the card.
import site from "site"
let count = site.projects.len()
site.print(count)
error[E0301]: type mismatch: expected `string`, found `i64`
╭─ script.eit:4:12
│
4 │ site.print(count)
│ ^^^^^import site from "site"
var n: i64 = 9223372036854775807
n = n + 1
site.print("${n}")
fault: integer overflow
╭─ script.eit:4:5
│
4 │ n = n + 1
│ ^^^^^ in `<module>`