01 Language
1.1. Syntax
The .dust format extends .ron. References, invocations, quotation shorthand, and mute shorthand belong exclusively to DUST. Their explicit tagged-element representations are ordinary data in RON and JSON.
Parsing DUST constructs forms without evaluating them. Reading source never executes user code or reader macros.
Parentheses delimit invocations, not literal lists or quotation forms.
[square brackets] are also used to delimit lists, used for literal
data structures and in specials and macros to delimit where new bindings
are introduced, such as argument lists and let bindings.
{curly braces} delimit maps containing key-value pairs and optional
tags.
Ordinary members pair a string key with a value.
Tags supply boolean-valued members using RON's shorthand.
Map keys must be strings.
Map values can be of any type.
1.1.1. Strings
DUST strings use double quotes or fences of two or more double quotes, with the same escapes as RON quoted strings. String literals produce strings, not quotation forms. Literal map keys are always strings and may be written bare.
In value position, a token matching a number, null, true, or false
denotes that value. Other unprefixed names denote local references.
Quote a name to write a string value.
A leading # introduces a tagged element, : a constant reference, and
/ a JSON Pointer. Leading `, ~, ,, and ,@ introduce quotation
forms. A leading \ mutes the next complete form.
["hello" ".-#1" "don't" true false null 42 -1.5 "true" "false" "null" "42" "-1.5" "nil" "#name" "^name" name "🙂" "" {true false}]
"hello" ".-#1" "don't" true false null 42 -1.5 "true" "false" "null" "42" "-1.5" "nil" "#name" "^name" name "🙂" "" <!true>
[hello .-#1 don't true false null 42 -1.5 "true" "false" "null" "42" "-1.5" nil "#name" ^name #local name 🙂 "" <!true>]
Whitespace separates list forms on every line. Putting [ alone on its
opening line has no effect on token boundaries. A string containing spaces
still requires quotes:
[ "Ada Lovelace" "Grace Hopper" ]
"Ada Lovelace" "Grace Hopper"
[ Ada Lovelace Grace Hopper]
Ordinary double-quoted strings use JSON escapes. Fenced strings allow double quotes inside without escaping them, but backslashes and control characters still use escapes. Unicode escapes decode to their characters:
["say \"hello\"" ""C:\\tmp\\notes.txt"" "\u03b5" "\u0000"]
""say "hello""" "C:\\tmp\\notes.txt" "ε" "\u0000"
[ say "hello" C:\tmp\notes.txt ε "\u0000"]
A fence of three or more quotes followed only by whitespace and a newline starts a multiline string. The newline after the opening fence and the newline before the closing fence are not part of the string. An extra blank line before the closing fence preserves a trailing newline. A single-line fence and a multiline fence can therefore contain the same string:
[ ""hello world"" """ hello world """ """ first line second line """ ]
"hello world" "hello world" """ first line second line """
[ hello world hello world """ first line second line """ ]
A quoted ., :, or / is a string. An unquoted : starts a
constant reference and / starts a pointer outside direct-callee position.
The old .name spelling is invalid. A caret has no special meaning.
["^name" "^x" name :name "^" name]
"^name" "^x" name :name "^" name
[^name ^x #local name #const name ^ #local name]
Binding forms interpret bare names as declarations. A direct callee is a
name encoded as a string in the first element of #invoke, without a
#local or #const wrapper. Surrounding quote characters in direct-callee
position belong to that name. A computed callee is an expression in the
first element, such as (:strings/case "upper" "hi").
Whitespace separates root forms, list elements, and invocation operands. Map keys follow RON's token rules and are always strings.
1.2. Source notation
1.2.1. Documents and form separation
A DUST file holds one or more forms. A file containing exactly one form is that form. Two or more forms, separated by whitespace including newlines, make an implied root list; its outer square brackets may be written or omitted. A root string value must be quoted. Unlike RON, whose default document is an implied outer object, DUST has no implied root map: a root map is written with braces.
Canonical DUST omits the root list's brackets when the list has two or more forms and its first non-comment form is not a literal list:
(+ 1 2)
(* 3 4)
Root forms are separated by whitespace, not lines, so a root string containing
spaces is quoted, as in "two words".
Explicit outer brackets around these forms are also accepted and produce the same list, but are not canonical.
Otherwise the brackets are kept, so a one-element list [x] stays distinct
from the form x, and [[1 2]] stays distinct from [1 2].
Once an earlier form establishes an implied root list, later literal lists
need only their own brackets.
A file is evaluated one top-level form at a time, from first to last, so a
form can use the top-level locals that earlier forms define. Its value is
the list of the forms' values: (+ 1 2) (* 3 4) evaluates to [3 12], and a
file with one form evaluates to that form's value. An empty file is an empty
list. Read for evaluation, as by the Stardust REPL, a written list is always
one form, so [1 2] followed by [3] is two forms, and each form can have a
depth of 256.
An #err value from one top-level form does not stop the later forms.
This is the language and evaluation API rule. The
CLI commands eval and run stop at the first form that returns #err.
In expression positions, unquoted (), [], and {} delimit forms and end reference names and direct-callee names.
These delimiters separate list forms and invocation operands without whitespace.
[["foo"(bar)] (foo(bar)) ["foo"["bar"]{}(bar)"baz"] [[foo(bar)][(bar):foo]]]
[["foo" (bar)] (foo (bar)) ["foo" ["bar"] {} (bar) "baz"] [[foo (bar)] [(bar) :foo]]]
[[foo #invoke [bar]] #invoke [foo #invoke [bar]] [foo [bar] {} #invoke [bar] baz] [[#local foo #invoke [bar]] [#invoke [bar] #const foo]]]
A map member value contains one form. foo(bar) contains two forms: the
reference foo and the invocation (bar). It may supply consecutive root
or list forms, but is invalid as one map member value. "foo(bar)" is one string.
Map keys use RON's token rules, including embedded brackets and parentheses, and require whitespace before their values.
Angle brackets delimit tag groups in map-member position.
A tag group can also stand alone as a tag-only map in value position.
For example, <staff mentor> is the canonical form of {staff true mentor true}.
In DUST, an empty tag group <> denotes the empty map and prints as {}.
See tag-only maps.
[{items[0] 1 foo(bar) 2 .name 3}]
[{.name 3 foo(bar) 2 items[0] 1}]
[{.name 3 foo(bar) 2 items[0] 1}]
Map keys are always strings. A key that starts with # is the same string with or without quotes,
at every member count and in every position, so {#zip null} and {"#zip" null} are the same map.
A tag is written without braces: #zip null.
[{#zip null} #zip null]
{#zip null} #zip null
[{#zip null} #zip null]
{#zip null} #zip null
A key that begins with ) is quoted, since a line that begins with ) closes a form:
{"(a" "b" ")" 1 ")x" 2 "x)" 3 "(" 4 k ["a <b" "c" "a<b"]}
{( 4 (a "b" ")" 1 ")x" 2 k [ "a <b" "c" "a<b"] x) 3}
( 4 (a b ) 1 )x 2 k [ "a <b" c a<b] x) 3
1.2.2. Comments
A DUST comment starts with ; and continues to the end of the line.
The ; starts a comment at the start of a line, after a space or tab, or
directly after an opening [, {, ( or < that starts a token.
In all other positions, ; is text, so a[;b is one token. A semicolon in a
quoted string is always text. RON and EDN use the same comment rules.
A $comment key is ordinary data in DUST and RON. JSON and TRON have no
comment syntax, so they keep all comments of a document in one root
$comment member: a JSON string of an object from the pointer of each
commented value to its text. The "" pointer is the root. This DUST:
; Spice math.
{rates {arrakis 10 caladan 15}
; reserve percent
reserve 10}
is this JSON:
{
"$comment": "{\"\":\"Spice math.\",\"/reserve\":\"reserve percent\"}",
"rates": {
"arrakis": 10,
"caladan": 15
},
"reserve": 10
}
A root that is not a map goes in {"$comment": "…", "$value": root}. See
stardust convert for the pointer steps.
Each value has a maximum of one comment text. These rules give each comment to a value:
- A comment after a value on the same line belongs to that value.
- A comment on its own line belongs to the next value.
- A comment directly after an opening bracket belongs to the next value.
- When closing brackets come before the comment on a line, the comment belongs to the outermost value that these brackets close.
In each of these examples, the comment c belongs to the value 1:
{x 1 ; c
y 2}
{y 2
; c
x 1}
[; c
1 2]
In this example, the comment belongs to the list [1 2] at /a, not to the
item 2:
{a [1 2] ; c
b 1}
When a value has more than one comment, the reader joins the texts in source
order, with a line feed between them. In this example, /a has the text
first, /b has second and third on two lines, and /c has fourth:
{a 1 ; first
; second
b 2 ; third
; fourth
c 3}
In a file with one form, a comment above the form belongs to that form. For
example, this file evaluates to 3, and its root form has the comment
Root documentation:
; Root documentation
(+ 1 2)
The reader refuses a comment that no value can own, with an
Invalid_Comment error at the offset of the first ; that has no value.
The reader also refuses a comment in some positions inside a value. In this
table, \n is a line feed:
| Refused comment | Example |
|---|---|
| Before a closing bracket | [1\n ; c\n] |
| In an empty container | {\n ; c\n} |
| After the last value of a file | 1\n; c |
| In a file that contains only comments | ; c |
| In a tag group | {<a ; c\n b>} |
A comment between a tag or quotation prefix and its payload is refused. Write the comment above the tagged value. A comment in the payload of a string template is refused.
A comment in the payload of a tag or quotation is permitted. In this example,
the comment the input belongs to the 1 in the quoted form:
{rule `(+ x
; the input
1)}
Canonical formatting writes each comment as ; lines directly above its
value. A text with line feeds gives one ; line for each line of the text.
A blank line goes above each comment block. There is no blank line at the
start of the file or directly after an opening bracket.
For example, canonical formatting changes this input:
{a 1 ; one
b 2}
to this form:
{
; one
a 1
b 2}
The example with four comments above formats as:
{
; first
a 1
; second
; third
b 2
; fourth
c 3}
1.2.3. Nesting depth
The parser and the evaluator have no nesting limit. A form or a value can nest as deep as the memory budget of the evaluation allows. For example, a list that is 256 levels deep evaluates to the same list:
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
A value that a program builds as it runs, such as a list that reduce wraps once for each item, can nest more than 100,000 levels deep in the default memory budget.
The code of a program has one bound that does not come from the budget.
The evaluator compiles a program to Lua, and LuaJIT runs it on a stack of 65,500 slots.
Deep code uses some of this stack for each level.
A program whose source nests control forms, such as if, about 30,000 levels deep, or a literal about 60,000 levels deep, can fill the stack.
The evaluation then gives #err <internal limit recursion>, the same error as a recursion that does not stop:
#err {<internal limit recursion>
message "program exceeds an internal limit: calls nest too deeply"}
Calls such as (+ 1 (+ 1 ...)) and (str (str ...)) nest past 100,000 levels.
Parser errors produce #err <invalid value>.
Formatting rejects a document when indentation would start after column 65,535.
1.2.4. Value size
A string, a byte string or a Bitset holds at most 4,294,967,295 bytes, and a
list, map or other container at most 4,294,967,295 items. This is a format
bound: a value cell stores its length in 32 bits. A longer text or a container
with more items is refused, never shortened; a decoder reports it as an
invalid value, and reading a longer stored list gives a limit error. Keep
larger payloads in the objects plugin, which stores a payload of any size
and reads it by byte range.
A value that crosses into or out of the runtime (an evaluation's bindings and
result, a host call's request and result, one page of query results) holds at
most 2,147,483,647 cells, 2,147,483,647 bytes of text and 2,147,483,647 facts
(repeated containers, functions and error positions). This is a runtime
bound: the runtime counts these in 32 bits, because 64-bit counts make every
value it writes slower. A value past it fails with #err <limit resource>
and a message that names the bound. One runtime string also holds less than
2 GiB.
1.2.5. References
Outside map-key and direct-callee positions, a bare name produces a #local
tagged element. : followed by a nonempty name produces a #const tagged
element. Names follow DUST's token and form-separation rules.
Numbers, booleans, and null keep their literal meanings; explicit tagged
notation can represent references to those spellings, such as #local "5".
The spellings .name, ., :, ..., ::x, and ."x" are syntax errors.
A . or : after the first character belongs to the name, as in a.b or a:b.
{var name const :name punctuation (fn? :+) qualified-var user/name qualified-const :math/pi colon a:b dot :a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] caret-name ^+ nested [x {value :y}]}
{caret-name ^+ colon a:b const :name dot :a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] nested [x {value :y}] punctuation (fn? :+) qualified-const :math/pi qualified-var user/name var name}
caret-name #local ^+ colon #local a:b const #const name dot #const a.b literal-names [#local "42" #local "-1" #local "1.5" #local "true" #local "false" #local "null"] nested [#local x {value #const y}] punctuation #invoke [fn? #const +] qualified-const #const math/pi qualified-var #local user/name var #local name
#err <name unbound>
(let [add :+] [(add 0 0) (add 1 2) (add -4 10)])
(let [add :+] [(add 0 0) (add 1 2) (add -4 10)])
#invoke [let [#local add #const +] [#invoke [add 0 0] #invoke [add 1 2] #invoke [add -4 10]]]
0 3 6
Parsing constructs the reference without looking up its name. Binding and parameter declarations use the same name forms as local references. A name in a binding or parameter position declares a local.
1.2.6. String Template Literals
A string template is a quoted or fenced string prefixed with ~, the
quasiquote prefix. Inside it, , followed by a form embeds that form, as
unquote does in a quasiquoted list. A string without ~ is always literal, so
",name" and "{{x}}" are plain text.
(let [name "Ada"] ~"Hello ,name") ; => "Hello Ada"
(let [subtotal 10 tax 2] ~"Total: ,(+ subtotal tax)") ; => "Total: 12"
~"Pi is ,:math/pi" ; => "Pi is 3.141592653589793"
(let [name "Ada"]
~"""
Hello ,name
Sum ,(+ 1 2)
""") ; => "Hello Ada\nSum 3"
An embedded form in parentheses, brackets, braces, or quotes ends at its closing delimiter. Any other form, such as a reference, reads a full name and ends at whitespace, a comma, a quote, or a bracket. A comma that ends it is consumed, so a reference can be followed directly by text:
(let [name "Ada"] ~"Hi ,name there") ; => "Hi Ada there"
(let [name "Ada"] ~"Hi ,name,!") ; => "Hi Ada!"
(let [foo! "bang"] ~"Hi ,foo!") ; => "Hi bang"
(let [name "Ada"] ~"Hi ,name,, there") ; => "Hi Ada, there"
A comma followed by whitespace or the closing quote is text, and ,, writes a
literal comma anywhere:
~"a, b" ; => "a, b"
~"x,,y" ; => "x,y"
Embedded forms may contain quotes, as in ~"a ,(str "x") b". A quoted string
cannot be embedded directly in a one-line template, because ," before the
closing quote is literal text and a quote otherwise ends the template; write
,(str "x") or use a fenced ~""" template. Only a string written directly
after ~ is a template; a string nested inside a quasiquoted list stays
literal, so ~[a ,x "b ,x"] keeps "b ,x".
The resulting template value keeps the literal pieces and evaluated values
separate, so template functions can inspect them or
escape each value. A printed or exported template value is its rendered string,
the same text str produces. Printing loses the parts: reading the printed
result back gives an ordinary string, not a template. A quoted template is a
form rather than an evaluated value, so it prints as a template literal.
In RON, the #template tagged representation contains a list of literal
strings and a list of forms. The first list has one more item than the second.
For example, this DUST template:
~"hello-,name"
has this RON representation:
#template [[hello- ""] [#local name]]
A comment can belong to a template as a whole. Write it above the template,
or after the template on the same line, as in ~"hello-,name" ; greeting.
A comment after the closing brackets of a #template form also belongs to
the template. A comment inside the payload, among the literal pieces or the
embedded forms, is an Invalid_Comment error at the comment. This rule
applies in DUST, RON and JSON. In JSON
that is a root $comment pointer into the payload, such as /t/0 for the
literal pieces of the template at /t.
#template [
["hello-" ""] ; refused: inside the payload
[name]]
DUST formatting writes the template literal when the tagged representation
can be expressed without changing its data. It always writes a one-line
~"…" literal, escaping line breaks as \n, so a multiline ~""" template
is reformatted on one line. A template that embeds a literal string value keeps the explicit
#template notation.
See string templates for construction, inspection, and rendering.
1.2.7. JSON Pointers
RFC 6901 defines JSON Pointer as a string syntax for identifying a value
within a JSON document. Its reference tokens are separated by /; within a
token, ~1 represents / and ~0 represents ~. The empty string refers
to the root, while / refers to a member with an empty name.
DUST uses that syntax for pointer text and adds pointer values and embedded forms. A pointer value can be used with DUST maps and lists. DUST distinguishes integer index segments from string key segments; numeric strings with valid index spelling become indices. Extensions to RFC 6901 lists everything DUST adds.
(get {a/b 1} /a~1b) ; 1
(get {items ["zero" "one"]} /items/1) ; one
(get {"" 7} /) ; 7
A slash-prefixed value constructs a pointer. Pass it to a collection path
function to read or update data. In callee position, / is division; a map
literal key beginning with / is a string.
(get {a 1} /a) ; 1
(/ 10 2) ; 5.0
(get {/a 1} "/a") ; 1
A pointer has slash-separated segments:
(get {"" 7} /) ; 7
(get {"" {a 1}} //a) ; 1
(get {a {"" 2}} /a/) ; 2
(get {a 1} (jsonptr "")) ; {a 1}
/ selects an empty key; it does not select the root. Use (jsonptr "")
for the root pointer.
Segments can contain embedded forms. As in a string template,
, followed by a form embeds it, and a comma that ends a token form is
consumed. A pointer needs no ~: a bare pointer cannot otherwise contain a comma.
(let [key "a"] (get {a 1} /,key)) ; 1
(let [id 2] (get {user-3 "ok"} /user-,(+ 1 id))) ; ok
(let [id 7] /users/,id,/name) ; /users/7/name
Names can contain /, so /users/,id/name reads the reference id/name;
the closing comma in /users/,id,/name ends id before the next segment.
An embedded segment value must be a string or an integer.
The RFC escapes ~1 and ~0 select keys containing / and ~:
(get {a/b 1} /a~1b) ; 1
(get {m~n 2} /m~0n) ; 2
DUST also accepts \{, \}, and \\ for literal braces and backslashes,
and ,, for a literal comma. Other tilde or backslash escapes are syntax
errors. Parentheses, caret, opening braces, and double quote are literal
pointer text; an unmatched closing parenthesis ends the pointer token.
Whitespace, square brackets, a closing brace, or a comma followed by whitespace
or a closer also ends the token.
1.2.7.1. Extensions to RFC 6901
A DUST pointer is RFC 6901 with the extensions in this table. Text that uses only RFC 6901 syntax selects what RFC 6901 selects, except that a token spelled as a negative index is an index on a list, where RFC 6901 has only keys.
| Extension | Example | RFC 6901 |
|---|---|---|
A negative index counts from the end of a list: -1 is the last item, -2 the one before it |
/items/-1 |
-1 is only a key, and has no meaning on an array |
| A segment can be a computed form | /users/,id,/name |
Tokens are text |
| A segment can join text and forms | /user-,(+ 1 id) |
Tokens are text |
Backslash escapes and ,, in source |
/a\{b |
Only ~0 and ~1 |
A negative index follows the same rules as a nonnegative one:
- A read before the first item is missing, as a read past the last item is, so
(get ["a"] -2)isnulland(contains? ["a"] -2)isfalse. - A write before the first item is
#err <invalid value>. There is no position to create, whereas a write at the list's length appends. - A removal before the first item changes nothing.
- On a map,
-1is the key"-1", as1is the key"1". - The token
-0is a key, not an index. - RFC 6901's
-token, which names the position after the last item, is a key.
(get ["a" "b" "c"] -1) (get ["a" "b" "c"] -2) (get ["a" "b" "c"] -3) (get ["a" "b" "c"] -4) (get ["a" "b" "c"] -4 "none") (get {items ["a" "b" "c"]} /items/-1) (let [i -2] (get {items ["a" "b" "c"]} /items/,i)) (get {items ["a" "b"]} (jsonptr "/items/-2")) (get {items ["a" "b"]} (lists/concat (jsonptr "/items") [-1])) (get {"-1" "key"} /-1) (get {items ["a"]} /items/-0) (get #b64 "F8gHWw==" -1) (contains? ["a"] -1) (contains? ["a"] -2) (put ["a" "b"] -1 "z") (put ["a" "b"] /-2 "z") (put ["a" "b"] -3 "z") (remove ["a" "b"] -1) (remove ["a" "b"] -3) (collections/update [1 2] -1 (fn [old] (+ old 10))) (str /a/-1)
(get ["a" "b" "c"] -1) (get ["a" "b" "c"] -2) (get ["a" "b" "c"] -3) (get ["a" "b" "c"] -4) (get ["a" "b" "c"] -4 "none") (get {items ["a" "b" "c"]} /items/-1) (let [i -2] (get {items ["a" "b" "c"]} /items/,i)) (get {items ["a" "b"]} (jsonptr "/items/-2")) (get {items ["a" "b"]} (lists/concat (jsonptr "/items") [-1])) (get {-1 "key"} /-1) (get {items ["a"]} /items/-0) (get #b64 "F8gHWw==" -1) (contains? ["a"] -1) (contains? ["a"] -2) (put ["a" "b"] -1 "z") (put ["a" "b"] /-2 "z") (put ["a" "b"] -3 "z") (remove ["a" "b"] -1) (remove ["a" "b"] -3) (collections/update [1 2] -1 (fn [old] (+ old 10))) (str /a/-1)
"c" "b" "a" null "none" "c" "b" "a" "b" "key" #err {<mismatch type> message "lists require integer indices"} 91 true false ["a" "z"] ["z" "b"] #err {<invalid value> message "index out of range"} ["a"] ["a" "b"] [1 12] "/a/-1"
Every format writes a pointer as RFC 6901 text when text can express it, and
/a/-1 is such text. A pointer with a computed segment is written as a list of
segments: /a/,i in DUST, #jsonptr [a #local i] in RON, and
{"#jsonptr":["a",{"#local":"i"}]} in JSON. Other RFC 6901 implementations read
/a/-1 as the key "-1", and can not read a list of segments.
RON represents a literal pointer as #jsonptr with a string payload. A
pointer containing embeds has a list payload. For example, these DUST pointers:
/a/0
/3/,"3"
/foo/user-,(+ 1 id)/,k,/0
have these RON representations:
[#jsonptr /a/0 #jsonptr /3/3 #jsonptr [foo [user- #invoke [+ 1 #local id]] #local k 0]]
Formatting the third pointer as DUST writes its embedded forms in the pointer
literal rather than the #jsonptr representation.
In the second example, both segments are indices. Map lookup converts an index to its decimal string key. Quotation, mute, and unevaluated parts of quasiquotation preserve tagged data; unquote follows the usual quasiquote rules.
(jsonptr? /) (str /) (str //a) (str /a/) (str /a~1b/x~0y) (str /f(x)) (let [k "name"] (str /users/,k)) (let [n 10] (str /user-,(+ n 1))) (let [k "a/b"] (str /,k)) (let [k "x~y"] (str /,k)) (let [p /3/,"3"] (get [null null null {3 "found"}] p)) (let [p /3/,(int "3")] (get [null null null ["a" "b" "c" "found"]] p)) /,null /,true (count /a/b/0) (first /a/b/0) (str (rest /a/b/0)) (= /a/0 (jsonptr "/a/0")) (let [x 3] (str /foo/,x)) (get ["a" "b" "c" "d"] /,"3") (get ["a" "b" "c" "d"] /,"\u0033") (let [n "3"] (get ["a" "b" "c" "d"] /,n)) (let [n "3"] (get {3 "yes"} /,n)) (let [n "03"] (get {03 "yes"} /,n)) (let [n "3"] (= /,n /3))
(jsonptr? /) (str /) (str //a) (str /a/) (str /a~1b/x~0y) (str /f(x)) (let [k "name"] (str /users/,k)) (let [n 10] (str /user-,(+ n 1))) (let [k "a/b"] (str /,k)) (let [k "x~y"] (str /,k)) (let [p /3/3] (get [null null null {3 "found"}] p)) (let [p /3/,(int "3")] (get [null null null ["a" "b" "c" "found"]] p)) /,null /,true (count /a/b/0) (first /a/b/0) (str (rest /a/b/0)) (= /a/0 (jsonptr "/a/0")) (let [x 3] (str /foo/,x)) (get ["a" "b" "c" "d"] /3) (get ["a" "b" "c" "d"] /3) (let [n "3"] (get ["a" "b" "c" "d"] /,n)) (let [n "3"] (get {3 "yes"} /,n)) (let [n "03"] (get {03 "yes"} /,n)) (let [n "3"] (= /,n /3))
true "/" "//a" "/a/" "/a~1b/x~0y" "/f(x)" "/users/name" "/user-11" "/a~1b" "/x~0y" "found" "found" #err {<mismatch type> message "pointer segments must be strings or integers"} #err {<mismatch type> message "pointer segments must be strings or integers"} 3 "a" "/b/0" true "/foo/3" "d" "d" "d" "yes" "yes" true
(let [p /3/,"3"] [p (get [null null null {3 "yes"}] p) (str p)]) (let [name "Ada"] (str /,~"hello-,name")) (str /,~"inner ,(str "x")") [(str /a,,b) (get {"a,b" 1} /a,,b) (str /a,,) (let [x "tail"] (str /,,,x))]
(let [p /3/3] [p (get [null null null {3 "yes"}] p) (str p)]) (let [name "Ada"] (str /,~"hello-,name")) (str /,~"inner ,(str "x")") [(str /a,,b) (get {"a,b" 1} /a,,b) (str /a,,) (let [x "tail"] (str /,,,x))]
[ [/3/3 "yes" "/3/3"] "/hello-Ada" "/inner x" ["/a,b" 1 "/a," "/,tail"]]
1.2.8. Invocations
Parentheses produce a #invoke tagged element whose payload is a list.
The first element is the callee, and the remaining elements are argument forms.
A direct callee is a name encoded as a string, without a #local or #const wrapper.
In this position, surrounding quote characters belong to the name.
This differs from string parsing in argument position.
A callee that begins with . or : is a reference, and therefore a computed callee.
(upper "hello")
#invoke [upper hello]
#cases [{bindings {upper (fn [x] x)} output "hello"}]
("upper" "hello")
#invoke [""" "upper" """ hello]
#cases [{bindings {""\"upper""" (fn [x] x)} output "hello"}]
("+" 1 2)
#invoke [""" "+" """ 1 2]
#cases [{bindings {""\"+""" (fn [a b] (+ a b))} output 3}]
(let [twice (fn [x] (* 2 x))] (twice 21))
(let [twice (fn [x] (* 2 x))] (twice 21))
#invoke [let [#local twice #invoke [fn [#local x] #invoke [* 2 #local x]]] #invoke [twice 21]]
(:upper "hello")
#invoke [#const upper hello]
#cases [{bindings {upper (fn [x] x)} output "hello"}]
(f :x)
#invoke [f #const x]
#cases [{bindings {f (fn [value] value) x "Ada"} output "Ada"}]
A computed callee is encoded as the first form in #invoke.
For example:
The parser does not resolve invocation names, check whether a callee produces a function, or evaluate arguments.
Unknown names and expressions such as (/ 1 0) are valid parser inputs.
Their evaluation belongs to DUST.
An empty invocation, (), parses as #invoke [].
Parsing does not require a callee; an empty invocation has no function to evaluate.
Whitespace separates forms throughout an invocation and list, including across
newlines, even when the callee begins on a later line. String arguments use
quotes or fences. Binding and parameter lists follow the same separation rules.
The parser does not interpret special-form names or binding positions.
(let [ first name "second name" ] ["first" "name"])
(let [ first name "second name"] ["first" "name"])
#invoke [let [ #local first #local name second name] [first name]]
1.2.9. Quotation forms
The four prefixes apply to the immediately following form and parse to a tagged element. The prefix and its form are adjacent; quote or fence a string beginning with one of these characters when it is meant as text.
| Prefix | Explicit tagged notation |
|---|---|
`form |
#quote form |
~form |
#quasiquote form |
,form |
#unquote form |
,@form |
#unquote-splicing form |
,@items
#unquote-splicing #local items
#err <outside quasiquote splicing unquote>
`~(f ,x ,@xs)
#quote #quasiquote #invoke [f #unquote #local x #unquote-splicing #local xs]
~(f ,x ,@xs)
Quoting a string does not turn it into a DUST quotation form.
#unquote name
,name
#unquote #local name
#err <outside quasiquote unquote>
Quotation names have no special meaning inside parentheses: (quote 1)
parses as #invoke [quote 1] and formats as (quote 1).
The explicit quotation notation is #quote 1, whose canonical DUST spelling
is `1. The same rules apply to the other three quotation tags.
Quote returns its enclosed form as data without evaluating references,
invocations, or collection contents within it.
Quasiquote constructs data in the same way, except that unquote evaluates
one enclosed form and substitutes its resulting value.
Unquote-splicing evaluates an enclosed list and inserts its elements into the
surrounding list, in order. Splicing null inserts nothing, so a rest
parameter that received no arguments splices as an empty list.
With x bound to 2 and xs bound to [3 4]:
`["a" x] ; returns ["a" x]
~["a" ,x ,@xs] ; returns ["a" 2 3 4]
Nested quasiquotes match unquotes by nesting depth: entering a quasiquote
increases the depth, and an unquote or splice belongs to its matching
quasiquote. An inner quasiquote's substitutions are not executed by an outer one.
Unquote outside quasiquote produces #err <outside quasiquote unquote>,
and unquote-splicing outside quasiquote produces
#err <outside quasiquote splicing unquote>.
Unquote-splicing outside a list-element position, or splicing a value that is
neither a list nor null, produces #err <invalid quotation>.
The DUST parser constructs the tagged elements. DUST decides how to resolve a reference, invoke a function, or process a quotation form. Those evaluation rules belong to DUST rather than the data format.
1.2.10. Application value prefixes
The meanings of #link, #dur, #utc, #uuid, #hash, and #b64 belong to DUST. They use RON’s generic #prefix value notation; RON accepts these prefixes without interpreting them. Payload validation and evaluation semantics belong to DUST. Parsing preserves the tagged representation without evaluating it, except that valid #utc, #dur, and #uuid payloads are rewritten to their canonical spelling: #utc 1970-01-01T00:00Z reads and formats as #utc 1970-01-01T00:00:00Z, and #dur PT90M as #dur PT1H30M. Invalid payloads produce parse errors.
#uuid holds a 16-byte UUID. Its string payload uses the hyphenated
8-4-4-4-12 representation. Input accepts uppercase or lowercase hexadecimal;
output uses lowercase. uuid? checks this native kind.
Stardust imports #utc as a typed UTC value. Evaluating it returns that same
value; it does not execute or reinterpret its timestamp payload. Formatting
exports the normal tagged representation through the selected notation codec.
#utc and #dur are distinct signed 64-bit counts of 100 ns ticks. UTC counts
from the Unix epoch; durations count elapsed ticks. Canonical text has at most
seven fractional second digits. Input accepts up to nine digits, rounded to the
nearest tick, with halfway cases rounded away from zero. A nonzero timestamp or
duration that would round to zero is represented by one tick in magnitude.
See the Time library for ranges, constructors, units,
calendar operations, and explicit tick/nanosecond conversion.
#link constructs a distinct link value with an integer, string, or tagged
payload. Integer payloads use the full signed 64-bit range. String payloads stay
strings, including numeric-looking names such as #link "42". Tagged payloads
retain their tag and value, as in #link #url "https://arst.com/arst".
String payloads require quotes: #link "foo" carries the name foo.
An unquoted payload such as #link foo evaluates the local reference foo. Stardust preserves
names without resolving them; a query or transaction engine can interpret a name
as a temporary ID. Stardust does not fetch or interpret tagged link targets.
A reference or invocation in the payload is evaluated before constructing the
link. For example, (let [foo 42] #link foo) produces #link 42.
Quotation preserves constructor syntax: `#link foo does not look up foo.
Booleans, floats, plain maps, and lists are invalid evaluated link payloads.
A payload that evaluates to an error is the result instead of a link:
#link missing returns the unbound-name error, so error? and falsiness see it.
#link missing #link (/ 1 0) (error? #link missing)
#err <name unbound> #err <division integer zero> true
Database patch documents declare temporary entities with keys beginning with
_. In patch values, a bare _name symbol refers to the temporary entity.
The quoted expression below produces a patch document as data:
`{patch {_paul {name "Paul"}
_chani {name "Chani" partner _paul}}}
Within a patch, _paul, #link _paul and #link "_paul" refer to the
same temporary entity. A plain string "_paul" remains text. Temporary
references work inside ordered lists, nested maps and ordinary tagged values.
A tagged target inside a link, such as #link #url "https://example.com",
keeps its own meaning rather than becoming an entity reference.
JSON uses a string link payload, because JSON has no symbols:
{"patch":{"_paul":{"name":"Paul"},
"_chani":{"name":"Chani","partner":{"#link":"_paul"}}}}
Temporary names need a suffix: _ alone is invalid. Every referenced name
must have a target in the same patch scope. Repeated names within a selected
query row refer to the same entity. Another row or invocation gets fresh
temporary entities. Existing entities still use integer links such as
#link 42. Outside patch values, _name follows ordinary binding rules.
Saving authored source preserves these symbols without creating entities.
The canonical form #link 42 has this JSON representation:
{"#link": 42}
A link is distinct from an integer even when their payloads match.
Both (int? #link 42) and (number? #link 42) return false, and numeric
operations reject link operands. Integer link payloads sort before string payloads, then tagged payloads.
Payloads use their type’s ordering; tagged ordering requires scalar tag payloads.
Comparing #link 42 with the integer 42 produces a type-mismatch error.
(do [#link 0 #link -1 #link -9223372036854775808 #link 9223372036854775807])
#link 0 #link -1 #link -9223372036854775808 #link 9223372036854775807
(do [(= #link 42 #link 42) (= #link 42 #link 43) (comparisons/identical? #link 42 #link 42)])
true false true
{ dependsOn #link 42 when #utc "2026-09-09T00:00:00Z" }
{dependsOn #link 42 when #utc "2026-09-09T00:00:00Z"}
dependsOn #link 42 when #utc 2026-09-09T00:00:00Z
{dependsOn #link 42 when #utc "2026-09-09T00:00:00Z"}
Braces make a map, not a tag:
{#utc "2026-10-24T12:34:56Z"}
"#utc" 2026-10-24T12:34:56Z
{#utc "2026-10-24T12:34:56Z"}
#hash holds a digest tagged with its algorithm; the
hash library defines its payload and equality.
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
#hash #sha256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
#hash #sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
#b64 holds bytes as base64 text; the
bytes library defines its payload and equality.
1.2.12. Mute
A backslash prefix, \form, mutes the immediately following complete form.
The prefix and its form are adjacent.
It applies to invocations, references, scalar values, lists, maps, and tagged elements.
The parser still reads the muted form's notation and balances its delimiters;
malformed strings or unmatched delimiters remain syntax errors.
A muted form is represented as a #mute tagged element whose payload is the
preserved form. For example, (+ 1 \(* 20 30) 2) has the form representation
#invoke [+ 1 #mute #invoke [* 20 30] 2].
The explicit #mute form spelling is accepted, and canonical DUST writes the
backslash shorthand. RON and JSON keep the tagged element.
(+ 1 #mute (* 20 30) 2)
(+ 1 \(* 20 30) 2)
#invoke [+ 1 #mute #invoke [* 20 30] 2]
When reading files or interpreting source lists and invocation argument sequences,
DUST excludes muted elements before evaluation, macro expansion, and arity or binding checks.
Their payloads are not evaluated or checked for semantic validity.
Muted elements contribute no element or argument, not a null placeholder.
The active forms must satisfy the usual rules.
Known tags inside a muted payload are still validated on import, so \#local 42
is invalid just as #local 42 is.
(+ 1 \(* 2 3) 4) ; evaluates to 5
[\missing \[1 2] \{a 1}]
\missing \[1 2] \{a 1}
[#mute #local missing #mute [1 2] #mute {a 1}]
A file containing only muted forms produces no evaluation results. A muted value
cannot supply a root expression, a map value or an invocation callee.
These uses are evaluation errors, not parse errors: #err <mute root value>,
#err <map mute value>, and #err <callee mute>.
Data values are not filtered for mute elements.
To begin a literal string with a backslash, quote the string.
["\\path" "\\(+ 1 2)"]
"\\path" "\\(+ 1 2)"
[ \path \(+ 1 2)]
"\\path" "\\(+ 1 2)"
1.2.13. Canonical expression formatting
Canonical DUST formatting preserves the parsed form.
Consecutive forms in an invocation or packed list are separated by a space when they share a line.
Consecutive closing delimiters can be adjacent.
An invocation stays on one line when it fits RON's 100-column target.
Otherwise, it wraps between complete arguments, with continuation lines
indented two spaces from the invocation's starting column.
Multiline def forms keep each name/value pair together, and cond keeps
each tests/result pair together. The binding lists of let and for
keep each binding pattern with its value. Each pair starts a new line when
the form or binding list needs to wrap; comments can separate a pair, and
long values can wrap across additional lines. Short forms stay on one line.
Function forms keep their declaration names and short parameter lists together.
Valid references use name and :name, invocations use parentheses (including ()),
quotation forms use their short prefixes, and muted forms use \. Explicit tagged data that has no
faithful shorthand, such as #local "two words", #const "", or #local ".x",
retains explicit notation. A direct callee whose name begins with . or :
also keeps the explicit #invoke notation. Formatting and parsing the result preserves the JSON representation.
A comment on an invocation element stays on that element.
Canonical formatting writes it as ; lines above the element.
[ (quote 1) (quasiquote ["a" "b"]) (unquote x) (unquote-splicing xs) ]
(quote 1) (quasiquote ["a" "b"]) (unquote x) (unquote-splicing xs)
[#invoke [quote 1] #invoke [quasiquote [a b]] #invoke [unquote #local x] #invoke [unquote-splicing #local xs]]
{empty #local "" spaces #local "two words" non-string #local 42 quoted-name #local ".x" colon-name #const ":x" non-list #invoke 42 numeric-callee #invoke [1 2] spaced-callee #invoke ["two words" 1] var-callee #invoke [#local "f" 1] const-callee #invoke [#const "f" 1] dotted-callee #invoke [".f" 1] quoted-callee #invoke [#quote f 1] empty-call #invoke []}
{colon-name #const ":x" const-callee #invoke [:f 1] dotted-callee #invoke [".f" 1] empty #local "" empty-call #invoke [] non-list #invoke 42 non-string #local 42 numeric-callee #invoke [1 2] quoted-callee #invoke [`f 1] quoted-name #local ".x" spaced-callee #invoke [ "two words" 1] spaces #local "two words" var-callee #invoke [f 1]}
colon-name #const :x const-callee #invoke [#const f 1] dotted-callee #invoke [.f 1] empty #local "" empty-call #invoke [] non-list #invoke 42 non-string #local 42 numeric-callee #invoke [1 2] quoted-callee #invoke [#quote #local f 1] quoted-name #local .x spaced-callee #invoke [ two words 1] spaces #local "two words" var-callee #invoke [#local f 1]
(f ; before the first argument 1 ; first argument 2)
(f ; before the first argument ; first argument 1 2)
#invoke [f ; before the first argument ; first argument 1 2]
(function-name "a string argument with several words" "a string argument with several words" "a string argument with several words" "a string argument with several words" )
(function-name
"a string argument with several words"
"a string argument with several words"
"a string argument with several words"
"a string argument with several words")
#invoke [
function-name
a string argument with several words
a string argument with several words
a string argument with several words
a string argument with several words]
["foo(bar)" "(bar)" "abc)" ".name" ":name"]
"foo(bar)" "(bar)" "abc)" ".name" ":name"
[foo(bar) (bar) abc) .name :name]
These rules apply to DUST source, not str, which formats collections through the canonical RON formatter.
1.3. Values and Evaluation
DUST is an expression-oriented programming language, thus every language construct evaluates to a value. We call these language constructs forms. Forms beget values by evaluation. At the bottom lie the self-evaluating values. These are the values that evaluate to themselves.
null is the value that represents the absence of a value.
null is falsey.
true is the value that represents truth.
true is truthy.
false is the value that represents falsehood.
false is falsey.
String values use RON quotes, fences, and escapes. Strings are interned.
Numbers are RON numbers: integers are signed 64-bit and floats are IEEE 754
doubles. A literal outside those ranges, such as 1e400, is a parse error.
Numbers never convert implicitly. Arithmetic and comparison operands must be
all integers or all floats, so (+ 1 2.5) is #err <mismatch type>; write
(+ 1.0 2.5) or convert with float and
int. Division is the one operation whose result kind
differs from its operands: / always returns a float.
Operations check their results. Integer overflow is #err <integer overflow>,
a float result that would be infinite or NaN is #err <float overflow>, and
division by zero is #err <division integer zero> or
#err <division float zero> by operand kind. NaN and infinity therefore never
exist as numbers: a value can only hold a number that JSON can spell.
DUST does not have keywords because RON does not have keywords. Map keys are strings, so DUST does not need a separate keyword type.
1.3.1. References
However DUST does need references.
A reference is a name that refers to something else; in other languages you might know it as an identifier.
DUST has two kinds. Bare names look up locals; the : prefix looks up constants:
| Source | Tagged form | JSON | Looks up |
|---|---|---|---|
name |
#local "name" |
{"#local": "name"} |
Local bindings: let, fn parameters, a function's own name, for, and top-level def |
:name |
#const "name" |
{"#const": "name"} |
Constants: library entries and bindings supplied by the host |
References follow the source notation rules.
A quoted string whose contents begin with . or : is not a reference.
Map keys are always strings, including names beginning with . or :.
Parsing constructs a reference without resolving its name.
Binding forms interpret name forms as declarations.
A local reference resolves to the nearest enclosing local binding, whether
its value is a function or ordinary data. With no enclosing binding, it is
the top-level local of that name, read each time the reference runs. It
never reaches a constant: math/pi is unbound unless a local binding has
that name. An unbound local is an error when evaluation reaches it, so
(if true 1 missing) returns 1.
Schemas need a few names without a prefix, so these names are the exception.
With no let, fn or for binding of that name, a reference to one of them
is a builtin or a schema marker:
- the kind predicates, such as
int?,string?andmap?(the list is in schemas/valid?); - the comparisons
<,<=,>,>=,=,==,!=andcomparisons/not=, andschemas/meet,schemas/joinandschemas/simplify; - a prefixed predicate, such as
chars/letter?; - the markers
any,never,⊤,⊥,meet,join,not,maybe,map-of,count,error,default,is,optional,bind,...and=>.
A marker is not a function. As a value, count is the count marker, while
(count xs) and :count reach the function; the same holds for not.
Calling a marker, as in (error "x"), is #err <expected function>.
A def of one of these names is #err <conflict name>, so a bare
name such as int? has the same meaning in every top-level form. A function
that refers to it does not read the scope for it. A let or fn binding
still shadows it:
; A bare kind name or marker with no binding is the builtin. (schemas/valid? [meet int? [is > 3]] 8) ; A let or fn binding shadows the builtin meaning. (let [int? (fn [v] false)] (schemas/valid? int? 8)) ((fn [int?] (schemas/valid? int? 8)) (fn [v] false)) (let [is 5] is) ; A function that reads only bare schema names gives the same answer each call. (def positive? (fn [x] (schemas/valid? [meet int? [is > 0]] x))) [(positive? 3) (positive? -3) (positive? "3")]
; A bare kind name or marker with no binding is the builtin. (schemas/valid? [meet int? [is > 3]] 8) ; A let or fn binding shadows the builtin meaning. (let [int? (fn [v] false)] (schemas/valid? int? 8)) ((fn [int?] (schemas/valid? int? 8)) (fn [v] false)) (let [is 5] is) ; A function that reads only bare schema names gives the same answer each call. (def positive? (fn [x] (schemas/valid? [meet int? [is > 0]] x))) [(positive? 3) (positive? -3) (positive? "3")]
true false false 5 positive? [true false false]
A constant reference never reaches a local binding: (let [x 1] :x) is
unbound. Library entries are fixed: a host binding with the same name as a
library entry is rejected, and every evaluation with that binding produces
#err <conflict name>, whether or not the program refers to the name. A host
that needs its own value supplies it under another namespace.
Every constant in a program is resolved once, before evaluation starts. If any
of them is unbound, the program evaluates to that #err <name unbound>, even
when the reference is in a branch that would not run. Constants inside quoted
or muted forms are not evaluated, so they are not resolved.
A pointer has the type name pointer and holds a sequence of Key string
segments and Index integer segments. RFC 6901 text is used when
constructing, encoding, or printing it. Decoding splits at /, replaces ~1
with / and ~0 with ~, and treats decimal digits with no leading zeroes
as an index, with a leading - for one counted from the end, saturating at the
largest signed 64-bit integer. Encoding writes
indices in decimal and escapes ~ before / in keys. After printing and
reading again, Key "0" becomes Index 0. The two select the same map key,
but only the index can select a list element.
Pointer equality compares segment kinds and values. list? is false for a
pointer, and jsonptr? is true. str returns the RFC 6901 text, while format
and the REPL print the canonical DUST form. Functions that accept arbitrary
values also accept pointers, including equality, distinctness, and map values.
A direct invocation resolves the exact name stored in the first element of #invoke.
It looks first in the local bindings and then in the constants, so both
(increment 4) with a let-bound increment and (+ 1 2) work.
("+" 1 2) looks up a name containing the quote characters as well as the plus sign.
(f 1) is a direct invocation that can call a local function.
(:+ 1 2) is a computed callee whose reference follows the rules above.
A missing binding produces an unbound-name error.
1.3.2. Evaluation
Evaluation turns a form into a value. RON and JSON representations of the same source form have identical evaluation semantics. Input values and returned values are values, not source to evaluate again.
Known tagged elements are validated before evaluation. This includes known tags
inside quotations, muted forms, and branches that would not be selected during evaluation.
Unknown tags remain generic tagged data. Evaluating one returns its tag and
payload as data, without evaluating the payload or any nested invocation.
For example, #custom (/ 1 0) preserves the invocation as data and does not
divide by zero. Formatting and notation round trips preserve the normal tagged
representation.
This opaque evaluation rule does not bypass import validation. Known tags
nested inside an unknown payload are still validated eagerly; for example,
#custom #local 42 has an invalid known reference payload. Today that is the
parse error invalid tag.
#application { symbol missing invocation (unknown-function missing) unquote ,missing splice ,@missing nested #another (unknown-function (/ 1 0)) }
#application {invocation (unknown-function missing) nested #another (unknown-function (/ 1 0)) splice ,@missing symbol missing unquote ,missing}
#application {invocation (unknown-function missing) nested #another (unknown-function (/ 1 0)) splice ,@missing symbol missing unquote ,missing}
The self-evaluating forms already represent their value, so evaluating them results in themselves. Other forms describe how to obtain a value, for example by looking up a name to grab what it represents or invoking a function.
An invocation is encoded as a #invoke tagged element containing the callee followed by its argument forms.
For an ordinary function call, a string in the first element of #invoke names the function to resolve.
Any other form in that position is evaluated once to obtain the function.
Direct invocation names resolve to the nearest local binding, then to a
constant. References resolve as described in References.
The result must be a function.
A direct invocation name with no binding gives #err <name unbound>, which
names the missing binding. A declared local that has no value yet is
also unbound. A bound or computed callee that is not a function gives
#err <expected function>.
A computed callee that returns a string is an error, even if that string names a function. There is no second name lookup.
DUST excludes muted argument forms, then evaluates the active argument forms from left to right and passes their resulting values to the function. The function's return value becomes the value of the invocation.
Examples show DUST source beside its expected result.
(nope 1) (def declared) (declared 1) (def x 1) (x 2) ((if true nope 1) 1) (do (nope 1) 42) (let [ignored (nope 1)] 42) ((fn [] (nope 1) 42))
#err {<name unbound> message "unbound name: nope"} declared #err {<name unbound> message "unbound name: declared"} x #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<name unbound> message "unbound name: nope"} 42 #err {<name unbound> message "unbound name: nope"}
(+ 1 (* 2 2)) can be thought of as being evaluated in two steps:
- Evaluate
(* 2 2)to obtain4. - Substitute
4for the multiplication, giving(+ 1 4), which evaluates to5.
Hence:
Square brackets construct lists and braces construct maps. List construction excludes muted elements and evaluates the active elements from left to right. Map construction evaluates each member value1; the order in which member values are evaluated is not defined. Canonical key order is a formatting rule, not an evaluation order. A muted form cannot supply a map member value.
Tags parse into ordinary boolean map members before evaluation. Their names are string keys, not references, and their boolean values evaluate to themselves. Tags introduce no new evaluation behavior.
An evaluation error is a value. It can be bound by let or stored in a list
or map, and evaluation of the other elements continues. A program can inspect
an error with error?.
A call whose argument is an error returns that error, and the function does
not run. The arguments are evaluated from left to right, and the first error
ends the call: the later arguments are not evaluated. Thus a function does not
replace the cause with an error of its own. For example, (count missing)
returns the unbound-name error of missing, not a type mismatch. The rule
applies to each call: of a library function, a plugin function, a function
made by fn, defn, defquery or defmutation, and a computed callee. A
callee is evaluated before the arguments, so a callee that is not a function
still gives its own error.
(count missing) (+ missing 1) (+ (/ 1 0) missing) (= missing 1) (compare (/ 1 0) 1) (str "rate: " missing) (format "%s" (/ 1 0)) (not missing) (put {} "a" (/ 1 0)) (lists/append [1] missing) (let [m {}] [(+ (/ 1 0) (count (put m "a" 1))) m]) (let [m {}] [(+ (* (/ 1 0) 2) (count (put m "a" 1))) m])
#err {<name unbound> message "unbound name: missing"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} [#err {<division integer zero> message "division by zero"} {}] [#err {<division integer zero> message "division by zero"} {}]
((fn [amount] 5) (/ 1 0)) (let [rate (fn [amount] (* amount 2))] (rate missing)) (let [inspect (fn [value] (if (error? value) "caught" value))] (inspect (/ 1 0))) (let [measure :count] (measure missing)) ((if true :count :str) missing) (let [callee null] (callee (/ 1 0))) (let [countdown (fn countdown [n] (if (= n 0) 0 (countdown (- n (/ 1 0)))))] (countdown 3)) ((fn [a b] [a b]) (+ 1 "a") (count 5)) ((fn [a] a) (str "k" (/ 1 0))) ((fn [a] a) (count (/ 1 0))) ((fn [value] [[join int? error?] => boolean?] (error? value)) (+ 1 "a")) (let [total (fn total [n acc] (if (= n 0) acc (total (- n 1) (+ acc "x"))))] (total 3 0)) (let [total (fn total [n acc] (if (= n 0) acc (total (- n 1) (* acc 3))))] (total 50 1)) (error? (+ 1 "a")) ((fn [m] 1) (put 3 "a" 1)) (let [fill (fn fill [i acc] (if (= i 2) acc (fill (+ i 1) (put acc i (/ 1 0)))))] (fill 0 {})) (nope (/ 1 0))
#err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<name unbound> message "unbound name: missing"} #err {<expected function> message "expected a function value"} #err {<division integer zero> message "division by zero"} #err {<mismatch type> message "expected a number"} #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} true #err {<mismatch type> message "expected a number"} #err {<integer overflow> message "integer overflow"} true #err {<mismatch type> message "expected a map or list"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: nope"}
Some functions receive an error argument and run:
error?, the
errors/ functions, the value argument of
schemas/valid? and
schemas/explain, which match an error
with error? or [error S], and a function whose contract admits an error
for that parameter. This also applies when such a function is the value of
a local.
(error? missing) (let [inspect :error?] (inspect (/ 1 0))) (schemas/valid? error? (/ 1 0)) (schemas/valid? int? (/ 1 0)) (schemas/explain error? (/ 1 0)) (schemas/valid? missing 1)
true true true false null #err {<name unbound> message "unbound name: missing"}
Because str and format return an error argument, a program writes an
error's text with errors/message:
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
(let [result (/ 1 0)] [(str "failed: " (errors/message result)) (str "failed: " result) (if (error? result) (str "failed: " (errors/message result)) result)])
"failed: division by zero" #err {<division integer zero> message "division by zero"} "failed: division by zero"
((fn [value] [[join int? error?] => boolean?] (error? value)) (/ 1 0)) ((fn [value] [int? => int?] value) (/ 1 0)) ((fn [value] [any => boolean?] (error? value)) (/ 1 0)) ((fn [a b] [int? [join int? error?] => int?] 1) missing (/ 1 0)) ((fn [a b] [[join int? error?] int? => int?] 1) missing (/ 1 0))
true #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} #err {<name unbound> message "unbound name: missing"} #err {<division integer zero> message "division by zero"}
Special forms are not calls. if, and, or and cond test an error as
falsey and evaluate only what they select, and let and do bind and
sequence errors as values. A list or map literal keeps an error as an
element or member value, but a call that adds an error to a collection, such
as put, returns the error.
(if (/ 1 0) "then" "else") (if true 1 missing) (and true missing) (or missing 3) (cond (error? missing) "error" true "value") (let [unused missing] 5) (when false missing)
"else" 1 #err {<name unbound> message "unbound name: missing"} 3 "error" 5 null
(count [missing missing]) [(/ 1 0) 1] {rate missing} (error? (first [(/ 1 0)]))
2 [#err {<division integer zero> message "division by zero"} 1] {rate #err {<name unbound> message "unbound name: missing"}} true
A higher-order function, such as map, reduce or lists/filter, calls its
function in the same way. An error element is the result of the call for that
element, and the function does not run for it.
(map (fn [x] (+ x 1)) [(/ 1 0) 1]) (map (fn [x] 7) [(/ 1 0) 1]) (map :error? [(/ 1 0) 1]) (lists/filter :error? [(/ 1 0) 1]) (lists/filter (fn [x] (error? x)) [(/ 1 0) 1]) (reduce :+ 0 [1 (/ 1 0)]) (apply :+ [(/ 1 0) 1]) (let [constant (if true (fn [x] 7) null)] (map constant [(/ 1 0) 1])) (map (functions/comp :count :str) [(/ 1 0) 12])
[[#err {<division integer zero> message "division by zero"} 2] [#err {<division integer zero> message "division by zero"} 7] [true false] [#err {<division integer zero> message "division by zero"}] [] #err {<division integer zero> message "division by zero"} #err {<division integer zero> message "division by zero"} [#err {<division integer zero> message "division by zero"} 7] [#err {<division integer zero> message "division by zero"} 2]]
In a query or mutation, a call that receives a captured error, such as
(in ?r ranks) with ranks bound to an error, makes the query return that
error, and a mutation then writes nothing.
An error is a #err tagged element. Its payload can be any value.
A map can contain a RON tag group that classifies the error and members
that describe the failure:
#err {<division integer zero>
column 1
line 1
message "division by zero"}
Match errors by their tags, such as #err <division integer zero>.
Messages and source positions can change between versions.
An error value retains its tags when passed through a program. Resource and
memory failures can stop evaluation.
Special forms control evaluation rather than following the ordinary function-call rule.
For example, if evaluates only the selected branch.
Macros transform forms before evaluation, while quotation allows a form to be used as data without evaluating it.
1.3.2.1. Error tags
Tags are a set, not a path: each tag is one word naming one facet of the
failure, so an error can be looked up by any predicate it carries. overflow
matches both integer and float overflow, integer matches every failure of
integer arithmetic, mismatch matches type and arity mismatches, and mute
matches every misuse of a muted form. Language errors use the tags below; Stardust errors carry
stardust, and applications should add a tag naming themselves.
| Tags | Raised when | Example |
|---|---|---|
<mismatch type> |
An operand has the wrong type, including mixed integer and float arithmetic | (+ 1 2.5) |
<integer overflow> |
An integer, duration, or timestamp result leaves the 64-bit range | (+ 9223372036854775807 1) |
<float overflow> |
A float result would be infinite or NaN | (* 1e308 10.0) |
<division integer zero> |
An integer or duration divisor is zero | (/ 1 0) |
<division float zero> |
A float divisor is zero | (/ 1.0 0.0) |
<invalid value> |
An argument has the right type but an unusable value | (time/duration "forever") |
<invalid tag> |
A known tag has a malformed payload | #utc "yesterday" |
<name unbound> |
A reference or callee has no visible binding | missing |
<conflict name> |
A host binding or a defmacro has the name of a special form or a library entry |
binding math/pi, (defmacro map [f xs] xs) |
<arity mismatch> |
A function receives a number of arguments it does not accept | ((fn [x] x)) |
<argument missing> |
A variadic operator receives no arguments where one is required | (/) |
<list missing> |
A function that takes lists receives none | (map :strings/case) |
<expected function> |
A callee evaluates to a non-function | (map upper [ada]) |
<callee string> |
A computed callee evaluates to a string | ((str "a") 1) |
<fn missing name rest> |
... is not followed by a capture name |
(fn [...] 1) |
<arity fn multiple variadic> |
More than one arity is variadic | (fn ([... a] 1) ([x ... b] 2)) |
<arity duplicate fixed fn> |
Two arities take the same fixed count | (fn ([x] 1) ([y] 2)) |
<arity exceeds fixed fn variadic> |
A fixed arity exceeds the variadic arity's minimum | (fn ([x y] 1) ([... r] 2)) |
<mute root value> |
A muted form supplies the root value | \1 |
<map mute value> |
A muted form supplies a map member value | {a \1} |
<callee mute> |
A muted form supplies a callee | (\f 1) |
<outside quasiquote unquote> |
Unquote appears outside quasiquote | ,x |
<outside quasiquote splicing unquote> |
Unquote-splicing appears outside quasiquote | ,@x |
<invalid quotation> |
Quasiquote splices into something other than a list | #quasiquote {a #unquote-splicing [1]} |
<algorithm hash unknown> |
hashes/digest receives an unsupported algorithm |
(hashes/digest "md5" 1) |
<function unrepresentable> |
A host asks for a function value without its source form | |
<invalid program> |
The engine rejects a program before evaluation, including a macro that returns an error or a non-form | (do (defmacro m [] 1)) |
<macro expansion limit> |
Expanding one form exceeds the macro expansion depth limit | (defmacro forever [] ~(forever)) then (forever) |
<configuration invalid> |
The host configured the engine incorrectly | |
<database no> |
A query, mutation or db/reactors call runs, but the database plugin has no path or temporary storage |
|
<limit resource> |
Parsing or evaluation exceeds a CPU, memory, or node limit | (bitsets/range 0 9007199254740992) |
<allocation failure> |
The host cannot allocate memory | |
<failure runtime> |
An evaluation failure |
1.3.3. Collection Paths
Collection paths select values in maps and lists. A string is always one
literal map key, including a string that starts with /. An integer is one
index; a negative index counts from the end of a list, as
Extensions to RFC 6901 describes. A list contains
only string keys and integer indices; an empty list selects the root. A pointer from /..., #jsonptr,
or jsonptr supplies its segments directly.
| Segment | Map | List | Null or missing entry |
|---|---|---|---|
Key s |
Member s |
#err <mismatch type> |
Missing |
Index n |
Member with decimal key n |
Zero-based element n |
Missing |
An out-of-range list index is missing. A missing read returns the default or
null, and contains? returns false. A write creates intermediate maps;
an index in a new map uses its decimal key. A list write at its length appends.
Other container types give #err <mismatch type>. A pointer inside a list path
is a type error.
A whole embedded segment becomes one segment based on its value:
| Embedded value | Result |
|---|---|
| String with valid index spelling | Index |
| Other string | Key, without further RFC 6901 decoding |
| Integer | Index |
| Null, boolean, float, list, map, pointer, or function | #err <mismatch type> |
| Error | The same error |
A mixed segment always becomes a key, even if its resulting text is digits.
Its literal parts and embedded strings are concatenated directly; null becomes
null, and other values use their canonical DUST text.
1.3.4. Calling a map or list
A map, list, or packed math value in callee
position reads from itself. The arguments are the
path and an optional default, as in get:
(c path) is (get c path), and (c path default) is (get c path default).
(let [cases {convert {to "json"}}] (cases /convert/to)) ; "json"
(let [cases {convert 1}] (cases "convert")) ; 1
(let [xs [5 6]] (xs 1)) ; 6
(let [cases {convert 1}] (cases /missing 0)) ; 0
({convert 1} /convert) ; 1
The callee can be a literal, a name, or the value of another form. A missing
entry returns the default, or null without one. The call raises the errors
of get: a call with no argument or more than two gives
#err <arity mismatch>, and a path that is not a string, integer, list, or
pointer gives #err <mismatch type>. Any other value that is not a function,
including a string, gives #err <expected function>. In callee position,
/ is still division, so (/ 10 2) is 5.0.
(let [cases {convert 1}] (cases /convert)) (let [cases {convert {from "edn" to "json"}}] (cases /convert/to)) (let [cases {convert 1}] (cases "convert")) (let [k "convert" cases {convert 1}] (cases /,k)) (let [cases {a/b 2}] (cases /a~1b)) ({convert 1} /convert) (let [get-to (fn [m] (m /to))] [(get-to {to 1}) (get-to {to 2})]) (let [id (fn [x] x) cases {convert 1}] ((id cases) /convert))
1 "json" 1 1 2 1 [1 2] 1
(let [xs [5 6]] (xs /1)) (let [xs [5 6]] (xs 1)) (let [xs [[1 2] [3 4]]] (xs /1/0)) (let [xs [{name "Ada"} {name "Bea"}]] (xs /1/name)) (let [i 0 xs [5 6]] (xs /,i)) ([5 6] 1) (let [xs [5 6]] (xs 2)) (let [xs [5 6]] (xs /-1))
6 6 3 "Bea" 5 6 null 6
(let [cases {convert 1}] (cases /missing)) (let [cases {convert 1}] (cases /missing 0)) (let [cases {convert 1}] (cases /convert 0)) (let [cases {convert null}] (cases /convert 0)) (let [cases <!convert>] (cases /convert true)) (let [xs [5 6]] (xs 9 "none")) (let [cases {convert 1}] (cases /convert/deeper "none"))
null 0 1 null false "none" #err {<mismatch type> message "path traverses a non-collection value"}
(let [cases {convert 1}] (cases)) (let [cases {convert 1}] (cases /convert /convert /convert)) (let [n 3] (n /a)) (let [s "convert"] (s /a)) (let [cases null] (cases /a)) (let [cases {convert 1}] (cases 1.5)) (/ 10 2)
#err {<arity mismatch> message "wrong number of arguments"} #err {<arity mismatch> message "wrong number of arguments"} #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<expected function> message "expected a function value"} #err {<mismatch type> message "path must be a string, integer, list, or pointer"} 5.0
During namespace initialization, such a call is a read and has no effect. A function that it returns still follows the initialization rules.
1.4. Scope & Binding
DUST is a lexically scoped language. What one might call variables in another language are called bindings in DUST. A scope is the region of code where a binding is valid. A reference with no visible binding produces an unbound-name error.
Code uses a library with import, under an alias. A library names
the members that it provides with export. An import path names a
.dust file beside the importing file, or a namespace that is saved in the
database (Files).
To create local bindings you need to introduce a new scope, and in DUST, like many lisps, the main way to do that is with the let special form.
1.5. Namespace names
Builtin namespaces use plural countable nouns: schemas, documents,
functions, comparisons, errors, bitsets, hashes, pegs, regexes,
processes, scripts, terminals, tests and formats. Existing plural
names such as lists, maps, strings, collections and templates follow
this rule. Request methods use sessions, namespaces and programs.
Domain names and mass nouns keep their established spelling: math, time,
random, encoding and crypto. Standard abbreviations such as io, fs,
db, cli, net and stats also keep their spelling. There are no singular
aliases for plural builtin namespaces. Imported libraries choose their own
explicit aliases.
1.6. Identity & Equality
Equality asks whether two values contain the same data, regardless of how they were constructed or where they came from. Whereas identity asks whether references point to the same value.
Equality in DUST is by value, except for functions which compare by identity.
Equal values have equal hashes, because a hash covers a value's canonical bytes, which keep the integer/float distinction and drop comments. The converse fails only for functions: two closures with the same source hash alike but are not equal, since each is its own identity.
Since functions, constructs that do not exist in JSON or RON, can close over state it only makes sense for them compare by identity.
DUST provides = to test equality and comparisons/identical? to test identity.
1.7. Truth and Control Flow
Control-flow constructs in DUST are also expressions (reminder: everything is an expression), so they evaluate to values. DUST provides the following special forms and macros to enable branching and repetition. They decide which forms get evaluated and how often.
Every condition must be interpreted as either logically true or false. We must categorize each value as either logically true or false. DUST defines truth and falsehood so:
- `null`, `false`, and
#errvalues are falsey - everything else is truthy
An error used as a test therefore selects the false branch: (if ( 1 null) a b)= is b, since ( 1 null)= is an #err value.
We say that they are false/y/ or truth/y/ because they are logically true or false. To say they are true or false would imply they equal true or false, which obviously makes no sense.
DUST provides true? and false? to answer if some value is true or false. And boolean to coerce a value to true or false, and not to negate a value's truthiness.
1.7.1. Branching
1.8. Special forms and macros
Special forms and macros control evaluation or introduce bindings.
A special form is lowered by the evaluator. A macro is a DUST function that
runs before evaluation and returns the form to evaluate. The Macros
section defines them, and defmacro adds new ones.
Ordinary functions are documented in the Function Index.
1.8.1. Function construction
1.8.1.1. fn
Special Form(fn name? doc-or-meta? [params*] body*) → function
(fn name? doc-or-meta? ([params*] body*)+) → function
Creates a function.
The optional name is local to the function and supports self-reference from every arity body.
Functions can be selected, bound, passed, returned, and called.
A function's canonical form is its fn source, so printing and
hashing a closure use that form; values it captures are not part of
it. A library function's canonical form is its quoted name, such as "strings/case".
Recursion is supported.
The optional function name and parameter names are written as bare names.
References to parameters in the body use those same names.
The optional doc-or-meta slot accepts either a string docstring or a map of metadata.
A string docstring supplies the dust/doc entry in the function's metadata.
A bare name after fn names the function. A quoted string is a docstring,
including for an anonymous function. A metadata map can supply documentation
before the parameter list or arity clauses.
Only a docstring or dust/doc metadata documents a function. A comment is
never its documentation: a comment on the parameter list stays on that list.
1.8.1.1.1. Parameters and bodies
A parameter list without ... accepts exactly as many arguments as it has parameters.
An empty parameter list accepts no arguments.
Required parameters accept names or binding patterns.
A variadic parameter list contains one ... name capture, with positional parameters before or after it.
All positional arguments are required, including those after the capture.
The capture receives the intervening values as a nonempty list, or null when there are none.
The capture target is a name or the discard _.
The ... marker replaces & for variadic parameters.
Malformed patterns and duplicate parameter names are compilation errors.
The destructuring examples cover trailing and middle captures, nesting, missing values and discards.
1.8.1.1.2. Contracts
A contract is optional. Put it immediately after each parameter list.
List the input constraints before => and one result constraint after it.
Each arity has a separate contract.
Use ... at the same position as the variadic parameter capture.
One input constraint applies to each positional parameter or binding pattern.
Contract checks do not convert values.
Input checks run before parameter destructuring and body expressions.
A failed input check prevents body effects.
Result checks run after body effects.
An error that stops the body before its final expression is the result that the check examines.
A result constraint admits an error only through error? or [error S];
without one it rejects an error-valued result.
any, tagged?, [not S] and other predicates do not implicitly admit errors.
A union admits an error only through a matching explicit error branch.
An input constraint that admits an error receives an error argument at that position.
At another position, the call returns the error argument, not #err <contract input>,
and the body does not run. A function without a contract never receives an error argument.
A function constraint keeps the relation between an accepted argument sequence and its result.
Input comparison is contravariant. Result comparison is covariant.
A declaration alone does not prove a callable's behavior.
schemas/valid? returns false when it cannot establish the callable contract.
A function contract boundary gives an unproven callable a checked wrapper.
The wrapper checks each invocation; it does not run the callable to test it.
The wrapper is a new function value and does not change the original callable.
Aliases to one wrapper share its identity.
Passing an argument list with apply does not replace callbacks in that list.
The wrapper canonical form contains the contract and the wrapped definition or reference.
Captured runtime state is not part of that form.
An unavailable captured environment causes an explicit reconstruction error.
Contract schemas are evaluated when the function is constructed, so they keep the predicates selected then.
Function source loaded from a document must have contract headers whose construction
uses known pure direct operations without callbacks. Dynamic calls and effects in
these headers cause an explicit reconstruction error; function bodies remain deferred.
(fn [amount]
[int? => int?]
amount)
(fn [first ... more]
[int? ... int? => int?]
(reduce :+ first more))
(defn contracted [amount] [int? => int?] amount) (contracted 5) (defschema ContractInt int?) ((fn [callback] [[ContractInt => ContractInt] => ContractInt] (callback 2)) (fn [value] value)) (defschema ContractAnswer 42) (let [returned ((fn [value] [ContractAnswer => ContractAnswer] value) ContractAnswer) document (documents/from-value returned) definition (documents/value document) closed (documents/close document)] definition) ((fn [amount] [int? => int?] amount) 80) ((fn [amount] [int? => int?] amount) "80") ((fn [amount] [int? => int?] "bad") 80) ((fn [amount] [int? => int?] (/ amount 0)) 1) ((fn [amount] [int? => [join int? error?]] (/ amount 0)) 1) ((fn ([x] [int? => int?] x) ([x y] [int? int? => int?] (+ x y))) 1 2) ((fn [first ... more] [int? ... int? => int?] (reduce :+ first more)) 1 2 3) ((fn [{amount amount}] [map? => int?] amount) {amount 4}) (let [state {ran false} result ((fn [amount] [int? => int?] (put state "ran" true) amount) "80")] [result (get state "ran")]) (let [state {ran false} result ((fn [amount] [int? => int?] (put state "ran" true) "bad") 80)] [result (get state "ran")]) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] (+ value 1))) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] "bad")) [(schemas/valid? [int? => number?] (fn [value] [number? => int?] 1)) (schemas/valid? [number? => int?] (fn [value] [int? => number?] value)) (schemas/valid? [int? => int?] (fn [value] value)) (schemas/valid? [int? ... int? => number?] (fn [first ... values] [number? ... number? => int?] 1)) (schemas/valid? [number? ... number? => int?] (fn [first ... values] [int? ... int? => number?] 1))] (let [callback (fn [value] value)] ((fn [first second] [[int? => int?] [int? => int?] => boolean?] (comparisons/identical? first second)) callback callback)) (let [wrapped ((fn [callback] [fn? => [int? => int?]] callback) (fn [value] (+ value 1))) document (documents/from-value wrapped) definition (documents/value document) closed (documents/close document)] definition) (let [function (fn [value] [int? => int?] value) document (documents/from-value function) definition (documents/value document) bytes (encoding/tron/encode document) copy (encoding/tron/decode bytes) restored (documents/value copy) closed (documents/close document) copy-closed (documents/close copy)] [(= (str function) (str definition)) (= (str definition) (str restored))]) (let [original (fn [value] value) checked ((fn [callback] [fn? => [int? => int?]] callback) original)] [(comparisons/identical? original checked) (schemas/valid? [int? => int?] checked) (checked 2)])
(defn contracted [amount] [int? => int?] amount) (contracted 5) (defschema ContractInt int?) ((fn [callback] [[ContractInt => ContractInt] => ContractInt] (callback 2)) (fn [value] value)) (defschema ContractAnswer 42) (let [returned ((fn [value] [ContractAnswer => ContractAnswer] value) ContractAnswer) document (documents/from-value returned) definition (documents/value document) closed (documents/close document)] definition) ((fn [amount] [int? => int?] amount) 80) ((fn [amount] [int? => int?] amount) "80") ((fn [amount] [int? => int?] "bad") 80) ((fn [amount] [int? => int?] (/ amount 0)) 1) ((fn [amount] [int? => [join int? error?]] (/ amount 0)) 1) ((fn ([x] [int? => int?] x) ([x y] [int? int? => int?] (+ x y))) 1 2) ((fn [first ... more] [int? ... int? => int?] (reduce :+ first more)) 1 2 3) ((fn [{amount amount}] [map? => int?] amount) {amount 4}) (let [state <!ran> result ((fn [amount] [int? => int?] (put state "ran" true) amount) "80")] [result (get state "ran")]) (let [state <!ran> result ((fn [amount] [int? => int?] (put state "ran" true) "bad") 80)] [result (get state "ran")]) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] (+ value 1))) ((fn [callback] [[int? => int?] => int?] (callback 2)) (fn [value] "bad")) [(schemas/valid? [int? => number?] (fn [value] [number? => int?] 1)) (schemas/valid? [number? => int?] (fn [value] [int? => number?] value)) (schemas/valid? [int? => int?] (fn [value] value)) (schemas/valid? [int? ... int? => number?] (fn [first ... values] [number? ... number? => int?] 1)) (schemas/valid? [number? ... number? => int?] (fn [first ... values] [int? ... int? => number?] 1))] (let [callback (fn [value] value)] ((fn [first second] [[int? => int?] [int? => int?] => boolean?] (comparisons/identical? first second)) callback callback)) (let [wrapped ((fn [callback] [fn? => [int? => int?]] callback) (fn [value] (+ value 1))) document (documents/from-value wrapped) definition (documents/value document) closed (documents/close document)] definition) (let [function (fn [value] [int? => int?] value) document (documents/from-value function) definition (documents/value document) bytes (encoding/tron/encode document) copy (encoding/tron/decode bytes) restored (documents/value copy) closed (documents/close document) copy-closed (documents/close copy)] [(= (str function) (str definition)) (= (str definition) (str restored))]) (let [original (fn [value] value) checked ((fn [callback] [fn? => [int? => int?]] callback) original)] [(comparisons/identical? original checked) (schemas/valid? [int? => int?] checked) (checked 2)])
contracted 5 ContractInt 2 ContractAnswer (defschema ContractAnswer 42) 80 #err <contract input> #err <contract result> #err <contract result> #err <division integer zero> 3 6 4 [#err <contract input> false] [#err <contract result> true] 3 #err <contract result> [false false false false false] true (fn [argument1] [int? => int?] (apply (fn [value] (+ value 1)) [argument1])) [true true] [false true 2]
(defn positive [value] (> value 0)) (defschema ContractInt int?) (defschema LocalContract (fn [value] [ContractInt => boolean?] (> value 0))) (defschema TaggedContract (fn [value] [positive => boolean?] (> value 0))) (defschema ParameterShadow (fn [ContractInt] [ContractInt => boolean?] (> ContractInt 0))) (let [positive (fn [value] (< value 0)) local-document (documents/from-value LocalContract) local-loaded (schemas/load (documents/value local-document)) tag-document (documents/from-value TaggedContract) tag-loaded (schemas/load (documents/value tag-document)) shadow-document (documents/from-value ParameterShadow) shadow-loaded (schemas/load (documents/value shadow-document))] [(schemas/valid? local-loaded 1) (schemas/valid? local-loaded -1) (schemas/valid? tag-loaded 1) (schemas/valid? tag-loaded -1) (schemas/valid? shadow-loaded 1) (schemas/valid? shadow-loaded -1)]) (let [positive (fn [value] (> value 0))] [((fn [value] [positive => int?] value) 1) ((fn [value] [positive => int?] value) -1)]) (let [wrapped ((fn [callback] [fn? => [int? => boolean?]] callback) :int?)] (schemas/valid? wrapped 1)) (defschema Factory (fn [] (fn [value] [positive => boolean?] (> value 0)))) (let [snapshot (documents/from-value Factory) restored (schemas/load (documents/value snapshot)) predicate (restored)] [(predicate 1) (predicate -1)])
(defn positive [value] (> value 0)) (defschema ContractInt int?) (defschema LocalContract (fn [value] [ContractInt => boolean?] (> value 0))) (defschema TaggedContract (fn [value] [positive => boolean?] (> value 0))) (defschema ParameterShadow (fn [ContractInt] [ContractInt => boolean?] (> ContractInt 0))) (let [positive (fn [value] (< value 0)) local-document (documents/from-value LocalContract) local-loaded (schemas/load (documents/value local-document)) tag-document (documents/from-value TaggedContract) tag-loaded (schemas/load (documents/value tag-document)) shadow-document (documents/from-value ParameterShadow) shadow-loaded (schemas/load (documents/value shadow-document))] [(schemas/valid? local-loaded 1) (schemas/valid? local-loaded -1) (schemas/valid? tag-loaded 1) (schemas/valid? tag-loaded -1) (schemas/valid? shadow-loaded 1) (schemas/valid? shadow-loaded -1)]) (let [positive (fn [value] (> value 0))] [((fn [value] [positive => int?] value) 1) ((fn [value] [positive => int?] value) -1)]) (let [wrapped ((fn [callback] [fn? => [int? => boolean?]] callback) :int?)] (schemas/valid? wrapped 1)) (defschema Factory (fn [] (fn [value] [positive => boolean?] (> value 0)))) (let [snapshot (documents/from-value Factory) restored (schemas/load (documents/value snapshot)) predicate (restored)] [(predicate 1) (predicate -1)])
positive ContractInt LocalContract TaggedContract ParameterShadow [true false true false true false] [1 #err <contract input>] true Factory [true #err <contract input>]
1.8.1.1.3. Inferred signatures
The compiler infers a signature from each function body. A declared contract adds runtime checks, but it does not prove the body. The compiler keeps the declaration source and the inferred facts separately.
Each inferred clause records these facts:
- Required and variadic arguments.
- Input kinds and nested field or list paths.
- Relations between inputs, results, callbacks, and returned functions.
- Mutation, clock, random, host, and unknown effects.
- Result aliases and mutation after-states.
- A possible success region and a guaranteed success region.
The possible region includes every input that can succeed.
The guaranteed region includes only inputs that the compiler proves will succeed.
The signature is exact when both regions are equal.
An unsupported operation or an analysis limit keeps the signature approximate.
Inference uses bounded iterative walks; a large body cannot consume the native call stack.
An indirect call without a supported rule also keeps the signature approximate.
Expressions that may raise, and results without known facts, cannot establish a guaranteed region.
It does not turn an unknown fact into a proven fact.
Builtin rules apply only when lexical lookup selects that builtin.
A parameter named + or get remains an arbitrary callable.
A local binding also hides an older input alias when its value is unknown.
A get call with a fallback does not prove that the input field exists or has the fallback's kind.
Reads in a function that may mutate collections do not prove constraints on original input fields.
A get path that may be empty does not require a collection root.
Map and list destructuring accept null, which binds missing members to null.
A failing conditional arm does not exclude inputs that can take a successful arm.
An ordinary call error in an unused binding also does not exclude an input when
the function can return a successful final value. A call error in an earlier body
expression stops the body, so it excludes the input.
An error argument is not part of an input region: a call with one returns it
before the body runs, unless the parameter's contract admits an error.
Relations remain part of the signature. For example, multiplication keeps the same-number-kind and integer-overflow relations. Division keeps the same-kind and nonzero-denominator relations. The compiler does not replace these relations with unrelated argument bounds.
(let [multiply (fn [left right] (* left right))
divide (fn [numerator denominator] (/ numerator denominator))]
[(multiply 3037000499 3037000499)
(error? (multiply 9223372036854775807 2))
(divide 9 3)
(error? (divide 9 0))])
The inferred multiplication signature requires compatible numeric or duration operands.
Numeric operands use matching kinds.
Its integer or duration result must fit in a signed 64-bit integer.
The inferred division signature also requires a nonzero denominator.
The boundary cases are in conformance/signatures/cases.dust.
Collection signatures keep paths, callback calls, aliases, and mutation after-states. A returned function remains linked to its inferred signature. Opaque callback behavior stays unknown because inference does not call the callback.
A body contains zero or more expressions, evaluated in order.
Its final expression supplies the return value.
An empty body returns null.
When an expression before the final expression has an #err value, the body
stops and returns that value. The later expressions do not run. An error inside
a list, a map or a call argument does not stop the body, and a reference
resolves only when it runs, so a function can still refer to a top-level local
that a later form defines.
((fn [] nope 1)) (let [check (fn [x] (/ 1 x) x)] [(check 2) (check 0)]) (map (fn [x] (/ 1 x) x) [1 0 2]) ((fn [amount] [int? => int?] (/ amount 0) amount) 1) ((fn [amount] [int? => int?] (+ amount 1) amount) 1)
#err <name unbound> [2 #err <division integer zero>] [1 #err <division integer zero> 2] #err <contract result> 1
1.8.1.1.4. Multiple arities
The single-arity form has one parameter list followed by its body expressions.
The clause form has one or more parenthesized arity clauses, each with a parameter list followed by its body expressions.
Both forms create one function.
The optional name and documentation or metadata apply to the whole function.
An arity clause parses as a #invoke tagged element containing its parameter list followed by its body forms.
fn interprets this structure as a clause, not a call.
A function can have distinct fixed arities and at most one variadic clause. With a variadic clause, no fixed arity may exceed its required parameter count. Duplicate fixed arities, multiple variadic clauses, and fixed arities above that count are errors when compiling the function.
A call selects an exact fixed-arity match first.
Otherwise, it selects the variadic clause if enough arguments were supplied for its required parameters.
If neither matches, the call produces an arity error.
Selection depends on argument count, not argument types or clause order.
Only the selected body is evaluated, with parameter bindings local to that call.
Ordinary calls and apply use the same selection rules.
Functions capture their lexical bindings, including bindings retained by escaping closures. Top-level functions can call each other through top-level locals. Tail-call guarantees remain to be defined.
1.8.1.1.5. Examples
(let [increment (fn increment [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn increment "Return x plus one." [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment "Return x plus one." [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn increment {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn increment {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
(let [increment (fn {dust/doc "Return x plus one."} [x] (+ 1 x))] [(increment 0) (increment 1) (increment 41)])
1 2 42
(let [increment (fn [x] (+ 1 x))] (increment 4))
(let [increment (fn [x] (+ 1 x))] (increment 4))
(let [greet (fn greet "Greet one or more people." ([name greeting ... more] (strings/join [greeting ", " name (strings/join more "")] "")) ([] (greet "world")) ([name] (greet name "Hello")) ([name greeting] (strings/join [greeting ", " name "!"] "")))] [(greet) (greet "Ada") (greet "Ada" "Hi") (greet "Ada" "Hi" " and " "Bob" "!")])
(let [greet (fn greet "Greet one or more people." ([name greeting ... more] (strings/join [ greeting ", " name (strings/join more "")] "")) ([] (greet "world")) ([name] (greet name "Hello")) ([name greeting] (strings/join [ greeting ", " name "!"] "")))] [(greet) (greet "Ada") (greet "Ada" "Hi") (greet "Ada" "Hi" " and " "Bob" "!")])
"Hello, world!" "Hello, Ada!" "Hi, Ada!" "Hi, Ada and Bob!"
1.8.1.2. defn
Macro(defn name doc-or-meta? [params*] body*) → name
Defines a top-level function using the existing def and fn semantics.
The name is a declaration. Documentation, metadata, parameter rules, contracts,
multiple arities and variadic clauses follow fn. The result is the binding name, as
with def. Nested defn forms are errors.
(defn increment "Add one." [n]
(+ n 1))
(increment 41)
; 42
This is shorthand for (def increment (fn "Add one." [n] (+ n 1))).
As for fn, comments do not become its documentation.
Canonical formatting keeps short function headers together, including
defn name [params], fn [params] and def name (fn [params]. Comments
and long parameter lists can require separate lines. Formatting keeps each
comment on its value and is idempotent.
(defn increment "Add one." [n] (+ n 1)) (increment 41) (defn sum ([] 0) ([x] x) ([x y ... more] (reduce :+ (+ x y) more))) [(sum) (sum 2) (sum 2 3 4 5)] (def odd?) (defn even? [n] (if (= n 0) true (odd? (- n 1)))) (defn odd? [n] (if (= n 0) false (even? (- n 1)))) [(even? 10) (odd? 9)] (defn scale {dust/doc "Multiply by two." category "example"} [n] (* n 2)) (scale 21) (defn identity-with-doc "Constructor note\nParameter note" [x] x) (str identity-with-doc) (defn no-body []) (no-body) (= (str identity-with-doc) (str (fn "Constructor note\nParameter note" [x] x))) (let [doc (documents/from-value identity-with-doc) bytes (encoding/tron/encode doc) closed (documents/close doc) copy (encoding/tron/decode bytes) same (= bytes (encoding/tron/encode copy)) text (encoding/dust/encode copy) closed-copy (documents/close copy)] [same (strings/includes? text "Constructor note") (strings/includes? text "Parameter note")]) (defn muted-definition #mute "ignored documentation" [x] #mute (get missing "value") x) (muted-definition 42) (= (str muted-definition) (str (fn [x] x)))
(defn increment "Add one." [n] (+ n 1)) (increment 41) (defn sum ([] 0) ([x] x) ([x y ... more] (reduce :+ (+ x y) more))) [(sum) (sum 2) (sum 2 3 4 5)] (def odd?) (defn even? [n] (if (= n 0) true (odd? (- n 1)))) (defn odd? [n] (if (= n 0) false (even? (- n 1)))) [(even? 10) (odd? 9)] (defn scale {category "example" dust/doc "Multiply by two."} [n] (* n 2)) (scale 21) (defn identity-with-doc """ Constructor note Parameter note """ [x] x) (str identity-with-doc) (defn no-body []) (no-body) (= (str identity-with-doc) (str (fn """ Constructor note Parameter note """ [x] x))) (let [doc (documents/from-value identity-with-doc) bytes (encoding/tron/encode doc) closed (documents/close doc) copy (encoding/tron/decode bytes) same (= bytes (encoding/tron/encode copy)) text (encoding/dust/encode copy) closed-copy (documents/close copy)] [same (strings/includes? text "Constructor note") (strings/includes? text "Parameter note")]) (defn muted-definition \"ignored documentation" [x] \(get missing "value") x) (muted-definition 42) (= (str muted-definition) (str (fn [x] x)))
increment 42 sum [0 2 14] odd? even? odd? [true true] scale 42 identity-with-doc """" #invoke [ fn """ Constructor note Parameter note """ [#local x] #local x] """" no-body null true [true true true] muted-definition 42 true
{missing (defn) name (defn "wrong" [x] x) parameters (defn f) clauses (defn f 1) nested (let [] (defn f [x] x)) bad-parameter (defn f [42] 1) duplicate-arity (defn f ([x] x) ([y] y))}
{bad-parameter (defn f [42] 1) clauses (defn f 1) duplicate-arity (defn f ([x] x) ([y] y)) missing (defn) name (defn "wrong" [x] x) nested (let [] (defn f [x] x)) parameters (defn f)}
#cases [{output #err <invalid program> select "missing"} {output #err <invalid program> select "name"} {output #err <invalid program> select "parameters"} {output #err <invalid program> select "clauses"} {output #err <invalid program> select "nested"} {output #err <invalid program> select "bad-parameter"} {output #err <arity duplicate fixed fn> select "duplicate-arity"}]
(defn quoted [] '[1 2]) (quoted) (defn typo [] nope 1) (typo) (defn never-called [] missing 1) 2 (defn uses-later [] later) (def later 5) (uses-later) (defn rest-fails [x] (/ 10 x) (* x 2)) [(rest-fails 5) (rest-fails 0)]
(defn quoted [] ' [1 2]) (quoted) (defn typo [] nope 1) (typo) (defn never-called [] missing 1) 2 (defn uses-later [] later) (def later 5) (uses-later) (defn rest-fails [x] (/ 10 x) (* x 2)) [(rest-fails 5) (rest-fails 0)]
quoted #err {<name unbound> message "unbound name: '"} typo #err {<name unbound> message "unbound name: nope"} never-called 2 uses-later later 5 rest-fails [10 #err <division integer zero>]
1.8.1.3. do
Special Form(do expr*) → value
Evaluates the expr forms in order and returns the last result.
With no expressions, returns null.
When an expression before the last has an #err value, do returns that value
and does not evaluate the later expressions.
do introduces no bindings.
[(do) (do 7) (do 1 2 3) (if true (do "ignored" 42) (/ 1 0))]
(do) (do 7) (do 1 2 3) (if true (do "ignored" 42) (/ 1 0))
null 7 3 42
(do nope 1) (error? (do (nope 1) 1)) (do (/ 1 0) 1) (do #jsonptr ["a" (/ 1 0)] 1) (def r (do nope 1)) (error? r) [(do (/ 1 0) 1) 2] {value (do (/ 1 0) 1)} (count [(do (/ 1 0) 1)]) (do "ignored" (+ 1 2) 3)
(do nope 1) (error? (do (nope 1) 1)) (do (/ 1 0) 1) (do /a/,(/ 1 0) 1) (def r (do nope 1)) (error? r) [(do (/ 1 0) 1) 2] {value (do (/ 1 0) 1)} (count [(do (/ 1 0) 1)]) (do "ignored" (+ 1 2) 3)
#err <name unbound> true #err <division integer zero> #err <division integer zero> #err <name unbound> true [#err <division integer zero> 2] {value #err <division integer zero>} 1 3
1.8.2. Destructuring
Binding patterns select values and bind names in fn parameters, let bindings and for bindings.
Map keys select members. The corresponding pattern value supplies a binding name or a nested pattern, or the member is a tag.
List patterns select values by position. Maps and lists can nest inside either pattern.
Each binding input is evaluated once. Later let bindings and for collections can use the names already bound.
Selected collections retain their ordinary aliases. Destructuring does not deep-copy them.
(let [{name pilot spice amount} {name "Chani" spice 80}] [pilot amount])
(let [[pilot amount] ["Chani" 80]] [pilot amount])
(let [{name pilot cargo [amount unit]} {name "Chani" cargo [80 "kg"]}] [pilot amount unit])
((fn [[pilot amount]] [pilot (* amount 2)]) ["Chani" 80])
(for [[pilot amount] [["Chani" 80] ["Stilgar" 120]]] [pilot (* amount 2)])
Results, in the same order:
["Chani" 80]
["Chani" 80]
["Chani" 80 "kg"]
["Chani" 160]
[["Chani" 160] ["Stilgar" 240]]
1.8.2.1. Missing values and type errors
Missing map members and list items bind null. List patterns ignore extra items unless a capture collects them.
A null input supplies null throughout a pattern, including nested patterns.
A non-null input of the wrong kind reports #err <mismatch type>.
Stardust responses include the error's source position when available.
For example, the list type error below points to its [a b] pattern.
(let [[a b] [1]] [a b])
(let [[a b] [1 2 3]] [a b])
(let [[a b] null] [a b])
(let [{name pilot} null] pilot)
Results, in the same order:
[1 null]
[1 2]
[null null]
null
The following examples show wrong input kinds and missing required function arguments:
(let [[a b] 42] [a b])
(let [{name pilot} ["Chani"]] pilot)
((fn [head ... middle last] [head middle last]) 1)
Results, in the same order:
#err {<mismatch type> message "list destructuring requires a list, a packed math value, or null"}
#err {<mismatch type> message "map destructuring requires a map or null"}
#err {<mismatch arity> message "wrong number of arguments"}
1.8.2.2. Captures
A list pattern can contain one ... name capture. Nested list patterns can each contain their own capture.
The capture selects the values between the positional prefix and suffix.
A nonempty capture creates a new list container. Its elements retain their ordinary aliases.
An empty capture is null.
For short inputs, the prefix consumes available items first.
The suffix aligns with the end of the remaining input. Missing suffix positions bind null.
No input item is used twice.
(let [[a ... remaining] [1 2 3]] [a remaining])
(let [[head ... middle last] [1 2 3 4]] [head middle last])
(let [[a ... remaining] [1]] [a remaining])
(let [[head ... middle last] [1 2]] [head middle last])
(let [[head ... middle last] [1]] [head middle last])
(let [[head ... middle before-last last] [1 2]] [head middle before-last last])
Results, in the same order:
[1 [2 3]]
[1 [2 3] 4]
[1 null]
[1 null 2]
[1 null null]
[1 null null 2]
(let [[[a ... xs] [b ... ys]] [[1 2] [3 4]]] [a xs b ys])
Results, in the same order:
[1 [2] 3 [4]]
The target immediately after ... must be a name or _.
To destructure a captured list, bind its name first and destructure that value in a later binding.
1.8.2.3. Tags
In a map pattern, a tag binds a member to a local with the same name as its key.
The pattern <name spice> binds the same names and values as {name name spice spice}.
A tag group can stand alone as a pattern, or it can share a map pattern with ordinary members.
A tag is a member whose value is true, thus {name true} is the same pattern as <name>.
The tag <_> is a discard.
(let [<name spice> {name "Chani" spice 80}] [name spice])
(let [{<name> spice amount} {name "Chani" spice 80}] [name amount])
(let [{pilot <name rank>} {pilot {name "Chani" rank 3}}] [name rank])
((fn [<name spice>] [name (* spice 2)]) {name "Chani" spice 80})
(for [<name spice> [{name "Chani" spice 80} {name "Stilgar" spice 120}]] [name spice])
(let [<name missing> {name "Chani"}] [name missing])
(let [<name> null] name)
Results, in the same order:
["Chani" 80]
["Chani" 80]
["Chani" 3]
["Chani" 160]
[["Chani" 80] ["Stilgar" 120]]
["Chani" null]
null
A negated tag, such as <!name>, is a compilation error. A tag whose key is not a name is also a compilation error.
1.8.2.4. Variadic functions
Function argument lists also support trailing and middle captures. Unlike a list pattern, a function requires every positional argument before and after its capture. Missing required arguments report an arity error. Fixed arity clauses retain precedence over a variadic clause at equal arity.
((fn [head ... remaining] [head remaining]) 1 2 3)
((fn [head ... middle last] [head middle last]) 1 2 3 4)
Results, in the same order:
[1 [2 3]]
[1 [2 3] 4]
1.8.2.5. Discards and duplicate names
The discard pattern _ consumes a value without creating a binding. Repeated discards are allowed, including a ... _ capture.
A discard does not remove a position like the source mute form.
(let [[a _ c] [1 2 3]] [a c])
(let [[head ... _ last] [1 2 3 4]] [head last])
Results, in the same order:
[1 3]
[1 4]
A name can appear only once within one pattern or one function parameter list. This check includes nested patterns and capture targets. Repeated names are compilation errors. Malformed patterns also fail during compilation. These forms demonstrate duplicate names, repeated captures, invalid capture targets and invalid tags:
[
(let [[a a] [1 2]] a)
(let [{name x age x} {name "Chani" age 27}] x)
(fn [a a] a)
(fn [{name x} [x]] x)
(let [[a ... xs ... ys] []] a)
(let [[a ... [b c]] [1 2 3]] a)
(let [[a ... {x x}] [1]] a)
(let [[a ...] [1]] a)
(let [[... a a] [1]] a)
(fn [a ... xs ... ys] a)
(fn [a ... [b]] a)
(fn [a & rest] a)
(let [42 1] 2)
(let [<!a> {a 1}] a)
(let [{<a> b a} {a 1 b 2}] a)
(let [{"not a name" true} {}] 1)
(let [{... true} {}] 1)
(let [[a true] [1 2]] a)
(let [true 1] 2)
(fn [<a> a] a)
]
Sequential let rebinding and ordinary lexical shadowing remain available.
Bind the whole input normally before destructuring it when both are needed.
(let [a 1 a (+ a 1)] a)
(let [shipment {name "Chani" spice 80} {name pilot} shipment] [shipment pilot])
Results, in the same order:
2
[{name "Chani" spice 80} "Chani"]
1.8.2.6. Defaults and scope
Use ordinary expressions to supply defaults:
(let [{name pilot} {}] (if (= pilot null) "Unknown" pilot))
Results, in the same order:
"Unknown"
Dedicated default syntax, whole-value pattern shorthand, map-rest captures and constraint annotations are deferred.
New patterns apply to fn, let and for. Other binding forms keep their existing behavior.
1.8.3. let
Special Form(let [bindings*] exprs*)
Introduces local bindings and evaluates a body in their scope.
The binding list contains zero or more pairs of binding patterns and value expressions. A name in a pattern declares a local. It does not look up an existing value. A later binding can reuse a name from an earlier binding.
(let [price (* 5 2) quantity 3] (* price quantity))
(let [price (* 5 2) quantity 3] (* price quantity))
The value expressions are evaluated once and in order. Each binding becomes available to use in later expressions.
(let [price 10 quantity 3 total (* price quantity)] total)
(let [price 10 quantity 3 total (* price quantity)] total)
Bindings are in scope throughout the body of their let and within nested expressions.
Inner scopes can introduce the same names, shadowing the outer bindings.
(let [price 10] [(let [price (+ price 2)] price) price])
(let [price 10] [(let [price (+ price 2)] price) price])
12 10
A function closes over the bindings it references from its surrounding lexical scope. The resulting closure has those bindings available when the function is called, even after execution has left that scope (indefinite extent).
(let [name "outer" read-name (fn [] name)] (let [name "inner"] (read-name)))
(let [name "outer" read-name (fn [] name)] (let [name "inner"] (read-name)))
"outer"
(let [read-name (let [name "outer"] (fn [] name))] (read-name))
(let [read-name (let [name "outer"] (fn [] name))] (read-name))
"outer"
Body expressions inside the let are evaluated in order.
When a body expression before the last has an #err value, the let returns
that value and does not evaluate the later expressions. A binding whose value is
an error does not stop the let.
The let special form is an expression and evaluates to the value of the final expression in the body of the let, unless the body is empty in which case it evaluates to null.
(let [] nope 1) (let [x 1] nope x) (let [x (/ 1 0)] x 1) (let [x (/ 1 0)] 1) (let [x (/ 1 0)] (error? x)) (let [x (do (/ 1 0) 1)] [x 2])
#err <name unbound> #err <name unbound> #err <division integer zero> 1 true [#err <division integer zero> 2]
Additional forms that introduce bindings are: fn, for, and def.
1.8.4. def
Special Form(def name value? ...) → local reference
Defines top-level locals: bindings that the later top-level forms of the same file, or of the same REPL session, read as their names.
def is a top-level form. Inside any other form it is
#err <invalid program>. Each top-level form is evaluated on its own, so a
form sees the locals that earlier forms define.
The operands are name/value pairs, evaluated from left to right. Each binding
is visible to the values that follow it and to later top-level forms.
(def name value) returns the reference name.
(def name value other other-value) returns the reference other.
Zero operands and an incomplete pair are #err <arity mismatch>. A name
position that is not a name is #err <invalid program>.
A later def with the same name gives the same binding a new value. A
reference to a top-level local is read each time it runs, so a function made
earlier sees the new value, and a function can call a function that is
defined after it, once that function exists.
(def name) declares a local without a value, and leaves the value of a
local that has one. A declared local is #err <name unbound> until a later
def gives it a value. A declaration lets two top-level functions call
each other, as in Clojure's declare.
(def odd?) (def even? (fn [n] (if (= n 0) true (odd? (- n 1))))) (def odd? (fn [n] (if (= n 0) false (even? (- n 1))))) (even? 10)
odd? even? odd? true
When a value is an #err value, def returns that value, declares the name
without a value, and does not evaluate later pairs.
A let, fn, or for binding with the same name shadows a top-level local.
A constant reference never reaches a top-level local. The name of a library
entry is #err <conflict name>, because a direct call of that name always
calls the library entry. The name of a schema marker, such as meet or is,
is also #err <conflict name>, because a bare marker name always means the
marker. This holds for a saved namespace and a REPL session too: a namespace
that defines such a name does not load, and in a REPL the def returns the
error and the name keeps its builtin meaning.
(def int? (fn [v] true))
#err {<conflict name> message "int? is a builtin constant"}
1.8.5. import
(import {alias path ...}) → null
Declares namespace dependencies under explicit aliases. The argument is one map. Each member imports one namespace. A map key is an unqualified alias.
A member value is one of:
- A JSON Pointer.
(import {spice /arrakis/spice})imports the saved namespacearrakis/spiceasspice. - A string namespace key.
(import {spice "arrakis/spice"})is the same import. true.(import {spice true})imports/spiceasspice.
A true member uses the map key as the namespace path and the last path segment
as its alias. A tag-only map is shorthand for such members.
(import <arrakis/spice guild/shipping>) imports arrakis/spice as spice
and guild/shipping as shipping.
(import {shipping /guild/shipping tax "imperial/tax"})
A pointer's segments decode and join with /. The root pointer, empty
segments, and segments that contain / are errors. A string value is a
namespace key, so a leading / is invalid. Boolean false and other values
are errors.
When formatting program source, stardust fmt uses the short form if an alias
is the last path segment.
(import {bar /foo/bar}) and (import {bar "foo/bar"}) format as
(import <foo/bar>). An explicit alias that is not the last segment stays a
map member, as in (import {label /a/b/c}). Data encoding and conversion keep
the map keys and values.
An import belongs at the top level, outside functions and other expressions.
It does not return a namespace object. The two-operand (import path alias)
form is invalid. Choose an alias that does not conflict with a local or a
selected builtin namespace, such as math or strings. A stored path may
still use those names; choose a different alias when importing it.
Save this source as arrakis/spice:
; Spice production calculations. (def reserve-percentage 10) (defn usable-spice "Return the harvest after the imperial reserve." [harvest] (/ (* harvest (- 100 reserve-percentage)) 100)) (defn harvester-output [crews yield] (* crews yield)) (export usable-spice harvester-output)
; Spice production calculations. (def reserve-percentage 10) (defn usable-spice "Return the harvest after the imperial reserve." [harvest] (/ (* harvest (- 100 reserve-percentage)) 100)) (defn harvester-output [crews yield] (* crews yield)) (export usable-spice harvester-output)
[ ; Spice production calculations. #invoke [def #local reserve-percentage 10] #invoke [ defn #local usable-spice Return the harvest after the imperial reserve. [#local harvest] #invoke [/ #invoke [* #local harvest #invoke [- 100 #local reserve-percentage]] 100]] #invoke [defn #local harvester-output [#local crews #local yield] #invoke [* #local crews #local yield]] #invoke [export #local usable-spice #local harvester-output]]
A second namespace can import its exports:
(import <arrakis/spice>) (defn shipment [harvest] (spice/usable-spice harvest)) (export shipment)
(import <arrakis/spice>) (defn shipment [harvest] (spice/usable-spice harvest)) (export shipment)
[#invoke [import <arrakis/spice>] #invoke [defn #local shipment [#local harvest] #invoke [spice/usable-spice #local harvest]] #invoke [export #local shipment]]
The call (shipping/shipment 1000) returns 900.0. Only explicitly exported
names are public; reserve-percentage remains private. Read an exported
constant with :alias/name, and invoke an exported function with
(alias/name arguments).
An import path can name a local file (Files). Other paths name saved namespaces. Use namespace commands to save a namespace.
Each namespace initializes its top-level definitions before its exports become available. Initializers may perform pure calculations. Host effects, reading the clock and executing a database query are refused during initialization. A function containing a query is valid: its query runs when called, rather than when its definition is loaded. Import cycles and missing exports are errors.
Unchanged imports keep their current mutable values. A new initializer reads
those values; loading a consumer does not reset its dependencies. For example,
if depot/lots started as [100] and an earlier call appended 200, a new
consumer's (def lots :depot/lots) shares [100 200] and
(count :depot/lots) returns 2. Later mutations through either reference
remain visible through the other.
A valid save checks the proposed source in a fresh context. Loading that version in an existing session may still fail because an imported value was mutated. A failed load keeps the previous aliases and instances intact. Calls requiring the changed version report the initialization error; they do not silently run the old definition. Repair the source or reset the session to recover.
An ordinary database invocation uses one consistent version of its code, imports and data. Later invocations observe valid saved changes without reloading an alias. This also applies to an exported function retained in a local for a later call. A running call keeps its starting version. Saving a namespace does not change an invocation already in progress.
1.8.5.1. Files
An import path can name a local file. The runtime looks for PATH.dust in the
directory of the importing file. Code without a file, such as a REPL entry,
uses the working directory. In app/main.dust, (import {s "lib/shapes"})
names app/lib/shapes.dust. When that file imports "util", the path names
app/lib/util.dust. A path to a file can contain . and .. segments, as in
(import {check "../lib/check"}). A saved namespace path cannot.
An import reads only files under an import root. The root of stardust eval,
run and a script is the directory of the program's file. The root of the
REPL and of an nREPL server is the working directory. The imports setting of
the configuration adds roots (Configuration
files). The runtime resolves symlinks and .. before it compares a file
with the roots. A file that exists outside every root is refused with
#err <denied fs>. Its message names the import path, the resolved file and
the roots:
#err {<denied fs>
column 1
line 1
message "import ../lib/check resolves to /home/ada/lib/check.dust, outside the import roots: /home/ada/tools"}
The .. of (import {check "../lib/check"}) in tools/main.dust thus needs
a configuration whose roots include the parent of tools/.
When the file exists and the database has no saved namespace of that path, the import uses the file. When only the saved namespace exists, the import uses it. When both exist, the import uses the newer one. The file is newer when its modification time is the same as or later than the save time of the namespace. The rule applies to each import, also to the imports in an imported file. Without a database, there are no saved namespaces, and an import of a path without a file fails.
The comparison uses the clock of the filesystem and the clock of the database. A file with a time in the future stays newer until a later save. A saved namespace without a recorded save time is older than all files. When the runtime cannot read the time of a file, it uses the file, and the read of the file then fails.
A file is one namespace, whatever path names it. Two importers in different
directories that name the same file share one namespace. The namespace of a
file does not replace the saved namespace of the same path for other code. A
saved namespace that imports that path continues to use the saved namespace.
The runtime does not save a file. Use
stardust namespace save to save one.
Each evaluation of an import form reads the files again. This includes the
files that the form names, the files that they import, and each file that the
session loaded before. A new or changed file initializes again, and so does
each file that imports it. An unchanged file keeps its values. A file
initializes as a saved namespace does, so its initializers have no host
effects. A library reads cli/args or scripts/path in a function, not in a
def. The runtime reads an imported file as source, as stardust eval reads
its file. Inside the roots, this needs no io grant.
The alias rules do not change. (import <lib/math>) gives the alias math,
which is a builtin namespace, and fails. Use (import {m "lib/math"}).
An import cycle through files is #err <cycle import>. A file that exists but
cannot be read is #err <fs io>. An error in an imported file gives the
file and the line and column in it. Parse errors, compile errors and
failed initializers are examples.
#err {<cycle import>
column 1
file "/home/ada/app/lib/a.dust"
line 1
message "import cycle: /home/ada/app/lib/a.dust -> /home/ada/app/lib/b.dust -> /home/ada/app/lib/a.dust"}
1.8.6. export
Special Form(export name*) → list
Names the top-level locals that a library file provides. When code
imports the file, as (import {s "lib/shapes"}) does, each named local becomes
the constant :s/name. Its value is the value of the local after the file
runs. The other locals of the file stay private. The file's functions read
them, not the locals of the code that calls them.
; lib/shapes.dust
(def area (fn [w h] (* w h)))
(def square (fn [s] (area s s)))
(def unit 1)
(export square unit)
After (import {s "lib/shapes"}), (s/square 3) returns 9 and :s/unit
returns 1. :s/area is #err <name unbound>.
export is a top-level form, and a file can have more than one. A file
with no export provides nothing. An import fails when export names a local
that does not exist or has no value, or when a top-level form returns an
#err value. Evaluated directly, export returns the list of the named
references and has no other effect.
1.8.7. Control Flow
1.8.7.1. and
Special Form(and forms*) → value
Evaluates forms once each, from left to right, and returns the first falsey
value without evaluating later forms; an #err value is falsey, so and returns it. If every form is truthy, returns the
last value. With no forms, returns true.
Only false, null, and #err values are falsey; zero and the empty string are truthy.
The result is an operand value rather than a conversion to boolean.
(and) (and 0 "" "x") (and false (/ 1 0)) (and null (/ 1 0)) (let [m {n 0}] [(and (do (patch m {n (+ (get m "n") 1)}) "x") "y") (get m "n")])
true "x" false null ["y" 1]
1.8.7.2. or
Special Form(or forms*) → value
Evaluates forms once each, from left to right, and returns the first truthy
value without evaluating later forms. If every form is falsey, returns the
last value. With no forms, returns null.
Only false, null, and #err values are falsey; zero and the empty string are truthy.
The result is an operand value rather than a conversion to boolean.
(or) (or null false "x") (or 0 (/ 1 0)) (or "" (/ 1 0)) (let [m {n 0}] [(or (do (patch m {n (+ (get m "n") 1)}) null) "y") (get m "n")])
null "x" 0 "" ["y" 1]
1.8.7.3. if
Special Form(if test then)
(if test then else)
Selects a branch according to the truthiness of a test.
The test is evaluated once. The resulting value's truthiness is used to choose a branch.
A truthy result selects then, and a falsey result selects else.
Only the selected branch is evaluated, and its value becomes the value of the whole if expression.
If else is omitted, a falsey test evaluates to null.
Each branch contains one expression.
if is a special form because it controls which arguments are evaluated, rather than evaluating all of them before making the choice.
1.8.7.4. when
Macro(when test body...)
Runs a body when its test is truthy.
It evaluates the test once, then evaluates the body expressions in order and returns the last result.
If the test is falsey, the body is not evaluated and the result is null.
An empty body also returns null.
Unlike if, when has no alternative branch and can contain several body expressions.
1.8.7.5. when-not
Macro(when-not test body...)
Runs a body when its test is falsey.
Like when, it evaluates the test once, evaluates the selected body in order, and returns the last result.
A truthy test skips the body and returns null, and an empty body returns null regardless of the test's value.
1.8.7.6. cond
Special Form(cond test result ...)
Chooses among pairs of tests and result expressions.
It evaluates tests once each, in order, until one is truthy.
It then evaluates and returns that test's result expression, without evaluating any later tests or results.
A selected result of false or null is still the result, not a reason to continue to another pair.
If no test is truthy, cond returns null.
With no pairs, it also returns null.
Every test must have a result expression, so an unmatched final test is an error before evaluation.
cond is a special form, not a macro: a macro would nest one if for each pair, and a cond of tens of thousands of pairs would then fill the LuaJIT stack (see Nesting depth).
A final pair with true as its test supplies a default result.
This is an ordinary truthy test, not a separate default-branch syntax.
1.8.7.7. for
Special Form(for [name collection ...] body)
Evaluates a body for each combination of collection values and returns a list of the results.
Evaluation is eager: all iterations complete before for returns.
Each collection value is bound through a name or binding pattern.
The bindings are local to the for.
Multiple binding pairs introduce nested iteration, with the leftmost binding as the outermost loop. Lists are traversed in order. The body evaluates once per combination, contributing one value to the result list.
(for [x [1 2] y [10 20]] (+ x y))
(for [x [1 2] y [10 20]] (+ x y))
11 21 12 22
Each collection expression is evaluated once each time its loop is entered. Later collection expressions can reference earlier bindings. An empty collection contributes no combinations.
The body contains one expression. Use (do ...) to evaluate several expressions
and collect the final value; callers may ignore the result list for effects.
A let in the body can introduce additional bindings for calculated values.
If the body produces a list, that list is one element of the result.
{ case0 (let [values []] [(for [x [1 2] y [10 20]] (do (lists/append values (+ x y)) (+ x y))) values]) case1 (let [values []] (for [x [1 2 3]] (do (lists/append values x) (lists/append values (- x)))) values) case2 (let [values []] (for [x [] y (lists/append values 1)] (lists/append values 2)) values) case3 (let [values []] (for [x [1 2] y (lists/range x)] (lists/append values [x y])) values) case4 (for [] 42) case5 (for [x [1 2]] (do)) case6 (for [x 42] x) case7 (for [x [1]] (do (for [x [2 3]] x) x)) case8 (let [x 10] (for [x [1 2]] x) x) case9 (let [values [] f (fn [xs] (for [x xs] (lists/append values x)))] (f [1 2]) (f [3]) values) case10 (for [x [1]] (tests/assert false "for body executes")) }
{case0 (let [values []] [(for [x [1 2] y [10 20]] (do (lists/append values (+ x y)) (+ x y))) values]) case1 (let [values []] (for [x [1 2 3]] (do (lists/append values x) (lists/append values (- x)))) values) case10 (for [x [1]] (tests/assert false "for body executes")) case2 (let [values []] (for [x [] y (lists/append values 1)] (lists/append values 2)) values) case3 (let [values []] (for [x [1 2] y (lists/range x)] (lists/append values [x y])) values) case4 (for [] 42) case5 (for [x [1 2]] (do)) case6 (for [x 42] x) case7 (for [x [1]] (do (for [x [2 3]] x) x)) case8 (let [x 10] (for [x [1 2]] x) x) case9 (let [values [] f (fn [xs] (for [x xs] (lists/append values x)))] (f [1 2]) (f [3]) values)}
#cases [{output [[11 21 12 22] [11 21 12 22]] select "case0"} {output [1 -1 2 -2 3 -3] select "case1"} {output [] select "case2"} {output [[1 0] [2 0] [2 1]] select "case3"} {output [42] select "case4"} {output [null null] select "case5"} {output #err <mismatch type> select "case6"} {output [1] select "case7"} {output 10 select "case8"} {output [1 2 3] select "case9"} {output #err <assertion test> select "case10"}]
1.8.8. Quotation
1.8.8.1. quote
Special Form#quote form
Returns the enclosed form as data without evaluating it. References, invocations, and collection contents retain their form representation. See Quotation forms for prefix syntax and encoding.
1.8.8.2. quasiquote
Macro#quasiquote form
Constructs data while evaluating unquotes at the matching nesting depth. List-element splices insert the elements of their evaluated list. See Quotation forms for prefix syntax and encoding.
1.8.8.3. unquote
Macro#unquote form
Evaluates the enclosed form within its matching quasiquote and substitutes the resulting value. Outside quasiquote, this is an error. See Quotation forms for prefix syntax and encoding.
1.8.8.4. unquote-splicing
Macro#unquote-splicing form
Evaluates the enclosed list within its matching quasiquote and inserts its elements into the surrounding list. A non-list result or a splice outside a list-element position is an error. See Quotation forms for prefix syntax and encoding.
1.8.9. Macros
A macro is a DUST function that the compiler runs before evaluation. Its parameters bind the unevaluated argument forms as data, and its result is the form that takes the place of the call. The compiler then lowers that form as if the program had contained it. Macros are procedural, as in Clojure, Janet and Fennel: the body is ordinary DUST code, and quasiquote is the usual way to build the result.
(defmacro unless [test ... body]
~(if ,test null (do ,@body)))
(unless (= 1 2) "ran")
; "ran"
(macroexpand-1 `(unless a b c))
; (if a null (do b c))
The core macros when, when-not and defn
are defined this way. The evaluator lowers the special forms if, cond,
let, fn, do, and, or, def, export and for directly.
1.8.9.1. defmacro
Special Form(defmacro name doc-or-meta? [params*] body*) → name
Defines a macro for the later forms of the file or session.
defmacro is a special form: it adds a macro instead of binding a
value. The name is a declaration, and the result is the name, as with
def and defn. The documentation slot, metadata, parameter
rules, variadic ... parameters and arity checks follow fn.
Each parameter receives one argument form, and the body returns a form.
Forms that the body does not include in its result are never evaluated.
A rest parameter with no argument forms is null, which a splice inserts
as nothing, so (do ,@body) with an empty body is (do).
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (unless (= 1 2) "ran") (unless (= 1 1) "skipped") (unless false 1 2 3)
unless "ran" null 3
(defmacro first-form "Returns its first argument form." [x ... more] x) (defmacro second-form {dust/doc "Returns its second argument form." category "example"} [x y] y) (first-form 1 (/ 1 0)) (second-form (/ 1 0) 2)
(defmacro first-form "Returns its first argument form." [x ... more] x) (defmacro second-form {category "example" dust/doc "Returns its second argument form."} [x y] y) (first-form 1 (/ 1 0)) (second-form (/ 1 0) 2)
first-form second-form 1 2
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (unless true) (unless false)
unless null null
defmacro is a top-level form. A defmacro inside another form is
#err <invalid program>, as a nested defn is. A missing name or parameter
list is the same error.
{missing (defmacro) name (defmacro "wrong" [x] x) parameters (defmacro m) nested-do (do (defmacro m [] 1)) nested-let (let [] (defmacro m [] 1))}
{missing (defmacro) name (defmacro "wrong" [x] x) nested-do (do (defmacro m [] 1)) nested-let (let [] (defmacro m [] 1)) parameters (defmacro m)}
#cases [{output #err <invalid program> select "missing"} {output #err <invalid program> select "name"} {output #err <invalid program> select "parameters"} {output #err <invalid program> select "nested-do"} {output #err <invalid program> select "nested-let"}]
1.8.9.1.1. Scope
A macro applies to the top-level forms that follow its definition in the same
file, saved namespace or REPL session. A form before the definition calls an ordinary function
of that name, or fails when there is none. The body of a macro can call
defn helpers defined earlier in the file, because the body runs as ordinary
code.
(wrapped 1) (defn wrap [form] ~(do ,form)) (defmacro wrapped [x] (wrap x)) (wrapped 5)
#err <name unbound> wrap wrapped 5
export can name a macro. Code that imports the file calls the
macro as alias/name, as it calls a function of the library. After
(import {c "lib/control"}), (c/unless ( x 0) (/ 1 x))= expands with the
imported unless. This applies to files and to saved namespaces. When the
imported namespace changes, the code that imports it expands the new version.
The forms of a namespace also expand its own macros and the macros of its
imports. Evaluated directly, export returns the list of the named references
and has no other effect.
A save checks the names in the forms that the macros expand to, as it checks the names in the source. A name that a macro adds is reported at the macro call.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (export unless)
unless [unless]
1.8.9.1.2. Not a value
A macro is not a value. Only an invocation whose head names the macro
expands. A reference to the name has no binding: :ns/name and a bare name
in an argument position are #err <name unbound>. Passing the name to
apply, or reaching the macro through a computed callee, is
#err <expected function>.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) :unless [unless] (apply unless [true 1]) ((functions/identity unless) true 1)
unless #err {<name unbound> message "unbound name: unless"} [#err {<name unbound> message "unbound name: unless"}] #err {<name unbound> message "unbound name: unless"} #err {<expected function> message "expected a function value"}
A let, fn or for binding of the same name shadows the macro inside its
scope. Inside the scope, the name calls the bound function. Outside the
scope, the macro applies again.
(defmacro twice [x] ~[,x ,x]) (twice 3) (let [twice (fn [x] (* 2 x))] (twice 3)) ((fn [twice] (twice 3)) (fn [x] (+ x 1))) (for [twice [(fn [x] (- x 1))]] (twice 3)) (twice 3)
twice [3 3] 6 4 [2] [3 3]
A defmacro whose name is a special form, a library entry or a schema
marker is #err <conflict name>, as a def of that name is.
1.8.9.1.3. Expansion
The compiler expands each invocation in two steps. First, while the head names a macro, it runs the macro and replaces the invocation with the result. A macro can expand to another macro call, and expansion continues until the head is not a macro. Then it expands the subforms of the result, and lowers the result.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (defmacro guard [test ... body] ~(unless (not ,test) ,@body)) (guard true "ok") (guard false "ok") (macroexpand-1 `(guard t a)) (macroexpand `(guard t a))
unless guard "ok" null (unless (not t) a) (if (not t) null (do a))
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (+ 1 (unless false 2)) [(unless false 1) {a (unless false 2)}] (let [x (unless false 3)] (if (unless false true) x "no"))
unless 3 [1 {a 2}] 3
Expansion does not enter a quote payload or a quoted builtin form such
as a query or mutation body. A macro call inside them stays data. Inside a
quasiquote, the unquoted parts are evaluated, so a macro call in an
unquote or a splice expands. The quoted parts stay data.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) `(unless a b) `[(unless a b)]
unless (unless a b) [(unless a b)]
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) ~(unless a ,(unless false 1)) ~[,@(unless false [1 2]) (unless x y)]
unless (unless a 1) [1 2 (unless x y)]
1.8.9.1.4. Hygiene
A macro of a saved namespace calls the namespace's own definitions from its
templates. In a quasiquote template of such a macro, a bare name that the
expansion calls or evaluates refers to the namespace's top-level definition
of that name, private or exported, when the namespace defines it and the
template does not bind it. The expansion holds a private reference to the
definition, written #private ["lib/helpers" helper] with the namespace's
path. A binding at the call site does not capture it, and the definition
stays private.
;; saved as lib/helpers
(defn helper [x] (* x 10))
(defmacro tenfold [x] ~(helper ,x))
(defmacro helper-name [] ~`helper)
(export tenfold helper-name)
;; caller
(import {helpers /lib/helpers})
(helpers/tenfold 3) ; 30
(let [helper (fn [n] n)] (helpers/tenfold 3)) ; 30
(helpers/helper 4) ; #err <name unbound>
(helpers/helper-name) ; helper
The reference resolves in the version of the namespace that the call runs
with, as an imported name does, and also while the namespace initializes
its own later forms. A name stays as written, and resolves at the call site,
when it is in an unquote or a splice, quoted, a literal map key, a name that
the template's let, for, fn, defn or schemas/match binds or that
its def, defn or defmacro declares, inside a quoted builtin form such
as a query, at another depth of a nested quasiquote, or a name that the
namespace does not define, such as a builtin. Macros of the namespace are
not definitions: a template that names one expands it at the call site.
Only the runtime makes a private reference. A #private tag that is typed,
pasted, read from a host document or from JSON is data. As a call's head it
is #err <name unbound> with the name it spells:
(#private ["lib/helpers" helper] 3) is #err <name unbound> with the
message unbound name: lib/helpers/helper. A function's printed form shows
the tag, and a function rebuilt from that text has no references. A
function that the runtime holds or stores keeps them.
Other names in a macro's result resolve at the call site: a macro of a
session or a REPL file, and a name that a namespace macro's template does
not resolve, can capture a name from the call site. The macro author
prevents this with new names.
gensym returns a new name, and a bare name ending in # inside a
quasiquote is an automatic gensym. Each different name# in one quasiquote
form is one new name. tmp# written twice in the same quasiquote is the
same name, and tmp# in another quasiquote is a different name.
(defmacro swap-order [a b]
~(let [tmp# ,a] [,b tmp#]))
(let [tmp 5] (swap-order tmp 2))
; [2 5]
New names are spelled prefix__N: tmp# becomes tmp__1, and (gensym)
becomes G__1. The counter starts at 1 when the expansion of a top-level
form starts. Every gensym and name# inside that expansion continues the
count in order of first use. A macroexpand call starts its own count.
Thus the same source expands to the same text.
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (defmacro two-forms [] [~tmp# ~tmp#]) (defmacro pair-names [] ~(let [a# 1 b# 2] [a# b#])) (let [tmp 5] (swap-order tmp 2)) (macroexpand-1 `(swap-order tmp 2)) (macroexpand-1 `(two-forms)) (macroexpand-1 `(pair-names))
swap-order two-forms pair-names [2 5] (let [tmp__1 tmp] [2 tmp__1]) [tmp__1 tmp__2] (let [a__1 1 b__2 2] [a__1 b__2])
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (= (macroexpand `(swap-order x 2)) (macroexpand `(swap-order x 2))) (str (macroexpand `(swap-order x 2))) (let [text (str (fn [] [(swap-order a 1) (swap-order b 2)]))] [(strings/includes? text "tmp__1") (strings/includes? text "tmp__2") (strings/includes? text "tmp__3")])
(defmacro swap-order [a b] ~(let [tmp# ,a] [,b tmp#])) (= (macroexpand `(swap-order x 2)) (macroexpand `(swap-order x 2))) (str (macroexpand `(swap-order x 2))) (let [text (str (fn [] [(swap-order a 1) (swap-order b 2)]))] [(strings/includes? text "tmp__1") (strings/includes? text "tmp__2") (strings/includes? text "tmp__3")])
swap-order true "#invoke [let [#local tmp__1 #local x] [2 #local tmp__1]]" [true true false]
1.8.9.1.5. Sandbox
A macro body runs with no capabilities. Calls to fs/, crypto/random/,
time/now, random/ and database operations fail inside a macro as they do in an
evaluation without the matching capability. The failure becomes an
#err <invalid program> at the call site. Expansion shares the memory and
CPU limits of the evaluation, and the expansion depth of one form is limited.
A macro that expands to itself without end is #err <macro expansion limit>.
A head chain permits 1000 expansions. Introspection inside a macro permits
four simultaneous macro calls; deeper re-entry returns the same error before
the native or Lua stack is exhausted.
(defmacro at-build [] (time/now)) (at-build)
#err {<invalid program> column 1 line 2}
1.8.9.1.6. Errors
A macro reports a bad call by returning an #err value. The compiler turns
it into #err <invalid program> positioned at the call site. Its message is
macro NAME: MESSAGE, with the macro's name and the message of the returned
error. A result that is not a form, such as a function, is the same error.
(defmacro checked [x] (if (int? x) ~(+ ,x 1) #err "checked needs an integer literal")) (checked "a")
#err {<invalid program> column 1 line 2 message "macro checked: checked needs an integer literal"}
1.8.9.1.7. Canonical functions
A function's canonical form is its expanded fn source. Printing, hashing
and storing a closure use the expansion. Two functions written with and
without a macro have the same text and the same hash. A stored function
recompiles from its expansion, without the macros that produced it.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (def safe-inverse (fn [x] (unless (= x 0) (/ 1 x)))) (str safe-inverse) (= (str safe-inverse) (str (fn [x] (if (= x 0) null (do (/ 1 x)))))) (= (hashes/digest "sha256" safe-inverse) (hashes/digest "sha256" (fn [x] (if (= x 0) null (do (/ 1 x)))))) [(safe-inverse 0) (safe-inverse 4)]
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (def safe-inverse (fn [x] (unless (= x 0) (/ 1 x)))) (str safe-inverse) (= (str safe-inverse) (str (fn [x] (if (= x 0) null (do (/ 1 x)))))) (= (hashes/digest "sha256" safe-inverse) (hashes/digest "sha256" (fn [x] (if (= x 0) null (do (/ 1 x)))))) [(safe-inverse 0) (safe-inverse 4)]
unless safe-inverse "#invoke [fn [#local x] #invoke [if #invoke [= #local x 0] null #invoke [do #invoke [/ 1 #local x]]]]" true true [null 0.25]
1.8.9.2. gensym
Function(gensym) → name
(gensym prefix) → name
Returns a new name that no source form contains.
The name is prefix__N, where N counts the new names of the current
expansion from 1. Without a prefix, the prefix is G. Two calls in one
expansion return different names. See Hygiene for the name#
quasiquote shorthand, which calls gensym once per quasiquote form.
(defmacro two-names [] [(gensym) (gensym)]) (defmacro prefixed [] ~(let [,(gensym "tmp") 1] 2)) (macroexpand-1 `(two-names)) (= (gensym) (gensym)) (macroexpand-1 `(prefixed))
two-names prefixed [G__1 G__2] false (let [tmp__1 1] 2)
1.8.9.3. macroexpand-1
Function(macroexpand-1 form) → form
Expands one macro call and returns the resulting form.
When the head of form names a macro, the result is the form the macro
returns, with the subforms unexpanded. Otherwise the result is form
unchanged, including forms that are not invocations. The argument is a form
value, usually built with quote.
(defmacro unless [test ... body] ~(if ,test null (do ,@body))) (defmacro guard [test ... body] ~(unless (not ,test) ,@body)) (macroexpand-1 `(unless a b c)) (macroexpand-1 `(guard a b)) (macroexpand `(guard a b)) (macroexpand-1 `(+ 1 2)) (macroexpand `(f (unless a b))) (macroexpand-1 `x) (macroexpand 42)
unless guard (if a null (do b c)) (unless (not a) b) (if (not a) null (do b)) (+ 1 2) (f (unless a b)) x 42
1.8.9.4. macroexpand
Function(macroexpand form) → form
Applies macroexpand-1 to the head again and again until it is not a macro call.
The subforms of the result are not expanded, because the compiler expands them in a later step. A form whose head is not a macro returns unchanged. Each call starts a new gensym count, so the same form expands to the same text.
Footnotes:
Because DUST forms have a JSON representation, keys are always (always!) strings.