Standard Library (Std)
Std is the one library that never needs to be named — Std::pln(...) and pln(...) call the same function. Every other library needs its own prefix (Time::now(), Http::fetch(...)), but anything shown here works bare.
One distinction worth keeping straight: this page is about library functions, which never need a receiver. A document function always does — self.myFunc(), super.myFunc(), through a variable, whatever fits — because it belongs to a specific node in the graph, not to the runtime itself.
Output
pln(..) -> void
Prints all arguments to the standard output stream — this is what every other page's examples have been using the whole time.
err(..) -> void
Same as pln, but to the error stream instead of standard output.
str(..) -> str
Formats all arguments the same way pln would, but returns the result as a string instead of printing it.
dbg(..) -> void
Prints all arguments as debug output. Depending on how the host environment wires up logging, this may not surface in every output stream pln does — worth checking your browser console too if it looks quiet.
Logging
The five log_* functions map onto the standard levels from Rust's log crate. Same caveat as dbg — whether these are visible depends on what the host has configured to receive them.
log_info(..) -> void
log_debug(..) -> void
#[main]
fn main() {
log_debug("this is what just happened, in case you need to debug me");
}log_warn(..) -> void
#[main]
fn main() {
log_warn("we encountered something, but are handling it");
}log_error(..) -> void
log_trace(..) -> void
Debugging & Tracing
Three deeper introspection tools — expect dense, VM-level output that looks different every run. That's normal; these aren't meant to be tidy.
peek(..) -> void
Prints your arguments, then a trace of the current process and the next instructions about to execute. Pass a trailing integer to control how many.
trace(..) -> void
Like peek, but shows the instructions that already ran leading up to this point, instead of what's coming next.
dbg_tracestack() -> void
Prints a snapshot of the current stack, with no arguments needed.
Assertions
Every one of these throws when the check fails — wrap the failing case in try/catch if you want execution to continue past it, same as anywhere else in Stof.
assert(value: unknown = false) -> void
#[main]
fn main() {
assert(true);
pln('first assertion passed');
try { assert(false); }
catch { pln('assert(false) throws'); }
}assert_eq(first: unknown, second: unknown) -> void
#[main]
fn main() {
assert_eq('a', 'a');
pln('equal values pass');
try { assert_eq(43, 42); }
catch { pln('unequal values throw'); }
}assert_neq(first: unknown, second: unknown) -> void
#[main]
fn main() {
assert_neq('a', 'b');
pln('different values pass');
try { assert_neq(34, 34); }
catch { pln('equal values throw'); }
}assert_not(value: unknown = true) -> void
#[main]
fn main() {
assert_not(false);
pln('falsy value passes');
try { assert_not(true); }
catch { pln('truthy value throws'); }
}assert_null(value: unknown) -> void
Throws if the value isn't null. A function that returns nothing counts as null.
fn nothing() {}
#[main]
fn main() {
assert_null(null);
assert_null(self.nothing());
pln('both are null');
try { assert_null(42); }
catch { pln('assert_null(42) throws'); }
}assert_not_null(value: unknown) -> void
Throws if the value is null.
#[main]
fn main() {
assert_not_null(42);
pln('42 is not null');
try { assert_not_null(self.missing); }
catch { pln('a missing field is null, so this throws'); }
}Errors & Process Control
throw(value: unknown = "Error") -> void
Throws any value, not just a string — the mechanism behind every try/catch example on the Error Handling page.
#[main]
fn main() {
try { throw("error message"); }
catch (msg: str) { pln('caught:', ' ', msg); }
}exit(..) -> void
Immediately halts the current process — nothing after it in the same process runs. Pass a promise to terminate that process's execution instead of the current one.
#[main]
fn main() {
pln('before exit');
exit();
pln('after exit — never runs');
}Parsing & Exporting
parse(source: str | blob, context: str | obj = self, format: str = "stof", profile: str = "prod") -> bool
Covered in depth on Import & Export — the runtime counterpart to the import statement, and it works fine sandboxed since it's just operating on a string.
Profiles: "prod" (the default; #[test] functions left out), "test", "docs", "prod_docs", and "untrusted", for Stof source from somewhere else: declarations only. Nothing runs while it's parsed (field and attribute values must be literals, and #[init] and #[dropped] functions are refused), it imports nothing, and it declares no #[type]s, roots, or binary data. Confined code's own parse is always "untrusted", and can't parse "bstf" or "pkg". Parse it into a fresh object, then seal it confined before calling anything in it.
#[main]
fn main() {
parse('fn hello() -> str { "hello" }');
pln(self.hello());
}stringify(format: str = "json", context: obj = null) -> str
Exports a string. Lossy for anything the target format can't represent — JSON has no concept of units, for instance, so they're silently dropped.
#[main]
fn main() {
const object = new { x: 3.14km, y: 42m };
pln(stringify("json", object));
}Some formats call functions first: #[attr] and #[text] functions in html and xml (see Formats). They're called before the export is written, and async ones are awaited:
#[tag('p')]
note: {
#[attr('class')] kind: 'hint'
#[text] fn message() -> str { 'Saved' }
}
#[main]
fn main() {
pln(stringify('html', self.note));
}blobify(format: str = "json", context: obj = null) -> blob
Same idea as stringify, exporting raw bytes instead of a string.
#[main]
fn main() {
const object = new { x: 3.14km, y: 42m };
const bytes = blobify("json", object);
pln(bytes.len() > 0, ' ', bytes as str);
}Constructing Collections
Mostly useful for building an empty collection, or building one from values you already have in hand rather than writing out literal syntax.
list(..) -> list
map(..) -> map
Takes tuples of key/value pairs.
set(..) -> set
Values & Memory
copy(val: unknown) -> unknown
A real deep copy — for an object, every field, function, and nested piece of data underneath it, recursively.
#[main]
fn main() {
const a = {1, 2, 3};
const b = copy(a);
b.clear();
pln(str(a), ' ', str(b));
}swap(first: unknown, second: unknown) -> void
Swaps two values in place — needs & on value types, the same reference operator from Variables & References, since a plain value type would just swap two disposable copies.
#[main]
fn main() {
let a = 42;
let b = -55;
swap(&a, &b);
pln(a, ' ', b);
}min(..) -> unknown
If an argument is a collection, only the values inside it are considered — not the collection as a whole.
max(..) -> unknown
drop(..) -> bool | list
Covered in depth on Document Memory Management — drops fields, functions, objects, or data from the graph, running #[dropped] on anything that has it. Given several things to drop at once, returns a list of one bool per item.
#[main]
fn main() {
const func = () => {};
const object = new {};
self.field = 42;
const results = drop("self.field", func, object);
pln(results);
}shallow_drop(..) -> bool | list
Same as drop, except if a dropped field pointed to an object, only the field is removed — the object itself stays in the graph. Useful when more than one field might point at the same object and you only want to disconnect this one.
#[main]
fn main() {
self.field = new {};
const object = self.field;
shallow_drop("self.field");
pln(self.contains("field"), ' ', object.exists());
}Sealing
A document can seal parts of itself, so code that runs later (an agent's function, a rule added at runtime) can call them but not change them, and confine code from somewhere else to what it's given. It's one-way: only the host can unseal. See Security and the Sandbox.
seal(obj: obj, fields: bool = false, removable: bool = false, reads: list = null, hosts: list = null, libs: list = null, time: ms = null, calls: list = null) -> str
Seals an object (or a type, like <Engine>) and everything under it: its functions can be called but not added, removed, renamed, replaced, or moved, and its attributes can't change. Its fields still change unless fields is true. Returns its digest. A change the seal refuses fails with a sealed: ... error.
removable: the object can still be dropped whole (nothing in it can change, and it can't be moved or renamed).reads(a list of objects or paths): confine its code. While it runs, it finds only itself and these objects, changes only itself, and can't hand anything else to a library function.[]means only itself. They're kept as paths and looked up each time the part runs, so an object replaced at a path is the one it reads.hosts(a list of host names): itsHttp.fetchreaches only these hosts.[]means no network.libs(a list of library names, like['Std', 'Str', 'Http']): its code calls only these libraries, the host's own included. Method calls count as their library's (text.split('/')isStr).[]means no library calls.time(like500ms): its code runs for at most this long each time it's entered, everything it calls included. Running past it is asealed: ...error only code outside the part can catch; its gates stop, and itssleepwakes at the limit. Whatever its code starts and doesn't await ends when the call into it returns.calls(a list of functions outside it, like[self.link.request]): gates, functions its code may call that run unconfined, as themselves. Hand them to it as values (a field madeonthe part, or an argument). A call is a gate's only when every confinement it runs under lists it, so seal once with everything. See Gates.
Sealing again only adds to a seal. See Confining Code From Somewhere Else.
rules: {
fn price(units: int) -> int { units * 50 }
}
#[main]
fn main() {
seal(self.rules);
try self.rules.price = (units: int): int => 0;
catch (e, message) pln(message);
pln(self.rules.price(2));
}digest(obj: obj, fields: bool = false) -> str
A SHA-256 (hex) over an object's functions and structure, plus its fields' values when fields is true. The same for the same document, parsed or loaded from binary, and wherever the object is (its own name isn't part of it), so it identifies exactly the logic it covers, in this document or another one it's sent to.
rules: {
fn price(units: int) -> int { units * 50 }
}
#[main]
fn main() {
pln(digest(self.rules));
}sha256(data: str | blob) -> str
The SHA-256 (lowercase hex) of text (its UTF-8 bytes) or a blob: the same as any other SHA-256 of those bytes, so another system can check it (a hash a protocol sends, say). For a part of the document, use digest.
#[main]
fn main() {
pln(sha256('abc'));
pln(sha256('abc' as blob) == sha256('abc'));
}sealed(obj: obj) -> map | null
How an object is sealed, or null when it isn't: part (the path of the object sealed, this one or one around it), fields, removable, and confined (one { reads, hosts, libs, time, calls } map per confinement its code runs under, calls as function paths).
inputs: { city: 'Boston' }
plugin: { fn forecast() -> str { 'sunny' } }
#[main]
fn main() {
pln(sealed(self.plugin));
seal(self.plugin, removable = true, reads = [self.inputs]);
const info = sealed(self.plugin);
pln(info.get('removable'));
pln(info.get('confined')[0].get('reads'));
}Signing and checking signatures (over a digest, or any message) is the Key library.
Infinity and NaN
inf() -> float
Positive infinity. Negate it for negative infinity. To check whether a number is infinite, use val.inf() from the Number Library.
#[main]
fn main() {
const limit = inf();
pln(limit > 1e308, ' ', -inf() < -1e308, ' ', limit.inf());
}nan() -> float
Not a number (NaN). NaN never equals anything, including itself, so check for it with val.nan().
#[main]
fn main() {
const value = nan();
pln(value.nan(), ' ', value == value);
}Introspection
Mostly useful for writing code that has to reason about the document generically — a validator, a debugging tool, anything that can't assume a fixed shape ahead of time.
funcs(attributes: str | list | set = null) -> list
Every function in the graph, optionally filtered to only those carrying a given attribute. Functions in a confined part aren't found: call them through the part (part.funcs(...)).
callstack() -> list
A list of function pointers currently on the stack — last one is this, the function calling callstack() itself.
fn inner() {
for (const func in callstack()) {
pln(func.obj().path(), ' ', func.name());
}
}
#[main]
fn main() {
self.inner();
}graph_id() -> str
A unique ID string for this graph/document.
format(format: str) -> bool
Is a given format loaded and available for parse/stringify/blobify?
format_content_type(format: str) -> str
The HTTP content-type header value for a loaded format — useful if you're serving Stof-produced data over the wire.
formats() -> set
Every format currently available to use.
lib(lib: str, func?: str) -> bool
Is a library — and optionally a specific function on it — loaded?
#[main]
fn main() {
pln(lib("Std"), ' ', lib("Render"));
pln(lib("Num", "abs"));
}libs() -> set
Every library currently available.
prof(name: str) -> bool
Was this graph parsed under a given profile name? Profiles are how parse's profile parameter tags a parse for later inspection.
Environment
These read and change the process's environment variables, so they're off by default: a document only has them when the host calls allow_system() (Rust, Python). The stof CLI turns them on, since it runs your own files. They aren't in the JavaScript package, so the examples below don't run on this site.
env(var: str) -> str
An environment variable's value, or null if it isn't set.
const host = env("HOST");
env_vars() -> map
Every environment variable, as a map of names to values.
const vars: map = env_vars();
set_env(var: str, value: str) -> void
Sets an environment variable for this process.
set_env("HOST", "localhost");
remove_env(var: str) -> void
Removes an environment variable from this process.
remove_env("HOST");
Timing
sleep(time: ms) -> void
Pauses the current process for at least the given duration — possibly longer, never less. Other processes keep making progress while this one sleeps, same cooperative model as Async.
#[main]
fn main() {
const start = Time::now();
sleep(50ms);
pln(Time::diff(start) >= 50);
}IDs & Text Helpers
nanoid(length: int = 21) -> str
A URL-safe random ID — collision probability is low and drops further as length increases.
xml(text: str, tag: str) -> str
Wraps a string in an XML tag — a small formatting helper, nothing more.
prompt(text: str = '', tag?: str) -> prompt
Builds a prompt value — a small tree of tagged text, meant for assembling structured prompts for AI contexts. += appends a nested prompt as a child.
#[main]
fn main() {
let p = prompt(tag = 'instruction');
p += prompt('do a thing', 'sub');
p += prompt('another thing', 'sub');
pln(p as str);
}