22 Document Codecs

Notation decoders return an immutable Document without evaluating DUST forms. Text decoders accept strings; TRON accepts Bytes. Encoders return text for JSON, DUST, RON and EDN, or Bytes for TRON. Documents preserve types, comments and map order supported by the selected format. JSON uses tagged objects for DUST kinds; TRON preserves integer/float distinctions. Output layout follows each format, so source whitespace is not retained.

Signature Result
(encoding/json/decode text [options]) Document
(encoding/dust/decode text [options]) Document
(encoding/ron/decode text [options]) Document
(encoding/edn/decode text [options]) Document
(encoding/tron/decode bytes [options]) Document
(encoding/json/encode document [options]) Text
(encoding/dust/encode document [options]) Text
(encoding/ron/encode document [options]) Text
(encoding/edn/encode document [options]) Text
(encoding/tron/encode document [options]) Bytes
(documents/from-value value [options]) Independent snapshot of a DUST value
(documents/value document) Independent DUST value; changing it leaves the Document unchanged
(documents/close document) Release its storage

The existing encoding/encode and encoding/decode dispatchers also accept format names "json", "dust", "ron", "edn" and "tron". Their three-argument convention is (encoding/decode format input options); all these functions put optional settings last. Byte/numeric codecs retain their existing inputs and outputs. Use the form option to distinguish one DUST value from a file of forms.

A function snapshot retains its definition and documentation as DUST source data. Reading the Document returns that source form without its captured values.

A named schema snapshot retains its finite definition graph, including named references and saved predicate definitions. A simple definition reads back as its canonical source form; a graph retains distinct definitions and their functions. Reconstruct it explicitly with schemas/load, then check candidates with schemas/valid?. Authored namespace source keeps its own comments. Snapshots made from evaluated schema values have no comments and do not include captured runtime state, compiled checkers, caches, or runtime handles.

Options are comments (default true), form (default true), width (1–65535), order ("source" or "sorted", default sorted), schema and presentation. With form false, DUST reads/writes a file of forms as a root list. With form true, a root list keeps its brackets. comments false omits annotations without changing the source Document or removing ordinary $comment data fields. Width/order configure DUST and RON; EDN also honors width. JSON uses compact source order. TRON output is binary.

For DUST and RON, schema is a named schema snapshot and presentation is a map of explicit JSON Pointer hints. Without an explicit order, a schema selects its shape declaration order. An explicit source or sorted order takes precedence and ignores schema presentation. A hint can contain order (a list of field names) and lines (true to put each child of that collection on its own line). The empty string names the root path. JSON and TRON keep their existing encodings.

(defschema Shipment
  {pilot string? destination string? spice int?})

(let
  [document
   (documents/from-value
     {spice 80 destination "Arrakeen" pilot "Chani"})
   rendered (encoding/dust/encode document {schema Shipment})]
  (documents/close document)
  rendered)
; Rendered DUST uses Shipment's field order.

Explicit hints override schema order:

(let
  [document (documents/from-value {pilot "Chani" spice 80 destination "Arrakeen"})
   rendered
   (encoding/dust/encode document
     {schema Shipment presentation {"" {order ["spice" "pilot" "destination"]}}})]
  (documents/close document)
  rendered)

Composition rules apply at each nested path. meet keeps the first appearance of each field, and join uses a common order only when all alternatives agree. Rendering does not run predicates to select a layout. Boolean members use ordinary key/value spelling when a leading tag group would violate the chosen field order. Without presentation overrides, the normal canonical tag grouping is unchanged. A hint inside a template or dynamic pointer uses its explicit tagged spelling when the compact text spelling would hide the target collection.

DUST
(defschema Shipment {pilot string? destination string? spice int?})
(defschema Person [meet {age int?} {name string?}])
(defschema UnionSame [join {a string? b int?} {a string? b int?}])
(defschema UnionDifferent [join {a string? b int?} {b int? a string?}])
(defschema NestedIntersection [meet {details {z int?}} {details {a int?}}])
(defschema NestedUnion [join {details {a int? z int?}} {details {z int? a int?}}])
(defschema House {name string? children [... House]})
(let
  [render
   (fn [value options]
     (let
       [document (documents/from-value value) output (encoding/dust/encode document options)]
       (documents/close document)
       output))
   render-document
   (fn [document options]
     (let [output (encoding/dust/encode document options)] (documents/close document) output))
   value
   {spice 80
    destination "Arrakeen"
    pilot "Chani"
    extra "kept"}]
  [(render value {schema Shipment})
   (render value {schema Shipment presentation {"" {order ["spice" "pilot" "destination"]}}})
   (render-document
     (encoding/dust/decode ""{spice 80 destination "Arrakeen" pilot "Chani" extra "kept"}"")
     {schema Shipment order "source"})
   (render value {schema Shipment order "sorted"})
   (render value {presentation {"" {order ["spice" "destination" "pilot"]}}})
   (render
     {steps [{a "x" b 1}]}
     {presentation {"" {order ["steps"]} /steps <lines> /steps/0 {order ["b" "a"]}}})
   (render {name "Paul" age 18} {schema Person})
   (render {a "x" b 1} {schema UnionSame})
   (render {a "x" b 1} {schema UnionDifferent})
   (render {details {a 1 z 2}} {schema NestedIntersection})
   (render {details {a 1 z 2}} {schema NestedUnion})
   (render [[1 2]] {presentation {/0 <lines>}})
   (render ~"hello ,{a 1 z 2}" {presentation {/1/0 {order ["z" "a"] lines true}}})
   (render-document
     (encoding/dust/decode "/x/,{a 1 z 2}" {form true})
     {presentation {/1 {order ["z" "a"] lines true}}})
   (render {name "Chani" active true} {presentation {"" {order ["name" "active"]}}})
   (render {b true a false c true} {presentation {"" {order ["c" "b"]}}})
   (render {name "Atreides" children [{name "Paul" children []}]} {schema House})
   (render {pilot "Chani"} {schema Shipment})
   (render-document
     (encoding/dust/decode
       """
         {pilot "Chani" ; pilot note
          destination "Arrakeen"}
       """
     )
     {schema Shipment})])
→
Canonical DUST
(defschema Shipment {destination string? pilot string? spice int?})
(defschema Person [meet {age int?} {name string?}])
(defschema UnionSame [join {a string? b int?} {a string? b int?}])
(defschema UnionDifferent [join {a string? b int?} {a string? b int?}])
(defschema NestedIntersection [meet {details {z int?}} {details {a int?}}])
(defschema NestedUnion [join {details {a int? z int?}} {details {a int? z int?}}])
(defschema House {children [... House] name string?})
(let
  [render (fn [value options]
            (let
              [document (documents/from-value value) output (encoding/dust/encode document options)]
              (documents/close document)
              output))
   render-document (fn [document options]
                     (let
                       [output (encoding/dust/encode document options)]
                       (documents/close document)
                       output))
   value {destination "Arrakeen"
          extra "kept"
          pilot "Chani"
          spice 80}]
  [(render value {schema Shipment})
   (render value {presentation {"" {order ["spice" "pilot" "destination"]}} schema Shipment})
   (render-document
     (encoding/dust/decode ""{spice 80 destination "Arrakeen" pilot "Chani" extra "kept"}"")
     {order "source" schema Shipment})
   (render value {order "sorted" schema Shipment})
   (render value {presentation {"" {order ["spice" "destination" "pilot"]}}})
   (render
     {steps [{a "x" b 1}]}
     {presentation {"" {order ["steps"]} /steps <lines> /steps/0 {order ["b" "a"]}}})
   (render {age 18 name "Paul"} {schema Person})
   (render {a "x" b 1} {schema UnionSame})
   (render {a "x" b 1} {schema UnionDifferent})
   (render {details {a 1 z 2}} {schema NestedIntersection})
   (render {details {a 1 z 2}} {schema NestedUnion})
   (render [[1 2]] {presentation {/0 <lines>}})
   (render
     ~"hello ,{a 1 z 2}"
     {presentation {/1/0 {<lines>
                          order ["z" "a"]}}})
   (render-document
     (encoding/dust/decode "/x/,{a 1 z 2}" <form>)
     {presentation {/1 {<lines>
                        order ["z" "a"]}}})
   (render
     {<active>
      name "Chani"}
     {presentation {"" {order ["name" "active"]}}})
   (render <!a b c> {presentation {"" {order ["c" "b"]}}})
   (render {children [{children [] name "Paul"}] name "Atreides"} {schema House})
   (render {pilot "Chani"} {schema Shipment})
   (render-document
     (encoding/dust/decode
       """
         {pilot "Chani" ; pilot note
          destination "Arrakeen"}
       """
     )
     {schema Shipment})])
=
DUST Result
Shipment
Person
UnionSame
UnionDifferent
NestedIntersection
NestedUnion
House
[
  """
    {pilot "Chani"
     destination "Arrakeen"
     spice 80
     extra "kept"}

  """
  """
    {spice 80
     pilot "Chani"
     destination "Arrakeen"
     extra "kept"}

  """
  """
    {spice 80
     destination "Arrakeen"
     pilot "Chani"
     extra "kept"}

  """
  """
    {destination "Arrakeen"
     extra "kept"
     pilot "Chani"
     spice 80}

  """
  """
    {spice 80
     destination "Arrakeen"
     pilot "Chani"
     extra "kept"}

  """
  """
    {steps [
       {b 1
        a "x"}]}

  """
  """
    {age 18
     name "Paul"}

  """
  """
    {a "x"
     b 1}

  """
  """
    {a "x"
     b 1}

  """
  """
    {details {z 2
              a 1}}

  """
  """
    {details {a 1
              z 2}}

  """
  """
    [[
       1
       2]]

  """
  """
    #template [[
                 "hello "
                 ""]
               [{
                  z 2
                  a 1}]]

  """
  """
    #jsonptr ["x"
              {
                z 2
                a 1}]

  """
  """
    {name "Chani"
     active true}

  """
  """
    <c b !a>

  """
  """
    {name "Atreides"
     children [{name "Paul" children []}]}

  """
  """
    {pilot "Chani"}

  """
  """
    {
      ; pilot note
      pilot "Chani"
      destination "Arrakeen"}

  """
]

JSON and TRON read and write all comments in the root $comment member, and a $comment below the root is data. A root $comment that is not an object of pointers to strings, or that names no value, is an error, and so is a root map with its own $comment key written to JSON or TRON. Unrepresentable data, malformed input and unsupported settings produce errors; memory/resource limits remain fatal evaluation failures.

Documents cannot be printed or serialized; encode their contents instead. A session can hold any number of open Documents; only the memory budget bounds them. Close unused Documents with documents/close, which returns their memory to the budget. A failed evaluation closes Documents it created. Ending the session closes the remaining Documents. Documents count toward the memory budget. A decode takes input of any size. It fails only when the memory budget runs out or a value passes the value size bound. No filesystem or OS grant is required.

DUST
(let [doc (encoding/json/decode "{\"name\":\"Paul\"}")
      value (documents/value doc)
      closed (documents/close doc)] value)
(let [value {name "Chani" skills <desert survival> scores [1 2.5]}
      doc (documents/from-value value)
      results (map (fn [format]
                     (let [wire (encoding/encode format doc)
                           other (encoding/decode format wire {<comments>})
                           result (= value (documents/value other))
                           closed (documents/close other)] result))
                   ["json" "dust" "ron" "edn" "tron"])
      closed (documents/close doc)] results)
(let [source {name "Paul"}
      doc (documents/from-value source)
      changed (put source "name" "Muad'Dib")
      value (documents/value doc)
      closed (documents/close doc)] value)
(let [doc (encoding/json/decode (str "{\"$comment\":\"" "{\\\"/name\\\":\\\"note\\\"}" "\",\"name\":\"Paul\"}"))
      text (encoding/json/encode doc)
      closed (documents/close doc)] text)
(let [doc (encoding/dust/decode "; about Paul\n{name \"Paul\"}\n")
      text (encoding/json/encode doc)
      copy (encoding/json/decode text)
      dust (encoding/dust/encode copy)
      a (documents/close doc)
      b (documents/close copy)] dust)
(let [doc (encoding/dust/decode "(+ 1 2)") value (encoding/dust/encode doc) closed (documents/close doc)] value)
(let [doc (encoding/dust/decode "[1 2]") closed (documents/close doc)] (error? (documents/value doc)))
(error? (encoding/json/decode "{"))

(let [doc (encoding/json/decode "{\"x\":{\"$comment\":\"literal data\"},\"name\":\"Paul\"}")
      encoded (encoding/dust/encode doc {comments false})
      closed (documents/close doc)]
  (not (null? (strings/index-of encoded "$comment"))))
(let [doc (encoding/dust/decode "; retained note\n{a 1}\n")
      plain (encoding/dust/encode doc {comments false})
      original (encoding/dust/encode doc)
      closed (documents/close doc)]
  [(null? (strings/index-of plain "retained note"))
   (not (null? (strings/index-of original "retained note")))])
(let [doc (encoding/dust/decode "1")
      refused (error? (encoding/json/encode doc {<comment-roundtrip>}))
      closed (documents/close doc)]
  refused)
(let [doc (encoding/dust/decode "; Spice math.\n{rates {arrakis 10 caladan 15}\n ; reserve percent\n reserve 10}\n")
      commented (encoding/json/encode doc)
      plain (encoding/json/encode doc {comments false})
      closed (documents/close doc)]
  [commented plain])
→
Canonical DUST
(let
  [doc (encoding/json/decode ""{"name":"Paul"}"")
   value (documents/value doc)
   closed (documents/close doc)]
  value)
(let
  [value {name "Chani"
          scores [1 2.5]
          skills <desert survival>}
   doc (documents/from-value value)
   results (map
             (fn [format]
               (let
                 [wire (encoding/encode format doc)
                  other (encoding/decode format wire <comments>)
                  result (= value (documents/value other))
                  closed (documents/close other)]
                 result))
             ["json" "dust" "ron" "edn" "tron"])
   closed (documents/close doc)]
  results)
(let
  [source {name "Paul"}
   doc (documents/from-value source)
   changed (put source "name" "Muad'Dib")
   value (documents/value doc)
   closed (documents/close doc)]
  value)
(let
  [doc (encoding/json/decode
         (str
           ""{"$comment":"""
           ""{\u005c"/name\u005c":\u005c"note\u005c"}""
           """
             ","name":"Paul"}
           """
         ))
   text (encoding/json/encode doc)
   closed (documents/close doc)]
  text)
(let
  [doc (encoding/dust/decode
         """
           ; about Paul
           {name "Paul"}

         """
       )
   text (encoding/json/encode doc)
   copy (encoding/json/decode text)
   dust (encoding/dust/encode copy)
   a (documents/close doc)
   b (documents/close copy)]
  dust)
(let
  [doc (encoding/dust/decode "(+ 1 2)")
   value (encoding/dust/encode doc)
   closed (documents/close doc)]
  value)
(let
  [doc (encoding/dust/decode "[1 2]") closed (documents/close doc)]
  (error? (documents/value doc)))
(error? (encoding/json/decode "{"))
(let
  [doc (encoding/json/decode ""{"x":{"$comment":"literal data"},"name":"Paul"}"")
   encoded (encoding/dust/encode doc <!comments>)
   closed (documents/close doc)]
  (not (null? (strings/index-of encoded "$comment"))))
(let
  [doc (encoding/dust/decode
         """
           ; retained note
           {a 1}

         """
       )
   plain (encoding/dust/encode doc <!comments>)
   original (encoding/dust/encode doc)
   closed (documents/close doc)]
  [(null? (strings/index-of plain "retained note"))
   (not (null? (strings/index-of original "retained note")))])
(let
  [doc (encoding/dust/decode "1")
   refused (error? (encoding/json/encode doc <comment-roundtrip>))
   closed (documents/close doc)]
  refused)
(let
  [doc (encoding/dust/decode
         """
           ; Spice math.
           {rates {arrakis 10 caladan 15}
            ; reserve percent
            reserve 10}

         """
       )
   commented (encoding/json/encode doc)
   plain (encoding/json/encode doc <!comments>)
   closed (documents/close doc)]
  [commented plain])
=
DUST Result
{name "Paul"}
[true true true true true]
{name "Paul"}
""{"$comment":"{\u005c"/name\u005c":\u005c"note\u005c"}","name":"Paul"}""
"""
  ; about Paul
  {name "Paul"}

"""
"""
  (+ 1 2)

"""
true
true
true
[true true]
true
[
  ""{"$comment":"{\u005c"\u005c":\u005c"Spice math.\u005c",\u005c"/reserve\u005c":\u005c"reserve percent\u005c"}","rates":{"arrakis":10,"caladan":15},"reserve":10}""
  ""{"rates":{"arrakis":10,"caladan":15},"reserve":10}""]