Foreign Function Interface
Silt can be embedded in Rust applications. The embedder declares host modules: modules whose functions are Rust closures. A silt program imports a host module like any other module, and every call is typechecked against the signature the embedder declared.
Quick Start
use std::path::Path;
use std::sync::{Arc, Mutex};
use silt::session::{Builtins, Config, Entry, HostModule, LockPolicy, ProjectSetup, Session};
use silt::{Buffer, HostIo, Vm};
// 1. Declare the host module: each function by its silt signature. A
// program's `main` returns nothing: it hands its result to the host
// through a function of the host's, `mylib.give` here.
let given = Arc::new(Mutex::new(0));
let slot = given.clone();
let mylib = HostModule::new("mylib")
.fn1("fn double(x: Int) -> Int", |x: i64| x * 2)
.fn1("fn give(x: Int) -> ()", move |x: i64| *slot.lock().unwrap() = x);
// 2. Open the program in a session that knows the module.
let mut session = Session::new(Config {
project: ProjectSetup::None,
lock: LockPolicy::ReadOnly,
host: vec![mylib],
builtins: Builtins::All,
});
let source = "import mylib\nfn main() { mylib.give(mylib.double(21)) }";
let file = session.set_overlay(Path::new("main.silt"), source.to_string());
// 3. Check it. Every static error is in the analysis.
let analysis = session.analyze(file);
for d in &analysis.diagnostics {
eprintln!("{}", d.message());
}
assert!(!analysis.has_errors());
// 4. Compile it and run it. What the program prints is collected in `out`.
let program = session.compile(file, Entry::Main).expect("compiles");
let out = Buffer::new();
Vm::new(HostIo::buffer(&out)).run_program(&program).unwrap();
assert_eq!(*given.lock().unwrap(), 42);
Declaring a host module
HostModule::new(name) starts a module. Each function is added with its
signature: a silt fn header with no body, which declares the type of
every parameter and the return type. The name in the signature is the
function’s name in the module.
let mylib = HostModule::new("mylib")
.fn0("fn answer() -> Int", || 42_i64)
.fn1("fn double(x: Int) -> Int", |x: i64| x * 2)
.fn2("fn add(a: Int, b: Int) -> Int", |a: i64, b: i64| a + b);
From silt (a program run in a session that declares mylib):
import mylib
println(mylib.add(mylib.double(20), mylib.answer() - 40)) -- 42
The module is imported the usual ways: import mylib,
import mylib.{ double }, import mylib as m. A program that does not
import it cannot see it.
Typed functions
fn0, fn1 and fn2 convert the arguments from silt values and the
result back, through the FromValue and IntoValue traits. The Rust
types must match the signature: Int is i64, String is String, and
so on (see the table below). The signature must declare as many
parameters as the closure takes: .fn1("fn answer() -> Int", ..) is an
error.
Functions on values
function takes the call, a &HostCall, and returns
Result<Value, VmError>. The arguments are call.args, a &[Value].
Use it for more arguments, for a generic signature, or for a function
that builds a value of a record or enum type (see “Host types” below):
let lists = HostModule::new("lists").function(
"fn first(xs: List(a)) -> Option(a)",
|call: &HostCall| {
let Value::List(xs) = &call.args[0] else {
return Err(VmError::new("expected a list".into()));
};
xs.first().into_value().map_err(VmError::new)
},
);
A type variable of the return type must be one that a parameter
introduces: by its type, as a is in first, or as a type a
parameter (fn pick(s: String, type a) -> Option(a)).
fn any() -> a is an error: no value it returns could be the type each
call asks for.
A signature writes a record by the name of its type: braces of fields
are no type. It names the types the host module declares (see “Host
types”), the types of the prelude, and the types of the builtin
modules, qualified by the module and without an import (a signature
has no file to write one in): time.Date, json.Value,
http.Request, io.IoError. A record of the program reaches a host
function through a type variable (fn same(x: a) -> a given a
Person gives back a Person): a host module cannot name the
program’s types.
The checker has already made sure the arguments have the declared types
and number, so a function can rely on its signature. When the function
returns, its result is checked against its return type, as far as a
value shows it: Int, Float, Bool, String, Bytes and ();
List, Set, Map, Option, Result and tuples of them; a
Channel; and a record or enum type, the host module’s or a builtin
one (time.Date, json.Value): its type, and the types of the fields
of the record or of the variant it is, as the declaration gives them
at the type’s arguments (Box(Int): its value: a is an Int),
inside it as deep as the check goes; a regex.Regex, url.Url,
tcp.TcpStream, tcp.TcpListener, postgres.PgPool, postgres.PgTx
or postgres.PgCursor(r): that it is one (what a task gives, and what
a cursor’s rows are, is not looked at). A value belongs to the program
it was made in: one a host keeps from another session’s program is not
told apart from a value of the same type id in this one. A -> Int function that returns a
String is a runtime error that names it (mylib.count: its signature returns Int, but it returned String "three"). No value is of Never:
a -> Never function that returns a value is that error too, and it
can only fail (return Err).
A type variable of the result is checked against the type the call’s
arguments show it has: the argument of that type, the first element
of a list of it, the value in an option of it, the type a type a
parameter (or t: TypeOf(a), the same written out) is given, and so
on, the first one a parameter shows. A type is taken only so, as
type a or a TypeOf around the variable alone (t: TypeOf(a), o: Option(TypeOf(a))): a signature that takes TypeOf(List(a)) (a
TypeOf around anything but a variable) is an error when the module
is registered, because the type it is given shows nothing of a that
the result could be checked against. Take type a, and build
List(a) in the program where it is needed. A
fn same(x: a) -> a that returns 5 for same("x") is that error:
mylib.same: its signature returns a, here String (the type of its argument `x`), but it returned Int 5. A record is checked so too: a
Person given back where the argument was a Pet is that error.
The constructors a function builds values with check them against their
types, in every build: Value::record takes the number of fields its type
declares, Tag::new a place its enum has a variant at, and
Value::variant the number of fields that variant declares. Anything else
panics inside the function, which is the runtime error host function 'mylib.f' panicked: Value::record: `Person` declares 2 fields, given 1
(see “Error Surfacing”); no malformed value reaches the program.
What no argument shows stays the function’s to get right: a variable
whose arguments hold no value of it (first([])), the parts of two
values that only one of them shows (the elements of an empty list, the
payload of another variant), and what a Channel carries. Of the type
a type a parameter is given, the head is checked (List, not
List(Int)). The check looks at a bounded part of the result: the
first 64 parts it compares (fields, elements, payloads), with each
element of a list, a set or a map compared with the first element of
the argument’s. The arguments are searched for the value that shows a
variable only when the result has a value of it to compare, and as far
as their first 64 parts: a variable shown only past them (the one
Some at the end of a long list of Nones) stays unchecked. What
lies beyond them is the function’s to get right.
A host function cannot take or return a function (fn f(g: Fn(Int) -> Int) -> Int is an error): a host function has no way to call one.
Host types
A host module declares record and enum types with declare_type, each
by its silt declaration. Its signatures name them, and a program names
them as geo.Point: it builds, reads, updates and matches them like
the types of any module.
use silt::session::{HostCall, HostModule};
use silt::{Value, VmError};
// The field `name` of the record `value`, an Int.
fn int(value: &Value, name: &str) -> Result<i64, VmError> {
match value {
Value::Record(record) => match record.get(name) {
Some(Value::Int(n)) => Ok(*n),
_ => Err(VmError::new(format!("no Int field `{name}`"))),
},
_ => Err(VmError::new("expected a record".into())),
}
}
let geo = HostModule::new("geo")
.declare_type("type Point { x: Int, y: Int }")
.declare_type("type Shape { Circle(Int), Rect(Point, Point) }")
.function("fn origin() -> Point", |call: &HostCall| {
call.record("Point", [("x", Value::Int(0)), ("y", Value::Int(0))])
})
.function("fn norm1(p: Point) -> Int", |call: &HostCall| {
let p = &call.args[0];
Ok(Value::Int(int(p, "x")?.abs() + int(p, "y")?.abs()))
})
.function("fn circle(r: Int) -> Shape", |call: &HostCall| {
call.variant("Shape", "Circle", vec![call.args[0].clone()])
});
From silt:
import geo
fn area(s: geo.Shape) -> Int {
match s {
geo.Circle(r) -> 3 * r * r
geo.Rect(a, b) -> (b.x - a.x) * (b.y - a.y)
}
}
fn show() {
let p = geo.Point { x: 3, y: -4 }
println(geo.norm1(p)) -- 7
println(geo.origin() == p.{ x: 0, y: 0 }) -- true
println(area(geo.Rect(geo.origin(), p.{ y: 4 }))) -- 12
println(area(geo.circle(2))) -- 12
}
A declaration is one type declaration of a record or an enum, with
type parameters if it has them (type Box(a) { value: a }); its
fields name the module’s types, the prelude’s and those of the builtin
modules (type Stamp { at: time.Date }). A type is not named like a
type or trait of the prelude (Option, Never, Display): that is
an error. Everything a host module declares is public, and no
declaration says so: pub in front of one is an error.
opaque type Conn { id: Int } declares a type a program can pass on
but not build or read: only the host functions build one and read its
fields.
A host type is shown by its structure, as every record and enum is:
"{p}" gives Point { x: 3, y: -4 }, and a main that returns
Err(geo.circle(2)) fails with Circle(2). That is its Display, so
it can be an error type. A program cannot give it a Display of its
own: an impl lives in the module of its type or of its trait, and a
host module has no impls.
A function reads a record it is given with record.get("x"), and
builds a value with the call:
call.record(type, fields): the record of the type with the fields, each given by name, in any order, every field once.call.variant(type, variant, fields): the variant with its fields, in the order the variant declares them.
The type is one the module declares ("Point"), or a builtin one,
qualified by its module where it has one ("time.Date"). A type, field
or variant that is not there, or a field missing or given twice, is a
runtime error that names the function (geo.origin: a Point has the fields x, y, each once; given: x). The typed functions fn0, fn1
and fn2 take a record as a Value and cannot build one: use
function for that.
Checking
A host module is checked from its signatures, like a module’s pub fns:
- A call with an argument of the wrong type is a type error before
anything runs (
mylib.double("hello"): expected Int, got String). - A call with the wrong number of arguments is an error.
- A function the module does not declare is an error
(
mylib.triple(3): module ‘mylib’ has no member ‘triple’).
What is wrong with the module itself is reported in every analysis,
whether or not the program imports it, at <host:mylib>:
- a signature that is not one
fnheader without a body, or that leaves a parameter or the return type untyped; - a signature that takes or returns a function;
- a signature whose return type has a type variable that no parameter
introduces (
fn any() -> a); - a typed function (
fn0,fn1,fn2) whose signature declares another number of parameters; - a type the signature names that does not exist, or one of a builtin
module this build lacks (
postgres.PgPoolwithout thepostgresfeature); - a type declaration that is not one
typedeclaration of a record or an enum (an alias, a function, two types in onedeclare_type), a type with a function in a field, and what is wrong with it as with any module’s type: a type it names that does not exist, a field written twice, a type named like another of the module or like a function of it; a type named like a type or trait of the prelude; a declaration written withpub; - a host module whose name is not an identifier (
my-lib), one named like a builtin module (list), or two host modules with one name.
An import mylib in a program whose package also has a mylib.silt or a
dependency named mylib is an error at the import.
Supported Types
The FromValue and IntoValue traits handle conversion between Rust and
silt types:
| Rust type | Silt type | Notes |
|---|---|---|
i64 | Int | |
f64 | Float | Returning NaN or an infinity raises a runtime error |
bool | Bool | |
String | String | |
() | () | |
Value | any | Passthrough, no conversion |
Vec<Value> | List(a) | |
Option<T> | Option(a) | Return only |
Result<T, String> | Result(a, String) | Return only |
let users = HostModule::new("users")
.fn1("fn find(id: Int) -> Option(String)", |id: i64| {
if id == 1 { Some("alice".to_string()) } else { None }
})
.fn1("fn parse_int(s: String) -> Result(Int, String)", |s: String| {
s.parse::<i64>().map_err(|e| e.to_string())
});
import users
match users.find(1) {
Some(name) -> println("found: {name}")
None -> println("not found")
}
let n = users.parse_int("42")? -- propagates Err with ?
Functions as values
A host function is a value like any other function: it can be passed to
list.map, piped with |>, and stored in data structures.
import list
import mylib
println([1, 2, 3] |> list.map(mylib.double)) -- [2, 4, 6]
Thread Safety
Host functions must be Send + Sync, since they may be called from any
thread in the task scheduler’s pool. The type system enforces this. Use
Arc<Mutex<T>> for shared mutable state in a host function.
A Session and what it gives (an analysis, a compiled Program) can
be made on one thread and used on another: a session made at start can
compile in a worker thread, and the program it compiled runs on a
third. A name means the same on every thread.
Output and clock
A Vm is made with a HostIo: where the program’s output goes, and the
clock it reads. It is set once, when the Vm is made, and holds for the
program’s own code and for every task.
let out = Buffer::new();
let vm = Vm::new(HostIo::buffer(&out));
| Constructor | stdout and stderr | Clock |
|---|---|---|
HostIo::buffer(&buffer) | both into buffer, in memory | system |
HostIo::new(stdout, stderr) | any two Outputs | system |
HostIo::process() | the process’s stdout and stderr (what the silt command uses), written by one thread of their own, in the order of the prints, so that a print does not wait for a slow reader (see Blocking operations) | system |
.clock(clock) on any of them | unchanged | clock |
Output. print and println write to stdout, io.eprint and
io.eprintln to stderr. What the runtime prints for the program goes to
stderr too: the report of failures that nothing read (see below), and the
log of an http.serve handler that failed. A Buffer collects text in
memory; its clones share the text,
so the embedder keeps one and reads it with contents() or take().
For anything else, implement Output:
struct Lines(std::sync::mpsc::Sender<String>);
impl Output for Lines {
fn write(&self, text: &str) -> std::io::Result<()> {
self.0.send(text.to_string()).map_err(std::io::Error::other)
}
}
write is called once for each print, println, io.eprint,
io.eprintln or report, from the thread that runs the program and from
the scheduler’s threads. A print’s text is at most as long as a string
may be (10,000,000 bytes; 1,000,000 in WebAssembly): a longer one is a
runtime error of the print (println: result would exceed maximum string size ...). (The process’s stdout and stderr, which silt run writes,
take a text of any length, in pieces.) An error write returns for a
print or println is a runtime error of the program (cannot write to stdout: ...), and so is a panic inside it; for a write to stderr both are
dropped.
The report of failures that nothing read is written when run_program
returns, for the failures that have happened by then. A failure that
nothing read is one of two: a stream stage that failed and whose
output nobody read, and the handler of an http.serve that a test
started and that called
process.exit (Exit::FailsTest), which fails that test. The report
does not change the result: run_program still says how main ended.
A stage that fails later (one that a top-level binding holds goes on
after main) is reported when the Vm is dropped, if it has failed by
then; vm.settle() waits for every task first (see
“The end of a program” below). With HostIo::process(), a program
that writes to a closed stdout pipe ends the process quietly with status
141; give HostIo::new your own Output if the process must go on.
Clock. A Clock gives the time of day, a monotonic reading, and a
way to block:
pub trait Clock: Send + Sync {
/// The time since the Unix epoch.
fn now(&self) -> Duration;
/// The time since some fixed moment; it never goes back.
fn monotonic(&self) -> Duration;
/// Block the calling thread until `duration` has passed.
fn sleep(&self, duration: Duration);
}
| The program | reads |
|---|---|
time.now, time.today, the timestamp in uuid.v7, the seed of math.random (at its first call) | now |
time.sleep outside a task | sleep |
time.sleep in a task, channel.timeout, channel.receive_timeout | monotonic: the wait ends when the reading reaches its deadline |
task.deadline | monotonic: the time of the function is over when the reading reaches the deadline; a wait of it is ended then, and a function that goes on without waiting is ended 2,000 steps after the first time slice of it that begins with the reading past the deadline. The function runs as a task, so a time.sleep in it waits for monotonic too, also when task.deadline is called outside a task |
SILT_IO_TIMEOUT | monotonic: a wait for I/O ends when the reading reaches the deadline |
The runtime’s own threads wait in real time between two readings of an
embedder’s clock. A task’s sleep, the channel timeouts, a
task.deadline and a wait for I/O that SILT_IO_TIMEOUT ends end within
a millisecond of the moment the clock reaches the deadline. Everything that
is not the program’s own waiting stays in real time: the scheduler’s
time slices, the socket timeouts of http and tcp, and how long I/O
takes.
If a method of the clock panics, the clock is not called again and the
program ends with the runtime error the clock panicked: ...: the
builtin that read it fails, and every wait that was pending on the clock
ends, its waiter failing the same way at its next step.
time.today gives the date of now in the local time zone (in UTC in a
build without the local-clock feature).
A program with a clock of its own, whose output is collected:
use std::path::Path;
use std::time::Duration;
use silt::session::{Builtins, Config, Entry, LockPolicy, ProjectSetup, Session};
use silt::{Buffer, Clock, HostIo, Vm};
// A clock that starts at a fixed time and moves only when the
// program sleeps.
struct Simulated(std::sync::Mutex<Duration>);
impl Clock for Simulated {
fn now(&self) -> Duration {
// 2026-10-05T12:00:00Z, plus what has passed.
Duration::from_secs(1_791_201_600) + self.monotonic()
}
fn monotonic(&self) -> Duration {
*self.0.lock().unwrap()
}
fn sleep(&self, duration: Duration) {
*self.0.lock().unwrap() += duration;
}
}
let mut session = Session::new(Config {
project: ProjectSetup::None,
lock: LockPolicy::ReadOnly,
host: vec![],
builtins: Builtins::All,
});
let source = r#"
import time
import result
fn main() {
println("started")
time.sleep(time.minutes(90))
println(time.now() |> time.to_datetime(0) |> time.format("%H:%M") |> result.unwrap_or(""))
}
"#;
let file = session.set_overlay(Path::new("main.silt"), source.to_string());
let program = session.compile(file, Entry::Main).expect("compiles");
// The program's output is collected in `out`; it reads `Simulated`.
let out = Buffer::new();
let io = HostIo::buffer(&out).clock(Simulated(Default::default()));
Vm::new(io).run_program(&program).unwrap();
assert_eq!(out.contents(), "started\n13:30\n");
WebAssembly
The library builds for wasm32-unknown-unknown with
default-features = false. That target has no clock, no threads and no
source of randomness of its own, so the embedder supplies them:
- Clock. Give the
VmaClock(in a browser, fromDate.now()andperformance.now()): the system clock panics there.sleepcannot block a browser’s main thread; it can return at once, or move a simulated clock on as above. - Tasks. There are no worker threads: the thread that runs the program runs its tasks, whenever the program waits (a receive, a send, a join, a sleep). A task that nobody ever waits for does not run.
- Timers and I/O. The same thread fires the timers while it waits,
and an I/O operation runs on it. Where every task waits and the next
thing to happen is a deadline (a task’s sleep, a timeout), the thread
cannot be put to sleep: it calls the clock’s
sleepfor the time that is left, and looks at the clock again when the call returns. - Sizes. A string or a
Bytesholds at most 1,000,000 bytes there (10,000,000 elsewhere): a builtin or an interpolation that would make a longer one is a runtime error, as one past the larger limit is elsewhere. - Randomness.
getrandomanduuidrefuse to build for the target until the embedder’s crate picks a source: in a browser, addgetrandom = { version = "0.4", features = ["wasm_js"] }anduuid = { version = "1", features = ["js"] }to its dependencies.
The crate in playground/ is such an embedder: the playground of
silt-lang.com.
Vm Lifecycle
A Vm is a single interpreter instance. vm.run_program(&program) runs
a compiled program: it takes in the types of the program’s values and
its global slots (one per top-level function, let, host function and
trait method), then runs the program’s script, which calls main. It
returns Ok(()) when main returned, and Err(VmError) when the
program failed (see “Error Surfacing” below). No value of the program
comes back this way: main returns () or Result((), e), and a
program hands its values to you through a host function it calls, as
mylib.give does in the Quick Start, or through what it prints. The
program carries its host functions, and the Vm its output and clock:
there is no other set-up.
Tests. A program compiled for Entry::Tests { filter } holds its
test functions: program.entry is EntryPoint::Tests(tests), a
TestFn for each, with its name and its kind (TestKind::Run, or
TestKind::Skip for a skip_test_ function, which is reported and not
called). vm.call_test(&test) runs one, as silt test does: Ok(())
when it passed, its error when it failed.
The end of a program. run_program returns when main has
returned; the stages of streams that the program still holds (a
top-level binding holds one) may still be at work.
vm.settle() waits until the program has ended as silt run defines
it: until none of its tasks can do more (each has ended or waits, and
no timer and no I/O is pending). It then drops the tasks that still
wait, and reports on stderr the failures that nothing read (the two
kinds above). An embedder that wants the exit rule of silt run calls it
after a run_program that returned Ok.
Without settle, the program’s tasks go on for as long as the Vm
lives: a task that waits stays where it is, and a stage that fails is
reported at the return of the next call into the Vm, or when the
Vm is dropped, if it has failed by then; a stage that has not failed
by then leaves no report. An embedder that must not wait for a
program’s stages (a playground with a time limit) does not call
settle, and drops the Vm.
process.exit ends the program’s run with its code, not your
process: whatever call into the Vm is running (run_program,
call_test) returns an error whose exit is Some(code), also when a
task made the call. No task runs further, nothing is waited for, and the
failures that nothing read are not reported. Your thread gets
the error at once where it waits for a task, a channel or an I/O
operation, and within about a million steps where it computes; a thread
asleep in your Clock::sleep, or inside one call of a builtin or a host
function, gets it when that returns. Every later call into that Vm
returns the same error. vm.set_exit(Exit::EndsProcess) makes it end
the process instead, as under silt run, and Exit::FailsTest makes it
a runtime error, as under silt test.
match vm.run_program(&program) {
Err(e) if e.exit.is_some() => println!("exit code {:?}", e.exit),
Err(e) => eprintln!("silt error: {}", e.message),
Ok(()) => {}
}
Dropping a Vm ends its program where it is. The threads that
served it end (the scheduler’s workers, the timer thread, the I/O workers; each when what
it is doing returns), tasks that are still running or waiting never run
again, and pending timers never fire. The state behind math.random
and uuid.v7 belongs to the Vm too: one Vm does not affect
another’s numbers.
Reusing a Vm. Run one program per Vm: build a fresh Vm::new(io)
for each. (The entries of a REPL session are compiled to follow one
another, and share one Vm.)
Thread safety. A single Vm is not Sync and must be driven from
one thread (the scheduler owns its own worker threads internally). To run
several scripts in parallel from Rust, create one Vm per thread.
Limits
Builtin modules. Config::builtins says which builtin modules a
program may import: Builtins::All (every one of the build), or
Builtins::Only(names). An import of any other, in any module of
the program, is an error when the program is checked (the builtin module 'fs' is not offered to this program: the application that runs it lets it import only list, string). The prelude (println,
Option, Result, …) and the host modules are every program’s.
A host that runs programs it did not write offers the modules that
compute (list, string, map, math, json, …) and keeps
the ones that reach out of the program: fs, io (files, stdin,
the command line), stream (files, stdin), env, process,
tcp, http, postgres. What a program prints goes to the
Vm’s HostIo, and the time it reads comes from its Clock.
let session = Session::new(Config {
project: ProjectSetup::None,
lock: LockPolicy::ReadOnly,
host: vec![],
builtins: Builtins::Only(vec!["list".into(), "string".into(), "math".into()]),
});
Memory. There is no limit on the memory a program uses: one call of a builtin can build a list of millions of elements within a step, so the step budget bounds the time a program runs, not its memory. A host that runs programs it did not write runs them in a process it can end, with the memory limit of the operating system.
Time slice. vm.set_time_slice(steps) makes the program run in
slices of that many steps: a task gives way to the other tasks after
steps instructions (the scheduler’s own slice is 2000), and the thread
that runs the program’s own code stops and goes on after steps too,
where it otherwise does so about every million steps. What a program
computes does not depend on the slice; a host sets one to test exactly
that. With set_time_slice(1) the program is stopped and resumed after
every instruction and after every step of a builtin that calls back
into it.
Step budget. vm.set_step_budget(steps) lets the program run that
many more steps, those of its tasks included. When they are used up,
whatever of the program still runs ends with a VmError whose
out_of_steps is true (message the step budget is used up): main,
and each task, whose join gives the error on. A program that loops for
ever ends there. The budget is looked at where a slice ends and before
one starts, so each thread of the program may run up to one slice more
than the budget before it ends: 1,999 steps at the scheduler’s slice of
2,000, with which a budget of 1 still runs a short program to its end.
With set_time_slice(1) the count is exact, and a budget of 0 runs
nothing at any slice. The start
of a wait counts as one step, so tasks that pass a value to and fro for
ever end too. A wait that never ends is not ended by the budget: that is
the deadlock check’s, or the host drops the Vm. out_of_steps marks
what the budget did: its own error, the error of a join of a task it
ended, and a deadlock that follows (the task waited for is gone). A
fault of the program itself, a division by zero or a panic, keeps it
false even when a task has used the budget up.
Frame budget. vm.set_frame_budget(mib) lets the calls in progress
of the program, and of its tasks, take that many MiB in all: 128 until it
is called, or what SILT_FRAME_BUDGET in the environment says. A
recursion that would take more ends with a VmError whose message is
stack overflow: call frames take more than <mib> MiB; this task holds <size>. A call counts its frame and the values it holds on the stack (24
bytes each), not the data they point to. The first 64 KiB of the
program’s own frames, and of each task’s, are outside the budget; the
rest is taken in pieces of 1 MiB and given back as the frames shrink and
when the task ends.
The budget belongs to the Vm that Vm::new made, and the program’s
tasks share it; it is not one budget for the process. Two Vms in one
process have one each, of 128 MiB unless set otherwise, so a host that
runs programs side by side gives each the share it can spare, as a test
that pins an overflow sets a small one. (silt run, silt test and
silt repl run one program, so there the budget is the process’s.)
Error Surfacing
- Static errors (type errors, unknown names, bad host signatures)
are the diagnostics of
session.analyze(file).session.compilereturns them as itsErrfor a program that has them. - Runtime errors (overflow, out-of-bounds, a failed assertion)
return as
Err(VmError)fromvm.run_program. - A
mainthat returnsErr(e)(often from a?) has failed: anErr(VmError)too, withreturnedset to the payload’s text (easprintlnwrites it), the messagemain returned Err: <that text>, and its place wheremainis bound (the name of itsfn, its name in aletor an import).call_testsays the same of a test function, at its name.silt runwrites such an error as the one lineerror: <text>, the program’s message to its user, and a host may do the same. The payload is shown by itsDisplay, which is code of the program: aprocess.exitthere (or the step budget used up) is the error instead; if it fails otherwise, the payload is shown by its structure, anddisplay_failuresays what failed: the type whose impl it was (type_name), the first line of the failure’s message (message) and its place (span).failure.note(session.sources())is the linesilt runwrites undererror: <text>afternote:,the Display impl of E failed: panic: display panics (main.silt:3:32). panic(...)in silt code reaches Rust as anErr(VmError)whose message carries the panicked string: its first 100,000 bytes, and… (N more bytes)past them. The text of amainthat returnsErris cut so too where itsDisplayfails and its structure is shown.- An
Errfrom a host function becomes a runtime error whose message starts with the function’s name:mylib.parse: bad input. So does a result whose checked parts (see “Functions on values”) are not of the type its signature returns. - A panic inside a host function is caught and becomes a runtime
error (
host function 'mylib.parse' panicked: ...). The scheduler worker survives and other tasks keep running. ReturningErris still the way to fail; the catch is a safety net. - A panic of silt’s own runtime is a bug in silt, and ends the
program, not your process. Wherever it happens (on the thread that
runs the program, on a worker that runs a task, on the timer’s thread
or a thread that does I/O), it comes out of the
Vmcall your thread is in, or of the next one it makes, as a Rust panic with the original payload:run_program,call_test,settle,stop_tasks,wait_until_idleandshow_textalike. Wrap those calls instd::panic::catch_unwindif your process is to survive it. No task of the program runs further, every later call on thatVmpanics again, and theVmcan only be dropped, which is safe. Your thread gets the panic at once where it waits for a task, a channel or an I/O operation, and within about a million steps where it computes; a thread asleep in yourClock::sleep, or inside one call of a builtin or a host function, gets it when that returns. (A thread that still finishes an I/O operation after itsVmwas dropped has nobody left to give a panic to: Rust’s lines for it are all there is.)
match vm.run_program(&program) {
Ok(()) => println!("the program ran to its end"),
Err(e) => eprintln!("silt error: {}", e.message),
}
Silt code has no access to the host filesystem, network or environment beyond what the builtin modules it may import (see “Limits”) and your host modules provide.
The environment. env.set and env.remove change the environment
of your whole process. A Vm refuses them once its program has started
a task or an I/O operation (from then on a thread of its own may read
the environment), but it cannot see your threads, nor another Vm’s.
While a Vm runs a program, read the environment on your other threads
only through std::env (which takes the lock that the change takes),
never through the C library (getenv, or a C library that calls it),
and do not run two programs that change it at once.
Showing errors as silt does
The session hands out five more types, which a function of yours can
take and a struct of yours can keep: silt::session::{FileId, Span, SourceMap, Diagnostic, Severity}.
FileIdnames a file of the session: whatsession.set_overlayreturns, and whatsession.analyzeandsession.compiletake.Spanis a place, the bytesstart..endof the filefile: where a diagnostic is (d.span()) and where a runtime error happened (e.span).SourceMapis whatsession.sources()returns, the text of every file the session has read:sources.line_col((span.file, span.start))is the line and the column, from 1, where a place starts.Diagnosticis an error or a warning that the session found: an item ofanalysis.diagnostics, and of theErrofsession.compile. It has amessage()of one line, aseverity(), a place (span()), itsnotes(), and its help lines (help(session.sources()), a place in them written asmain.silt:3:5).SeverityisSeverity::Error, which stops a program from being compiled, orSeverity::Warning, which does not.
session.render(&d) is the diagnostic as silt check prints it: the
header, the place with its line of source and a caret, then its other
places, notes and help. An analysis lists its diagnostics in the order
it found them; silt check prints them by file and place, with an empty
line between two. e.render(&session) is a runtime error as
silt run prints it: the header, the place with its line of source,
and the call stack; for a main that returned Err, the one line
error: <text>. Both come from the code the silt command prints
with, and give plain text: no colour codes, whatever the process’s
stderr is and whatever NO_COLOR or FORCE_COLOR say.
use silt::VmError;
use silt::session::{Diagnostic, FileId, Session, Severity, SourceMap, Span};
/// Where `span` starts: its line and column, from 1.
fn place(sources: &SourceMap, span: Span) -> (u32, u32) {
sources.line_col((span.file, span.start))
}
/// The diagnostic in one line of your own: `2:16 error: type mismatch: ...`.
fn one_line(session: &Session, d: &Diagnostic) -> String {
let (line, col) = place(session.sources(), d.span());
let word = match d.severity() {
Severity::Error => "error",
Severity::Warning => "warning",
};
let mut text = format!("{line}:{col} {word}: {}", d.message());
for note in d.notes() {
text += &format!(" (note: {note})");
}
for help in d.help(session.sources()) {
text += &format!(" (help: {help})");
}
text
}
/// Each diagnostic of `file` as `silt check` prints it, in the order the
/// analysis found them, and whether one is an error.
fn check(session: &mut Session, file: FileId) -> (Vec<String>, bool) {
let diagnostics: Vec<Diagnostic> = session.analyze(file).diagnostics.clone();
let texts = diagnostics.iter().map(|d| session.render(d)).collect();
let failed = diagnostics.iter().any(|d| d.severity() == Severity::Error);
(texts, failed)
}
/// What `silt run` prints for the error that ended the program.
fn report(session: &Session, e: &VmError) -> String {
e.render(session)
}