Skip to main content

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.

pln.stofPlayground ↗
#[main]
fn main() {
  pln("hello, world");
}
Output

err(..) -> void​

Same as pln, but to the error stream instead of standard output.

err.stofPlayground ↗
#[main]
fn main() {
  err("hello, world");
}
Output

str(..) -> str​

Formats all arguments the same way pln would, but returns the result as a string instead of printing it.

str.stofPlayground ↗
#[main]
fn main() {
  pln(str("hello, world"));
}
Output

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.

dbg.stofPlayground ↗
#[main]
fn main() {
  dbg("hello, world");
}
Output

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-info.stofPlayground ↗
#[main]
fn main() {
  log_info("we just did something cool");
}
Output

log_debug(..) -> void​

log-debug.stofPlayground ↗
#[main]
fn main() {
  log_debug("this is what just happened, in case you need to debug me");
}
Output

log_warn(..) -> void​

log-warn.stofPlayground ↗
#[main]
fn main() {
  log_warn("we encountered something, but are handling it");
}
Output

log_error(..) -> void​

log-error.stofPlayground ↗
#[main]
fn main() {
  log_error("we have a problem");
}
Output

log_trace(..) -> void​

log-trace.stofPlayground ↗
#[main]
fn main() {
  log_trace("tracing through this code path");
}
Output

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.

peek.stofPlayground ↗
#[main]
fn main() {
  peek("getting here");
}
Output

trace(..) -> void​

Like peek, but shows the instructions that already ran leading up to this point, instead of what's coming next.

trace.stofPlayground ↗
#[main]
fn main() {
  trace("getting here");
}
Output

dbg_tracestack() -> void​

Prints a snapshot of the current stack, with no arguments needed.

dbg-tracestack.stofPlayground ↗
#[main]
fn main() {
  dbg_tracestack();
}
Output

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​

assert.stofPlayground ↗
#[main]
fn main() {
  assert(true);
  pln('first assertion passed');

  try { assert(false); }
  catch { pln('assert(false) throws'); }
}
Output

assert_eq(first: unknown, second: unknown) -> void​

assert-eq.stofPlayground ↗
#[main]
fn main() {
  assert_eq('a', 'a');
  pln('equal values pass');

  try { assert_eq(43, 42); }
  catch { pln('unequal values throw'); }
}
Output

assert_neq(first: unknown, second: unknown) -> void​

assert-neq.stofPlayground ↗
#[main]
fn main() {
  assert_neq('a', 'b');
  pln('different values pass');

  try { assert_neq(34, 34); }
  catch { pln('equal values throw'); }
}
Output

assert_not(value: unknown = true) -> void​

assert-not.stofPlayground ↗
#[main]
fn main() {
  assert_not(false);
  pln('falsy value passes');

  try { assert_not(true); }
  catch { pln('truthy value throws'); }
}
Output

assert_null(value: unknown) -> void​

Throws if the value isn't null. A function that returns nothing counts as null.

assert-null.stofPlayground ↗
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'); }
}
Output

assert_not_null(value: unknown) -> void​

Throws if the value is null.

assert-not-null.stofPlayground ↗
#[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'); }
}
Output

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.

throw.stofPlayground ↗
#[main]
fn main() {
  try { throw("error message"); }
  catch (msg: str) { pln('caught:', ' ', msg); }
}
Output

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.

exit.stofPlayground ↗
#[main]
fn main() {
  pln('before exit');
  exit();
  pln('after exit — never runs');
}
Output

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.

parse.stofPlayground ↗
#[main]
fn main() {
  parse('fn hello() -> str { "hello" }');
  pln(self.hello());
}
Output

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.

stringify.stofPlayground ↗
#[main]
fn main() {
  const object = new { x: 3.14km, y: 42m };
  pln(stringify("json", object));
}
Output

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:

stringify-computed.stofPlayground ↗
#[tag('p')]
note: {
  #[attr('class')] kind: 'hint'
  #[text] fn message() -> str { 'Saved' }
}

#[main]
fn main() {
  pln(stringify('html', self.note));
}
Output

blobify(format: str = "json", context: obj = null) -> blob​

Same idea as stringify, exporting raw bytes instead of a string.

blobify.stofPlayground ↗
#[main]
fn main() {
  const object = new { x: 3.14km, y: 42m };
  const bytes = blobify("json", object);
  pln(bytes.len() > 0, ' ', bytes as str);
}
Output

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​

list.stofPlayground ↗
#[main]
fn main() {
  pln(list(1, 2, 3));
}
Output

map(..) -> map​

Takes tuples of key/value pairs.

map.stofPlayground ↗
#[main]
fn main() {
  pln(str(map(("a", 1), ("b", 2))));
}
Output

set(..) -> set​

set.stofPlayground ↗
#[main]
fn main() {
  pln(str(set(1, 2, 3)));
}
Output

Values & Memory​

copy(val: unknown) -> unknown​

A real deep copy — for an object, every field, function, and nested piece of data underneath it, recursively.

copy.stofPlayground ↗
#[main]
fn main() {
  const a = {1, 2, 3};
  const b = copy(a);
  b.clear();
  pln(str(a), ' ', str(b));
}
Output

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.

swap.stofPlayground ↗
#[main]
fn main() {
  let a = 42;
  let b = -55;
  swap(&a, &b);
  pln(a, ' ', b);
}
Output

min(..) -> unknown​

If an argument is a collection, only the values inside it are considered — not the collection as a whole.

min.stofPlayground ↗
#[main]
fn main() {
  pln(str(min(1km, 2m, 3mm)));
}
Output

max(..) -> unknown​

max.stofPlayground ↗
#[main]
fn main() {
  pln(str(max(1km, 2m, 3mm)));
}
Output

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.

drop.stofPlayground ↗
#[main]
fn main() {
  const func = () => {};
  const object = new {};
  self.field = 42;

  const results = drop("self.field", func, object);
  pln(results);
}
Output

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.

shallow-drop.stofPlayground ↗
#[main]
fn main() {
  self.field = new {};
  const object = self.field;

  shallow_drop("self.field");
  pln(self.contains("field"), ' ', object.exists());
}
Output

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): its Http.fetch reaches 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('/') is Str). [] means no library calls.
  • time (like 500ms): its code runs for at most this long each time it's entered, everything it calls included. Running past it is a sealed: ... error only code outside the part can catch; its gates stop, and its sleep wakes 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 made on the 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.

seal.stofPlayground ↗
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));
}
Output

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.

digest.stofPlayground ↗
rules: {
  fn price(units: int) -> int { units * 50 }
}

#[main]
fn main() {
  pln(digest(self.rules));
}
Output

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.

sha256.stofPlayground ↗
#[main]
fn main() {
  pln(sha256('abc'));
  pln(sha256('abc' as blob) == sha256('abc'));
}
Output

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).

sealed.stofPlayground ↗
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'));
}
Output

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.

inf.stofPlayground ↗
#[main]
fn main() {
  const limit = inf();
  pln(limit > 1e308, ' ', -inf() < -1e308, ' ', limit.inf());
}
Output

nan() -> float​

Not a number (NaN). NaN never equals anything, including itself, so check for it with val.nan().

nan.stofPlayground ↗
#[main]
fn main() {
  const value = nan();
  pln(value.nan(), ' ', value == value);
}
Output

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(...)).

funcs.stofPlayground ↗
#[main]
#[main_or_test]
fn main() {
  pln(funcs("main_or_test").len());
}
Output

callstack() -> list​

A list of function pointers currently on the stack — last one is this, the function calling callstack() itself.

callstack.stofPlayground ↗
fn inner() {
  for (const func in callstack()) {
      pln(func.obj().path(), ' ', func.name());
  }
}

#[main]
fn main() {
  self.inner();
}
Output

graph_id() -> str​

A unique ID string for this graph/document.

graph-id.stofPlayground ↗
#[main]
fn main() {
  pln(graph_id().len() > 10);
}
Output

format(format: str) -> bool​

Is a given format loaded and available for parse/stringify/blobify?

format.stofPlayground ↗
#[main]
fn main() {
  pln(format("json"), ' ', format("docx"));
}
Output

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.

format-content-type.stofPlayground ↗
#[main]
fn main() {
  pln(format_content_type("json"));
}
Output

formats() -> set​

Every format currently available to use.

formats.stofPlayground ↗
#[main]
fn main() {
  pln(formats().contains("json"));
}
Output

lib(lib: str, func?: str) -> bool​

Is a library — and optionally a specific function on it — loaded?

lib.stofPlayground ↗
#[main]
fn main() {
  pln(lib("Std"), ' ', lib("Render"));
  pln(lib("Num", "abs"));
}
Output

libs() -> set​

Every library currently available.

libs.stofPlayground ↗
#[main]
fn main() {
  pln(libs().superset({"Std", "Fn", "Num", "Set"}));
}
Output

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.

prof.stofPlayground ↗
#[main]
fn main() {
  pln(prof('test'), ' ', prof('prod'));
}
Output

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.

sleep.stofPlayground ↗
#[main]
fn main() {
  const start = Time::now();
  sleep(50ms);
  pln(Time::diff(start) >= 50);
}
Output

IDs & Text Helpers​

nanoid(length: int = 21) -> str​

A URL-safe random ID — collision probability is low and drops further as length increases.

nanoid.stofPlayground ↗
#[main]
fn main() {
  pln(nanoid() != nanoid(33));
}
Output

xml(text: str, tag: str) -> str​

Wraps a string in an XML tag — a small formatting helper, nothing more.

xml.stofPlayground ↗
#[main]
fn main() {
  pln(xml("hello, world", "msg"));
}
Output

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.

prompt.stofPlayground ↗
#[main]
fn main() {
  let p = prompt(tag = 'instruction');
  p += prompt('do a thing', 'sub');
  p += prompt('another thing', 'sub');
  pln(p as str);
}
Output