Skip to content

7. Libraries and the Standard Library

Draws on: ADR 0002, ADR 0003, ADR 0005, ADR 0007, ADR 0008, ADR 0011, ADR 0012, ADR 0013, ADR 0014, ADR 0016, ADR 0020, ADR 0021, ADR 0022, ADR 0023, ADR 0024, ADR 0025, ADR 0029, ADR 0030, ADR 0033, ADR 0034, ADR 0035, ADR 0036, ADR 0037, ADR 0050, ADR 0053, ADR 0062, ADR 0069, ADR 0060, ADR 0096, ADR 0179.

Scripts share code through Libraries: stateless units of source that the Host registers on a Script Group, and whose code runs in the caller’s Run. The Standard Library is two tiers. The Built-ins are a small set of functions and Constants that the Cores implement natively and that are always available. The seven stdlib Libraries are written in the language and imported like any other Library. The Standard Capabilities are Capabilities whose Operation Declarations this chapter fixes, and whose answers each Host supplies.

This chapter states what Libraries are and how they are used, then every Built-in, every stdlib export and every Standard Capability Operation. The export lists live in stdlib.toml. The syntax of use, constant, private and function is in chapter 2, and the Host calls that register Libraries are in chapter 9.

Recovery Offers let a caller choose an action declared inside retained Library frames in the same Run, preserving Library accumulators and earlier work (chapter 4). An unrelated rejecting catch in an intermediate Library preserves those offers. A catch-all accepts, discards deeper failed frames and their offers, and remains a barrier even when its body logs and throws the Error again.

  • A Library is a unit of source code that the Host registers on a Script Group. It holds Handlers, functions and Constants, named Shapes among them, and nothing else (ADR 0020).
  • It isn’t a Script. It has no Script Variables, no me, no mailbox, no Grants and no Owning Script role. It is never loaded, messaged or run on its own. A top-level script variable in a Library is a load error.
  • Constants: constant name = expr declares a Constant. Its initialiser may use only literals, other Constants and Built-ins other than random, so evaluating it has no effects. Scripts may declare Constants too. A Function Value in a Library Constant, including nested ones and captures, takes the importing or calling Script as its Home Script when the Constant is bound or read there; its code and display position still name the Library. This also applies to Library parameter defaults. The compiled Library does not bind these values to one Group.
  • Exports: every top-level definition of a Library is exported unless it starts with private. private in a Script is a load error.
  • No re-exports: a name a Library imports isn’t exported again, so a use … from line always names the Library that defines the name.

Example. A small Library, registered as layout:

use padLeft from text
constant ruleWidth = 40
private function widthOf s
return the length of s
end widthOf
function banner title, fill = "*"
put ruleWidth - widthOf(title) into room
return padLeft(title, widthOf(title) + room div 2, fill)
end banner
  • A default: a function’s trailing parameters may have defaults, written name = expression (ADR 0035). A call may leave off any of those trailing arguments, and each one left off takes its default.
  • What a default may use: literals, Constants and Built-ins other than random, as a Constant’s initialiser may. Anything else, such as another parameter, a Script Variable or a function call, is a load error. A default is fixed at load.
  • Order: a parameter without a default after one with a default is a load error.
  • Checked at load: a call that names a function, in the Script or imported, passes at least the parameters without defaults and at most all of them. Any other count is a load error at the call.
  • Checked at run time: a Function Value made from a named function accepts the same range. A call outside it raises wrong arity.
  • Only functions: Handlers, Lambdas and Capability Operations have no defaults.

This chapter writes every optional argument of a stdlib function or Built-in as a default, as in round(x, places = 0, mode = "half up").

  • What it is: a Built-in written with a trailing …, as in max(x, …), takes its named arguments and then any number more. Only Built-ins are variadic. A Script or Library function, a Handler, a Lambda and an Operation take a fixed range (ADR 0099).
  • Checked at load: a call passes at least the named arguments without defaults. There is no upper bound.
  • Not values: a Built-in isn’t a value (chapter 4), so no Function Value is variadic and functionArity never meets one.
  • Allowed: its own definitions, the Libraries it imports, Built-ins, Capabilities through ask and tell, wait d, wait for and Joins.
  • Load errors: me, the target, pass, veto, send, a well-known object name (ADR 0016), a Handler that an importer defines, and a bare Name in a wait for’s from that would name a Script.
  • So a Library is a function of its arguments, of the Capability answers it gets, and of the messages its caller’s Script receives while it waits. Anything else that depends on its caller is passed in.
  • Waiting for a message: a wait for in Library code observes the messages dispatched to the Script whose Run is executing it, however many Library calls deep, as the same wait written in that Script would (chapter 5, ADR 0113). Its from may filter by a Host Object the caller passes in.

Example. A shared confirmation, which a Script calls as confirm "DO YOU WANT TO BUY?", 5 s and wait:

on confirm question, duration
ask display to prompt question and wait
wait for
when pressed key where key = "Y" then
return true
after duration then
return false
end wait
end confirm

The pressed message still reaches the Script’s own Handlers, and two Runs waiting in confirm both resume on one key.

  • use a, b from lib imports the listed names from the Library lib, and they are used unqualified. use pad from text as padLeft renames a single import.
  • Only what is listed: an Import brings in only the names it lists. A Library that later exports more can’t break an importer.
  • Where: use is a top-level declaration, in a Script or a Library. Libraries may import Libraries.
  • Missing and cyclic: importing a name the Library doesn’t export, a Library the Group doesn’t hold, or a cycle of Libraries is a load error.
  • At a Session prompt, the stdlib Libraries are always registered, so use pad from text works there (chapter 12).
  • Clashes are load errors. An imported name, after any rename, that clashes with a local Handler, function, Constant, Script Variable or well-known object name is a load error, and so are two Imports of the same name.
  • Built-ins may be shadowed. An Import, or a Script’s or Library’s own Handler, function or Constant, may take the name of a Built-in function or Built-in Constant, and the Script’s name wins inside it. So a Built-in added in a later language version never stops a Script or Library from loading (ADR 0034). How the other names of a body resolve, and which of them may shadow a Built-in, is in chapter 4.
  • Resolution: a Command Call resolves to a local Handler, then an imported one, and only then climbs the Message Path (chapter 5). Since clashes are errors, the order never breaks a tie.
  • Never entry points: an imported Handler never runs for a message, and a Library never joins a Message Path.
  • A plain call: a call into a Library runs in the caller’s Run, like a call to the Script’s own Handler or function.
  • Charged to the caller: it charges Fuel, the Allocation Budget and call depth to the caller, and costs the same as a local call in the Cost Model (chapter 8).
  • Frames: its frames sit on the caller’s stack. While the Run is suspended, they count toward the caller’s Persistent State.
  • Faults and errors: a Limit Fault inside Library code rolls back the caller’s Segment, as anywhere (chapter 6). Errors unwind through Library frames, each through its own Library’s Unwind Table, and unwinding is charged per frame.
  • Linked, not inlined: a call to a Library is resolved at load and lowered as a call to it by name. Its body is never copied into the importer.
  • Suspension: a Command Call to an imported Handler that may suspend is written name args and wait, as for a local one, and a function never suspends (chapter 5).
  • Function Values: a Library function’s bare name is a Function Value whose Home Script is the Script that made it, and it runs in that Script’s Runs (chapter 5). A Lambda written in a Library can’t name a Script Variable, since a Library has none.

The Host may register the parseRows function from chapter 4’s example as Library rows. Its caller chooses policy without passing that policy through the Library API:

use parseRows from rows
on parseInput
try
put parseRows(["5", "bad", "7"]) into parsed
catch {code: "can't convert"} before unwind where offerAvailable("skip")
choose offer skip
end try
-- parsed is [5, 7], retaining the Library's rows local.
end parseInput

Deeper cleanup precedes the action; the offering try’s finally follows it:

function parseOne text
try
return text as number
finally
-- Deeper cleanup: runs before a selected action.
end try
end parseOne
function parseRows lines
put [] into rows
repeat for each line in lines
try
put parseOne(line) after rows
offer skip
-- Action: the deeper cleanup has finished.
next repeat
offer useValue value
put value after rows
finally
-- Owning cleanup: runs after the action, including next repeat.
end try
end repeat
return rows
end parseRows

For a failed conversion with skip chosen, the order is selection, parseOne’s finally, skip, the offering try’s finally, then the next iteration. An Error escaping deeper cleanup cancels the chosen action; an Error caught locally inside that cleanup does not. Offers remain eligible until action entry, including during cleanup.

  • A Library has no Grants. It acts only with its caller’s. A Host Command in a Library resolves when it is compiled, against its compilation declarations, after its own Handlers and imports, and joins its needs.
  • Declarations for compilation: CompileLibrary(src, imports, declarations) receives a map of names used for Grants to Operation names and their modes, argument Shapes, labels and command flags. In TS this is GrantDecls, the optional third argument to compileLibrary; omission gives an empty map, sufficient only when the Library makes no direct Capability calls. A Library never captures Host functions or binding data. Replacement recompiles dependent Libraries with their saved compilation declarations and rechecks affected Scripts against their own Grants.
  • needs: when a Library is compiled, the loader records every Operation it uses, through the Libraries it imports too, and checks each ask, tell and and wait against the Host’s Operation Declarations. The list includes all definitions, including private or unused ones, and say counts as console.write. It has one entry per distinct (capability, operation), sorted by capability name and then Operation name in Unicode code-point order; capability here is the Grant name the Library uses, which the Script may bind to a differently named Capability. The calls are validated on every compilation request, even when their code identity is cached. That list is the Library’s needs, which the Host can read before any import and which goes into the Host Manifest (chapter 9).
  • Checked at import: loading a Script checks the needs of every Library it imports, directly or through another Library, against the Script’s Grants. A missing Grant is the Script’s load error, reported at the use line, and its diagnostic message names the original Library call site, including through transitive imports. At each use line, one missing grant is reported per distinct missing Operation, naming the first call site encountered in direct source order followed by imported Libraries in import order. All calls are also rechecked against the Script’s Operation modes, argument counts, Argument Labels and literal Shapes; an incompatible declaration reports the ordinary call diagnostic at the use line, naming the original call site. Library compilation and this import check use names as written in Library source; renaming an imported definition never renames a Grant.
  • Grants as used: a Host that grants “what the Script uses” counts its Libraries’ needs too.

For the import check, an original call site is identified by its defining Library’s code identity and its source position. At each use line, visit the named Library’s direct calls in source order, then its imported Libraries in import order, recursively, visiting each Library identity only once. A shared dependency reached through both branches of a diamond therefore contributes each of its call sites once. Distinct sites remain distinct even when they make identical calls. Each original call site is rechecked once; additional import paths produce no additional diagnostics. Missing Operations still report once per distinct Operation as above. Each separate use line repeats this check independently, including when it names the same Library under another import alias.

  • Registration: the Host compiles a Library once per process and adds it to a Group before loading the Scripts that import it. Adding a Library is a Host Input, recorded in the Trace (chapter 9). Compiling runs every checker diagnostic, which parity covers. Only the Grant check waits for an import.
  • Imports first: a Group adds a Library only once it holds every Library that one imports, with the same code identities, and otherwise refuses it (library mismatch). A refused add changes nothing.
  • One version per name: a Group holds at most one Library of each name. A Host may not register a Library under a stdlib Library name (reserved name).
  • Code identity: a Library’s code identity covers its source, the language and Cost Model versions, and the identities of the Libraries it imports. A Script’s code identity includes the identities of every Library it imports, directly or through another Library. The Group Fingerprint covers them all.
  • Sharing: a Core compiles each Library once per process, and Groups share it when the code identities match. Code isn’t Persistent State. A Library’s Constants count once per Group, as a fixed overhead.
  • Code positions: a code position is a code unit and an instruction index, and a code unit is a Script or a Library named by its code identity (chapter 8). So a suspended Run can be paused inside Library code, and a Snapshot can hold it.
  • Replacing a Library is one Host Input. The Core recompiles every Library that imports it, then stop-and-reloads every Script that imports any of them, all at once. Script Variables carry over by name if the Host asks, and with keepMailbox each Script keeps its mailbox for the new code. Suspended Runs, including those paused in Library frames, are discarded and reported. If anything fails to check, nothing changes.
  • Stale values: replacing a Library makes every Function Value made from its code stale, and calling one raises function gone (ADR 0025).
  • Extending a Script may add use lines, since that adds names without touching existing code (ADR 0014).
  • Snapshots record Library code identities, not source. A restore needs matching Libraries registered first, and a mismatch falls back to a variables-only restore (chapter 10, ADR 0008).
  • Two tiers: the Built-ins, which are ambient, and the seven stdlib Libraries, text, list, map, bytes, json, date and units, which a Script imports with use (ADR 0021).

  • Reserved names: the seven Library names are the only reserved Library names. A new stdlib Library name is a language-version change.

  • Unique names: every stdlib name, Built-in or exported, is unique across the Built-ins and all seven Libraries, so no combination of stdlib Imports can clash. None is a Reserved Word or a Built-in property. Names are camelCase. The generator checks this against stdlib.toml.

  • Versioned with the language: the stdlib is part of the language version, and a stdlib Library’s code identity is fixed by it. Its version is the language version, and its identity is computed from its source here as any Library’s is (chapter 9), so it covers the stdlib Libraries it imports.

  • Always there: every Group holds the seven stdlib Libraries without the Host adding them, and a user Library may import them too.

  • Written in the language: each stdlib Library’s source is normative Spec text, with Disassembly Cases like any Library’s. This chapter states what each export does, and the source does exactly that. The source also fixes what this chapter leaves to it: its private helpers, its Fuel, and the order of any calls it makes where this chapter doesn’t give one.

  • Operation names are their own namespace, so an Operation may share a name with a stdlib function, as locale’s upper does with the upper Built-in.

  • The source is spec/stdlib/, one .talk file per Library: text, list, map, bytes, json, date and units. bun run grammar:check parses them, and the generator checks that each exports exactly what stdlib.toml lists, with the same parameters and defaults.

  • Errors from stdlib source look exactly like a Built-in’s. A stdlib Library raises a catalogue error with throw, giving the catalogue’s fields and no message. The Core then adds the message from the template, and at names the Script’s call into the stdlib, not a line of the Library (chapter 6, ADR 0037).

These hold for every Built-in function and every stdlib export, unless its own entry says otherwise.

  • Kinds: an argument of the wrong kind raises wrong kind, with {expected, got, value}, before any work is done. The tables below don’t list it.
  • Out of domain: an argument of the right kind that the function can’t take raises out of domain, with function its name and value the argument. Where two arguments are at fault together, value is the list of both.
  • Integers: a count, width or position must be an integer, and a number that isn’t raises wrong kind with expected "integer", as everywhere (chapter 3). An integer outside what the function takes, such as a negative width, raises out of domain.
  • Lists: an argument that must be a list takes a list only. An integer range isn’t one, so a Script passes the items of r.
  • Positions are 1-based Character positions, as everywhere in text (ADR 0011).
  • White space is a Character whose first scalar has the Unicode White_Space property, the same test that divides words.
  • Text out is always NFC.
  • Searching text: a function that searches text takes a text or a Text Pattern as its needle. A text needle matches only on whole-Character boundaries. A Text Pattern is searched leftmost-first (ADR 0007). No function takes an ignoring case flag, so a case-insensitive search passes a Text Pattern, as in offset(<"abc" ignoring case>, s).
  • Showing values: “shown as & shows it” means the canonical text form, the one automatic conversion (ADR 0003).
  • Function Value arguments:
    • A stdlib function calls a Function Value argument in list order, once per item unless its entry says otherwise, with the number of arguments its entry says.
    • A Function Value that may suspend, or whose Home Script is another Script, raises would suspend when it is called (ADR 0025). A Script that waits per item writes a repeat for each loop, or a Join around sends.
    • A Function Value that can’t take that number of arguments raises wrong arity.
    • An error raised inside a Function Value unwinds out of the stdlib function unchanged.
    • A test (keep or test) must give a boolean, and anything else raises wrong kind with expected "boolean", as if 0 does.
  • What qualifies: a function is a Built-in only if it can’t be written in the language, because it needs the pinned Unicode tables, the Text Pattern engine, decimal internals or the representation of a value kind, or if a Guard must be able to call it. Speed alone never makes a function built in (ADR 0021).
  • Ambient: every Built-in is available without an Import.
  • Guards may call every Built-in, and no other function (chapter 5). A call through a name that shadows a Built-in isn’t a call to the Built-in, so a Guard can’t make it (chapter 4).
  • Leaves: a Built-in never suspends, never calls a Capability and never calls Script code. Each call is one instruction, charged by its Cost Model entry: a static base plus per-unit terms over its operands and result (chapter 8).
  • Unicode: the pinned Unicode tables are reached only through Built-ins, chunks, Text Pattern classes and ignoring case. There is no raw property lookup.

The Built-in properties are read with the <name> of x. Their names are listed in chapter 2, and what each gives, and of which kinds, is in chapter 4.

Built-in Gives Also raises
min(x, …) The least of its arguments under <, the first of equal ones; a lone list argument gives the least of its items out of domain, can't compare
max(x, …) The greatest of its arguments under <, the first of equal ones; a lone list argument gives the greatest of its items out of domain, can't compare
codePoint(c) The code point of c, a text of exactly one code point, as a number out of domain
fromCodePoint(n) The text of the code point n, normalised to NFC out of domain
upper(s) s under Unicode full default uppercase mapping, then NFC
lower(s) s under Unicode full default lowercase mapping, then NFC
offset(needle, s) The Character position where the leftmost match of needle, a text or a Text Pattern, starts in s, or 0 if there is none
isDisposed(o) Whether the Host Object o has been disposed
objectKind(o) The name of the Object Kind of the Host Object o, as text
rangeStart(r) The first end of the range r, as written
rangeEnd(r) The second end of the range r, as written
kindOf(x) The name of the kind of x, as text, such as "number" or "civil date"
conforms(value, shape) Whether value fits the Shape shape invalid shape
check(value, shape) value unchanged, if it fits the Shape shape; raises the first mismatch otherwise invalid shape, not encodable
explain(value, shape) The list of every mismatch of value against the Shape shape, empty if it fits invalid shape
functionArity(f) The range of argument counts the Function Value f accepts, from its required parameters to all of them
functionName(f) The name of the function the Function Value f was made from, as defined, or Nothing for a Lambda
offerAvailable(textName) Whether the current recovery’s retained failure chain has an eligible offer with this Name; false outside recovery or for a malformed or unknown Name
  • min and max take their values as arguments, so max(6, 3, 9) is 9 and min(a, b) is the lesser of a and b (ADR 0099).
    • A lone list: with exactly one argument that is a list, the values are that list’s items, so max([6, 3, 9]) is also 9. A single argument of any other kind is the only value, so max(7) is 7. To compare lists themselves, pass two or more.
    • Comparing: they compare with <, so they take any values that < orders against each other (chapter 3). The result is the value itself, with its own Unit, and the first of equal ones.
    • Errors: an empty lone list raises out of domain, and two values that can’t be compared raise can't compare. A call with no arguments is the load error wrong argument count.
  • codePoint(c) takes a text of exactly one code point. Any other text raises out of domain.
  • fromCodePoint(n) takes an integer from 0 to 1114111 that isn’t a surrogate (55296 to 57343). Anything else raises out of domain. The result is normalised to NFC, so a few code points come back as a different one.
  • upper and lower use Unicode full default case mapping, with no Locale, so the length can change (upper("ß") is "SS"). Locale case mapping is the locale Capability’s (below).
  • offset(needle, s) gives 0 when there is no match, so a Guard can test it without a failure. An empty text needle matches at 1.
  • rangeStart(r) and rangeEnd(r) give a range’s two ends exactly as written, for any range, so rangeStart(5..4) is 5, and rangeEnd(3 m/s..7 m/s) is 7 m/s. An empty match’s range, p..p-1, has no items, and rangeStart is how to read where it was (ADR 0036).
  • isDisposed(o) takes a Host Object, and anything else raises wrong kind. Guards use it to skip a disposed object at dispatch, as in where not isDisposed(u).
  • objectKind(o) gives the name of the Object Kind o was made with, as the Host defined it (chapter 9), so a Guard can route on it, as in where objectKind(o) is "door". It takes a Host Object, and anything else raises wrong kind. The kind is the Core’s, so it never calls the Host, and a disposed object still answers (ADR 0044).
  • kindOf(x) gives the kind name of any value, one of the names in chapter 3’s Kinds table, the same names an error’s got field holds. It never raises. A whole number gives "number", since integer is a test and not a kind, and a Host Object gives "object", whatever its Object Kind (ADR 0043).
  • functionArity(f) gives the range of argument counts f accepts, the range wrong arity checks: from a named function’s required parameters to all of them (ADR 0035), or n..n for a Lambda with n parameters. So a function with no parameters gives 0..0, and 2 is in functionArity(f) tests a call before it is made.
  • functionName(f) gives the name of the named function f was made from, as the code unit that defines it writes it, or Nothing for a Lambda, a Library’s included. An Import renamed with use … as keeps its Library name, so after use pad from text as padLeft, functionName(padLeft) is "pad".
  • functionArity and functionName take a Function Value, and anything else raises wrong kind. They read data the value holds, so a stale Function Value still answers both, and only calling it raises function gone (chapter 3).

conforms(value, shape), check(value, shape) and explain(value, shape) test a value against a Shape written as data, with the acceptance of chapter 9’s Shapes (ADR 0080). They are ordinary Built-ins, so a Guard may call them. Each validates the whole Shape definition first, unused oneOf alternatives included, and only then looks at the value. A definition that isn’t a Shape raises invalid shape from all three; it is never a false answer or a mismatch. Resource exhaustion during validation or matching is a Limit Fault, never a truncated report or a false answer.

  • conforms gives true exactly when the value fits.
  • check gives the value itself, unchanged and uncopied, when it fits, and raises the first mismatch otherwise.
  • explain gives a list of every mismatch, empty when the value fits. It continues through independently checkable siblings, but doesn’t descend into a node whose container kind is wrong: expecting a list and finding text is one mismatch, not a missing item per position.

The data spelling is the Host Manifest’s (chapter 9). A Shape is a kind name from chapter 3’s Kinds table, "any" or "value" as text, or a one-key wrapper map: {quantity: unit}, {unitKind: kind}, {object: kind}, {list: shape}, {oneOf: [shape, …]}, {optional: shape}, or a map Shape {map: [{key: text, shape: shape, optional: boolean}, …], open: boolean}, whose two boolean flags may be left out and then mean false. A Quantity’s Unit is parsed and normalised with the Unit Catalogue, and matching is by the exact normalised Unit, as at the Host boundary. A Unit Kind name must be one of the Catalogue’s. An Object Kind name is only a text label: defining or checking an Object Shape never queries a Host registry or reads a Host Object’s properties, and a disposed handle still answers with its Object Kind. Unknown keys in a wrapper map or a field declaration are ignored metadata: they are not read as Shapes, never change acceptance or diagnostic order, and a misspelling such as opne doesn’t open a map.

Definition errors. invalid shape carries reason, a Shape-relative path, a Path (wrapper keys as text, oneOf alternatives and map fields by 1-based position, the empty Path / for the Shape itself) and the offending value. Validation is depth-first over the recognised structure, in field-declaration and alternative order, with each node’s own errors found before its children’s; the first error in that walk is the one raised, whichever metadata surrounds it. Within one field declaration, its key is read first, then the presence of its Shape, then its optional flag, then whether its key duplicates an earlier field’s, and only then is its Shape validated. A map Shape’s open flag is read before its fields. The reasons are:

Reason When value
not a shape the node is neither text nor a map, or a map with no recognised wrapper key the node
unknown kind a text node names no kind, and isn’t "any" or "value" the text
ambiguous shape a map holds more than one of quantity, unitKind, object, list, oneOf, optional and map the map
invalid unit a quantity payload isn’t text, or doesn’t parse as a Unit the payload
unknown unit kind a unitKind payload isn’t text naming a Unit Kind the payload
invalid object kind an object payload isn’t text the payload
invalid alternatives a oneOf payload isn’t a list the payload
empty union a oneOf payload is an empty list the payload
invalid fields a map payload isn’t a list the payload
invalid field a field declaration isn’t a map the declaration
invalid field key a declaration’s key is missing or isn’t text the key, or the declaration when missing
missing field shape a declaration has no shape the declaration
invalid flag an open or field optional flag is present and isn’t a boolean the flag
duplicate field two fields of one map Shape share a key the repeated key

Acceptance is exactly a Capability Shape’s, including that any refuses Function Values at any depth while value and function take them, that an open map’s undeclared fields must still be data, that a map field whose Shape is {optional: …} is still required unless its optional flag is true, that Units match exactly rather than by convertibility, and that a Unit Kind Shape takes only a Quantity whose Unit is a single Unit of that Kind at exponent 1.

Mismatches keep the Host boundary’s errors, without its context. A mismatch is wrong kind with expected, got and value, or not encodable with kind and path, for a Function Value where the Shape takes only data. Paths are Paths relative to the checked value, with text map keys and 1-based list positions: wrong kind omits path when the value itself mismatches, as a Capability argument’s does, and not encodable always carries it, the empty Path / at the root. No capability, operation or argument is added. List items are visited in position order, declared map fields in declaration order and then extra fields in the value’s insertion order; the first mismatch in that order is check‘s. A missing required field mismatches with got "nothing" and Nothing as its value, an extra field of a closed map with expected "nothing", and an Optional Shape adds " or nothing" only to a mismatch at its own node. A failed oneOf mismatches at the union’s node, its expected the alternatives’ joined with " or "; in an explain report that record also carries alternatives, the list of each alternative’s own mismatch list, in alternative order, its paths still relative to the checked value. A union some alternative fits contributes nothing, in either Built-in. The records explain returns are plain maps of the same fields, code included, but with no message and no at; an error check raises gets both in the usual way at the call.

Charging. Shape checks are metered, unlike the Host boundary’s uncharged check: each rate’s scanned counts the definition work (every Shape node and every entry of a visited wrapper or field map, metadata entries included, plus the scalar values of each kind, Unit and Unit Kind text read) and the matching work (every value/Shape pair attempted, every value node a data scan under any or an open map’s extra fields visits, a missing or extra field counting one pair). Failed validation, failed alternatives and work before a raised mismatch are charged; conforms and check stop at the first mismatch, and explain counts the whole traversal and allocates its report by logical size, repeated offending values included. Traversal is stack-safe at any depth the budgets allow, under the ordinary Fuel and Allocation Budgets, with no Shape-specific depth or report limit.

shape Name is <Shape Expression> declares a named Shape: a Constant whose value is the Shape’s canonical data, in the ordering of chapter 9 (ADR 0168). It follows every Constant rule: it can’t be put into, private keeps it in its Library, use … from imports it, and the clash rules of Names and clashes apply. It is evaluated at load with the other Constants, and has no effect.

shape Line is {sku: text, qty: number}
shape Invoice is {type: text, amount: GBP, ref: optional text, lines: list of Line}

Lowering. Each Shape Term lowers to Shape data:

Written Lowers to
a kind name, such as text or civil date, or any or value that name as text
a Unit, such as GBP or m/s {quantity: unit}, with the Unit as written
a quantity of K {unitKind: "K"}
object of K {object: "K"}
list of S {list: S}
optional S {optional: S}
S or T … {oneOf: [S, T, …]}, in written order
{k: S, …} {map: [{key: "k", shape: S}, …]}, fields in written order; a field written k: optional S adds optional: true and lowers S alone; a trailing ... adds open: true
a named Shape its data

Brackets add nothing. So Invoice above is {map: [{key: "type", shape: "text"}, {key: "amount", shape: {quantity: "GBP"}}, {key: "ref", shape: "text", optional: true}, {key: "lines", shape: {list: {map: [{key: "sku", shape: "text"}, {key: "qty", shape: "number"}]}}}]}.

Names in a Shape. A Name in a Shape Term is read as a kind name, any or value first, then as a Unit, then as a named Shape in scope: one declared in the unit, above or below, or imported. A named Shape may name others, and the loader inlines their data. A Shape that reaches itself is an error, since Shape data can’t be recursive.

Load errors. A malformed declaration is the load diagnostic bad shape, at the offending token. It is a load diagnostic, not the run-time error invalid shape the Shape check Built-ins raise:

  • a Name that is no kind, Unit or named Shape in scope;
  • a quantity of a name that isn’t a Unit Kind of the Unit Catalogue;
  • a Unit that doesn’t parse with the Unit Catalogue;
  • two fields of one Shape Map with one key;
  • a Shape that reaches itself, at the first Name on the cycle in source order;
  • a Shape named like a kind, any, value, a Unit or a Unit Kind, at its name;
  • when the unit loads with a Host Manifest, object of a name that isn’t one of its Object Kinds. A Library loads without one, so this isn’t checked there, and an Object Kind is otherwise only a text label, as in Shape data.

A declaration that loads always lowers to data that Shape checks accept, so its value never raises invalid shape at run time.

is a with a named Shape. After is a or is an, a Name is read as a kind or Unit first and then as a named Shape in scope; anything else is still unknown kind. Only a name declared with shape, directly or through use, is read this way: Shape data in a variable or in a plain Constant goes through conforms. x is a S is conforms(x, S), with the same acceptance, errors and charge, and x is not a S is not conforms(x, S). is a with a kind is unchanged. Literal-value Shapes (#861) aren’t part of the spelling yet.

offerAvailable(textName) validates text using ordinary Built-in argument rules. Wrong kind raises wrong kind; outside recovery, a malformed Name or an unknown Name returns false. Names are case-sensitive and obey the ordinary Name rules; reserved words and _ are malformed. A valid query searches the current recovery’s eligible offers, including from a Guard, synchronous helper or pending transfer cleanup before action entry. It ignores arity; choice checks exact arity without falling back to an outer same-name offer. A nested recovery queries only its own bounded failure chain (chapter 6). Malformed Names and calls outside recovery pay the base/text rate with no lookup charge (chapter 8).

Built-in Gives Also raises
abs(x) x without its sign
floor(x) The greatest integer at or below x
ceiling(x) The least integer at or above x
truncate(x) x with its fraction dropped, toward zero
round(x, places = 0, mode = "half up") x rounded to places digits after the point, by mode out of domain
sqrt(x) The square root of x out of domain
exp(x) e to the power x overflow
ln(x) The natural logarithm of x out of domain
log10(x) The base-10 logarithm of x out of domain
power(x, y) x to the power y out of domain, overflow
sin(x) The sine of x radians
cos(x) The cosine of x radians
tan(x) The tangent of x radians
asin(x) The arcsine of x, in radians from -pi/2 to pi/2 out of domain
acos(x) The arccosine of x, in radians from 0 to pi out of domain
atan(x) The arctangent of x, in radians between -pi/2 and pi/2
atan2(y, x) The angle of the point (x, y) from the positive x-axis, in radians above -pi and at most pi out of domain
degrees(x) x radians in degrees overflow
radians(x) x degrees in radians
random(n) A whole number from 1 to n, the next from the Script Group’s generator out of domain
  • Exact functions: abs, floor, ceiling, truncate and round are exact. floor, ceiling and truncate give an integer with no digits after the point (floor(-2.5) is -3).
  • On Quantities: abs, floor, ceiling, truncate and round also take a Quantity, act on its number and keep its Unit (round(2.567 kg, 2) is 2.57 kg). The other number functions take plain numbers only.
  • round(x, places = 0, mode = "half up"):
    • places is an integer, 0 or more, and the result has exactly that many digits after the point, so round(3, 2) is 3.00.
    • mode is one of "half up", "half even", "up", "down", "floor" and "ceiling", and any other text raises out of domain. The names are those of the General Decimal Arithmetic: "half up" rounds a tie away from zero, "up" rounds away from zero and "down" toward it.
    • So by default round(2.5) is 3 and round(-2.5) is -3, while round(2.5, 0, "half even") is 2.
  • Correctly rounded: sqrt, exp, ln, log10, power, the trigonometric functions, degrees and radians give the exact mathematical value rounded half-even to 34 significant digits, or at exponent −6176 if that keeps fewer digits, then with any trailing zeros after the point dropped (chapter 3). So both Cores agree by definition, and sqrt(4) is 2 and exp(0) is 1. The one exception is power(x, y) for an integer y, which is x ^ y, so power(2.50, 2) is 6.2500.
  • Domains: sqrt of a negative number, ln or log10 of a number at or below 0, asin or acos outside -1 to 1, atan2(0, 0), and power of a negative number to a non-integer raise out of domain, with value the argument, which is x for power and 0 for atan2. power(0, y) for a negative y raises division by zero, and power(0, 0) is 1.
  • Overflow: a result of 10^34 or more in magnitude raises overflow, with operator the function’s name, as in exp(100) or round(x, places) when x has too many integer digits to keep places digits after the point. A result too small to keep rounds, and never raises.
  • Angles are in radians, Talk’s one angle unit, in the Built-ins and in Host Operations alike. degrees(x) is x × 180/π and radians(x) is x × π/180, each correctly rounded, so radians(180) is pi and degrees(pi) is 180.

random(n) gives a whole number from 1 to n, each as likely as the others, drawn from a generator the Script Group holds (ADR 0096). Every Core uses the same generator, so the same seed gives the same draws on every Core.

  • n is a whole number from 1 to 2^32 (4294967296). A number that isn’t whole, or is outside that range, raises out of domain with function "random" and value n; anything but a number, a Quantity included, raises wrong kind.
  • One generator per Group: every Script of a Group draws from the same generator, in the order the Runs make their calls. A Library’s code draws from its caller’s Group.
  • The seed: the Host gives the Group a seed when it makes it, a whole number from 0 to 2^64 − 1, and 0 if it gives none (chapter 9). A Host that wants different draws each time seeds from somewhere that changes, such as its clock; the Core never reads one itself, so random is a Built-in, not a Capability.
  • The generator is PCG32 (XSH RR), whose state is a 64-bit unsigned integer and whose arithmetic wraps modulo 2^64. Written with the bit Built-ins:
    • a step is state := (state × 6364136223846793005 + 1442695040888963407) mod 2^64
    • an output is taken from the state before a step: x := bitAnd(bitShiftRight(bitXor(bitShiftRight(state, 18), state), 27), 2^32 - 1), then bitRotateRight(x, bitShiftRight(state, 59), 32)
    • a seed s gives the state step(step(0) + s)
  • A draw for n takes outputs, stepping after each, until one, r, is at least (2^32 − n) mod n, and gives (r mod n) + 1. So no result is more likely than another.
  • Examples: seeded 0, ten calls of random(6) give 1, 6, 1, 3, 2, 6, 6, 6, 3, 5. Seeded 42 they give 3, 6, 4, 4, 4, 5, 1, 6, 3, 4. Seeded 0, random(1), random(2), random(7), random(100) and random(4294967296) give 1, 2, 4, 89 and 3443325254.
  • Saved and replayed: the generator’s state is part of the Group’s state, so a save carries it (chapter 10), and a replay with the same seed and Host Inputs gives the same draws.
  • Not rolled back: a draw is final once its call is charged, like an id the Core assigns. A Limit Fault’s rollback, a Rewind and a discarded Run leave the generator where it is, and a call that faults on its own charge draws nothing.
  • Effects: a call changes the Group’s state, so random may not appear in a Constant’s or Script Variable’s initialiser or a parameter’s default (not constant), and a restricted callback that calls it raises restricted operation (chapter 8). A Guard or whose clause may call it, and each test it makes draws.

The bit Built-ins treat a number as the 64 binary digits of a whole number from 0 to 2^64 − 1 (18446744073709551615), bit 0 being the lowest (ADR 0149). Every such number is exact in a decimal number’s 34 digits, so every Core agrees without a fixed-width integer kind.

Built-in Gives Also raises
bitAnd(a, b) The bits set in both a and b out of domain
bitOr(a, b) The bits set in a, b or both out of domain
bitXor(a, b) The bits set in exactly one of a and b out of domain
bitNot(x, width) x with its low width bits inverted out of domain
bitShiftLeft(x, n, width = nothing) x shifted left n bits, kept to its low width bits when width is given out of domain, overflow
bitShiftRight(x, n) x shifted right n bits, filling with zeros out of domain
bitRotateLeft(x, n, width) The low width bits of x rotated left n places out of domain
bitRotateRight(x, n, width) The low width bits of x rotated right n places out of domain
bitCount(x) How many bits of x are set out of domain
bitTest(x, i) Whether bit i of x is set, bit 0 being the lowest out of domain
  • Arguments: a, b and x are whole numbers from 0 to 2^64 − 1. A width is a whole number from 1 to 64, and x must be below 2^width wherever a width is required. A shift n is from 0 to 64, a rotation n is any whole number 0 or more, taken modulo width, and a bit index i is from 0 to 63. A number outside its range, or one that isn’t whole, raises out of domain with function the Built-in’s name and value the argument; anything but a number, a Quantity included, raises wrong kind.
  • No sign: there are no negative bit patterns. bitNot takes a width because a complement is only defined within one, so bitNot(0, 8) is 255.
  • Shifting left: without width, a result of 2^64 or more raises overflow with operator "bitShiftLeft", just as arithmetic does. With width, the result keeps its low width bits, so bitShiftLeft(255, 4, 8) is 240. Wrapping is never silent.
  • Shifting right fills with zeros, and bitShiftRight(x, 64) is 0.
  • Examples: bitAnd(12, 10) is 8, bitOr(12, 10) is 14, bitXor(12, 10) is 6, bitRotateLeft(1, 1, 3) is 2, bitRotateRight(1, 1, 3) is 4, bitCount(255) is 8 and bitTest(4, 2) is true.
  • Not operators: << and >> stay the Binary Pattern brackets (ADR 0013), and the Built-ins act on numbers, not Bytes.
  • Cost: each has a flat rate, whatever its arguments, since none exceeds 64 bits (chapter 8).
Built-in Gives Also raises
fromFloat64(b, order = "big") The number an IEEE 754 binary64 float in the 8 Bytes b holds, as its shortest round-trip decimal out of domain, can't convert
fromFloat32(b, order = "big") The number an IEEE 754 binary32 float in the 4 Bytes b holds, as its shortest round-trip decimal out of domain, can't convert
toFloat64(n, order = "big") The 8 Bytes of the binary64 float nearest n, ties to even out of domain
toFloat32(n, order = "big") The 4 Bytes of the binary32 float nearest n, ties to even out of domain

Floats come into and go out of the language only through these four (ADR 0021, ADR 0030).

  • Byte order: order is "big" or "little", and any other text raises out of domain.
  • Reading: fromFloat64 needs exactly 8 Bytes and fromFloat32 exactly 4, and any other length raises out of domain. The result is the shortest decimal that rounds to the same float, at most 17 or 9 significant digits, the nearest to the float of those, and of two equally near the one whose last digit is even, the same rule as the Host’s float-to-decimal conversion. So a binary32 reading of 0.1 is 0.1. Negative zero gives 0. NaN, ±Infinity and a value of 10^34 or more in magnitude raise can't convert, with to "number", as the Host’s conversion refuses them (ADR 0034).
  • Writing: toFloat64 and toFloat32 round to the nearest float, ties to even. Every number is below the largest float32, so neither ever overflows, and a value too small rounds to zero or a subnormal as IEEE 754 says, keeping its sign, so a negative one can give negative zero. The number 0 gives positive zero.

Example.

put fromFloat32(<<0x3D, 0xCC, 0xCC, 0xCD>>) into x -- 0.1
put toFloat64(1.5, "little") into b -- <<0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x3F>>
Built-in Gives Also raises
year(d) The year of the Civil Date d, from 1 to 9999
month(d) The month of d, from 1 to 12
day(d) The day of the month of d, from 1 to 31
hour(d) The hour of the date-time d, from 0 to 23 out of domain
minute(d) The minute of the date-time d, from 0 to 59 out of domain
second(d) The whole seconds of the date-time d, from 0 to 59 out of domain
microsecond(d) The fraction of a second of the date-time d, in whole microseconds from 0 to 999999 out of domain
weekday(d) The ISO 8601 day of the week of d, 1 for Monday to 7 for Sunday
dayOfYear(d) The day of the year of d, from 1 to 366
isoWeek(d) The ISO 8601 week number of d, from 1 to 53
isoWeekYear(d) The ISO 8601 week-numbering year of d
hasTime(d) Whether the Civil Date d has a time of day
toCivil(i, offset) The date-time on the wall clock at the Instant i, at offset from UTC or under the Zone Rules offset out of domain, out of range
toInstant(c, offset, disambiguation = nothing) The Instant at which the wall clock, at offset from UTC or under the Zone Rules offset, reads the date-time c out of domain, out of range, ambiguous time
  • Civil Dates only: the field functions take a Civil Date (ADR 0023). An Instant raises wrong kind, so a Script turns it into a Civil Date first, with toCivil or the calendar Capability.
  • Time fields: hour, minute, second and microsecond of a date-only value raise out of domain.
  • ISO 8601 weeks: weekday is 1 for Monday to 7 for Sunday, and isoWeek and isoWeekYear follow ISO 8601 week numbering. Day names come only from the locale Capability.
  • Fixed offsets: offset in toCivil and toInstant is either an exact duration Quantity that is a whole number of minutes and less than 24 hr in magnitude, or Zone Rules. UTC is 0 s. Any other offset raises out of domain.
  • toInstant(c, offset, disambiguation = nothing) takes a date-time, and a date-only value raises out of domain. disambiguation applies only to Zone Rules: with a fixed offset, a disambiguation other than Nothing raises out of domain, with value the argument.
  • Range: a result outside 0001-01-01 to 9999-12-31 raises out of range, with field "year".
  • Names: day, month, year and min are also Units, and second an ordinal, but a Unit is only a suffix straight after a numeric literal and an ordinal only follows the, so day(d) and second(d) are calls.

Rationale. A time field of a date-only value raises out of domain rather than wrong kind, because a date-only value and a date-time share the kind name civil date, and wrong kind would name the same kind twice (ADR 0033).

Zone Rules let toCivil and toInstant convert in a named time zone without a Grant, so local time works in a Guard (ADR 0179). They are a plain map, which a Host usually builds from its zone data (chapter 9), and which a Script may also write:

put {zone: "Europe/London", until: londonUntil,
changes: [{at: londonFrom, offset: 0 s}, {at: springForward, offset: 1 hr}]} into london
put hour(toCivil(raisedAt, london)) >= 22 into late
  • Shape: a map with exactly the keys zone, until and changes. zone is text. until is an Instant. changes is a non-empty list of maps, each with exactly the keys at, an Instant, and offset, a fixed offset as above. The at values strictly increase, and the last is before until.
  • Window: the first change’s at opens the window, and until closes it, exclusive. A change’s offset holds from its at until the next change’s at, or until until for the last.
  • Checked whole on every call: any map that breaks the shape raises out of domain, with function the Built-in and value the map, before any conversion. The check doesn’t stop at the change a conversion needs, so a malformed map never gives an answer.
  • toCivil(i, rules) gives the date-time at i plus the offset in effect at i. An i before the window opens, or at or after until, raises out of range, with field "zone" and value i.
  • toInstant(c, rules, disambiguation): the candidates are each Instant c - o for an offset o of a change whose span holds c - o. A single candidate is the answer. With none, c falls in the gap where the offset rises from o1 to o2, and with two, in an overlap. disambiguation resolves them as calendar’s toInstant does (calendar). "compatible", the default for Nothing, gives c - o1 in a gap, moving the time forward by the gap’s length, and the earlier candidate in an overlap. "earlier" gives c - o2 in a gap and the earlier candidate in an overlap. "later" gives c - o1 in a gap and the later candidate in an overlap. "reject" raises ambiguous time, with civil c and zone the map’s zone. Any other disambiguation raises out of domain, with value the argument.
  • Outside the window: toInstant raises out of range, with field "zone" and value c, when c - o for any offset o in the map, or the answer, is outside the window. So a Civil Date near either edge is refused rather than resolved against offsets the map doesn’t hold.
  • A copy: Zone Rules hold the offsets they were built with. Nothing refreshes them, and a stored or saved copy keeps its data and window. A Host that wants current data builds them again.
  • Not a value kind: Zone Rules are an ordinary map, compared, printed, stored and saved as one.

Rationale. Zone Rules are a map rather than a value kind of their own so that display, saves, Shapes and the Host boundary need nothing new, and they are taken by Built-ins rather than date Library functions because a Guard may call only Built-ins. Converting outside the window raises rather than extrapolating, since a silently wrong offset is the bug they exist to prevent (ADR 0179).

Constant Value Is
pi 3.141592653589793238462643383279503 pi, rounded half-even to 34 digits
newline U+000A A line feed, as text
tab U+0009 A tab, as text
quote U+0022 A double quote, as text

A Guard may use the Built-in Constants, and a Script’s own name may shadow them (Names and clashes).

Export Gives Also raises
pad(t, width, fill = " ") t with fill added at the end until it is width Characters long out of domain
padLeft(t, width, fill = " ") t with fill added at the start until it is width Characters long out of domain
trim(t) t without the white space at its start and end
trimStart(t) t without the white space at its start
trimEnd(t) t without the white space at its end
split(t, separator) The list of the texts between the matches of separator, a text or a Text Pattern, in t out of domain
join(xs, separator = "") The items of xs, each shown as & shows it, with separator between each pair
repeated(t, n) n copies of t, joined out of domain
lastOffset(needle, t) The Character position where the last match of needle, a text or a Text Pattern, starts in t, or 0 if there is none
format(template, values) template with each ${name} replaced by the value of that key of values, shown as & shows it out of domain
formatNumber(n, symbols, places = nothing) The number n written with a Locale’s numberSymbols, rounded to places digits after the point if places is given out of domain
parseNumber(t, symbols) The number t writes with a Locale’s numberSymbols can't convert, out of domain
  • pad and padLeft: width is an integer, 0 or more, and fill a text of exactly one Character, or they raise out of domain. A text already width Characters or longer comes back unchanged, so they never truncate.
  • trim, trimStart and trimEnd remove white space Characters.
  • split(t, separator):
    • A text separator matches as a needle does, left to right, without overlapping. An empty text separator raises out of domain.
    • A Text Pattern separator matches where the Match Search every match of separator in t finds its matches, and an empty match separates nothing.
    • The result always has one more item than there are separators, so split("a,,b,", ",") is ["a", "", "b", ""] and split("", ",") is [""]. This differs from items, where a trailing delimiter makes no empty item.
  • join(xs, separator = "") shows each item as & shows it, so a list of numbers joins without converting first.
  • repeated(t, n): n is an integer, 0 or more.
  • lastOffset(needle, t) gives the start of the last of the successive matches the Match Search finds, taking a text needle as a Text Pattern that matches exactly that text. So lastOffset("aa", "aaa") is 1.
  • format(template, values) fills a Format Template:
    • ${name} shows the value of the key name of the map values, as & shows it. $$ is a literal dollar. Other dollar signs and ordinary braces are literal.
    • A name that isn’t a key raises out of domain with value the name. An unterminated ${ raises it with value the template. Keys are looked up exactly, including spaces and punctuation; no expression is evaluated. $${name} produces literal ${name}.
    • There is no width or precision: pad and round do that.

Example.

use format, pad, split from text
on show
put format("${name} owes ${amount}", {name: "Ann", amount: 2.50 GBP}) into owed -- "Ann owes 2.50 GBP"
put pad("id", 5, ".") into head -- "id..."
put split("a;b;c", ";") into parts -- ["a", "b", "c"]
end show

formatNumber and parseNumber write and read numbers with the separators and digits a Locale gives, from the locale Capability’s numberSymbols (ADR 0024). They are written in the language, so rounding, grouping and parse errors are the same on every Host.

  • symbols is a map with every key numberSymbols gives: decimal, group and minus as text, digits as a list of ten texts, zero first, and primaryGroup, secondaryGroup and minGrouping as integers. Anything else raises out of domain, with value the map.
  • formatNumber(n, symbols, places = nothing):
    • n is a plain number, and a Quantity raises wrong kind, so a Script formats the number part itself.
    • Without places, the digits are those of the canonical form, written out without an exponent, so trailing zeros survive. With places, an integer, 0 or more, the number is first rounded as round(n, places) rounds it.
    • A negative number starts with minus. The fraction, if there is one, follows decimal. Each digit is written with digits.
    • The integer part is grouped only when it has at least primaryGroup + minGrouping digits. Then group goes before the last primaryGroup digits and before every secondaryGroup digits to the left of those, so a secondaryGroup of 2 writes 12,34,567.
  • parseNumber(t, symbols):
    • It accepts exactly what formatNumber could write for some places, and the same without any group separators: an optional minus, at least one digit, and optionally decimal followed by at least one digit. There is no exponent, no plus sign and no white space.
    • The result keeps its digits, so "2,50" in a Locale with a , decimal gives 2.50.
    • A mismatch, or a number past the number limits, raises can't convert, with {value, to: "number", offset} and offset the position of the first Character that doesn’t fit.

Example.

use formatNumber from text
on price amount
ask locale to numberSymbols "de-DE"
put formatNumber(1234567.5, it, 2) into shown -- "1.234.567,50"
end price
Export Gives Also raises
sum(xs) The items of xs added with +, left to right, or 0 for an empty list incompatible units
average(xs) The sum of xs divided by its length out of domain, incompatible units
zip(xs, ys) The list of pairs [x, y] of items at the same position, as long as the shorter list
unique(xs) xs without the items equal to an earlier item
reverse(xs) xs in reverse order
flatten(xs) xs with each item that is a list replaced by its items, one level deep
sort(xs, direction = "ascending") xs sorted by <, stably out of domain, can't compare
sortBy(xs, key, direction = "ascending") xs sorted by < on the value key gives for each item, stably out of domain, can't compare
sortWith(xs, compare, direction = "ascending") xs sorted by the two-argument comparator compare, stably out of domain
filter(xs, keep) The items of xs for which keep gives true, in order
map(xs, f) The list of what f gives for each item of xs, in order
reduce(xs, f, initial) f(f(f(initial, x1), x2), …) over the items of xs, or initial for an empty list
group(xs, key) A map from each text key gives to the list of items that gave it, keyed in first-seen order
partition(xs, keep) [matching, rest]: the items for which keep gives true and the others, each in order
any(xs, test) Whether test gives true for some item, stopping at the first that does
all(xs, test) Whether test gives true for every item, stopping at the first that doesn’t
find(xs, test) The first item for which test gives true, or Nothing
indexOf(xs, value) The position of the first item equal to value, or 0 if there is none
  • sum and average add with +, left to right from the first item, so a list of Quantities sums in the first item’s Unit. A number and a Quantity together raise wrong kind, and Quantities of different dimensions raise incompatible units. average of an empty list raises out of domain.
  • zip stops at the end of the shorter list. unique compares with = and keeps each first occurrence. flatten goes one level deep.
  • filter, map, partition, any, all and find call their Function Value with one argument, the item. any, all and find stop at the first item that settles the answer. any of an empty list is false, and all of one is true. partition always gives two lists.
  • reduce(xs, f, initial) calls f with two arguments, the value so far and the item.
  • group(xs, key) calls key with one argument. Its result must be text, since map keys are text, and anything else raises wrong kind with expected "text". Each list keeps its items in input order.
  • indexOf(xs, value) compares with =.
  • direction is "ascending" or "descending", and any other text raises out of domain, with value the direction.
  • Keys: sort sorts by the items themselves. sortBy first calls key once per item, in order, with the item, and then sorts by the keys it gave. Lists order lexicographically under < (ADR 0003), so a list key sorts by several keys, as in sortBy(rs, given r: [the city of r, the temp of r]).
  • The merge sort: all three sort the same way, so the order of comparisons, and so the order of comparator calls and the first can't compare, is fixed:
    1. A list of fewer than 2 items is already sorted.
    2. Otherwise, sort its first ⌊n/2⌋ items and its remaining items, each the same way.
    3. Merge the two halves. While both have items left, compare the first remaining item of the first half, left, with the first remaining item of the second, right. Take right if it must come strictly before left, and otherwise take left. Then append what remains of either half.
  • Strictly before: for sort and sortBy, ascending, right comes first when key(right) < key(left), and descending when key(left) < key(right). For sortWith, compare(left, right) is called with two arguments and must give a number, or it raises wrong kind. Ascending, right comes first when the number is greater than 0, and descending when it is less than 0.
  • Stable: items that tie keep their input order, in either direction.
  • Mixed directions chain stable sorts, the last sort being the main key: sortBy(sortBy(rs, temp, "descending"), city) sorts by city, then by falling temperature. Or they use sortWith.

Example.

use sortBy, filter, map, reduce from list
on summarise readings
put filter(readings, given r: the wind of r > 10) into gusty
put sortBy(gusty, given r: the temp of r, "descending") into hottest
put map(hottest, given r: the city of r) into cities
put reduce(readings, given total, r: total + the rain of r, 0 mm) into rain
end summarise
Export Gives Also raises
merge(a, b) The map with the entries of a and then of b, where b’s value wins for a key in both
without(m, keys) m without the entries whose keys are in the list keys
pick(m, keys) m with only the entries whose keys are in the list keys, in m’s order
entries(m) The list of pairs [key, value] of m, in order
fromEntries(pairs) The map with the entries of the list of pairs pairs, where a later pair wins for a repeated key
mapValues(m, f) m with each value replaced by what f gives for it, keys and order kept
lookup(m, path, default = nothing) The value the Path or Value Path path locates inside m, or default if a key or position along it is missing or holds Nothing
withPath(m, path, v) m with v at the Path or Value Path path
withoutPath(m, path) m with the key or item at the Path or Value Path path removed
hasPath(m, path) Whether the Path or Value Path path locates a value inside m that isn’t Nothing
transform(value, mapping) A complete fresh mapped value, or ordered diagnostics without partial output invalid mapping
  • Order: maps keep insertion order. merge(a, b) gives a’s keys in a’s order, with b’s value for a key in both, then b’s other keys in b’s order.

  • Key lists: keys in without and pick is a list of text. A key that isn’t in m is ignored.

  • fromEntries(pairs): each pair is a list of exactly two items, the first a text. A list of another length raises out of domain with value the pair. A repeated key keeps its first position and takes the last value.

  • mapValues(m, f) calls f with one argument, the value, in the map’s order. lookup remains supported unchanged. Optional key reads and otherwise provide map-only nullable steps and a lazy default. lookup evaluates its default argument eagerly, validates the whole path before traversal, also supports list positions, and reports a cumulative error path.

  • lookup(m, path, default) follows path, a Path or a Value Path, one step at a time. x at p reads as lookup(x, p) does (chapter 4). A text step reads that key of a map, and an integer step reads that item of a list, counted as in item n of, so -1 is the last. It gives default as soon as it reaches Nothing, so a missing key, a key that holds Nothing, a position out of range and an m that is Nothing all give default. An empty path gives m. A text step at anything but a map, or an integer step at anything but a list, raises wrong kind with expected "map" or "list", value the value it reached and path the Path that reached it. So text, a Range, Bytes and a Host Object are never stepped into, and lookup never calls the Host. path must be a Path, or a list of texts and integers, checked before any step is taken. Taking either kind is not a coercion (ADR 0003): each is a kind the function defines.

    put decodeJson(body) into order
    put lookup(order, ["customer", "address", "city"], "unknown") into city
    put lookup(order, ["lines", -1, "sku"]) into lastSku
  • withPath(m, path, v), withoutPath(m, path) and hasPath(m, path) take a Path or a Value Path as lookup does: it is checked before any step, a text step works on a map and an integer step on a list, and a step at anything else raises wrong kind with the path that reached it. When the steps taken hold one a Path can’t, a 0 or a position past the position limit, that path is the longest prefix of the steps taken that is a Path, and an integral position such as 1.0 is written as 1; the error is the same wrong kind. Each gives a new value and never calls the Host (ADR 0136).

    • withPath writes as put does, and a write into a Container c at p is withPath (chapter 4). Only the last step may add a key, or pad a list past its end with Nothing. A step through a missing key or Nothing raises wrong kind with expected "map" or "list" and got "nothing", since a missing parent is never made. An empty path gives v.
    • withoutPath removes as delete does: a key leaves its map, and a list item goes and the rest move up. A step that reaches a missing key, a position out of range or Nothing leaves the value as it was. An empty path raises out of domain.
    • hasPath is lookup(m, path) is not nothing, so a key that holds Nothing counts as missing.
    put withPath(config, ["components", "door", "isLocked"], true) into config
    put true into config at /components/door/isLocked -- the same write
    put withoutPath(config, ["lights", 1]) into config

transform(value, mapping) combines selection, comprehensive input/output Shape checks and restricted unary conversion (ADR 0081). It gives {ok: true, value: output} or {ok: false, errors: diagnostics}. The output is a fresh map; any failure discards it. An empty rules list gives an empty map. It is a Library function, unavailable in Guards.

Definition. A Mapping is a map containing only rules, an ordered list of rule maps. A rule contains required from and to, optional input and output Shapes, optional transform Function Value accepting one argument, and optional missing policy: "error" (default), "skip" or "default". A default key must be present exactly for the "default" policy; its value may be any Kind, including Nothing. Unknown Mapping/rule keys are rejected; Shape metadata follows the Shape checks’ separate rules above.

from is a Selection Path: a list of text keys, nonzero integers or exactly {each: true}. An empty path selects the whole input; text "*" is literal. to is a nonempty list of text map keys (empty text is a valid key). It constructs intermediate maps, never list positions. Duplicate destinations and ancestor/descendant destination overlaps are rejected, even for rules that would skip. Sibling destinations share their intermediate map.

Definition precedence. The whole definition is checked before selection or any callback. First check Mapping Kind, unknown keys in insertion order, presence of rules, then its Kind. Visit rules in declaration order. In each rule check: Kind; unknown keys in insertion order; presence/Kind of from then its steps in order; presence/Kind/nonemptiness of to then its steps in order; the complete input then output Shape definitions; transform Kind then acceptance of one argument; missing word; default presence or prohibition; finally destination overlaps against earlier rules in order. Each earlier check takes precedence over every later check, including failures in subsequent rules.

invalid mapping carries reason, definition-relative path and offending value. A missing required key locates its enclosing definition and uses that map as value. Other locations include the field key and, for path steps, the 1-based position. Reasons and their locations are fixed as follows:

Reason Location / offending value
not a mapping root / Mapping argument
unknown key unknown key / its value
missing rules root / Mapping map
invalid rules rules / its non-list value
invalid rule rules, rule number / its non-map value
missing from, missing to rule / rule map
invalid source path, invalid destination path rule’s from or to / its non-list value
invalid selection step from, step number / neither text, nonzero integer nor exact wildcard
empty destination to / empty list
invalid destination step to, step number / non-text value
invalid shape input or output / whole embedded Shape, with the original invalid shape error in error
invalid transform, invalid transform arity transform / non-function or function unable to accept one argument
invalid missing policy missing / unrecognised value
missing default rule / rule map
unexpected default default / its value under error or skip
overlapping destination to / later path, with earliest conflicting 1-based rule in otherRule

Embedded Shape errors preserve their own reason, Shape-relative path, value, message and at in error. Validation uses conforms(nothing, shape) to validate each Shape without treating a false answer as failure; this also charges that ordinary Built-in’s attempted match. Function eligibility beyond arity (foreign Home Script, suspension or stale code) is tested when called, and failures become transform-stage diagnostics.

Selection. Every rule reads the original input. A text step requires a map, an integer step a list, and a wildcard either. Incompatible containers give source-stage wrong kind diagnostics, regardless of missing policy. Host Object properties are never traversed. A present Nothing is a selected value; traversing further through it is a container mismatch. Positive list positions are 1-based; negative positions count backwards and successful reads record positive indices. A missing key or out-of-range index terminates that branch: error emits a missing selection diagnostic, skip omits it, and default supplies one selected value without resuming traversal inside that default.

Wildcards visit list items in index order and map values in insertion order, flattening nested matches depth-first. Empty containers contribute no items. Any path containing a wildcard writes a flat list, even when absence occurs before its first wildcard; skipping all branches writes an empty list. A skipped single-value rule omits its destination. Successful/defaulted values can be any Kind and complete lists pass through without flattening unless selected by a wildcard. Unmapped fields are omitted.

Execution and diagnostics. For each rule, selection finishes before its items execute. Each present/defaulted item is checked comprehensively against input, if supplied. Failed input suppresses its callback. A successful input is passed to transform, if supplied, using the private restricted-call boundary of chapter 8, then checked comprehensively against output. Output Shapes check individual items, never the final wildcard collection. Ordinary callback errors are collected unchanged inside a transform-stage diagnostic, qualifying the general stdlib callback-error propagation rule. Caught restriction errors may yield valid fallback values. Limit Faults escape; they never become diagnostics.

Every diagnostic carries rule (1-based), sourcePath, destinationPath, stage (source, input, transform or output) and error. Field insertion order is those locations, optional position, optional failedStep, then stage and error, as the normative source fixes. A Shape diagnostic’s inner path remains item-relative. Callback errors retain all their original details and metadata. Source errors are plain records without message or at. For a failed selection, sourcePath is the successfully resolved concrete prefix and failedStep is the original attempted token; the missing error’s step repeats that token. No positive position is invented for an out-of-range negative index. Defaulted items keep these failed-selection locations through input, transform and output diagnostics.

Wildcard rules additionally carry position: the 1-based depth-first ordinal of every terminal branch, counting present, missing and incompatible branches, including skipped branches. Empty wildcard containers contribute no ordinal. This ordinal is independent of the successful result list and identifies failures after skipped branches unambiguously. Diagnostic order is rule order, then terminal branch order, then comprehensive Shape traversal order. Failed items supply no output. Any collected error returns only ok and errors; otherwise the complete map is returned under value.

Resources. Definition validation, selection, intermediate construction, callbacks and reports use ordinary Library instruction Fuel and Allocation Budgets, plus the existing Shape checker and restricted-call rates. All returned values and reports are charged by logical size, repeated offending values included. Iterative selection and destination construction introduce no recursion-based path limit, new depth cap or report truncation. Full results succeed or a Limit Fault escapes. Preemption/restore retains ordinary Library work and active callback boundaries; no additional snapshot format is needed.

Export Gives Also raises
toHex(b) The Bytes b as lowercase hexadecimal text, two digits per byte
fromHex(t) The Bytes the hexadecimal text t writes can't convert
toBase64(b) The Bytes b in the base64 alphabet of RFC 4648, padded
fromBase64(t) The Bytes the padded base64 text t writes can't convert
toBase64Url(b) The Bytes b in the base64url alphabet of RFC 4648, unpadded
fromBase64Url(t) The Bytes the unpadded base64url text t writes can't convert
decodeText(b, encoding = "utf-8", mode = "strict") The text the Bytes b hold in encoding, normalised to NFC can't convert, out of domain
encodeText(t, encoding = "utf-8") The Bytes of the text t in encoding can't convert, out of domain
  • Hexadecimal: toHex writes lowercase digits. fromHex accepts digits in either case, an even number of them and nothing else: no spaces and no 0x.
  • Base64: toBase64 and fromBase64 use the alphabet of RFC 4648 section 4, with = padding. toBase64Url and fromBase64Url use the alphabet of section 5, without padding. The readers accept only the canonical form: the right alphabet, the right length and padding, zero in any unused trailing bits, and no white space.
  • Errors: a text these readers can’t accept raises can't convert, with {value, to: "bytes", format, offset}, where format is "hex", "base64" or "base64url", and offset is the position of the first Character that doesn’t fit, or the last Character when the length is wrong.

decodeText and encodeText name one of these encodings. Any other text raises out of domain, with value the name.

Encoding Bytes
"utf-8" UTF-8, as the Unicode Standard defines it; a leading U+FEFF is dropped when decoding
"utf-16le" UTF-16, each code unit little-endian, with surrogate pairs; a leading U+FEFF is dropped when decoding
"utf-16be" UTF-16, each code unit big-endian, with surrogate pairs; a leading U+FEFF is dropped when decoding
"latin-1" ISO/IEC 8859-1: each byte is the code point of the same value, from U+0000 to U+00FF
"windows-1252" The windows-1252 index of the WHATWG Encoding Standard: bytes 0x80 to 0x9F map as that index says, and every other byte as in latin-1
  • decodeText(b, encoding = "utf-8", mode = "strict"):
    • In "strict" mode, bytes that aren’t well-formed in the encoding raise can't convert, with {value: b, to: "text", format: encoding}. latin-1 and windows-1252 decode every byte.
    • In "replace" mode, each maximal ill-formed subsequence becomes U+FFFD, as the Unicode Standard’s “U+FFFD substitution of maximal subparts” says. For UTF-16, an unpaired surrogate or an odd final byte each become one U+FFFD.
    • Any other mode raises out of domain.
    • A leading U+FEFF is dropped for the three UTF encodings, and the text is then normalised to NFC.
  • encodeText(t, encoding = "utf-8") writes the scalars of t, which is already NFC, and never writes a byte order mark. A Character with no byte in latin-1 or windows-1252 raises can't convert, with {value: t, to: "bytes", format: encoding}.
  • as text and as bytes stay strict UTF-8 (ADR 0011). The one difference from decodeText(b) is that b as text keeps a leading U+FEFF.

Rationale. UTF-8 and UTF-16 cover what current systems write, and latin-1 and windows-1252 cover the legacy Western text that spreadsheets and old files still produce. Every one of them maps bytes to code points without tables larger than 32 entries, so they can be written in the language. Other legacy encodings (Shift_JIS, GB 18030, the other ISO 8859 parts) need large tables, and a Host that must read them decodes the bytes itself and passes text in (ADR 0021).

Export Gives Also raises
decodeJson(t) The value the JSON text t holds can't decode
encodeJson(v) The value v as compact JSON text not encodable
pointerPath(t) The Path the JSON Pointer text t locates, with each array index as a 1-based position
applyPatch(doc, patch) doc with the RFC 6902 JSON Patch patch, a list of operations, applied in order can't patch

This mapping is the one rule for plain JSON. The json Library follows it, and so does each Core’s Host-side JSON codec (ADR 0030). The lossless form for every kind is the Value Encoding, which only Hosts can reach (chapter 9).

JSON Value
null Nothing, allowed inside lists and maps
true, false a boolean
a number a number, exactly as written
a string a text, normalised to NFC
an array a list
an object a map, in the order its members are written
  • Decoding, decodeJson(t):
    • t is one JSON value as RFC 8259 defines it, with optional JSON white space (space, tab, LF, CR) before and after.
    • A number is read exactly, keeping its digits, so 2.50 decodes to 2.50, and -0 to 0. A JSON exponent is applied, and a positive result exponent is rescaled to 0, so 1e5 decodes to 100000 and 2.50e1 to 25.0. A number past the number limits is invalid. Numbers are never read through a float.
    • A string’s escapes are decoded, and a \u surrogate pair gives one scalar. A lone surrogate, or an unescaped control character, is invalid.
    • Two members of one object whose names are equal after NFC are invalid.
    • decodeJson never produces a Quantity, range, Path, Civil Date, Instant or Bytes.
    • Invalid JSON raises can't decode, with {format: "json", offset}, where offset is the position of the first Character that can’t continue valid JSON, or one past the end.
  • Encoding, encodeJson(v):
    • The output is compact, with no white space between tokens.
    • Nothing is null. A number is written in its canonical form, so trailing zeros survive. A list is an array. A map is an object, in the map’s order.
    • A text is a JSON string. " and \ are written \" and \\. U+0008, U+0009, U+000A, U+000C and U+000D are written \b, \t, \n, \f and \r, and the other characters below U+0020 as \u00 and two lowercase hex digits. Every other character is written as itself.
    • A Path is a JSON string of its text form, so encodeJson({at: /reviews/2}) gives {"at":"/reviews/2"}. Decoding gives the text back, and as path reads it, unless a key needed a hole in the text form (chapter 3), which as path refuses.
    • A Quantity, range, Civil Date, Instant, Bytes, Text Pattern, Host Object or Function Value raises not encodable, with {kind, path}: kind is its kind name, and path the Path that leads to it from v, for the first such value in depth-first order. There is no object form for them. A Script converts first: q as text gives "5 kg", q / 1 kg a plain number, and formatDate a date.

Example. encodeJson({name: "Ann", scores: [2.50, nothing]}) gives the text {"name":"Ann","scores":[2.50,null]}, and decodeJson of that text gives the map back. encodeJson({total: 5 kg}) raises not encodable with kind "quantity" and path /total.

  • JSON Pointer, pointerPath(t): gives the Path that the RFC 6901 JSON Pointer text t names, so a pointer is used with at and the map Library’s path functions rather than as a second path syntax (ADR 0184). "" gives the empty Path. Otherwise t starts with /, and each reference token between slashes is one step, with ~1 read as / and ~0 as ~. A token of digits with no leading zero is an array index and gives the integer one past it, since positions count from 1, and any other token gives its text, the empty token included. Text that doesn’t start with /, or a ~ not followed by 0 or 1, raises out of domain. So pointerPath("/lines/0/sku") gives /lines/1/sku, and a map key written in digits can’t be reached through a pointer.
  • JSON Patch, applyPatch(doc, patch): applies the RFC 6902 operations of the list patch, a value such as decodeJson gives, to doc in order and gives the result. Inside a patch the RFC’s rules hold rather than the map path functions’ (ADR 0137):
    • Operations are maps with op, path and, as the RFC says, value or from. A value member may hold Nothing, which is JSON null. Other members are ignored.
    • Pointers resolve against the value they reach: a token is a key on a map and, written as an array index, a position on a list, counted from 0 as JSON counts. - names the place past a list’s end, only for add. A map key that holds Nothing is present.
    • add puts a map key, or inserts into a list and moves the later items up. remove and replace need their target to exist. move removes from from and adds at path, copy adds a copy, and test compares with =. The empty pointer "" is doc itself.
    • Failures raise can't patch with index, the operation’s 1-based position in patch, its op and path as given, and a reason: "invalid operation" for a malformed operation, "invalid pointer", "missing target" for a target or parent that isn’t there, "test failed" and "move into itself". doc is a value, so a failed patch leaves nothing half done.
Export Gives Also raises
makeDate(y, m, d) The date-only Civil Date y-m-d out of range
makeDateTime(y, m, d, h, mi, s = 0, us = 0) The date-time y-m-d at h:mi:s and us microseconds out of range
atTime(d, h, mi, s = 0, us = 0) The date-time on the date of d at h:mi:s and us microseconds out of range
dateOnly(d) The date of the Civil Date d, without its time of day
daysInMonth(d) The number of days in the month of the Civil Date d
isLeapYear(y) Whether the integer y is a leap year in the proleptic Gregorian calendar
formatDate(d, template) The Civil Date d written by template out of domain
parseDate(t, template) The Civil Date the text t writes by template can't convert, out of domain, out of range
splitDuration(d) The exact duration d as the map {days, hours, minutes, seconds} incompatible units
monthsBetween(a, b) The number of whole calendar months from the Civil Date a to b, negative if b is earlier can't compare
epoch = 1970-01-01T00:00:00Z The Unix epoch, as an Instant
  • Building: makeDate, makeDateTime and atTime are written in the language over as civil date. Each field is an integer in its range: year 1 to 9999, month 1 to 12, day 1 to the month’s length, hour 0 to 23, minute 0 to 59, second 0 to 59, and microsecond 0 to 999999. Anything else raises out of range, with field the field’s name ("year", "month", …) and value the argument. Nothing is ever normalised, so makeDate(2026, 2, 30) raises.
  • atTime(d, h, mi, s = 0, us = 0) adds a time of day to a date-only value. A date-time raises out of domain, and a Script that wants to replace a time writes atTime(dateOnly(d), …).
  • isLeapYear(y) takes any integer, by the proleptic Gregorian rule.
  • splitDuration(d) takes an exact duration Quantity and gives plain numbers: whole days, hours from 0 to 23 and minutes from 0 to 59, with the fraction kept in seconds, which is less than 60. A negative duration gives the parts of its magnitude, each negated. A Quantity of another Unit Kind raises incompatible units.
  • monthsBetween(a, b) takes two date-only values or two date-times, and mixing them raises can't compare. When a is at or before b, it is the greatest n for which a + n months is at or before b, with month arithmetic clamping the day as chapter 3 says. When b is earlier, it is minus monthsBetween(b, a). So from 2026-01-31 to 2026-02-28 is 1.
  • epoch is the Instant 1970-01-01T00:00:00Z. A Unix timestamp n is epoch + n s, and back again is (i - epoch) / 1 s.

formatDate and parseDate share one template language of named, numeric fields in dollar-brace placeholders (ADR 0023).

  • Tokens: ${year}, ${month}, ${day}, ${hour}, ${minute}, ${second} and ${weekday}, each with an optional width :n, and ${fraction:n}, the first n digits of the microseconds, with n from 1 to 6. $$ is a literal dollar. Other dollar signs and ordinary braces are literal. Everything else is literal text.
  • All numeric: there are no names, no 12-hour clock and no AM/PM, which are Locale concerns. Month and day names come from the locale Capability.
  • A valid template holds ${year}, ${month} and ${day}. A time token needs ${hour} and ${minute}. Each token appears at most once. Any other token, a missing width on ${fraction} or an unclosed ${ is invalid. An invalid template raises out of domain, with value the template.
  • formatDate(d, template):
    • d is a Civil Date, so an Instant goes through toCivil or the calendar Capability first. A template with time tokens given a date-only value raises out of domain, with value the date.
    • Digits are ASCII. :n pads with zeros to n digits and never truncates. ${fraction:n} truncates the microseconds to n digits.
  • parseDate(t, template):
    • The whole text must match. Literal text matches exactly. A token with a width takes exactly that many ASCII digits, and one without takes the longest run of one or more.
    • Seconds and microseconds default to 0. The result is a date-only value unless the template has time tokens.
    • A mismatch, or a ${weekday} that disagrees with the date, raises can't convert, with {value: t, to: "civil date", format: template, offset} and offset the position of the first Character that doesn’t fit, or of the weekday’s digit.
    • A field that matches but is outside its range raises out of range, as makeDate does.

Example.

use formatDate, parseDate, makeDateTime from date
on stamp
put makeDateTime(2026, 9, 27, 14, 5) into d
put formatDate(d, "${day:2}/${month:2}/${year} ${hour:2}:${minute:2}") into shown -- "27/09/2026 14:05"
put parseDate("2026-09-27", "${year}-${month}-${day}") into back -- 2026-09-27
end stamp
Export Gives Also raises
celsiusToFahrenheit(c) c * 9 / 5 + 32
fahrenheitToCelsius(f) (f - 32) * 5 / 9
celsiusToKelvin(c) c + 273.15
kelvinToCelsius(k) k - 273.15
fahrenheitToKelvin(f) (f - 32) * 5 / 9 + 273.15
kelvinToFahrenheit(k) (k - 273.15) * 9 / 5 + 32
  • Plain numbers: each takes and gives a plain number. Temperature Units are differences only (ADR 0022), so an absolute temperature is a plain number, and a Quantity raises wrong kind.
  • Order of operations: each computes exactly the expression in its entry, left to right, rounding each step as arithmetic does (ADR 0002). So celsiusToFahrenheit(100) is 212.

A Standard Capability is a Capability whose Operation Declarations this chapter fixes, so every Host offers the same shapes, while each Host supplies the answers (ADR 0014, ADR 0023, ADR 0024, ADR 0050, ADR 0070, ADR 0077).

The Standard Capabilities are clock, calendar, locale, timer, console, store, sqlite, user, http and peer. sqlite, user, http and peer are optional: a Host may choose not to offer them, but a Host that offers one follows every rule this chapter gives for it.

  • Optional for Hosts, not for Cores: every Core defines every Standard Capability, and a Host offers an optional one by calling its factory (chapter 9). A Script that calls one its Host doesn’t offer has no Grant for it, so it fails to load like any other ungranted call.
  • Ordinary Capabilities otherwise: a Script reaches one only through a Grant, under the name it is granted as, and calls it with ask or tell (ADR 0012). A Script that calls one it wasn’t granted fails to load, and there is no silent fallback. A Grant may still limit a Script to some of its Operations.
  • The Host implements each Operation, with any library it likes, except clock.now, and sets each one’s per-call cost (chapter 9).
  • Parity: the Trace records each answer. A Trace Case supplies Host answers as Stubs; clock.now reads the Pump’s Clock without a Stub (chapter 11).
  • Modes: every clock, calendar, locale, store and sqlite Operation is immediate, both timer Operations, console’s write and user’s notify are fire-and-forget, and console’s read, user’s confirm, choose and enter, http’s serve and fetch, and peer’s expose, reach and call, are suspending, http’s unserve and respond and peer’s unexpose are immediate, and peer’s post is fire-and-forget.
  • Arguments are checked against the fixed Shapes before the Host function runs, and a mismatch raises wrong kind (chapter 6). Where an Operation takes a word from a fixed list, the Core checks the word too, and any other raises out of domain, with function the Operation’s name.
  • Error codes: the calendar Operations declare unknown zone and ambiguous time, and the Host fails with them. The Core raises bad locale itself. The store Operations declare can't store, store full and store busy, which the Host fails with, and invalid key, which the Core raises. The sqlite Operations declare sql, constraint, sqlite busy, not read-only, too many rows and unrepresentable, which the Host fails with, and the Core raises out of range, unrepresentable and sql for the checks it makes itself. The user Operations declare user busy, which the Host fails with, and the Core raises out of domain for an empty choose list. The http Operations declare address in use, bad address, already responded, exchange closed, not owner, network error and response too large, which the Host fails with, and the Core raises invalid serve, invalid response, invalid request and out of domain. The peer Operations declare bad address, name in use, not exposed and send failed, which the Host fails with, and the Core raises out of domain, wrong kind, bad message name and not encodable. Chapter 6 says how both kinds are checked.
Operation Mode Gives Errors
now immediate The Pump’s Clock reading, as an Instant

clock has no zone. A Script that only timestamps events needs no zone, and reading the time is a Grant of its own. Its answer is the Pump’s Clock reading, so the Host implements nothing.

now takes no arguments and returns an Instant. It declares no Script error codes.

Operation Mode Gives Errors
today [zone] immediate The date-only Civil Date in the zone at the Pump’s Clock reading unknown zone
now [zone] immediate The date-time in the zone at the Pump’s Clock reading unknown zone
toCivil i [, zone] immediate The date-time in the zone at the Instant i unknown zone
toInstant c [, disambiguation] [, zone] immediate The Instant at which the zone’s wall clock reads the date-time c unknown zone, ambiguous time
offset i [, zone] immediate The zone’s offset from UTC at the Instant i, as an exact duration unknown zone
zone [zone] immediate The IANA id of the zone in use unknown zone
  • Shapes: today, now and zone take one Optional text; toCivil and offset take an Instant and one Optional text; toInstant takes a Civil Date and two Optional texts. An omitted or Nothing zone uses the Grant’s default. The factory passes that as an absent zone to the Host, which reads its binding. The supplied argument list, including Nothing, remains unchanged in the Trace.
  • Zones: the Grant binds a default IANA zone id, and every Operation takes an optional trailing zone id that overrides it. An unknown zone makes the Host fail with unknown zone, with {zone}.
  • toInstant c [, disambiguation] [, zone]: c is a date-time; a date-only value raises out of domain, with function: "toInstant" and value: c. With two supplied arguments, a second argument that is one of "compatible", "earlier", "later" and "reject" is the disambiguation, and any other text is a zone. With three supplied arguments, the second is the disambiguation and the third the zone; an unrecognised disambiguation raises out of domain, with function: "toInstant" and value the second argument. Omitted or Nothing disambiguation means "compatible". These domain checks follow Shape checks, before charging the call or running the Host function.
  • Gaps and overlaps: "compatible", the default, moves a time in a DST gap forward by the gap’s length, and takes the earlier Instant for a time in an overlap. "earlier" and "later" take that Instant in both cases. "reject" makes the Host fail with ambiguous time, with {civil, zone}.
  • Results: today gives a date-only value, and now and toCivil a date-time. toInstant gives an Instant. offset gives an exact duration in s, and zone text naming the IANA id in use. The Core checks these result kinds, the presence or absence of a Civil Date’s time, and the exact s Unit; a mismatch becomes host error. The Host supplies zone data and applies the gap/overlap rules.

Example.

on remind due
ask calendar to today
if due - it < 7 days then tell log to write "due soon"
end remind
Operation Mode Gives Errors
compare a, b [, options] [, tag] immediate -1, 0 or 1, as the text a sorts before, with or after b under the Locale’s Collation bad locale
rank texts [, options] [, tag] immediate A map from each distinct text of the list texts to its dense, 1-based rank under the Locale’s Collation bad locale
upper s [, tag] immediate s under the Locale’s uppercase mapping, then NFC bad locale
lower s [, tag] immediate s under the Locale’s lowercase mapping, then NFC bad locale
numberSymbols [tag] immediate The map {decimal, group, minus, digits, primaryGroup, secondaryGroup, minGrouping} for the Locale bad locale
monthNames [options] [, tag] immediate The Locale’s 12 month names, January first bad locale
dayNames [options] [, tag] immediate The Locale’s 7 day names, Monday first bad locale
tag [tag] immediate The BCP 47 tag of the Locale in use, after fallback bad locale
  • Call shape: the arguments come first, then an optional options map, then an optional BCP 47 tag. The two optional arguments are told apart by kind, a map against a text, as in ask locale to compare a, b, {sensitivity: "base"}, "de". compare requires two texts, rank a list of texts, and upper and lower one text; the other Operations have no required arguments. compare, rank, monthNames and dayNames accept an Optional choice of their closed options map or text, followed by Optional text. The others accept just Optional text. If both optional positions are supplied, the first must be a map or Nothing; text there raises out of domain, with function the Operation name and value that text.
  • Defaults: omitted or Nothing options mean an empty map, and omitted or Nothing tags use the Grant binding. The factory fills absent option keys with the defaults below, passing a complete map to the Host in the documented key order. An absent tag reaches the Host as absent; it reads the default from its binding. The Core validates the effective tag on each call; an explicit tag overrides even a malformed default. The Trace keeps only the supplied arguments, including explicit Nothing.
  • Checks: option maps allow only the listed keys, with text for word-valued fields and boolean for numeric; a present Nothing field breaks its Shape. After Shape checks, the Core checks option words in map order, then the effective tag, before charging the call or entering the Host. Unknown words raise out of domain, with function the Operation name and value the word. bad locale is raised only by the Core; the Host error declarations are empty, so every Host failure becomes host error.
  • Naming a Locale: the Grant binds a default tag, and any call can name another. A tag that isn’t well-formed BCP 47 raises bad locale, with {locale}, before the Host runs. Well-formed means the case-insensitive ASCII ABNF of RFC 5646 §2.1, including private-use and grandfathered tags. As §2.2.9 distinguishes, this is syntax, not registry validity: the Core does not check registrations, duplicate variants or duplicate extension singletons. It neither trims nor canonicalises tags, and does not consult platform Locale data. A well-formed tag the Host doesn’t support falls back by lookup, dropping subtags from the right (de-CH to de), down to the root Locale und, which every Host supports. tag gives the tag in use, after fallback.
  • Every Operation for every Locale: a Host that offers locale implements every Operation for every tag it resolves to.
  • Collation options, for compare and rank: sensitivity, one of "base", "accent", "case" and "variant" (the default), and numeric, a boolean, false by default, which sorts "file 10" after "file 9".
  • rank texts: every item of texts must be text. The answer maps each distinct text to its rank, dense and 1-based, with texts that compare equal sharing one. The Core checks the answer: its keys must be exactly the distinct texts it was given, and its ranks dense, or the call ends as host error.
  • Sorting by Collation uses rank and a stable sort, so texts of equal rank keep their input order. rank takes the place of a comparator, which would put one locale call per comparison in the Trace.
  • Case: upper and lower use the Locale’s case mapping, such as Turkish dotted İ. The upper and lower Built-ins keep full default case mapping, and ignoring case keeps simple folding.
  • numberSymbols gives the closed map {decimal, group, minus, digits, primaryGroup, secondaryGroup, minGrouping}, as Numbers in a Locale uses it: nonempty texts for the three separators/signs, ten nonempty texts for digits, and positive integers for the three grouping fields.
  • Results: the Core checks compare is exactly -1, 0 or 1; upper and lower return text (Value construction ensures NFC); monthNames and dayNames return lists of exactly 12 and 7 texts; numberSymbols meets the rules above; and tag returns well-formed tag text. A mismatch becomes host error. The Host supplies the actual mappings, Collation and Locale data, including supported-tag lookup and fallback.
  • Name options, for monthNames and dayNames: width, one of "long" (the default), "short" and "narrow", and form, one of "format" (the default), for use inside a date, and "standalone". item weekday(d) of it names a date’s day.

Example.

use map, sortBy from list
on showPeople people
ask locale to rank map(people, given p: the name of p)
put it into ranks
put sortBy(people, given p: the (the name of p) of ranks) into sorted
end showPeople
Operation Mode Gives Errors
schedule name, at, message, args fire-and-forget Stores a durable timer that delivers message with the list args to the Script at the Instant at, replacing one of the same name
cancel name fire-and-forget Removes the Script’s timer called name, if there is one

timer is the durable-timer pattern for waits that must outlive memory (ADR 0005). wait stays in memory only.

  • schedule name, at, message, args: name is a text, at an Instant, message a message name as text, and args a list. Names are scoped to the Script, and scheduling a name again replaces its timer.
  • cancel name removes the timer, and cancelling an unknown name does nothing.
  • Delivery: the Host stores timers durably. When one is due, the Host delivers message with args to the Script as an ordinary Delivery, at its next opportunity if at has already passed. The Core takes no part in it.

schedule takes exactly four arguments, with Shapes text, Instant, text and a list of any; cancel takes exactly one text. As with every Host boundary, the list cannot contain Function Values, even nested in Containers. Neither Operation declares Script error codes, so a Host failure becomes host error.

Operation Mode Gives Errors
write value fire-and-forget Shows the text form of value, any value, as one or more lines of output
read suspending The next line of input the user types, as text, without its line break

console is the user’s terminal or output pane. Every REPL session grants it, and any other Host may (chapter 12).

  • write value takes any value, and the Host shows its text form. say x is short for tell console to write x.
  • read answers with the next line the user types, as text, without its line break. Its maxPending is 2,147,483,647 ms, the largest MaxWait every Core honours, so a user can take their time (chapter 6).

write takes exactly one argument, with the value Shape: every value, including Function Values nested in lists or maps. read takes no arguments and returns text, including empty text for an empty line. Both declare no Script error codes; a Host failure becomes host error. The Console factory forwards write’s Value to the Host, which shows its text form, and starts read with a Call that the Host answers with text. Both calls retain the Grant’s binding and the Script’s name.

Operation Mode Gives Errors
get key [, default] immediate The value under key, as the Segment sees the Store, or else default, or Nothing invalid key
set key, value immediate Nothing; puts value under key when the Segment commits, and Nothing deletes the key invalid key, can't store, store full, store busy
delete key immediate Nothing; removes key when the Segment commits, if it is there invalid key, store busy
keys [prefix] immediate The keys the Segment sees that begin with prefix, in Unicode code-point order
increment key [, by] immediate The key’s value as the Segment sees it after adding by, 1 by default; commit adds by to the value committed then invalid key, wrong kind, incompatible units, overflow, store full, store busy
swap key, expected, new immediate true, after putting new under key, if the Segment sees expected there, and false otherwise invalid key, can't store, store full, store busy
watch name, prefix [, message] immediate Nothing; from now on, each commit that changes keys beginning with prefix delivers message to the Script, replacing its watch called name invalid watch, watch limit
unwatch name immediate Nothing; removes the Script’s watch called name through this Grant, if there is one invalid watch

store keeps data values under text keys, outside every Script, so they outlive a reload and are shared by every Script granted the same Store (ADR 0050). Its writes commit or roll back with the Segment that made them, as Script Variables do (ADR 0006). Like timer, the Spec states its semantics as obligations on the Host, and the Core takes no part in keeping the Store.

  • Naming a Store: the Grant’s binding is the Store’s name, never the Script’s text. Every Grant whose binding names the same Store reaches the same contents, across Scripts and Groups.
  • Shapes of the six data Operations: the first argument is text: a key, or keys’ prefix. get takes an Optional any default; set an any value; keys an Optional text prefix; increment an Optional choice of number or Quantity; and swap two any values. delete takes only its key.
  • Keys are nonempty text, compared exactly as NFC text (ADR 0011). Empty text raises invalid key after the Shape checks, before the call is charged or the Host function runs.
  • Values are data values, stored by the Value Encoding. A Function Value anywhere in a value raises not encodable from the Shape check, and the Host fails with can't store, with kind the Object Kind, for a Host Object anywhere in one. A key holding Nothing and a missing key are one state, so setting Nothing deletes the key.
  • What a Segment sees: the committed Store, with the Segment’s own uncommitted writes applied in call order. Every other Segment sees only the committed Store.
  • Segment-bound: set, delete, increment and swap are Segment-bound, so the first of them through a Grant enrolls that Grant in the Segment’s participant (the lifecycle contract). Their effects reach the committed Store only when the Segment commits, and a rollback discards them. A Grant of only get and keys never enrolls.
  • One coordinator: a Store implementation maps every Store it keeps to one Segment Coordinator, so writes to several of its Stores, or to one Store through several Grants, in one Segment enroll in one participant and commit together (ADR 0069). Writing in the same Segment through a Segment-bound Grant the Host maps to another coordinator raises segment participant conflict.
  • In a sqlite database: a Host may keep its Stores in a database it offers through sqlite, and map that database to the Store implementation’s coordinator, so one Segment can write to both and commit them together (ADR 0070). The Store’s commit then writes inside the Segment’s database transaction. A Store write takes the database’s write lock at its call, as sqlite’s change does, so a commit never finds the database busy, and fails with store busy while another Segment holds it. Every sqlite Grant is denied the Store’s table, for reads too.
  • get key [, default] gives the value the Segment sees, or else default if one was given, or Nothing.
  • set key, value and delete key give Nothing. Deleting a missing key changes nothing.
  • keys [prefix] gives the keys the Segment sees whose code points begin with prefix’s, all of them without one, as a list of text in Unicode code-point order.
  • increment key [, by]: by is 1 if omitted or Nothing. The answer is the value the Segment sees plus by, under the + rules of chapter 3, and a missing key gives by itself, so a Quantity can start a key. A value that isn’t a number or a Quantity, or doesn’t add to by, makes the Host fail with the error + would raise: wrong kind, incompatible units or overflow. Commit adds by to the value committed then, so increments from several Segments never lose a count. The call also fails if by wouldn’t add to the committed value with every other live Segment’s pending increments of the key applied, so a commit never meets those errors.
  • swap key, expected, new gives true and writes new, which deletes for Nothing, if the value the Segment sees equals expected under =. Otherwise it gives false and writes nothing. expected of Nothing means “only if missing”.
  • Reserved keys: an uncommitted set, delete or swap that wrote reserves its key until its Segment ends, and an uncommitted increment reserves its key against every write but another increment. A write to a key another live Segment has reserved makes the Host fail with store busy, with {key}, before anything changes (ADR 0062). A Store kept in a sqlite database also fails a write with store busy while another Segment holds that database’s write lock (below). Reads are never refused. A reservation outlives a stretch of execution only when its Run is preempted inside its Segment, or when another Group sharing the Store runs at the same time, as Groups pumped on separate threads do. So a Host without a Fuel Slice, which pumps the Groups sharing a Store one at a time, never raises it.
  • Quotas: each Store has a total size, a key count and a largest value, which its Host sets. A key and its value count by their logical sizes. A write that would take the committed Store, with every live Segment’s pending writes, past a quota makes the Host fail with store full, with limit one of size, keys and value. So a commit never exceeds a quota.
  • Commit applies the Segment’s writes to every Store it wrote, at once, in call order, so a commit publishes all of them or none, and one that fails reports failed or unknown as any Segment-bound commit does. Reservations make a commit’s result independent of other Segments’ writes, so a Store fails a commit only when its own storage fails.
  • Outside the Script: Store contents never count toward Persistent State, and no save includes them (chapter 10). Converting a value get gives is charged to the Run, as for any result (chapter 9).
  • Results: get gives a data value; set and delete Nothing; keys a list of text; increment a number or a Quantity; and swap a boolean. The Core checks these result kinds, and a mismatch becomes host error.

The six data Operations and the two watch Operations are immediate: a Segment-bound Operation must be, and a read answers at once. A Host backed by remote storage answers from a working set it holds.

Example.

script variable total = 0
on scored points
ask scores to increment "total", points
put it into total
end scored
on claimPrize name
ask scores to swap "winner", nothing, name
if it then tell log to write name & " won"
end claimPrize
  • Watch: a Script’s registration, made by watch through one named Grant. A watch is a Subscription. It is identified by its owner, the Group, Script and named Grant, and by its name, chosen by the Script. Its parameters are its prefix and message.
  • Notification: the Delivery a watch receives. An ordinary Notification names changed keys; a Reconciliation Marker asks for the watch’s whole prefix to be refreshed.
  • Router: the Host component that holds watches, routes commits to them and admits Notifications into Groups. Its rules are normative for every Host that offers watch; chapter 9 declares the router each Core supplies.
  • Pending work: Notifications the router holds for a watch that no Group has admitted yet. A Notification is admitted when the recipient Group accepts its Delivery at the call. From then on it belongs to the Core like any other Delivery.

The two watch Operations have these call rules:

  • Shapes: watch takes text, text and an Optional text, and unwatch one text. Both give nothing, and the Core checks the result kind; anything else becomes host error.
  • Mode: both are immediate and neither is Segment-bound. They never enlist a participant, so they don’t conflict with another Store’s writes in the same Segment. A Grant of only get, keys, watch and unwatch lets a Script observe a Store without being able to write to it.
  • Final at the call: a registration takes effect when the Host function returns. A later Limit Fault, rollback, effect failed or cancellation of the calling Run doesn’t undo it.
  • Arity: watch takes two or three supplied arguments, and unwatch exactly one. Omitting or passing Nothing as message means storeChanged. The Trace and the Host function’s supplied arguments keep the call as the Script wrote it. The store factory gives the implementation the effective message, as calendar resolves its default zone.

After the Shape checks and before charging the call or running the Host function, the Core checks these, in order. A failure raises invalid watch, with field set to name or message. No call id is allocated and the Host isn’t called, so an invalid replacement leaves an existing watch unchanged.

  1. name, for both Operations, is nonempty text.
  2. The effective message, for watch, is a plain Name (chapter 1): not a Reserved Word, _ or all, and not a Selector. A Notification carries exactly one argument, so a name containing : is refused even when it would be a one-part Selector.

The prefix is any text, including empty text, which watches the whole Store. Values are NFC, so a prefix is compared as the keys Operation compares it, by code points.

These checks are the Core’s. Every other failure is the Host’s: watch limit (Limits) and, as for any declared Operation, host error for anything undeclared. capability revoked and capability disabled come before every one of these, as for any Operation.

  • Identity: a watch belongs to its owner and name. Two named Grants bound to the same Store hold separate watches, even with the same name, and each Notification names the Grant it came through.
  • watch, new name: registers the watch with no pending work.
  • watch, same parameters: a watch whose prefix and effective message both equal the existing one’s does nothing, and keeps the watch’s pending work and its place in the order of watches.
  • watch, different parameters: replaces the watch. The router discards the old watch’s pending work, routes nothing more under the old parameters, and keeps the watch’s place in the order of watches. Notifications already admitted keep the old prefix in their payload, which still describes them.
  • unwatch: removes the watch and discards its pending work. Unwatching a name the owner hasn’t registered does nothing.
  • The registration boundary: registration and commit routing share the Store’s synchronization (Routing), so each commit is either before a registration, and never routed to it, or after, and routed. A Segment’s uncommitted writes commit after a watch made in that same Segment, so they are routed to the watch.
  • Initial reconciliation: a Script registers first and then reads the Store. Its reads may already include a commit that a Notification will also report, and several reads need not observe one Store version. No snapshot Operation is offered.

A commit is any change to a Store’s committed contents: a Segment commit hook that returns ok, and every Host-originated change, such as a Session’s :store load or :store clear, an import or an administrative write. A commit that fails, a rollback, and a Segment’s uncommitted writes produce nothing.

The Store applies a commit and the router routes it as one step under the Store’s synchronization: a per-Store mutual exclusion that watch, unwatch, every commit, marker admission and checkpointing also take. A Host that runs several Groups on several threads, or reaches one Store from several processes, must provide it. Store commit order is the order commits take it.

  • Changed keys: a key changes when its committed value after the commit differs from its value before, compared by the bytes of the Value Encoding. A missing key and a key holding Nothing are one state.
  • Whole commits only: intermediate writes inside one commit aren’t seen. A key set and then restored, a delete of a missing key and a set of the value already there change nothing.
  • No change, no work: a commit with no changed keys routes nothing and doesn’t change the Store’s revision.

For a commit with changed keys, each watch on that Store whose prefix is a code-point prefix of at least one changed key receives one ordinary Notification, holding each such key once. Every watch matches, including those of the Script whose Segment committed.

The router visits matching watches in its order of watches: by Group, in the order the router first registered a watch from that Group, then by Script, in the Group’s load order, then by named Grant and watch name, each in Unicode code-point order. A Group that comes to hold no watches loses its place, and takes a new one when it next registers. A replaced watch keeps its place; one removed and registered again goes to its new place. The router reads load order with Group.ScriptNames, which is safe inside a Pump and adds no Trace line (chapter 9).

A Notification is a Delivery addressed to the owning Script with Script.Deliver. It has the watch’s effective message as its name, exactly one argument and no limit override. The argument is a map with these keys, in this order:

Key Value
grant the named Grant the watch was made through, as text
watch the watch’s name
prefix the watch’s prefix
keys an ordinary Notification’s changed keys under the prefix, nonempty and in Unicode code-point order, as store.keys orders them; [] for a Reconciliation Marker
resync false for an ordinary Notification, true for a Reconciliation Marker

The payload never holds values, old or new, or the Grant’s binding. Each Notification is recorded in the Trace as the ordinary deliver Host Input it is.

A watch is in one of two states: ordinary, with zero or more pending ordinary Notifications in commit order, or resyncing, with exactly one pending Reconciliation Marker.

  1. Routing a commit to an ordinary watch with no pending work: the router delivers the Notification at once. If the Group accepts it, it is admitted. If the Group refuses it as MailboxFull, the Notification becomes the watch’s pending work, subject to step 3.
  2. Routing a commit to an ordinary watch with pending work: the Notification joins the end of its pending work, subject to step 3, so a later commit is never admitted before an earlier one.
  3. Overload: if holding the Notification would take the Store’s pending work past the pending or pendingSize limit, the router discards the watch’s pending ordinary Notifications and makes the watch resyncing instead. This sacrifices per-commit detail. It never fails, delays or reports the commit itself.
  4. Routing a commit to a resyncing watch adds nothing: its pending marker already covers the commit.
  5. Any other refusal: if a Delivery is refused for any reason other than MailboxFull, such as the Script no longer being in the Group, the router removes the watch and discards its pending work.

Admission is never undone. A Notification already admitted is never rewritten, withdrawn or replaced by a marker, and stays subject to the Core’s own rules, such as Stop and Reload dropping a mailbox.

  • When: after each Pump of a Group returns, the Host calls the router, and the router attempts to admit pending work for that Group’s watches. Retrying needs no further Store write and no polling by a Script, and the Pump never discards pending work.
  • Fair order: a retry round visits the Group’s watches with pending work in the order of watches, starting with the watch after the one that started the Group’s previous round and wrapping around. For each watch it delivers pending Notifications oldest first, stopping at that watch’s first refusal and moving on to the next watch.
  • A marker’s return: admitting a Reconciliation Marker makes its watch ordinary again, under the Store’s synchronization, so each commit is either covered by the marker or routed as an ordinary Notification after it.
  • Progress: pending work is admitted provided the Host goes on pumping the Group and the recipient eventually accepts a Delivery. The router tells the Host when a Group still has pending work, so a driver can schedule another Pump.
  • Order: within one watch, Notifications are admitted in Store commit order, and a marker is admitted after everything it replaced would have been. Nothing is promised between different watches, Stores or Groups, or about when a Group pumps.
  • Admission, not handling: the router guarantees admission, falling back to one marker under overload. It doesn’t promise that a Handler runs or succeeds. There are no acknowledgements and no retries after admission. A Notification that reaches the end of the Message Path is unhandled, and an errored Handler is the Script’s to deal with.
  • Handlers: , queued is recommended for a Handler of ordinary Notifications, so batches aren’t dropped or replaced. A wait for that waits for one Notification and then waits again can miss the ones in between.
  • Reacting to a marker: a Handler refreshes the watch’s entire prefix from current state, including removing keys it holds that no longer exist.
  • Writing back: a Handler that writes to a key it watches receives a Notification for its own write. It converges because a write that changes nothing routes nothing.

A watch belongs to its owner, the loaded Script and named Grant, not to the Run that registered it. It outlives that Run, and cleanup never depends on a Script finally block or a Capability Scope. The store factory forwards the implementation’s Grant release hook to the router.

On release, the router removes every watch the owner holds and discards their pending work, and no later commit routes through them. Only a new watch registers again, which a revoked or disabled Grant refuses. Notifications already admitted aren’t touched. Stop and a successful Reload drop the Script’s mailbox under their own rules, and after a revocation or disablement any that remain are delivered and handled as usual.

After a Reload, a Script has no watches. A Host that reloads Scripts sends the message its Scripts use to start up, such as start above, so they register again and reconcile. Extend keeps every watch, since no code is replaced and no Grant is released.

When a Host stops using a Group, it tells the router to detach it, and the router removes every watch the Group’s Scripts hold. A Group that is only saved and later restored is a different Group, with routing of its own (Checkpoints).

Each Store’s router state has four finite limits, which its Host sets:

Limit Counts Exceeded
watches the Store’s watches, across every Script and Group watch limit {limit: "watches"} at watch
watchSize the total size of the Store’s watches: for each, the logical sizes of its name, prefix and effective message as text watch limit {limit: "size"} at watch
pending the Store’s pending Notifications, with one reserved for every watch watch limit {limit: "pending"} at watch; overload when routing
pendingSize the total logical size of their payload maps, with every watch’s marker reserved watch limit {limit: "pending"} at watch; overload when routing
  • The reservation: every watch always counts one Reconciliation Marker toward pending and pendingSize, whether or not it has pending work. A resyncing watch’s marker occupies that reservation, so a marker always fits and is never lost to a limit.
  • Registering: a watch checks all four limits with its own watch, and its reservation, in place of any it replaces. If a limit would be exceeded, the Host fails the call with watch limit, naming the first limit in the table’s order, and the existing watch and its pending work are unchanged. Same-parameter watch and unwatch never fail on a limit.
  • Pending ordinary Notifications count in addition to the reservations, and overload is decided against both pending limits.
  • Restoring a checkpoint registers restored watches without checking these limits, so a restore never drops a watch for space. Later registrations are checked against the restored totals.

A Script that keeps a view of shared Store data asks to hear when that data changes, instead of polling. Each successful commit that changes watched keys sends the Script one ordinary Delivery naming those keys. The Handler then reads current state.

script variable board = {}
on start
ask scores to watch "board", "score/", "scoresChanged"
refresh()
end start
on scoresChanged change, queued
if the resync of change then
refresh()
else
repeat for each key in the "keys" of change
ask scores to get key
put it into the (key) of board
end repeat
end if
end scoresChanged
function refresh
put {} into board
ask scores to keys "score/"
repeat for each key in it
ask scores to get key
put it into the (key) of board
end repeat
end refresh

A commit that sets score/alex to a new value delivers scoresChanged with one argument:

return {grant: "scores", watch: "board", prefix: "score/", keys: ["score/alex"], resync: false}

start registers before it reads, so no commit falls into a gap between the two. A Notification may describe a key whose value refresh already read: reconciliation is repeatable, and the Handler applies the same rule whoever wrote the key.

Operation Mode Gives Errors
query sql, params [, max] immediate The rows the read-only statement sql gives with params bound, as a list of maps from column name to value, in column order sql, not read-only, too many rows, unrepresentable, out of range
change sql, params [, max] immediate The map {changes, rows}: the rows the statement sql changed, and the rows it gave, such as those of a RETURNING clause; it commits with the Segment sql, constraint, sqlite busy, too many rows, unrepresentable, out of range
begin immediate Nothing; opens the scope transaction, which rollback abandons sqlite busy, scope already open, scope in join
commit immediate Nothing; closes the scope transaction, keeping its changes until the Segment commits scope not open
rollback immediate Nothing; closes the scope transaction, discarding its changes scope not open

sqlite runs SQL against a database the Host keeps, for a Script that keeps records it needs to search, join or total, which outgrow the Store’s whole values under text keys (ADR 0070). It is optional: a Host need not offer it, and a Host that does follows every rule here. Its writes commit or roll back with the Segment that made them, as the Store’s do.

  • The database: the Grant’s binding names a database the Host keeps, never a path or a handle a Script can see. It may limit the tables the Grant can use, and it sets the most rows a call may give (chapter 9). Every Grant whose binding names the same database reaches the same contents, across Scripts and Groups.
  • Dialect: SQLite 3.45.0 or later. A Host may run a newer SQLite, and a portable Script keeps to what 3.45 accepts.
  • Results may drift: a newer SQLite can change what the same SQL gives. 3.53, for example, casts a REAL to text with 17 digits instead of 15. So raw SQL is portable only up to the Host’s SQLite version. The value mapping below converts doubles itself and isn’t affected, and a Trace replays exactly, since it records every result.
  • Shapes: sql is text, params a list or a map of data values, and max an Optional number. begin, commit and rollback take no arguments.
  • One statement: each call runs exactly one statement, and trailing statements raise sql.
  • Parameters are always bound, never spliced into the SQL. A list binds positionally, to ? and ?NNN, and a map binds by name, to :name, from keys written without the colon, so {id: 3} binds :id. The number of params must equal the number of placeholders. @name and $name, a statement that mixes positional and named placeholders, and a list given for named placeholders or a map for positional ones all raise sql.
  • Values in: Nothing binds as NULL. A number whose canonical text has no fraction digits (3, but not 3.0) and that fits a signed 64-bit integer binds as INTEGER, and every other number as REAL, by the nearest double. Text binds as TEXT, Bytes as BLOB, and true and false as 1 and 0. Every other kind raises wrong kind, with path locating it inside params, and a Script converts it explicitly (ADR 0003).
  • Values out: NULL gives Nothing, INTEGER a number, TEXT NFC text and BLOB Bytes. REAL gives the shortest decimal that reads back as the same double, as a float entering a Core does. A NaN, an infinity, a REAL of magnitude 10^34 or more, and TEXT that isn’t valid UTF-8 raise unrepresentable, with column its column’s name. SQLite has no booleans, so a boolean comes back as 0 or 1.
  • Rows: a row is a map from column name to value, with its keys in the statement’s column order. A result that names a column twice raises sql, so a Script names each column once, with AS where needed.
  • max: a call gives at most max rows. An omitted or Nothing max is the binding’s row cap, and a max that isn’t a whole number from 0 to that cap raises out of range, with field: "max". A statement that gives more rows raises too many rows, with max. A result is never truncated.
  • query sql, params [, max] gives the list of rows. Its statement must be read-only, which SQLite checks before it runs, and a statement that could write raises not read-only. query is never Segment-bound, so a Grant of only query is read-only and never enrolls.
  • change sql, params [, max] gives {changes, rows}: changes is the number of rows the statement inserted, updated or deleted, and rows the rows it gave, such as a RETURNING clause’s, or an empty list. There is no last inserted id, which would be meaningless for a multi-row insert, and RETURNING gives the ids instead. change accepts a statement that only reads, and still enrolls.
  • Segment-bound: change, begin, commit and rollback are Segment-bound, so the first of them through a Grant enrolls it in the Segment’s participant (the lifecycle contract). Their changes reach the database’s committed state only when the Segment commits, and a rollback discards them. Without begin, a change commits or rolls back with its Segment.
  • Transactions: begin opens the Capability Scope transaction, whose abandonment is rollback, and commit and rollback close it (ADR 0047). The scope is a savepoint inside the Segment’s transaction: commit keeps its changes, but only until the Segment ends, and rollback discards them. An ordinary error with the scope open abandons it, discarding its changes, and then the Segment commits the rest. A Limit Fault, cancellation, Stop or Rewind rolls back everything, explicit commits included. With the scope open, a wait, a suspending call or a Join raises scope open (the lifecycle contract).
  • Deferred constraints are checked when the Segment commits, not at commit, so a deferred foreign key a Segment breaks fails the Segment’s commit, and the Run ends effect failed. Every other constraint is checked at the statement, which raises constraint, with kind one of unique, primary key, not null, check, foreign key, datatype and trigger, or other for any other.
  • One coordinator per database: every Grant whose binding names one database, aliases included, maps to that database’s Segment Coordinator (ADR 0069). Writing to a second database, or to a Store kept elsewhere, in the same Segment raises segment participant conflict. A Segment can’t commit several databases at once.
  • Contention: a Segment takes the database’s write lock at its first change or begin, and holds it until the Segment ends. If another Segment holds it, the call raises sqlite busy before anything changes. Another Segment holds the lock only when its Run is preempted inside it, or when it belongs to another Group sharing the database that runs at the same time, as Groups pumped on separate threads do. So a Host without a Fuel Slice, which pumps the Groups sharing a database one at a time, never raises it. A Script catches it and retries after a wait. Reads are never blocked: a Segment that holds the lock reads its own uncommitted changes, and every other Segment reads the last committed state.
  • What the Host refuses: statements that would step outside the Segment’s transaction or the binding raise sql. These are BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, VACUUM INTO, load_extension, every PRAGMA but the read forms of table_info, table_xinfo, index_list, index_info, index_xinfo, foreign_key_list and user_version, and any use of a table outside the binding’s limits (chapter 9).
  • Cost: each call charges its declared cost. query and change also charge the Host’s perStep Fuel before every statement step, including completion and overflow probes. A successful N-row result normally costs N+1 steps; an empty result or non-returning change costs one, even with max 0. Refusal stops before stepping and rolls back Segment-bound writes. This meters steps, not database engine work inside a step. Result conversion and allocation are still charged independently (SQLite step authorization).
  • Outside the Script: database contents never count toward Persistent State, and no save includes them (chapter 10). An open transaction or an enrolled participant makes a save fail with effects pending (ADR 0049).

All five Operations are immediate: a Segment-bound Operation must be, and SQLite runs in the Host’s own process.

Example.

on transfer fromId, toId, amount
ask db to begin
ask db to change "UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, fromId], 0
if the changes of it is 0 then throw {code: "no account", id: fromId}
ask db to change "UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, toId], 0
ask db to commit
end transfer

The throw abandons the open transaction, which discards the debit, and the Segment commits nothing else.

Operation Mode Gives Errors
confirm message suspending true when the person accepts the question message, and false when they decline or dismiss it user busy
choose items [, options] suspending The item of the list of texts items the person chose, or with multiple: true a list of those they chose, in list order; Nothing if they cancel user busy, out of domain
enter message [, options] suspending The text the person entered for message, starting from options’ default; Nothing if they cancel user busy
notify message [, options] fire-and-forget Shows message, with options’ title, without waiting for anyone

user asks the person running the Script, for a Host that has someone to ask (ADR 0077). It is optional: a Host need not offer it, and many server Hosts have no person to ask, but a Host that does follows every rule here. The Host supplies the UI, such as a dialog, a terminal prompt or a form in its client, and the Trace records each answer, so a replay needs nobody there.

  • The binding: none. The Host knows whom it asks.
  • Shapes: message is text. items is a list of texts. Each options is an Optional closed map: {prompt, multiple} for choose, with prompt text and multiple a boolean, {default} for enter, with default text, and {title} for notify, with title text. Every key is optional, and any other key raises wrong kind, as a closed map’s Shape check does.
  • confirm message gives true when the person accepts the question, and false when they decline or dismiss it.
  • choose items [, options] shows items, under the prompt when given, and gives the item the person chose. With multiple: true, the person may choose any number of them, none included, and it gives a list of the chosen items in the order they appear in items. An empty items raises out of domain, with value the list, before the Host is called.
  • enter message [, options] gives the text the person entered. The Host offers default, when given, as the starting answer. It never converts the text, and a Script converts it explicitly (ADR 0003).
  • Cancelling isn’t an error: a cancelled choose or enter gives Nothing. confirm has no separate cancel, and dismissing it gives false.
  • notify message [, options] shows message, with the title when given, and waits for nobody.
  • One prompt at a time: while a Script has a confirm, choose or enter the Host hasn’t answered, the Host fails that Script’s next one with user busy, before it shows anything. This holds inside a Join too. Prompts from different Scripts may queue. A prompt abandoned by a timeout, a cancellation or a Stop is no longer pending, and the Host takes it down.
  • Waiting: confirm, choose and enter each have a maxPending of 2,147,483,647 ms, the largest MaxWait every Core honours, as console’s read does. A Script that wants a deadline writes a Timeout Block, and a deadline that runs out raises timeout as for any call.
  • Answers the Core checks: a confirm answer is a boolean, and an enter answer is text or Nothing. A choose answer is Nothing, or one of items, or with multiple: true a list that is a subsequence of items: each item in it is one of items, in their order, and no position of items is taken twice. Any other answer is the Host’s fault, and the call ends as host error (chapter 9).

Example.

on tidy files
ask user to confirm "Delete " & the length of files & " files?" and wait
if not it then return
ask user to choose ["Small", "Medium", "Large"], {prompt: "Pick a size"} and wait
if it is nothing then return
put it into size
tell user to notify "Tidied", {title: size}
end tidy
Operation Mode Gives Errors
serve name, prefix [, message [, options]] suspending {host, port} once the Host listens; from then on, each HTTP request whose path the text prefix begins delivers message to the Script, replacing its Serve Registration called name invalid serve, address in use, bad address
unserve name immediate Nothing; removes the Script’s Serve Registration called name through this Grant, if there is one invalid serve
respond exchange, response immediate Nothing; answers the HTTP Exchange exchange with the map response’s status, headers and body or json invalid response, already responded, exchange closed, not owner
fetch url [, request] suspending {status, headers, body}: the final response to one HTTP request for the absolute URL url, made with the map request’s method, headers, query and body or json, with body always Bytes invalid request, bad address, network error, response too large, out of domain

http lets a Script serve HTTP and make HTTP requests. To serve, it claims a path prefix, receives each matching HTTP request as an ordinary Delivery, and answers it (ADR 0124). To make a request, it calls fetch and waits for the whole response (ADR 0151). It is optional. A Host that offers it follows every rule here.

  • Two sets of Operations: serve, unserve and respond are the server Operations, and fetch the client Operation. A Host may offer either set or both (chapter 9). A Script that calls an Operation its Host doesn’t offer fails to load, as for any ungranted call.
  • The binding: the addresses the Grant may listen on, and the origins it may fetch from. For listening, a Host may allow any, fix one, or allow a set. For fetching, it allows no origin, a list of origins, or any origin. It refuses others with bad address. The Script Runner allows any of both (chapter 12).
  • Shapes: name and prefix are text. message is an Optional text. options is an Optional closed map {host, port}, with host text and port a whole number from 0 to 65535. exchange is a Host Object of kind httpExchange. response is a closed map {status, headers, body, json}, every key optional: status a whole number, headers a map whose values are texts or lists of texts, body text or Bytes, and json any value the json Library can write. url is text. request is an Optional closed map {method, headers, query, body, json}, every key optional: method text, headers as for response, query a map whose values are texts or lists of texts, body text or Bytes, and json any value. Any other key raises wrong kind.
  • Identity: a Serve Registration belongs to its owner, the Group, Script and named Grant, and to its name, chosen by the Script, as a store watch does. Its parameters are its prefix, its effective message and its address.
  • serve, new name: registers it, listening on the address if no listener holds it yet, and gives {host, port}: the host as the Host listens on it, and the port, which for port: 0 is the one the Host chose.
  • serve, same parameters: does nothing more than give the address again.
  • serve, different parameters: replaces the registration. HTTP Exchanges already delivered are unaffected.
  • unserve: removes the registration. Unserving a name the owner hasn’t registered does nothing. A listener with no registrations left stops listening.
  • Defaults: omitting message, or passing Nothing, means httpRequest. Omitting host means the binding’s default, and omitting port the binding’s default port.
  • Validation: before charging the call or running the Host function, the Core checks, in order, that the name isn’t empty, that the prefix begins with /, and that the effective message is a plain Name, as for a store watch’s message. A failure raises invalid serve, with field set to name, prefix or message.
  • Matching: registrations on one host and port share a listener. An HTTP request goes to the registration whose prefix is the longest one the request’s path begins with, comparing code points. Equal prefixes from two owners are a conflict: the later serve fails with address in use.

An HTTP request that a registration matches is an HTTP Exchange. The Host Delivers it to the owning Script with Script.Deliver, named by the registration’s effective message, with exactly one argument: a map with these keys, in this order.

Key Value
method the method, in uppercase, as text
path the path as received, without the query, as text
segments the path split on /, each part percent-decoded, without empty parts, as a list of texts
query a map from each query key to its text, or to a list of texts when the key repeats, all percent-decoded
headers the headers by the Host conventions: lowercase names, repeated values joined with , , and set-cookie a list
body the body as Bytes, empty when there is none
exchange a Host Object of kind httpExchange with one read-only property, closed, a boolean
  • Ownership: only the Run that Delivery started may respond. Any other Run’s respond fails with not owner (ADR 0125). There is no handoff. A Run that wants to wait for something before answering uses wait for, wait or a suspending call.
  • respond exchange, response answers it once. status defaults to 200 and must be from 100 to 599. A text body is sent as UTF-8, and the Host adds content-type: text/plain; charset=utf-8 unless headers has one. A Bytes body is sent as it is. json is written by the json Library’s rules, with content-type: application/json unless headers has one. Giving both body and json, a status out of range, a header value that isn’t text or a list of texts, or two header names that differ only in case raises invalid response, with field naming the key, before the Host function runs.
  • Once: a second respond fails with already responded. After the client has gone, respond fails with exchange closed, and closed is true. A client going away never cancels the Run.
When Status
No registration matches the path 404
The Delivery’s Run ends unhandled 404
The Run ends with an uncaught error or a Limit Fault, or ends without responding 500
The Delivery is refused as MailboxFull, the Run is cancelled or dropped, or the Group is stopping 503

The Host logs the error of a 500 and never sends it to the client. It settles these from the Pump’s reports (chapter 9).

  • Saving: a Host doesn’t save a Group with an open HTTP Exchange. After a restore, an exchange’s Host Object is gone.
  • Not offered when serving: streaming bodies, upgrades such as WebSockets, server-sent events and TLS, which is a proxy’s job.

Example.

on start args
ask http to serve "site", "/", "httpRequest", {port: 3000} and wait
say "listening on " & the port of it
end start
on httpRequest {method: "GET", segments: [], exchange: x}
ask http to respond x, {body: "hello"}
end httpRequest
on httpRequest {method: "GET", segments: ["users", id], exchange: x}
ask http to respond x, {json: {id: id}}
end httpRequest
on httpRequest {method: "POST", segments: ["echo"], body: b, exchange: x}
ask http to respond x, {status: 201, body: decodeText(b)}
end httpRequest

A GET /users/7 runs the second clause. A DELETE / matches no clause, so its Run ends unhandled and the Host answers 404.

fetch url [, request] makes one HTTP request and gives the final response once the Host has received all of it, as the map {status, headers, body}. It decides nothing for the Script: the body is Bytes, every status is a result, and the Host follows no redirect, retries nothing, decompresses nothing and caches nothing.

  • Defaults: an omitted or Nothing request is an empty map, and an omitted method is GET.
  • Methods: method is one of GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS, in uppercase, as an HTTP Exchange’s method is. Any other text raises out of domain, with function: "fetch" and value the method.
  • Checks: after the Shape checks, the Core checks the method, the URL, headers, query, then body and json, before charging the call or running the Host function. Each failure but the method’s raises invalid request, with field naming the argument or key.

url is an absolute HTTP or HTTPS URL in a strict ASCII profile, so that every Core and Host reads the same destination (RFC 3986). Anything outside it raises invalid request, with field: "url".

  • Characters: only printable ASCII, with no space and no \. Non-ASCII path or query text must be percent-encoded, and a non-ASCII host name written in punycode. Every % begins two hexadecimal digits.
  • Scheme: http or https, in any case, then ://.
  • Host: a name of letters, digits, - and ., whose last label isn’t all digits; an IPv4 address of four decimal parts from 0 to 255, without leading zeros; or an IPv6 address in brackets. Shortened, hexadecimal and octal IPv4 spellings such as 127.1 and 0x7f.0.0.1 are refused. There is no user or password before @: a Script authenticates with headers.
  • Port: omitted, or a decimal number from 1 to 65535.
  • Path and query: the path is empty or begins with /, and the query follows ?. Both use RFC 3986’s unreserved characters, its sub-delimiters, :, @, /, ? in the query, and percent escapes.
  • Normalizing: the Core lowercases the scheme and host, drops a port equal to the scheme’s default (80 or 443), writes an empty path as /, and drops a fragment from #. It changes nothing else: the path’s and query’s escapes and dot segments stay as written, so normalizing a normalized URL gives it back unchanged.
  • The origin is the normalized URL’s scheme, host and port, the scheme’s default when the port is omitted. The Host refuses an origin the binding doesn’t allow with bad address. An origin names a host; it doesn’t promise where the name resolves. A Host that keeps Scripts off private networks also checks the addresses it connects to, and refuses them with bad address too.
  • query is percent-encoded and added to the URL, so a Script never encodes a URL component by hand. Each key and each value is written as UTF-8, and every byte other than A–Z, a–z, 0–9, -, ., _ and ~ becomes % and two uppercase hexadecimal digits. Each key gives key=value, or one pair per item of a list, in map and list order, joined with & after ?. A nonempty query with a URL that already has a query raises invalid request, with field: "query". An empty query adds nothing.
  • headers: each name is an HTTP token (RFC 9110 §5.6.2), and each value text with no control character but tab, and no space or tab at either end. A list sends one field line per item, in order. Two names that differ only in case, or a name the Host controls, raise invalid request, with field: "headers". The Host controls host, content-length, transfer-encoding, connection, keep-alive, proxy-connection, te, trailer and upgrade, in any case.
  • The body: a text body is sent as UTF-8, with content-type: text/plain; charset=utf-8 unless headers has one. A Bytes body is sent as it is. json is written by the json Library’s rules, with content-type: application/json unless headers has one. These are respond’s rules. Giving both body and json, or a json value the json Library can’t write, raises invalid request, with field: "json". A GET or HEAD with either raises it with field the key given.
  • Encoding: the Host sends accept-encoding: identity unless headers has an accept-encoding.
  • The Trace keeps the arguments as the Script wrote them, and so do saved calls. The Host receives the normalized URL, with query added, and the request (chapter 9).
Key Value
status the final response’s status, a whole number from 200 to 599
headers the response’s headers: lowercase names in code point order, repeated values joined with , in the order received, and set-cookie a list of texts
body the content as Bytes, empty when there is none
  • Statuses are results: a 404 or a 500 is an ordinary answer, and the Script decides which statuses it accepts. A 3xx is returned as it is, with its location. A Script that follows it fetches again, and the binding checks the new origin.
  • Only the final response: the Host skips informational (1xx) responses. A 101 switching protocols fails the call with network error, since fetch can’t upgrade.
  • Content as sent: the Host removes transfer framing, such as chunked encoding, but never decompresses. A server may still send coded content, and body then holds it with content-encoding saying so.
  • Trailers are read and counted toward the header bound, but the result doesn’t include them.
  • Complete or nothing: the call is answered only once the whole response has arrived. Any failure to get it, including DNS, connection, TLS and protocol failures, fails the call with network error. A Host may explain the cause in its diagnostics, but the Script sees one code.
  • Answers the Core checks: an answer that isn’t a map with exactly these keys in this order, a status outside 200 to 599, headers breaking the rules above, or a body that isn’t Bytes ends the call as host error.
  • Bounds: the Host receives at most 8,388,608 bytes of body and 65,536 bytes of headers unless the binding sets other bounds, and a Script can’t raise them. Body bytes are counted as returned, after transfer framing is removed. Header bytes are, for every field line received, trailers and repeated names included, the bytes of its name and value plus 4. Exceeding either fails the call with response too large, with field set to headers or body and limit the bound, and no partial response is given. The bounds limit what the Host buffers, which Script allocation limits don’t cover.
  • TLS: an HTTPS request verifies the server’s certificate and host name, and a Script can’t turn this off. The Host chooses which certificate authorities it trusts.
  • Nothing ambient: fetch sends no cookies, credentials or login state the Script didn’t put in headers, and keeps no cookies or responses between calls. A Script that wants a conditional request sends its own if-none-match or if-modified-since and handles the 304. A proxy is the Host’s choice.
  • Waiting: fetch has no maxPending of its own, so it waits for the Script’s MaxWait (chapter 6), 30,000 ms by default, and a shorter Timeout Block wins.
  • Abandoned calls: a call abandoned by a timeout, a cancellation, a Stop or a Rewind makes the Host abort the request as far as it can. A server may already have acted on it, and nothing undoes that. The Host never retries a call; a Script that wants a retry fetches again.
  • Saving: a pending fetch is saved as any pending call is. On restore the Host settles it as it chooses, and a Reissue sends the request again, accepting that the server may act on it twice. A replay answers from the Trace and makes no request.
  • Cost: fetch charges its declared cost and the conversion of its answer. Network work and Host buffering charge no Fuel.
  • Not offered when fetching: streaming bodies, cookies kept between calls, control of connections, decompression, redirects followed by the Host, retries, caching, and the CONNECT and TRACE methods.

Example.

on findUser email
ask http to fetch "https://api.example.com/users", {query: {email: email}} and wait
if the status of it is not 200 then throw {code: "lookup failed", status: the status of it}
put decodeJson(decodeText(the body of it)) into user
say "found " & the name of user
end findUser
on createUser token, name
ask http to fetch "https://api.example.com/users", {method: "POST", headers: {authorization: "Bearer " & token}, json: {name: name}} and wait
if the status of it is not 201 then throw {code: "create failed", status: the status of it}
end createUser

A findUser "ann@example.com" fetches https://api.example.com/users?email=ann%40example.com. A 404 is an answer, not an error, so findUser throws its own.

Operation Mode Gives Errors
expose [name] suspending A Peer to the calling Script, once it is an Exposed Script: reachable from other Groups by the text name through this Grant, or without name through a new unnamed exposure only that Peer reaches bad address, name in use, out of domain
unexpose exposure immediate Nothing; withdraws the Script’s exposure through this Grant that exposure names, as the text name of a named one or the Peer expose gave, if there is one out of domain
reach address suspending A Peer: a Host Object of kind peer standing for the Exposed Script the text address names bad address, not exposed, out of domain
post peer, message, args fire-and-forget Sends the message message with the list args to the Peer peer’s Exposed Script, at most once; a plain send to a Peer is this out of domain, wrong kind, bad message name, not encodable
call peer, message, args suspending The reply of the Peer peer’s Exposed Script to the message message with the list args, sent at most once; send … and wait to a Peer is this send failed, out of domain, wrong kind, bad message name, not encodable
caller immediate The Caller Identity of the Remote Send that started the calling Run: the data the receiving Host vouches for about who made it, or Nothing

peer lets Scripts in different Groups, on one Host or several, message each other with send (ADR 0153). A Script makes itself an Exposed Script with expose, and another gets a Peer for it with reach, or is handed one inside a Remote Send, and sends to it (chapter 5). Holding a Peer is permission to send to it (ADR 0155), and the receiver may ask who sent (ADR 0154). It is optional. A Host that offers it follows every rule here.

  • The binding resolves each logical name to a real destination, and decides which names the Grant may reach and which it may expose. It refuses others with bad address. It is never checked at post or call: a Peer a Script holds, however it got it, is one it may send to. A Script never sees a host, port, node id, key or certificate.
  • One per Script: Load refuses a Script given two Grants of peer, as the Host error invalid value. Every Remote Send goes through the sending Script’s peer Grant, whichever Script’s reach made the Peer.
  • Always together: a Grant of peer that includes reach or expose includes post and call, since a send is known to be remote only when it runs, and one that includes expose includes caller.
  • Shapes: name is an Optional text, and address is text. exposure is text or a Host Object of kind peer. peer is a Host Object of kind peer. message is text, and args a list of any.
  • Transport is the Host’s own. This chapter fixes what Scripts see, not how a Remote Send travels, beyond what makes holding a Peer authority (chapter 9).
  • Identity: an exposure belongs to its owner, the Group, Script and named Grant. A named one also has its name, as a Serve Registration does. An unnamed one has none, so nobody can reach it.
  • expose name: makes the calling Script reachable as name and gives the Peer for that exposure once it is. Exposing a name the owner already holds gives the same Peer again. A name another owner holds fails with name in use. An empty name raises out of domain, with function "expose", before the call is charged.
  • expose with no name: makes a new unnamed exposure each time and gives its Peer, the only way to it. A Script hands it to another Group inside a Remote Send, as a reply-to or push channel.
  • unexpose exposure: withdraws the exposure that the text exposure names, or that the Peer exposure stands for, when the calling Script owns it. Unexposing one the owner doesn’t hold does nothing. A Remote Send already delivered is unaffected. Afterwards a call to it fails with send failed, reason not exposed, and a post to it is dropped.
  • Lifetime: an exposure lasts until it is withdrawn, the Script is stopped or its owner is disposed, as a Subscription does, or until the Grant that made it is revoked or disabled. A successful Reload keeps it, since the Script goes on. Nothing counts the Peers held for it elsewhere, so a Peer handed on never keeps it alive. A Host may cap a Grant’s exposures through its binding, failing expose with bad address.
  • Arrival: the receiving Host gives a post to the Exposed Script with Script.Deliver and a call with Script.Request, under the Selector it was sent with and its arguments. Handler Clauses and a Fallback Handler dispatch it as any Delivery, and the Run’s result is the reply.
  • caller: gives the Caller Identity: the data the receiving Host vouches for about who made the Remote Send that started the calling Run, such as {principal: "alice"}, or Nothing when the Host authenticated nobody. Only that Run has one. A Run started by a send in the Group, a Function Value call, a Join or any other Delivery gets Nothing, and a Script that hands the work on passes the identity as data. The Host decides what it vouches for, and this chapter fixes no keys. The identity is the sender’s own Host or connection, never the Script that handed it a Peer.
  • reach address: gives the Peer for the named exposure address names. It fails with bad address when the binding refuses the name, and with not exposed when no Script is exposed under it. An empty address raises out of domain, with function "reach".
  • post peer, message, args and call peer, message, args are what a Remote Send is (chapter 5). A Script may also call them directly. message is checked as a send’s computed name is, raising wrong kind or bad message name, and args as a Remote Send’s arguments are, before the call is charged. A Peer may sit at any depth in args, and in a call’s reply.
  • call’s failures: the Host fails call with send failed, with the reason and error of the receiving Request, or with reason mailbox full, not exposed or unreachable. post never fails in the Script.
  • Peers handed over: a Peer that arrives in a Remote Send’s arguments or reply is a Peer of the receiving Group for the same exposure. Within a Group there is one Peer per exposure, however it came, so is tells whether two Peers reach the same Script. A Peer for a Script of the receiving Group is still a Peer, and a send to it is still a Remote Send.
  • Saving: a Group may be saved with a call pending. After the restore, the Host settles it with Fail, send failed with reason unreachable, never with Reissue or Adopt (chapter 10). A Run that owes a remote reply is saved as one that owes a Request its reply, and the reply of a restored one is dropped. A Peer is resolved like any Host Object, and one the Host doesn’t resolve comes back disposed. The Host makes its exposures again on Restore, as it routes Subscriptions (ADR 0061), unnamed ones with the same identity, so Peers held for them in other Groups keep working.

Example.

-- in the billing Group
on start
ask peer to expose "billing" and wait
end start
on charge order
return {receipt: the id of order}
end charge
-- in a shop Group
on checkout order
ask peer to reach "billing" into billing and wait
send charge with order to billing into receipt and wait
end checkout

The send is a call through the shop Script’s peer Grant. If the billing Group’s Host can’t deliver it, send raises send failed with reason unreachable.

Example.

-- a browser Script
on start
ask peer to reach "chat" into server and wait
ask peer to expose into inbox and wait
send join with "#talk", inbox to server and wait
end start
on said channel, nick, text
say nick & ": " & text
end said
-- the chat server's Script, exposed as "chat"
on join channel, inbox
ask peer to caller
if it is nothing then throw {code: "forbidden"}
send said with channel, "server", the principal of it & " joined" to inbox
return true
end join

inbox is an unnamed exposure, so only a Script handed that Peer can send said to the browser Script. The server takes the nick from caller, which its Host vouches for, not from the arguments, and its send … to inbox is a post.

  • Standard Capability answers: each Host’s zone rules, Locale data and supported Locales are its own. The Trace records every answer, so a replay follows the Host it came from.
  • Per-call costs of Standard Capability Operations are set by each Host.
  • Store contents are each Host’s own, like its zone and Locale data. The Trace records what each store call gave.
  • sqlite results are each Host’s own SQLite’s, which a newer version can change, as can the reason of an sql error. The Trace records what each sqlite call gave.
  • Remote Sends travel by each Host’s own transport, and each Host decides what a Caller Identity holds. The Trace records what each peer call gave.
  • user answers are the person’s, and how a Host shows a prompt or a notification is its own. The Trace records what each user call gave.