Command line and REPL

Work in progress. These tools and this page are incomplete and subject to change.

The stardust command converts and formats documents, evaluates DUST, opens an interactive REPL, and serves nREPL clients. Evaluations run under CPU and memory limits.

For use from C or another host language, see Embedding and ABI.

See DUST for the language and the Function Index for its functions.

01 Installation and first use

Stardust builds from this repository with Nix. You need Git, Nix with the nix-command and flakes features enabled, and access to the repositories named by the flake inputs. The build uses pinned compiler and library versions. The Odin flake defines Linux and macOS targets for x86-64 and ARM64. Native process, stream, network and terminal services currently support Linux.

1.1. Build or install the command

From a checkout of the repository:

git clone https://git.bitflip.ai/stardustdb/mentat.git
cd mentat
nix build .#stardust
./result/bin/stardust --help

The executable is result/bin/stardust. Keep the Nix store paths reachable: this build uses the Nix runtime environment. Copying the executable alone is not a portable installation on a machine without its runtime dependencies.

To put stardust on your Nix profile's command path, run this from the checkout:

nix profile add .#stardust
stardust --help

To run without adding it to a profile, use nix run . -- --help. The stardust package installs the command-line tool. Build the shared library separately as described in Building the ABI library.

1.2. Run a DUST program

Save one expression in a file and evaluate it:

printf '(+ 20 22)\n' > hello.dust
./result/bin/stardust eval hello.dust

The result is 42. Start an interactive session with ./result/bin/stardust repl. Use the DUST reference for syntax and functions, and the command table for conversion, formatting, persistent databases and editor connections.

1.3. Build in the development shell

From the repository root:

nix develop
cd implementations/odin
task build
./build/stardust --help

task build produces the optimized, stripped CLI at implementations/odin/build/stardust relative to the repository root. The compiler uses -o:speed; this command also generates the prelude and native bridges. Use the pinned shell rather than a separately installed Odin compiler.

For an embedded application, continue with Embedding and ABI.

02 Command line

Command Does
stardust convert INPUT OUTPUT [--from FORMAT] [--to FORMAT] [--no-sort] [--schema PATH] Converts between formats or formats a document
stardust convert --from FILES --to FILES [--no-sort] [--schema PATH] Converts every file a path or glob names
stardust fmt [PATH...] [--write] [--check] [--from FORMAT \vert FILES] [--include GLOB] [--exclude GLOB] [--schema PATH] Formats DUST and RON files, keeping their key order
stardust eval FILE [--quiet] [--config FILE] [-- ARG...] Evaluates FILE form by form and writes each result as canonical DUST, stopping at the first error; --quiet writes only the program's own output (Script runner)
stardust run FILE [--config FILE] [-- ARG...] Runs a script: stardust eval --quiet
stardust repl [--config FILE] Starts the REPL
stardust nrepl [options] Serves editor clients over TCP
stardust namespace save PATH FILE --config FILE Validates and saves one namespace source file
stardust namespace read PATH --config FILE Prints saved source as canonical DUST
stardust namespace list [PREFIX] --config FILE Lists saved namespace paths and revisions
stardust namespace delete PATH --expected-revision TX --config FILE Deletes a namespace at the expected revision
stardust namespace apply FILE --config FILE Publishes one atomic batch of namespace changes

Use stardust eval --config app.dust query.dust to read a database from DUST. The configuration file app.dust names the database, for example {plugins {stdlib true database {path "app.db"}}} (Configuration files). The command preserves top-level locals between forms. Each form reads a fresh database snapshot. The database file persists after evaluation. See defquery for executable query examples. An import in the file names a .dust file beside it, or a saved namespace of the database. When both exist, the newer one is used (Files).

convert supports .json, .edn, .tron, .ron, and .dust. The input and output extensions select the formats. Using the same extension for both files writes a normalized representation. The output file is written only after the input has been parsed and converted successfully.

Use - for standard input or standard output. Specify standard input's format with --from FORMAT and standard output's format with --to FORMAT. The format names are json, edn, tron, ron, and dust. These options can also override a file extension.

Comments go through every format. DUST, RON and EDN write each comment as ; lines above its value. JSON and TRON keep all comments of a document in one $comment member, the first member of the root object. Its value is a JSON string. The string holds an object from the RFC 6901 pointer of each commented value to the text of its comment:

{"$comment":"{\"\":\"Spice math.\",\"/reserve\":\"reserve percent\"}","rates":{"arrakis":10,"caladan":15},"reserve":10}
  • When the root is not an object, or is an object whose only key is $value, the writer puts it in a wrapper: {"$comment": "…", "$value": root}.
  • A pointer has one step for each value. The step is the index of a list item, an invocation argument or a pointer segment; the key of a map member; or the name of a tag such as #quote or #link, which goes into its payload. For example, the 1 in {rule `(+ x 1)} is /rule/#quote/2. The "" pointer is the root.
  • A $comment member below the root is ordinary data.
  • A root $comment that is not such an object, or that has a pointer to no value, is an Invalid_Comment error.
  • A root object that has its own $comment key cannot go to JSON or TRON: the write fails with Reserved_Key. DUST, RON and EDN write the key as data.

DUST, RON and EDN read only ; lines as comments, and use the same comment rules. In DUST and RON, a $comment key is ordinary data.

A comment inside a template's payload is refused as Invalid_Comment: a ; line, in a template written as a tag or in a fenced template's embedded form, or a root $comment pointer into the payload.

stardust convert input.dust output.json
stardust convert input.dust - --to json
cat input.edn | stardust convert - output.dust --from edn
cat input.dust | stardust convert - - --from dust --to json
stardust convert input.dust - --to dust --schema schema.dust

--from and --to also take files. --from is then a path or a glob, and --to a path, or a directory followed by *.EXT or **/*.EXT. Each matching file is converted to the path it maps to: the --to directory, then, with **, the file's directories below the --from directory, then its name with the --to extension. Formats come from the extensions. Missing directories are created, an output that would not change is not rewritten, and two inputs that map to one output are an error before anything is written. A single --from file with a --to format name goes to standard output.

stardust convert --from order.ron --to order.dust
stardust convert --from 'data/**/*.json' --to 'out/**/*.dust'   # data/x/b.json -> out/x/b.dust
stardust convert --from 'data/*.json' --to 'out/*.ron'          # top level of data only

In a glob, *, ?, and [...] match within one name and a ** name matches any number of names, none included. ** does not enter hidden directories, and hidden files match only a name pattern that starts with ..

Run stardust convert -h for command help and examples.

DUST and RON output sorts map keys and the tags in a tag group, which gives the canonical form. --no-sort keeps both in source order instead. Either way a map's tag group comes first. A source that does not parse gives a #err diagnostic with its line and column on standard error and exit status 1.

--schema PATH reads a declarative schema snapshot and uses its shape order for DUST and RON output. --no-sort keeps source order and ignores the schema. fmt also keeps source order, so it reads the snapshot but does not apply its presentation. Parsing a schema snapshot never evaluates a DUST program.

fmt is convert from each file to its own format, dust or ron, with --no-sort, and its output ends with a newline, as editors save files: DUST output already does, and fmt adds one to RON output, which convert writes without one. A PATH is a file, a directory, or - for standard input (with --from dust or --from ron); with no PATH and no --from files, it is the current directory. A directory is searched recursively for files that match an --include glob (default *.dust and *.ron) and no --exclude glob. Hidden files and directories, build, and vendor are always skipped, and an excluded directory is not entered. A glob without / matches a name at any depth; one with / matches the path below the directory. --from also takes files, as for convert.

One file prints its result. --write (-w) rewrites each file whose result differs: it writes a temporary file in the same directory, gives it the file's permissions, and renames it over the file, so the file is never half written. Through a symbolic link it rewrites the target and keeps the link. --check writes nothing; it names each file formatting would change on standard error. Several files need --write or --check. A file that does not parse gives its path and a #err diagnostic on standard error, and the other files are still formatted. The exit status is 1 when any file failed or would change, and 2 for an invalid combination of options.

stardust fmt order.dust
stardust fmt --write order.dust
stardust fmt --check                                 # the current directory
stardust fmt --write src --exclude fixtures
stardust fmt --check . --include '*.dust'
stardust fmt --write --from 'src/**/*.dust'
cat order.dust | stardust fmt - --from dust

For example, with tags and keys out of order, and with a root list:

Input stardust fmt stardust convert ... --to dust
{b 1 a 2 <z x>} {<z x> / = b 1= / = a 2}= {<x z> / = a 2= / = b 1}=
[1 2 7] 1, 2, 7 on three lines the same

EDN lists and sets become arrays, while keywords, symbols, and characters become text. Map keys become strings. Numeric ratios and decimal values become floating point numbers; integers outside the supported range are rejected. EDN #inst values are represented by #utc, and #uuid values become native UUIDs. Other EDN tags retain their tag and value as DUST tagged elements. DUST tags are written as EDN tagged elements when their names can be read as EDN tags; otherwise they are represented as maps. These mappings do not preserve all original EDN types. Only the first EDN form is read; an empty input reads as nil.

TRON encodes JSON-compatible values as a binary document. Floating-point values retain their numeric kind, including integral floats such as 1.0. This can differ from encoders that normalize integral floats to integers. A Bytes value, #b64 in text formats, is written as binary data and read back as Bytes.

Each REPL session can use 1 GiB of memory. stardust eval can use 256 MiB. An nREPL session, and a REPL or eval with database storage, can use the memory limit of its database. Exceeding the budget produces an error. Sessions retain top-level locals and namespaces between evaluations. !reset starts a fresh session.

2.1. Selecting plugins

eval, run, repl, nrepl, test, request and namespace take their plugins, capabilities and database from one configuration file: --config FILE (Configuration files). There are no separate options for plugins or a database.

Without --config, the CLI selects every plugin except backups: stdlib, io, database, planner, sdks, skills, retention, blackholes, objects and lsp. It grants the capabilities that io uses: filesystem, secure random, processes, streams, network and terminal. The database plugin has no storage settings, so evaluation works and each database operation fails with no_database. When a command opens a database, lsp listens on port 1980, or the next free port, and writes its warning to standard error (Editor integration). The sdks plugin generates nothing without a configured language, and skills writes nothing without dir; retention removes no history without configured fields. The objects plugin requires database, and its operations use database ABI requests. The backups plugin requires database and cannot be selected with retention; select it in a configuration file. On Windows, a file backup target refuses the open with backups: the file target is not supported on Windows (Backups).

A configuration file selects only the plugins that its plugins map names and grants only the capabilities that it lists. stdlib adds library functions, including seeded random, lexical paths and pure cryptography. io adds host-backed operations and requires stdlib. The database plugin provides named queries and mutations. planner adds query planning and requires database. The plugin reference lists the members and dependencies from the registered plugin catalog. With an empty plugins map, core expressions, unqualified collection operations and native values remain available. defquery and defmutation require database. The sdks development plugin takes its settings in the configuration.

Unknown names and missing requirements are errors before evaluation begins.

{plugins <stdlib>}
stardust eval --config stdlib.dust text.dust
stardust eval arithmetic.dust

For example, (+ 20 22) works with an empty plugins map, while (strings/case "upper" "arrakis") requires stdlib and returns "ARRAKIS". Calling a function of a plugin that is not selected reports #err <name unbound>. Selection also applies to loaded files, interactive sessions and database evaluations. A smaller selection does not reduce the size of the installed executable.

2.2. Configuration files

A configuration file contains the map that stardust_open takes (Configuration and codecs). Its keys are workers, requests, sessions, batch-size, limits, plugins, capabilities, scheduled-reactors and imports. Its extension selects the notation: .dust, .json, .edn, .ron or .tron. An unknown or incorrect setting stops the command.

The settings of the database plugin give the storage. {path FILE} opens a database file. {temporary true} opens a temporary database, which the command deletes when it stops. Without these settings, there is no storage: evaluation works, and each database operation fails with no_database. A top-level path is refused.

imports {roots [DIRECTORY ...]} adds import roots. An import reads only .dust files under a root (Files). For eval and run, the first root is the directory of the program's file. For repl and nrepl, it is the working directory. This setting adds the other roots. A relative directory is relative to the directory of the configuration file. A directory that does not exist stops the command. The database does not use this setting.

{plugins <io stdlib> capabilities {filesystem true} imports {roots [".."]}}

The repository's scripts in tools/ import lib/ with tools/stardust.dust, whose root is the repository: stardust run --config tools/stardust.dust tools/check-fmt.dust.

The namespace commands refuse a configuration without path. eval, run and repl evaluate against the database when the configuration has storage, and without a database otherwise. nrepl, request and test open the database of the configuration, with or without storage.

{sessions 8 plugins {<stdlib io> database {path "arrakis.db"}} capabilities {filesystem true}}
stardust namespace list arrakis --config arrakis.dust
stardust nrepl --config arrakis.dust --port 7888

2.3. Script runner

stardust eval FILE -- ARG... runs a DUST program as a script. It writes the result of each form, as eval always does. With --quiet, it writes only the output that the program writes itself, for example with io/stdout/println. stardust run FILE -- ARG... is stardust eval --quiet FILE -- ARG.... A script can start with a shebang line such as #!/usr/bin/env -S stardust run.

stardust run report.dust -- --count 10 dune.dust
stardust eval --quiet --config tools/stardust.dust tools/client.dust -- 7888
stardust eval --config app.dust seed.dust

Without --config, the program has every plugin except backups and the filesystem, process, stream, network and terminal grants. A configuration file gives only the plugins and grants that it lists (Selecting plugins).

These script features work with and without a database:

  • cli/args returns the arguments after FILE. Put -- before the first argument that starts with -.
  • scripts/path returns the absolute path of FILE.
  • The first line can be a shebang line.
  • The hooks that processes/on-exit registers run when the program stops.
  • INT, TERM, HUP or QUIT stops the program. The process groups of its child processes receive the signal, the hooks run, and the command restores its signal handlers and ends by that signal. The command waits for each child to exit; a child that has not exited 2 seconds after the signal receives SIGKILL.

A program uses a library file with import. The path is relative to the program's file, not to the working directory. In tools/client.dust, (import {nrepl "../lib/nrepl"}) names lib/nrepl.dust, and only its exports are visible. The directory of the program's file is its import root. This import thus needs a configuration whose imports roots include the parent of lib/, as tools/stardust.dust does (Configuration files). With database storage, the newer of the file and a saved namespace of the path is used (Files).

The program keeps its top-level locals between forms. It stops at the first failure or returned #err, which it reports as eval does (Errors and positions). An assertion failure gives status 1; processes/exit selects a status from 0 to 255.

When the --config file has database storage, the program runs in one session of that database, through the requests of the ABI (Scripts in sessions). sessions/open gets the arguments and the path. Each form is one eval request. A signal sends cancel with the signal for the running request, and sessions/close runs the hooks. The memory and CPU limits of the database apply to each request. Without storage, the program runs in the stardust process.

A configuration file must select io and grant its capabilities to use these services in eval, run, repl and nrepl. See DUST's process, stream and utility contracts. Process, stream, TCP and terminal operations currently support Linux.

2.4. Generated function tests

stardust test FILE selects top-level function definitions and expressions in a DUST file and runs the shared check operation. Non-function definitions remain available during preparation. Preparation uses a read-only database session with no filesystem, network, or process grants, whatever the configuration grants. A configuration with path supplies namespace imports from that database and reads it at a fixed snapshot, so the tests cannot write it. Without storage, a write fails with no_database.

stardust test functions.dust --seed 42 --cases 1000 --size 256
stardust test functions.dust --replay 'BLOB'

The defaults are seed 0, 1,000 cases, and size 8,192. Each check retains the existing database request limits, including five seconds of CPU. Large runs can reach that limit; reduce --cases to fit the available budget. An incomplete run exits 3. Hosts can configure their request limits when opening the database. Replay cannot be combined with generation flags. For one selected function the command prints its complete native report. For several functions it prints a named report for each, followed by a summary. Replay selects the first function whose definition and schema snapshot match the blob. A file with no functions is unsupported.

Exit Meaning
0 All selected checks passed
1 A generated case failed
2 A selected function is unsupported
3 Invalid input, snapshot mismatch, or an interrupted/incomplete operation

Reports retain minimized inputs, modeled effects, before/after state, shared schema diagnostics, and replay blobs. See check for supported contracts, isolation, resource limits, and replay rules. The command does not grant tested functions access to real host effects.

2.5. nREPL server

Start a server for an editor client:

stardust nrepl --config arrakis.dust
stardust nrepl --config arrakis.dust --port 7888
stardust nrepl --config arrakis.dust --bind 127.0.0.1 --port-file /tmp/stardust.port

All sessions of the server use the database that --config describes (Configuration files). Because each session is a database session, queries, mutations, saved namespaces and exported queries are available when the configuration has storage. Without storage, sessions evaluate code. A query or a mutation then returns #err <database no>, and save and subscribe report no database in ex. With {plugins {database {temporary true}}}, the server uses a temporary database and deletes it when it stops. The sessions setting limits the number of open sessions. An evaluation without a session uses a new session for that request only. A different program that uses the same database file sees what the sessions write and save. The editor connection of the lsp plugin is an example.

The default address is 127.0.0.1 and the default port is 0, which asks the operating system to choose a port. The server writes that port to .nrepl-port in the current directory, or to the path given by --port-file. On shutdown it removes the file only if it still contains this server's port. The protocol has no authentication; choose the bind address accordingly.

Messages use bencode. These examples show their contents as maps:

client -> {op "clone", id "1"}
server <- {id "1", new-session "s-1", status ["done"]}

client -> {op "eval", id "2", session "s-1", code "(+ 1 2)\n(+ 3 4)"}
server <- {id "2", session "s-1", value "3"}
server <- {id "2", session "s-1", value "7"}
server <- {id "2", session "s-1", status ["done"]}

An import in eval names a file relative to the directory of the request's file. Without file, it names a file relative to the working directory of the server. When the database also has a saved namespace of the path, the newer one is used (Files). The server reads imported files from its own disk, and only under its import roots: its working directory and the imports roots of its configuration. The root does not follow file or file-path: a client cannot read a file outside the roots, whatever grants the configuration gives.

load-file evaluates file, the full text of a file, as the session's code, as the nREPL specification defines the operation. Each form returns its value as in eval. An editor can send an unsaved buffer. The imports of the text name files relative to the directory of file-path, and file-path names the source in error responses. In this example, app/lib/shapes.dust exports square:

client -> {op "load-file", id "3", session "s-1", file "(def unit 7)\n(* unit 2)", file-path "app/main.dust", file-name "main.dust"}
server <- {id "3", session "s-1", value "unit"}
server <- {id "3", session "s-1", value "14"}
server <- {id "3", session "s-1", status ["done"]}
client -> {op "eval", id "4", session "s-1", file "app/main.dust", code "(import {s \"lib/shapes\"})\n(s/square 3)"}
server <- {id "4", session "s-1", value "null"}
server <- {id "4", session "s-1", value "9"}
server <- {id "4", session "s-1", status ["done"]}

A failure in an imported file comes in ex, with file, line and column in that file. lookup reports the name and type of a symbol from the session or the core libraries:

client -> {op "lookup", id "5", session "s-1", sym "math/abs"}
server <- {id "5", session "s-1", info {name "math/abs", type "function"}, status ["done"]}

If the name is unknown, the response omits info.

describe maps each operation name to a descriptor. The descriptors are empty unless the request has verbose?, which adds each operation's doc and, for eval, its requires, optional, and returns fields:

client -> {op "describe", id "6"}
server <- {id "6", ops {clone {}, close {}, describe {}, eval {}, interrupt {}, load-file {}, lookup {}, save {}, stdin {}, subscribe {}}, status ["done"]}

subscribe sends the result of a query immediately and after each commit that changes it, as queries/subscribe does (Database requests). To name an exported query, give ns, query and optional args, a DUST list. Or give a query map in code. Each event is a value with its tx. An interrupt with the ID of the request, or close of the session, ends the subscription. Its last message has status ["interrupted" "done"]:

client -> {op "subscribe", id "7", session "s-1", ns "dune/people", query "older", args "[18]"}
server <- {id "7", session "s-1", tx "4", value "[]"}
server <- {id "7", session "s-1", tx "8", value "[[\"Leto\"]]"}
client -> {op "interrupt", id "8", session "s-1", interrupt-id "7"}
server <- {id "8", session "s-1", status ["interrupted" "done"]}
server <- {id "7", session "s-1", status ["interrupted" "done"]}

save publishes the DUST source in file as the namespace ns, as namespaces/save does (Namespace files). Add revision to require the current revision of the namespace. The revision 0 requires that the namespace does not exist. The value is the result of the save. A failure comes in ex, with its position in file:

client -> {op "save", id "9", ns "dune/people", file "(defquery older [minimum] {find [?n] <tuples> where [[?e name ?n] [?e age ?a] (> ?a minimum)] order-by [?n]})\n(export older)"}
server <- {id "9", value "{namespaces [{<!deleted> entity #link 1 path \"dune/people\" revision 4}] tx 4}"}
server <- {id "9", status ["done"]}

eval with ns evaluates the code in the scope of the namespace of a file that the session imported. ns is the path of the file, relative to the working directory of the server, with or without .dust, such as ns "app/lib/shapes". The private definitions of the namespace are then visible (eval namespace in Namespace files). The server ignores an ns that names no imported file.

clone starts a fresh session; copying a session is unsupported. eval returns each top-level form's result separately, as one DUST form: a list keeps its brackets, so [1 2 (+ 3 4)] returns [1 2 7] and [] returns [], and map keys are in canonical order. A session keeps the top-level locals that its evaluations define. A returned #err is a DUST value: it arrives in value, with file, line, and column for its source. Parse, compilation, and evaluation failures arrive in ex. interrupt stops an evaluation at a checkpoint and leaves the session usable. Completed mutations are not rolled back. Run stardust nrepl -h for the options and examples.

eval writes each form's result to standard output and exits with 0. It stops at the first form that fails or returns an #err value, writes the error to standard error as a #err element, and exits with 1. Results written before that form stay on standard output. A returned #err gets the line and column of its top-level form, unless it has its own line or column. A parse or compile failure gives the position of the source that failed; other failures, such as an exceeded memory limit, have no position. With database storage in --config, each failure after parsing arrives as an #err value and gets the position of its top-level form. run reports errors in the same way:

$ echo '(/ 1 0)' > zero.dust
$ stardust eval zero.dust
#err {<division integer zero>
      column 1
      line 1
      message "division by zero"}

The tag group classifies the failure; the other members are diagnostics. See error tags for every tag set.

03 Editor integration

The lsp plugin serves the Language Server Protocol to editors and agents while a database is open. Editor integration lists its settings. Start a server that keeps the database open, and connect the editor to the port:

stardust nrepl --config arrakis.dust
{plugins {<stdlib io> database {path "arrakis.db"} lsp true}}

Without port, the plugin listens on port 1980. If a different process uses 1980, the plugin tries 1981, 1982 and so on up to 65535, and uses the first port that is free. A port setting selects one port: if that port is in use, the database does not open. The startup warning on standard error gives the port, for example stardust: warning: plugin lsp listens on 127.0.0.1:1981 .... The stardust/status request also reports it. To give the port to an editor script, set port-file: the plugin writes the port to that file, as the nREPL server writes .nrepl-port. An editor connects to 1980 by default. Set the port of the editor when the warning gives a different port.

The socket has no authentication. A peer that connects can evaluate code and write the database. Keep the default loopback address if the network is not trusted.

3.1. Buffers and namespaces

A buffer holds a namespace when its URI names one:

  • file:///<root>/<path>.dust is the namespace <path>, for a file below the definitions root. The root is the workspace folder. The definitionsRoot initialization option can name a different folder, relative to the workspace folder. dune/houses.dust is the namespace dune/houses.
  • stardust://namespaces/<path> is the saved namespace <path>. The editor reads its text with workspace/textDocumentContent. Add ?asOf=T for the revision at transaction T. When you save such a buffer, the server publishes the namespace. When you rename it, the server moves the namespace. A filesystem provider sends stardust/renameNamespace with oldUri and newUri and waits for its response before it reports success. Set initializationOptions.namespaceFileOperations to true when the provider sends this request. The server then ignores workspace/didRenameFiles from that client to prevent a second move. Other clients can use workspace/didRenameFiles to move a namespace.
  • stardust://entities/<id> shows the fields of entity <id> as DUST. The server reads them with entities/read. Add ?asOf=T for the entity at transaction T. You cannot change this document.

The server decodes each .dust buffer at each change. A syntax error is a diagnostic immediately. Then namespaces/check examines a namespace buffer against the other saved namespaces of the database. The editor shows each form that does not compile and each unavailable name. This includes a removed export that a saved namespace still imports. The server publishes such an error in the namespace that imports the changed one: in its open buffer, or else in its stardust://namespaces/<path> document. The error is at the form that uses the changed name, and its relatedInformation points at the change. After each namespace save, from this editor or from a different client, the server examines each open namespace buffer again and sends its new diagnostics. Each diagnostic has the error code in code, and the namespace, form and cell in data. While a buffer has a syntax error, features that need a parse use the last text that decoded. Positions count UTF-8 bytes when the client gives utf-8 in positionEncodings. Otherwise, they count UTF-16 code units.

3.2. Saving and conflicts

The stardust.namespaces.save command, with {uri}, publishes the buffer with namespaces/save. It sends the base revision of the buffer as expected-revision. This is the revision when the buffer opened, or the revision of its last save. With paths, a list of URIs, the command publishes many buffers in one atomic save. If a different client saved the namespace first, the command returns {error category "conflict" path expected actual} and publishes nothing. stardust.namespaces.overwrite saves without the revision check. The command registry marks it as a command that the user must confirm. With saveOnDidSave true in the initialization options, a save in the editor also publishes the file. Sessions use a saved namespace at their next evaluation. Named subscriptions use it at their next event.

3.3. Live interaction

Each connection has a database session. The session opens at the first session command and closes with the connection. A session argument names a different session. The commands take their input as the first argument object of workspace/executeCommand:

Command Input Requests Result
stardust.forms.evaluate uri and range, position (the top-level form) or neither (the whole buffer) namespaces/load of the buffer, then one eval per form with namespace {values [{text error range}]}
stardust.namespaces.load uri, optional alias namespaces/load with forms {path alias exports}
stardust.sessions.reset optional session sessions/reset {}
stardust.queries.subscribe uri and position of a defquery or query map, or namespace, name and args queries/subscribe {subscription}
stardust.queries.unsubscribe subscription cancel {}
stardust.expressions.evaluate programText, optional bindings eval without a session {values [{text error}]}
stardust.queries.run queryText, a query map, optional bindings query {rows pages}, after a stardust/queryPage notification for each page
stardust.transactions.apply mutationText, optional bindings and dryRun transact {tx result}; with dryRun true, {tx null dryRun true result}
stardust.schemas.validate valueText and schemaText or name schemas/valid? {valid diagnostics}
stardust.namespaces.save, stardust.namespaces.overwrite uri or paths namespaces/save {tx namespaces}
stardust.namespaces.reload uri namespaces/read Replaces the buffer with the saved source

stardust.forms.evaluate loads a namespace buffer into the session without the selected forms. Then it evaluates each selected form in the scope of the namespace, where private definitions are visible. Each result is an inlay hint at the end of its form and a stardust/evaluationResult notification. The hint stays until the text of the form changes or the session resets. A failure or a returned #err value is a diagnostic with the source stardust eval. A subscription sends stardust/queryEvent {subscription uri event tx rows result} for each event. At its end, it sends {subscription done error}. Its form shows live · N rows · tx T. The subscription ends with stardust.queries.unsubscribe, when its buffer closes, or with the connection. Results are DUST text.

textDocument/codeLens puts Evaluate above each top-level definition and Subscribe above each defquery. When the database reports reactors (reactors/status), a defreactor form also shows its runs, changes and failures. textDocument/codeAction gives the commands as source actions. It renames an unavailable imported name to the nearest export of its namespace. After a save conflict, it gives Reload from database and Save anyway.

With dryRun true, stardust.transactions.apply sends transact with dry-run true. The dry run writes nothing, and result shows the changes that the transaction would make (Database requests). The VS Code extension shows this preview first, and applies the transaction only after the user confirms it.

$/cancelRequest cancels the database requests of a command. A command that committed still returns its result. When every database request slot is busy, a command waits for a free slot instead of failing. Waiting commands send each ready database operation to the end of the queue. Those operations start in the order that they were queued. A command can wait for as long as every slot stays busy, for example while live queries hold all the slots. $/cancelRequest removes a waiting command, and the reply says that the request was cancelled. When the connection closes, its waiting commands are removed and do not run. stardust/capabilities returns the command registry. For each command, the registry gives its request, whether the command has a preview (stardust.transactions.apply with dryRun), and whether the client must ask the user first, as for stardust.transactions.apply and stardust.namespaces.overwrite. Session commands and saves use worker zero. A long evaluation delays them. The commands without a session run on any worker.

3.4. Editor features

The server also replies to these requests. It uses the last text of the buffer that decoded:

  • textDocument/semanticTokens/full and range color each DUST value, comment and builtin call. There is no other highlighting.
  • textDocument/formatting and rangeFormatting return one edit to the stardust fmt form (Formatting). A range formats the top-level forms that it touches. A CRLF buffer stays CRLF.
  • textDocument/documentSymbol, foldingRange and selectionRange show the top-level definitions, the containers over several lines and comment runs, and the values that hold a position.
  • textDocument/hover, signatureHelp, completion and completionItem/resolve use the function documentation of DUST in the binary, the definitions of the buffer and programs/names.
  • textDocument/definition, references and documentHighlight find a top-level name of the buffer. For alias/name, they find the declaration of the export in an open buffer of the namespace or in stardust://namespaces/<path>. The references of an export include the open buffers that import it.
  • A local name goes to its nearest binding. A let, for or loop binding vector, or a fn, defn or defmacro parameter vector, binds a local name. Completion gives the local names around the position, the innermost first.
  • The definition of a #link value is its stardust://entities/<id> document.
  • textDocument/prepareCallHierarchy, callHierarchy/incomingCalls and outgoingCalls show the calls between the defn forms of the open buffers. An incoming call from a different namespace calls alias/name.
  • stardust/entityBacklinks {entity asOf} and stardust/entityHistory {entity field limit asOf} return the results of entities/backlinks and entities/history. entity is an entity ID or a stardust://entities/ URI. Each value and link is DUST text. Each entity has its uri.
  • workspace/symbol lists the saved namespaces and their exports.

3.5. Editors

  • VS Code: task vscode:install builds and installs the stardust extension (tools/vscode/stardust). The extension registers dust and ron. It connects to stardust.host and stardust.port (default 1980). stardust.saveOnDidSave and stardust.definitionsRoot become initialization options. Ctrl+Enter evaluates the form or the selection. Ctrl+Alt+S saves the namespace. You can open, save and rename stardust://namespaces/<path> documents as files. Results show after their forms. Query events show in the Stardust output channel.
  • Neovim: add tools/neovim to runtimepath and call require('stardust').setup({ port = 1980 }). It connects with vim.lsp.rpc.connect and turns on inlay hints and code lenses. It adds these commands: :StardustEval, :StardustLoad, :StardustSave[!], :StardustSubscribe, :StardustUnsubscribe and :StardustReset.
  • Emacs: load tools/emacs/stardust.el after dust-mode. It adds an Eglot contact for dust-mode and commands under C-c C-d.
  • Helix and other clients that start a server process connect through a byte bridge:
[[language]]
name = "dust"
scope = "source.dust"
file-types = ["dust"]
comment-token = ";"
language-servers = ["stardust"]

[language-server.stardust]
command = "nc"
args = ["127.0.0.1", "1980"]

Clients without an extension can evaluate, save and subscribe, because each feature uses standard requests, code actions and inlay hints.

04 Namespace files

A saved namespace is a source file identified by a path, such as arrakis/spice. Keep related helpers, queries and other definitions together. Use import to declare dependencies and export to select the public names.

For example, save the spice and shipping sources from the language reference. The configuration file arrakis.dust names the database:

{plugins {stdlib true database {path "arrakis.db"}}}
stardust namespace save arrakis/spice spice.dust --config arrakis.dust --expected-revision 0
stardust namespace save arrakis/shipping shipping.dust --config arrakis.dust --expected-revision 0
stardust namespace list arrakis --config arrakis.dust
stardust namespace read arrakis/spice --config arrakis.dust
stardust eval run.dust --config arrakis.dust

The run.dust file imports shipping and calls its function:

DUST
(import <arrakis/shipping>)
(shipping/shipment 1000)
→
RON
[#invoke [import <arrakis/shipping>] #invoke [shipping/shipment 1000]]

The result is 900.0. Paths are case-sensitive, slash-separated names. List prefixes match complete path segments: arrakis includes arrakis/spice, while arra does not. Reading prints the authored forms without synthetic outer list brackets, preserving comments and function documentation.

4.1. Atomic updates

Use apply when multiple files must change together. The file contains one ordinary DUST data map; it is not evaluated:

DUST
{changes [
  {path "arrakis/spice"
   expected-revision 0
   forms [(def reserve-percentage 10)
          (defn usable-spice [harvest]
            (/ (* harvest (- 100 reserve-percentage)) 100))
          (export usable-spice)]}
  {path "arrakis/shipping"
   expected-revision 0
   forms [(import <arrakis/spice>)
          (defn shipment [harvest] (spice/usable-spice harvest))
          (export shipment)]}]}
→
Canonical DUST
{changes [{expected-revision 0
           forms [(def reserve-percentage 10)
                  (defn usable-spice [harvest] (/ (* harvest (- 100 reserve-percentage)) 100))
                  (export usable-spice)]
           path "arrakis/spice"}
          {expected-revision 0
           forms [(import <arrakis/spice>) (defn shipment [harvest] (spice/usable-spice harvest))
                  (export shipment)]
           path "arrakis/shipping"}]}
→
RON
changes [{expected-revision 0
          forms [#invoke [def #local reserve-percentage 10]
                 #invoke [defn #local usable-spice
                          [#local harvest]
                          #invoke [/ #invoke [* #local harvest #invoke [- 100 #local reserve-percentage]] 100]]
                 #invoke [export #local usable-spice]]
          path arrakis/spice}
         {expected-revision 0
          forms [#invoke [import <arrakis/spice>]
                 #invoke [defn #local shipment [#local harvest] #invoke [spice/usable-spice #local harvest]]
                 #invoke [export #local shipment]]
          path arrakis/shipping}]
stardust namespace apply install.dust --config arrakis.dust

Use a fresh database for this installation example. expected-revision 0 requires that the path does not yet exist. To replace an existing namespace, omit expected-revision or supply its current revision from list. A stale revision reports conflict and publishes nothing.

Change the reserve to 15 and rename usable-spice to shippable-spice in both namespaces together:

DUST
{changes [
  {path "arrakis/spice"
   forms [(def reserve-percentage 15)
          (defn shippable-spice [harvest]
            (/ (* harvest (- 100 reserve-percentage)) 100))
          (export shippable-spice)]}
  {path "arrakis/shipping"
   forms [(import <arrakis/spice>)
          (defn shipment [harvest] (spice/shippable-spice harvest))
          (export shipment)]}]}
→
Canonical DUST
{changes [{forms [(def reserve-percentage 15)
                  (defn shippable-spice [harvest] (/ (* harvest (- 100 reserve-percentage)) 100))
                  (export shippable-spice)]
           path "arrakis/spice"}
          {forms [(import <arrakis/spice>)
                  (defn shipment [harvest] (spice/shippable-spice harvest))
                  (export shipment)]
           path "arrakis/shipping"}]}
→
RON
changes [{forms [#invoke [def #local reserve-percentage 15]
                 #invoke [defn #local shippable-spice
                          [#local harvest]
                          #invoke [/ #invoke [* #local harvest #invoke [- 100 #local reserve-percentage]] 100]]
                 #invoke [export #local shippable-spice]]
          path arrakis/spice}
         {forms [#invoke [import <arrakis/spice>]
                 #invoke [defn #local shipment [#local harvest] #invoke [spice/shippable-spice #local harvest]]
                 #invoke [export #local shipment]]
          path arrakis/shipping}]
stardust namespace apply update.dust --config arrakis.dust
stardust eval run.dust --config arrakis.dust

The result is now 850.0. Existing loaded aliases and retained exported function references see this valid version on their next invocation.

Every batch checks its imports, exports, initializers and affected saved dependents together. Removing shippable-spice while shipping still requires it fails the batch. Correct the source or change shipping in that same batch, then retry. The previous valid version remains available after a rejected save. An unchanged source is a successful no-op and retains its revision. An empty changes [] batch succeeds with tx null and no namespace entries.

Delete with the revision reported by list:

stardust namespace delete arrakis/shipping --expected-revision 12 --config arrakis.dust

Replace 12 with the actual revision. A dependent namespace must also be updated or deleted in the same apply batch before its dependency can be deleted.

4.2. Historical reads and sessions

read and list accept --as-of TX-OR-UTC:

stardust namespace read arrakis/spice --as-of 12 --config arrakis.dust
stardust namespace list arrakis --as-of 2026-11-08T12:00:00Z --config arrakis.dust

These bounds select application transactions. A UTC timestamp selects the latest transaction at or before that instant. A bound before the first save sees no namespace; a future bound selects the current head.

Clients can use the same operations through the database request interface:

Method Parameters Result
namespaces/read path, optional as-of and saved path, entity link, revision, source forms list, exported names as tags, and with saved true the saved time
namespaces/list Optional segment prefix, as-of and saved Ordered list of path, entity, revision, exports, and with saved true the saved time
namespaces/save changes list tx or null and ordered namespaces entries
namespaces/load session, path, alias, optional as-of or forms; or session and sources Path, alias, revision and exports; with sources, {namespaces [{path exports}]}
namespaces/check changes list, optional initialize, analysis and as-of valid, diagnostics and, with analysis true, analysis

Each save entry contains its path, entity link, revision and deleted boolean. Source forms are data, including quoted expressions, comments and function definitions. Saving a definition does not invoke it. A change with forms may give its comments as a comments map instead, from the JSON Pointer of each value to its text, such as {"/0" "Keep spice."}. A pointer counts the source forms from /0, map members by key and tagged payloads by tag name, as in /0/2/#quote/1. A pointer that names no value reports invalid_comment with its pointer; forms that also carry comments report invalid_source.

A namespace stores its comments apart from its source, so a save that changes only comments is a new revision, and a save that changes neither publishes nothing. Separate requests in a submission batch are separate operations; put every coordinated change in one namespaces/save request.

Source-file and notation clients send written (fn ...) expressions. The distinct native function-definition kind is preserved by stored source and owned database requests/results, but notation encoders currently reject that kind. They do not serialize running functions or captured environments, and do not silently change a native definition into a different kind.

namespaces/check validates changes as namespaces/save does, but saves nothing. It examines the changed namespaces against the other saved namespaces. A removed export that a saved namespace still imports is a diagnostic of that namespace. The request reports each form that does not compile and each unavailable name as {code message path name dependency position}. A failure that stops validation, for example an import cycle, is the last diagnostic. An old expected-revision is a conflict diagnostic. Initializers run only with initialize true. With analysis true, the result also has the declarations, imports, references and exports of each changed namespace. Each item has its form-index, source-index and span. An editor uses this request to examine a buffer while the user types.

{method "namespaces/check" params {changes [{path "dune/new" forms [(defn a [] missing) (export a)]}]}}
; result {valid false diagnostics [{code "name_unbound" path "dune/new" name "missing" message "missing" position {form-index 0 source-index 5}}]}

namespaces/load with a forms list loads unsaved source as the namespace path, in that session only. It saves nothing. The source replaces the saved source for the namespace and for each namespace that imports it. This continues until the session loads the namespace again or resets. The revision of the result is null. If the source does not compile, the load reports the error and keeps the source that the session loaded before. An editor uses this to try a buffer before it saves the buffer.

namespaces/load with sources loads several unsaved namespaces together, without an alias. sources is a list of {path forms} entries. Each entry with forms loads that source as the namespace path, as forms does. An entry without forms removes the unsaved source of path, and the saved one, if any, applies again. One refresh applies all entries, so the entries can import each other in any order. When the refresh fails, the session keeps its sources. This request needs no storage when no source imports a saved namespace. The CLI and the nREPL server use it to load the files that an import names (Files):

{method "namespaces/load" params {session 1 sources [{path "home/ada/app/lib/shapes" forms [(defn square [x] (* x x)) (export square)]}]}}
; result {namespaces [{exports <square> path "home/ada/app/lib/shapes"}]}

saved true in namespaces/read and namespaces/list adds saved, the time of the transaction that saved the namespace, as a #utc value. A namespace without a recorded time has no saved member.

eval with a namespace path evaluates code in the scope of that namespace, as code inside the namespace. The private definitions and import aliases of the namespace are visible. The locals and aliases of the session are not visible. The namespace is the forms that the session loaded, if any. Otherwise, it is the saved source. Each request runs the top-level forms of the namespace again in a new scope, without host effects, as a load does. Definitions that the code makes stay in the scope of that request.

{method "namespaces/save" params {changes [{path "dune/houses" forms [(def secret 7) (defn shown [] (* secret 2)) (export shown)]}]}}
{method "eval" params {code [secret (shown)] forms true namespace "dune/houses"}}
; result [7 14]

sessions/open may select an as-of transaction Integer or native UTC value. namespaces/load can select it for an otherwise live session. The selected context covers all code, transitive imports and database queries, and remains fixed as later commits arrive. The session reads one database snapshot until it closes or resets, so no later write or history removal changes what it reads. While it is open, the database cannot reuse the pages of that snapshot, and the file can grow. A conflicting nested query or request reports <snapshot mismatch>. Historical contexts cannot save or delete namespaces. sessions/reset clears the context, loaded aliases and locals. A missing historical definition never falls back to the current one.

A failed request's result is an #err value with a code, a message and the diagnostic's members when available: the path, position, referenced export or import cycle (Errors and positions). If a storage failure reports outcome "unknown", reopen the database and read the revisions before deciding whether to retry.

4.3. Errors and positions

Every failure a request reports is one value: the result is #err of a map, whatever failed. code is the failure's code as a set of words, such as <unknown method>, <invalid params>, <cancelled>, <resource limit>, <invalid program> or <mismatch type>; message is its text, when it has one; position says where the failing form is, only when that is known. A namespace diagnostic adds its path and name; an unsupported ABI adds supported [1]. Inside DUST an error is #err {<tags> message …}; a published response moves the tags into code, so (count 3) evaluates to #err {<mismatch type> message "…"} and arrives as #err {code <mismatch type> message "…" position {…}}. Every #err in a result takes this form; only the value eval returns, or each value of a forms true list, carries a position. Publishing never replaces what the program wrote: a payload that is no map, or that itself names code, position or value, is kept whole under value, so #err 42 arrives as #err {code {} value 42}. The position's members are:

Member Meaning
request The UUID of the request whose params.code holds the form
path, revision The stored namespace whose source holds the form
form-index The namespace's top-level form that holds it, counted from 0
source-index The form's cell: an index into its request Document or the namespace's forms list, the list itself being 0
span [start end], the form's byte range in the text the request was decoded from

A request decoded with spans true has spans; one decoded without them, or built from values, has source-index alone. Byte offsets count UTF-8 bytes. Hosts that need a line and column compute them from their own copy of the text.

For example, a request can contain a failing call:

{message-id #uuid "00000000-0000-4000-8000-000000000001"
 method "eval"
 params {code (count 3)}}

Its response contains this result:

#err {code <mismatch type>
      message "count requires a list, map, string, bytes, or null"
      position {request #uuid "00000000-0000-4000-8000-000000000001"
                source-index 8}}

A function defined by an earlier request of the session raises its error in that request: the position names the earlier request's UUID and its cell, so source-index and span are read against that request. A form a macro received keeps the position the user wrote it at; a form the macro made is positioned at the macro call.

With forms true, each failing form's value carries its own position.

A function of a loaded namespace raises its error in the namespace's stored source: the position names its path and revision, the form-index and the source-index among its forms, as namespaces/read returns them, and no span, since the store keeps forms rather than text. The conformance/abi/positions/imported-function case shows a batch that saves, loads and calls one. A diagnostic of namespaces/save or namespaces/load has its path beside the code and its form-index, source-index and span under position.

Nothing is fabricated. A cancellation, #err {code <cancelled>}, an exhausted memory or CPU limit, an error in a function a document carried as data, and a lookup of an unbound name have no position. Each session keeps the positions of the sources it compiled, up to 65,536 sources and 4 MiB of spans, within its memory limit; past those, later sources have cell indices without spans, or no position.

Each database keeps up to 65,536 request identities for source positions in a fixed table. A collision removes the older identity. Returned Documents do not change. User errors do not expose LuaJIT or generated code messages.

05 Database requests

A client submits request Documents to an open database and polls response Documents. Each request has a UUID message-id, a string method and a params map. Each response has its own message-id, a correlation-id and a causation-id that identifies its request. The result of a failed request is an #err value of code, message and the failure's other members. The namespace read methods and query read; namespaces/save and transact write:

Method Parameters Result
transact code mutation map, optional bindings, session and dry-run tx or null and the ids of temporary names; with dry-run true, also dry-run and changes

code is a native mutation value, {patch {...}} with optional if and query members, as Transactions describes. A string in code is never parsed. For example, against a new database:

{message-id #uuid "00000000-0000-4000-8000-000000000001" method "transact"
 params {code {patch {_paul {name "Paul" spice 100}
                      _chani {name "Chani" partner _paul}}}}}

The response names the entity of each temporary name:

{message-id #uuid "10000000-0000-4000-8000-000000000001" correlation-id #uuid "00000000-0000-4000-8000-000000000001" causation-id #uuid "00000000-0000-4000-8000-000000000001" result {tx 6 ids {_chani #link 1 _paul #link 2}}}

ids maps each temporary name to its entity link; with a query, to the list of its entities in row order, one per row whose body for the name holds a fact. A transaction that changes nothing returns tx null and ids {}. A failed if condition or two differing proposals for one field report #err {code <conflict> …} and write nothing. A form the mutation compiler refuses, or an expression that fails to compute, reports its position in the request as an evaluation error does.

With dry-run true, transact does a dry run. The dry run does all the steps of a real run in the write transaction: selection, expressions, proposals, conditions and schema checks. Then it rolls back the transaction and does not commit it. A dry run gives the same errors as a real run. It publishes no transaction, sends no subscription event, and does not change the ID sequence or the field catalog. dry-run false is a real run.

The result of a dry run has tx null, the ids that the real run would allocate, dry-run true and a changes list. The list has one map for each entity that the run would change, in ID order. entity is the entity link. created is true for a new entity. name is the temporary name of the entity, when it has one. fields maps each changed field to its action, "assert", "retract" or "merge". before and after are the values of the field before and after the transaction. A value is not in the map when the field has no value. A merge is a map at a field that merges into the entity that the field links to. When the link does not change, before and after are the same link. For example:

{message-id #uuid "00000000-0000-4000-8000-000000000009" method "transact" params {dry-run true code {patch {2 {spice 60} _leto {name "Leto"}}}}}

Response:

{message-id #uuid "10000000-0000-4000-8000-000000000009" correlation-id #uuid "00000000-0000-4000-8000-000000000009" causation-id #uuid "00000000-0000-4000-8000-000000000009" result {tx null ids {_leto #link 24} dry-run true changes [{entity #link 2 created false fields {spice {action "assert" before 80 after 60}}} {entity #link 24 created true name "_leto" fields {name {action "assert" after "Leto"}}}]}}

A real run of the same request, with no other write between the two runs, allocates the same IDs.

Transactions and namespace saves share one writer: requests in one batch publish in submission order, and each request is one transaction. Requests with as-of, and sessions opened with as-of, are historical contexts and report #err {code <read only> …}. A transaction runs under the request's CPU and memory limits; a request cancelled or out of budget before its commit writes nothing, and one cancelled after its commit still returns its result. If a storage failure reports #err {code <storage failed> outcome "unknown"}, reopen the database and read the data before deciding whether to retry.

DUST evaluations attached to the database can also call named mutations; see Transactions for literal, query-driven and saved-function examples. Each call is its own transaction; an eval request is not an atomic batch of all its calls. An error after a committed call reports outcome "committed" and its transaction result. Preparation can run alongside queries; publication uses the same single writer as the request methods above.

5.1. Schema checks and signatures

schemas/valid? requires value and exactly one of schema or name. A schema is a native constraint value or an owned definition snapshot. A literal string schema requires that exact string; it is never a namespace name. A name is a qualified name such as "cargo/Shipment", resolved using the optional session and its loaded namespace aliases. as-of selects the usual historical context. Missing names and invalid schemas are request errors.

This complete request checks an integer:

[{message-id #uuid "00000000-0000-4000-8000-000000000001" method "schemas/valid?" params {schema #builtin "int?" value 80}}]

Its response is:

{id 1 result <valid>}

A mismatch returns {valid false diagnostics [...]}. Each diagnostic is the same data that explain supplies: path points into the schema, in points into the candidate, and schema, value and message describe the mismatch. Both paths are native JSON Pointers. Checking never inserts defaults or changes the candidate.

programs/signature requires code as native source forms. Optional bindings, session and forms use the request interface's existing value conventions. With forms true, code is a list and the response contains one signature record per form. Source strings remain strings; the method does not parse them. It analyzes definitions without evaluating the program or invoking its macros. References to supplied bindings, namespaces or captured values stay symbolic when the body alone does not establish their behavior.

[{message-id #uuid "00000000-0000-4000-8000-000000000008" method "programs/signature" params {code (fn [x] x)}}]

The complete response preserves the identity relation:

{id 8
  result {<complete>
          functions [{<complete>
                      clauses [{<!declared exact !variadic>
                                after []
                                contract ""
                                effect-inputs []
                                effect-outputs []
                                effects []
                                guaranteed {<possible>
                                            constraints []
                                            relations [{argument 0
                                                        count 0
                                                        function 0
                                                        kind "Aliases"
                                                        left {term {input -1
                                                                    path []}}
                                                        operation "None"
                                                        right {term {input 0
                                                                     path []}}}]}
                                inputs 1
                                possible {<possible>
                                          constraints []
                                          relations [{argument 0
                                                      count 0
                                                      function 0
                                                      kind "Aliases"
                                                      left {term {input -1
                                                                  path []}}
                                                      operation "None"
                                                      right {term {input 0
                                                                   path []}}}]}
                                required 1
                                result {<known>
                                        alias {input 0
                                               path []}
                                        kinds []}}]
                      definition (fn [x] x)
                      environment "symbolic"
                      id 0}]}}

Each function has its source definition, a numeric id and clauses. A clause includes inputs, required and variadic arity information, result, exact, guaranteed and possible success regions, effects, effect-inputs, effect-outputs and mutation after states. Regions retain constraints and relations, including overflow and alias relations. An input number of -1 denotes the result; a path's strings and integers select fields and list elements. A function reference names another function's id. complete false marks unsupported analysis or an analysis limit, without claiming a guarantee. environment "symbolic" means the definition excludes captured runtime state; it does not restore a closure.

Both methods return immutable owned Documents. A result remains usable after its session and database are released. Rendering a returned definition runs no validators. Cancellation and resource limits remain request failures. Foreign clients use the existing submit, poll, encode and release calls; there are no additional C exports.

The CLI can submit the same request file:

stardust request check-request.dust --config arrakis.dust
stardust request signature-request.dust --config arrakis.dust

request prints response pages as DUST. It exits nonzero for a request error; a successful schema mismatch remains a result with valid false.

The request file holds one list of request maps, also for one request. For another file, request sends no request. It writes the file name and the problem to standard error and exits 2:

stardust: single.dust: expected a list of requests, got a map; write one request as [{...}]
stardust: item.dust: index 0: expected a request map, got an integer
stardust: empty.dust: expected a list of requests, got an empty file
stardust: bad.dust:1:7: invalid request file: Unexpected_End

A request that the database refuses before it runs, such as one whose method is not a string, stops the command with exit 1. The message gives the index of that request in the list. The command prints the responses of the requests that the database accepted before the refusal. The other requests do not run.

06 Formatting

Converting a DUST document to DUST writes its canonical spelling: the same value always formats to the same bytes. For example, stardust convert input.dust output.dust writes canonical DUST to output.dust. stardust fmt keeps map keys in source order, so its output is canonical only when the keys are sorted. Canonical output is what stardust prints, and what hash digests, so two programs that format alike are the same program.

The rules are those of RON and DUST. In brief, the formatter:

  • sorts map keys and collects boolean members into a tag group;
  • uses the short forms name, :name, (f x), `x, and \x for locals, constants, invocations, quotes, and muted forms;
  • drops the brackets of a root list with two or more forms, writing one form per line;
  • normalizes #utc and #dur payloads, so #dur PT90M becomes #dur PT1H30M.

07 REPL

The REPL reads an entry, evaluates each of its top-level forms on its own, and prints each result as one canonical DUST form. A list keeps its brackets, so [1 2 (+ 3 4)] prints [1 2 7]. It keeps history and highlights input as you type. A form that spans lines continues until its brackets balance.

> (+ 1 2)
3  eval 57.9µs cpu · 130.5KiB peak · +4.6KiB net · 323.5KiB live
> (+ 1 2)
3  eval 17.3µs cpu · 128.5KiB peak · +2.5KiB net · 326.0KiB live

A def form defines a top-level local that later entries read:

> (def rate 3)
rate  eval 10.6µs cpu · 5.7KiB peak · +3.3KiB net · 580.8KiB live
> [rate (* rate 2)]
[3 6]  eval 8.1µs cpu · 8.4KiB peak · +5.5KiB net · 586.3KiB live

7.1. Importing files

An import in the REPL names a .dust file relative to the working directory, which is also the import root. The REPL reads no file outside it and the imports roots of its configuration. With a database (With a database), the newer of the file and a saved namespace of the path is used. The file's export forms name the members that the alias makes available, and its other locals stay private. Each evaluation of the import form reads the file again, so an edit takes effect (Files). An alias cannot be a builtin namespace such as math: use (import {m "lib/math"}). A line that starts with ! is a REPL command. Every other line is DUST.

Given lib/shapes.dust:

(def double (fn [x] (+ x x)))
(def square (fn [x] (* x x)))
(export square double)
> (import {shapes "lib/shapes"})
null  eval 132.2µs cpu · 76.6KiB peak · +71.6KiB net · 1.5MiB live
> (shapes/square 7)
49  eval 16.6µs cpu · 5.5KiB peak · +5.5KiB net · 1.6MiB live
> (import {s "lib/shapes"})
null  eval 8.9µs cpu · 2.6KiB peak · +2.6KiB net · 1.6MiB live
> (s/double 4.5)
9.0  eval 15.0µs cpu · 5.2KiB peak · +5.2KiB net · 1.6MiB live

!reset clears top-level locals, aliases and imported files. The new session contains only the core libraries:

> !reset
reset: locals, namespaces, and compiled programs cleared
> (shapes/square 7)
#err {<name unbound>
      message "unbound name: shapes/square"}  eval 25.4µs cpu · 9.2KiB peak · -208.4KiB net · 1.3MiB live

7.2. With a database

When the --config file has database storage, a path or temporary true (Configuration files), the REPL opens that database, as eval does, and evaluates each form in one database session. Named queries and mutations work, and a database file keeps its data after the REPL stops:

{plugins {stdlib true database {path "app.db"}}}
$ stardust repl --config app.dust
> (defmutation seed [] {patch {_u {email "a@x"}}})
seed  eval 301.4µs
> (seed)
{ids {_u #link 1}
 tx 3}  eval 3.6ms
> (defquery q [] {<tuples> find [?e] where [[?e email ?m]]})
q  eval 424.8µs
> (q)
[[1]]  eval 842.2µs

Each result shows the time of its request, measured by the REPL; the database reports no compile or memory cost. The database's limits apply. !reset starts the database session again: it clears top-level locals and imported files, and the data stays. An imported file loads as an unsaved namespace of the session and saves nothing (Files). Without storage settings, the REPL evaluates without a database, as described above.

08 Costs

Every evaluation reports its cost, dimmed, to the right of the result. A REPL with a database shows only the time of the request (With a database).

8.1. Evaluation

eval 57.9µs cpu · 130.5KiB peak · +4.6KiB net · 323.5KiB live

Field Meaning
cpu CPU time spent evaluating the program
peak The peak memory growth during evaluation
net The change in memory use after evaluation (+ or -)
live Memory in use after evaluation, including loaded namespaces

cpu and memory are the quantities the engine's limits bound: a program that exceeds either fails with #err <limit resource>. Costs vary from run to run, so compare them by order of magnitude rather than exactly.

A regex pattern can contain at most 4,096 UTF-8 bytes and 16 capture groups. Each bound of a counted repetition is limited to 64. A pattern or search that exceeds available resources produces a resource-limit error.