kdl

    KDL document language parser, formatter, query engine, and schema validation library for MoonBit

    kdl
    parser
    formatter
    query
    kql
    schema
    configuration
    document
    Download zip
    Author
    Version
    0.2.0
    License
    Apache-2.0
    Last updated
    3 months ago
    Downloads
    63

    No dependencies

    #lenitain/kdl

    mooncake

    A MoonBit library for working with KDL documents: parsing, serialization, querying (KQL), schema validation, and typed decoding/encoding between KDL and MoonBit structs. Zero external dependencies.

    This README is a literate test file. Every mbt check block below is compiled and run by moon test, so the examples stay in sync with the API. The examples call the unified entry point lenitain/kdl/full fully-qualified as @full.*.

    #Installation

    Add the dependency to your moon.mod:

    import { "lenitain/kdl@0.2.0" }

    #Quick Start

    lenitain/kdl/full re-exports the whole API. Declare the dependencies in moon.pkg, then bring the entry points into scope with using:

    # moon.pkg import { "lenitain/kdl", "lenitain/kdl/full", }

    The root package is imported alongside full so that methods on the core types (doc.get(...), doc.to_kdl_string(), ...) are in scope:

    ///|
    using @full {parse}

    ///|
    test "quick start" {
    let doc = parse("server host=\"a.example\" port=8080").unwrap()
    assert_eq(doc.to_kdl_string(), "server host=\"a.example\" port=8080")

    let port = doc.get("server").unwrap().get_prop("port").unwrap()
    assert_eq(port.to_kdl_string(), "8080")
    }

    #KDL in 30 seconds

    A node has a name, zero or more arguments and properties, and an optional { } block of child nodes:

    foo 1 "three" key="val" { ╮ ─┬─ ┬ ───┬─── ────┬──── │ │ │ │ ╰───── property (can be multiple) │ │ │ │ │ │ ╰────┴────────────── arguments │ │ │ └── node name ├─ node "foo", with │ "bar" and "baz" bar │ being children (role)baz 1 2 │ ──┬─ │ └────── type name for node named "baz" │ } ╯

    Key rules:

    • Arguments (1, "three") and properties (key="val") both come after the node name, in any order. A { } block can only contain nodes — this library rejects server { host="a" }.
    • Values are strings, numbers, #true / #false, #null, #inf, or bare identifiers (tcp). The legacy v1 spellings true / false / null are accepted on input; serialization always emits the v2 #-prefixed forms.
    • Type annotations and separators: (role)baz is node baz of type role; sibling nodes are separated by a newline or ;.

    #Parsing

    parse reads KDL v2 by default; parse_v1 and parse_v2 pin the version, and detect_version reports which dialect an input uses:

    ///|
    test "parsing" {
    let doc : @full.KdlDocument = @full.parse("node 1").unwrap() // KDL v2 (default)
    assert_eq(doc.nodes().length(), 1)

    let legacy = @full.parse_v1("node 1").unwrap() // KDL v1
    assert_eq(legacy.nodes().length(), 1)

    assert_eq(@full.detect_version("node 1"), 1)
    assert_eq(@full.detect_version("/- kdl-version 2\nnode"), 2)
    }

    Every parse function returns Result[KdlDocument, KdlError]. A document is an array of nodes; a node holds a name, entries (arguments + properties) and optional children.

    MethodReturnsMeaning
    doc.get(name)KdlNode?first top-level node named name
    node.get_arg(i)KdlValue?i-th positional argument
    node.get_prop(name)KdlValue?value of property name
    node.get_child(name)KdlNode?first child node named name
    node.children_by(name)Array[KdlNode]every child node named name
    node.arg_count()Intnumber of positional arguments
    node.name_str()Stringnode name as a plain string

    #Errors

    Parsing and validation failures are collected as KdlError — a list of KdlDiagnostics, each with a source span, a message and optional help text. to_display_string() renders them as line/column reports with the offending source line and a caret, without external dependencies:

    ///|
    test "errors" {
    match @full.parse("server { a=1 }") {
    Err(e) => {
    let text = e.to_display_string()
    assert_true(text.contains("unexpected `=` inside a children block"))
    assert_true(text.contains("line 1, col 11"))
    }
    Ok(_) => assert_true(false)
    }
    }

    error: unexpected `=` inside a children block --> line 1, col 11 | 1 | server { a=1 } | ^ = help: A children block can only contain nodes. Entries and properties must follow the node name on the same line. error: expected a child node, but found an entry value

    #Types

    TypeDescription
    KdlDocumenttop-level document: an array of nodes, optional version marker
    KdlNodea named node with entries and optional children
    KdlEntrya positional argument or a key=value property
    KdlValueString, Identifier, Integer(Int64), Float(Double), Bool, Null
    KdlIdentifiera node/property/type name, with an optional original repr
    KdlErrora collection of KdlDiagnostics
    KdlDiagnosticone diagnostic: span, message, label, severity

    Bare identifiers (values written without quotes, like tcp) parse to KdlValue::Identifier — equal to a String with the same content, but serialized without quotes.

    #Serialization

    A KdlDocument (or KdlNode) serializes back to KDL text: to_kdl_string() pretty-prints with 2-space indentation; to_kdl_string_formatted(n) chooses the width.

    to_kdl_string is a serializer, not a formatter. It rebuilds text from the parsed data model and does not preserve comments or original formatting. Use it to generate new documents or write back a modified model. To edit an existing file without losing comments, use parse_preserve below.

    #Format-preserving editing

    parse_preserve parses while retaining the original source text, per-node spans and leading comments. Unmodified documents round-trip byte-for-byte; editing a node rebuilds only that node and keeps its leading comments:

    ///|
    test "format-preserving round trip" {
    let input =
    #|// server config
    #|server host="a.example" port=8080
    #|
    let doc = @full.parse_preserve(input).unwrap()
    assert_eq(doc.to_kdl_string(), input) // byte-for-byte while unmodified

    let pn = doc.nodes()[0]
    let node = pn.node()
    node.entries[1] = @full.KdlEntry::new_prop(
    @full.KdlIdentifier::new("port"),
    @full.KdlValue::Integer(9090L),
    )
    doc.nodes()[0] = pn.set_node(node)
    assert_eq(
    doc.to_kdl_string(),
    "// server config\nserver host=\"a.example\" port=9090\n",
    )
    }

    • push / insert add nodes; remove_at removes a node together with its leading comment (comments belong to the node they precede).
    • KdlPreservedDocument::to_kdl_document() down-converts to the plain KdlDocument, so query / schema / decode still work on an edited document.
    • KdlPreservedNode exposes node(), leading(), body(), comments(), children(), is_unchanged(), set_node(...) and set_orig(...).

    #Querying (KQL)

    query evaluates a KQL expression (spec) against a parsed document and returns the matching nodes:

    ///|
    test "querying" {
    let matches = @full.query(
    @full.parse("root { a 1; a 2 }").unwrap(),
    "root > a",
    ).unwrap()
    assert_eq(matches.length(), 2)
    }

    Selectors support child (>), descendant (>>), next-sibling (+), later-sibling (++) and union (||) combinators, filters on node name and type annotation, and accessor comparisons like server[prop("host") = "localhost"].

    #Schema validation

    A schema is itself a KDL document describing the allowed nodes, properties, values and children:

    ///|
    test "schema validation" {
    let schema_src =
    #|document {
    #| node "server" {
    #| prop "host" { required #true }
    #| prop "port" { type "number" }
    #| }
    #|}
    #|
    let schema = @full.parse_schema(@full.parse(schema_src).unwrap()).unwrap()
    match @full.validate(@full.parse("server port=8080").unwrap(), schema) {
    Err(e) =>
    assert_true(
    e.to_display_string().contains("missing required property 'host'"),
    )
    Ok(_) => assert_true(false)
    }
    }

    parse_schema and validate both return Result and report problems as KdlError diagnostics.

    #Decoding (KDL → structs)

    decode maps a KDL source string onto your own struct via the Decode trait — one fn decode_from_node per type:

    ///|
    struct Server {
    host : String
    port : Int64
    } derive(Eq, Debug)

    ///|
    impl @full.Decode for Server with fn decode_from_node(node : @full.KdlNode) -> Server raise @full.DecodeError {
    let host = @full.decode_prop(node, "host")
    let port = @full.decode_prop(node, "port")
    { host, port }
    }

    ///|
    test "decoding" {
    let server : Server = @full.decode("server host=\"localhost\" port=8080").unwrap()
    assert_eq(server.port, 8080L)
    }

    Decoding is strict: a missing node/property or a type mismatch raises DecodeError with a descriptive message — never a panic.

    Helpers: decode_prop / decode_opt_prop (properties), decode_child / decode_opt_child / decode_children (children), decode_value / decode_node / decode_document (whole values / nodes / documents). Prebuilt impls exist for String, Int64, Double, Bool, KdlValue, Array[T] (all positional arguments) and T? (#null → None).

    #Lower-boilerplate: derive(FromJson) + decode_via_json

    MoonBit cannot derive(Decode), so decode_via_json offers a shortcut: derive the built-in FromJson trait and let KDL be converted to JSON under the hood — no impl Decode to write:

    ///|
    struct JsonServer {
    host : String
    port : Int64
    timeout : Int64?
    } derive(Eq, Debug, FromJson)

    ///|
    test "decode via json" {
    let server : JsonServer = @full.decode_via_json(
    "server host=\"localhost\" port=8080",
    ).unwrap()
    assert_eq(server.port, 8080L)
    assert_eq(server.timeout, None)
    }

    The KDL → JSON mapping (documented on node_to_json):

    KDLJSON
    node key=value propertyobject field "key": ...
    node { child ... } childnested field keyed by child name (single → object, repeated → array)
    positional args on an object node"$args" array
    node with only positional argsthe args themselves (protocol tcp → "tcp")
    #null valuesomitted (optional fields decode to None)
    integer valueJSON string ("8080"), because MoonBit Int64/UInt64 FromJson reads integers from strings

    Trade-offs: pros — no impl Decode; plain property/children configs decode with a one-line derive(FromJson). Cons — positional args are awkward in JSON, enums don't map to KDL's bare-value style (protocol tcp), and integers are JSON strings. Configs dominated by positional args should keep the hand-written Decode route.

    #Encoding (structs → KDL)

    encode is the mirror of decode: implement the Encode trait (one fn encode_to_node) and call the top-level encode:

    ///|
    impl @full.Encode for Server with fn encode_to_node(self) -> @full.KdlNode {
    let entries = []
    entries.push(@full.encode_prop("host", self.host))
    entries.push(@full.encode_prop("port", self.port))
    @full.KdlNode::with_entries(@full.KdlIdentifier::new("server"), entries)
    }

    ///|
    test "encoding" {
    let text = @full.encode({ host: "localhost", port: 8080L }).unwrap()
    assert_eq(text, "server host=\"localhost\" port=8080")
    }

    encode_* are the exact inverses of the decode_* helpers (encode_prop / encode_opt_prop / encode_child / encode_opt_child / encode_children); prebuilt impls cover String, Int64, Double, Bool, KdlValue, KdlNode, Array[T] (elements as positional args) and T? (None → #null). The output is valid KDL that decode reads back — a type-level round-trip:

    ///|
    test "encode/decode round trip" {
    let server : Server = @full.decode("server host=\"localhost\" port=8080").unwrap()
    let back : Server = @full.decode(@full.encode(server).unwrap()).unwrap()
    assert_eq(back, server)
    }

    encode fails only when the encoded node has no name. Like Decode, Encode is an open trait — implement it for your own types in any package.

    #Package layout

    ImportContents
    lenitain/kdlcore types and methods (document model, serialization, errors)
    lenitain/kdl/fullunified entry point — re-exports the entire API
    lenitain/kdl/parserparsing (parse, parse_v1, parse_v2, parse_preserve)
    lenitain/kdl/queryKQL queries
    lenitain/kdl/schemaschema validation (parse_schema, validate)
    lenitain/kdl/decodeKDL ↔ structs (Decode/Encode, decode*, encode*, decode_via_json)

    Subpackages are compiled on demand: importing only the root package does not compile the parser, query, schema or decode packages.

    #Known limitations

    • No derive(Decode) / derive(Encode). MoonBit has no custom derives, so typed decoding needs a hand-written impl Decode (or the derive(FromJson) + decode_via_json route).
    • Plain serialization drops comments. to_kdl_string rebuilds the data model; use parse_preserve when comments matter.
    • Same-line sibling nodes are not diagnosed (server a=1 server b=2 parses as one node). Missing separators are inherently ambiguous in KDL.
    • Hand-written format validators. With zero dependencies, schema format checks and regex patterns are implemented in this library rather than delegated to external crates.

    #License

    Apache-2.0

    KdlDiagnostic

    pub struct KdlDiagnostic {
    input : String
    span_start : Int
    span_len : Int
    message : String?
    label : String?
    help : String?
    severity : KdlSeverity
    } derive(Eq,
    Debug
    )

    One diagnostic: a source span, message, optional label and help, and a severity.

    test {
    let d = KdlDiagnostic::new(
    "a b",
    0,
    1,
    Some("boom"),
    None,
    None,
    KdlSeverity::Error,
    )
    assert_eq(d.message, Some("boom"))
    assert_eq(d.severity, KdlSeverity::Error)
    }

    KdlDiagnostic::new

    fn KdlDiagnostic::new(input : String, span_start : Int, span_len : Int, message : String?, label : String?, help : String?, severity : KdlSeverity) -> KdlDiagnostic

    Build a diagnostic with a source span, message and severity.

    test {
    let d = KdlDiagnostic::new(
    "a b",
    0,
    1,
    Some("boom"),
    None,
    Some("try again"),
    KdlSeverity::Error,
    )
    assert_eq(d.message, Some("boom"))
    assert_eq(d.help, Some("try again"))
    assert_eq(d.severity, KdlSeverity::Error)
    }

    KdlDiagnostic::to_display_string

    fn KdlDiagnostic::to_display_string(self : KdlDiagnostic) -> String

    Render this diagnostic as a miette-style human-readable report: severity + message, line/column, the offending source line(s) with a caret under the span, an optional label annotation and optional help text.

    error: unexpected `=` inside a children block --> line 1, col 9 | 1 | server { host="a" } | ^

    The label is appended after the caret when present (the parser's constant "here" label is omitted as redundant). When the diagnostic has no source text (input is empty) only the header — plus help, if any — is rendered.

    test {
    let d = KdlDiagnostic::new(
    "a b",
    2,
    1,
    Some("boom"),
    None,
    Some("try again"),
    KdlSeverity::Error,
    )
    let out = d.to_display_string()
    assert_true(out.contains("boom"))
    assert_true(out.contains("try again"))
    }

    KdlDocument

    pub struct KdlDocument {
    nodes : Array[KdlNode]
    version : Int?
    } derive(
    Debug
    )

    A top-level KDL document: an array of nodes plus an optional version marker.

    test {
    let doc = KdlDocument::new()
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    assert_eq(doc.nodes().length(), 1)
    assert_true(doc.get("a") is Some(_))
    }
    impl Eq for KdlDocument

    KdlDocument::get

    fn KdlDocument::get(self : KdlDocument, name : String) -> KdlNode?

    The first top-level node with the given name, if present.

    test {
    let doc = KdlDocument::new()
    doc.push(KdlNode::new(KdlIdentifier::new("server")))
    assert_eq(doc.get("server").unwrap().name_str(), "server")
    assert_true(doc.get("missing") is None)
    }

    KdlDocument::get_version

    fn KdlDocument::get_version(self : KdlDocument) -> Int?

    The version marker (1 or 2), if the document declares one.

    test {
    let doc = KdlDocument::new()
    assert_eq(doc.get_version(), None)
    doc.set_version(Some(2))
    assert_eq(doc.get_version(), Some(2))
    }

    KdlDocument::new

    An empty document with no version marker.

    test {
    let doc = KdlDocument::new()
    assert_eq(doc.nodes().length(), 0)
    assert_eq(doc.get_version(), None)
    }

    KdlDocument::nodes

    fn KdlDocument::nodes(self : KdlDocument) -> Array[KdlNode]

    All top-level nodes.

    test {
    let doc = KdlDocument::new()
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    assert_eq(doc.nodes().length(), 1)
    }

    KdlDocument::push

    fn KdlDocument::push(self : KdlDocument, node : KdlNode) -> Unit

    Append a top-level node.

    test {
    let doc = KdlDocument::new()
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    doc.push(KdlNode::new(KdlIdentifier::new("b")))
    assert_eq(doc.nodes().length(), 2)
    }

    KdlDocument::set_version

    fn KdlDocument::set_version(self : KdlDocument, version : Int?) -> Unit

    Set the version marker.

    test {
    let doc = KdlDocument::new()
    doc.set_version(Some(1))
    assert_eq(doc.get_version(), Some(1))
    doc.set_version(None)
    assert_eq(doc.get_version(), None)
    }

    KdlDocument::to_kdl_string

    fn KdlDocument::to_kdl_string(self : KdlDocument) -> String

    Serialize a document to KDL text (2-space indentation).

    test {
    let doc = KdlDocument::new()
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    doc.push(KdlNode::new(KdlIdentifier::new("b")))
    assert_eq(doc.to_kdl_string(), "a\nb")
    }

    KdlDocument::to_kdl_string_formatted

    fn KdlDocument::to_kdl_string_formatted(self : KdlDocument, indent : Int) -> String

    Serialize a document with a chosen indentation width.

    test {
    let doc = KdlDocument::new()
    let p = KdlNode::with_children(KdlIdentifier::new("p"), [
    KdlNode::new(KdlIdentifier::new("c")),
    ])
    doc.push(p)
    assert_eq(doc.to_kdl_string_formatted(4), "p {\n c\n}")
    }

    KdlEntry

    pub struct KdlEntry {
    ty : KdlIdentifier?
    value : KdlValue
    name : KdlIdentifier?
    } derive(Eq,
    Debug
    )

    A node entry: either a positional argument or a key=value property.

    test {
    assert_false(KdlEntry::new(KdlValue::Integer(1L)).is_prop())
    assert_true(
    KdlEntry::new_prop(KdlIdentifier::new("k"), KdlValue::Null).is_prop(),
    )
    }

    KdlEntry::is_prop

    fn KdlEntry::is_prop(self : KdlEntry) -> Bool

    Whether this entry is a property (has a key) or a positional argument.

    test {
    assert_true(
    KdlEntry::new_prop(KdlIdentifier::new("k"), KdlValue::Null).is_prop(),
    )
    assert_false(KdlEntry::new(KdlValue::Null).is_prop())
    }

    KdlEntry::new

    fn KdlEntry::new(value : KdlValue) -> KdlEntry

    A positional argument (no key).

    test {
    let e = KdlEntry::new(KdlValue::Integer(42L))
    assert_false(e.is_prop())
    }

    KdlEntry::new_prop

    fn KdlEntry::new_prop(name : KdlIdentifier, value : KdlValue) -> KdlEntry

    A key=value property.

    test {
    let e = KdlEntry::new_prop(
    KdlIdentifier::new("port"),
    KdlValue::Integer(8080L),
    )
    assert_true(e.is_prop())
    assert_eq(e.to_kdl_string(), "port=8080")
    }

    KdlEntry::new_prop_with_ty

    fn KdlEntry::new_prop_with_ty(ty : KdlIdentifier?, name : KdlIdentifier, value : KdlValue) -> KdlEntry

    A property whose key carries a type annotation.

    test {
    let e = KdlEntry::new_prop_with_ty(
    Some(KdlIdentifier::new("u16")),
    KdlIdentifier::new("port"),
    KdlValue::Integer(8080L),
    )
    assert_true(e.is_prop())
    }

    KdlEntry::to_kdl_string

    fn KdlEntry::to_kdl_string(self : KdlEntry) -> String

    Serialize an entry (argument or property) to KDL text.

    test {
    assert_eq(KdlEntry::new(KdlValue::Integer(1L)).to_kdl_string(), "1")
    assert_eq(
    KdlEntry::new_prop(KdlIdentifier::new("port"), KdlValue::Integer(8080L)).to_kdl_string(),
    "port=8080",
    )
    }

    KdlEntry::with_ty

    fn KdlEntry::with_ty(ty : KdlIdentifier?, value : KdlValue) -> KdlEntry

    A positional argument carrying a type annotation.

    test {
    let e = KdlEntry::with_ty(
    Some(KdlIdentifier::new("u8")),
    KdlValue::Integer(255L),
    )
    assert_false(e.is_prop())
    assert_eq(e.to_kdl_string(), "(u8)255")
    }

    KdlError

    pub struct KdlError {
    input : String
    diagnostics : Array[KdlDiagnostic]
    } derive(Eq,
    Debug
    )

    A collection of diagnostics produced by parsing or validation.

    test {
    let e = KdlError::new("x")
    e.push(
    KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
    )
    assert_false(e.is_empty())
    }

    KdlError::is_empty

    fn KdlError::is_empty(self : KdlError) -> Bool

    Whether this error holds no diagnostics.

    test {
    let e = KdlError::new("x")
    assert_true(e.is_empty())
    e.push(
    KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
    )
    assert_false(e.is_empty())
    }

    KdlError::new

    fn KdlError::new(input : String) -> KdlError

    An error with no diagnostics yet.

    test {
    let e = KdlError::new("input")
    assert_true(e.is_empty())
    }

    KdlError::push

    fn KdlError::push(self : KdlError, diag : KdlDiagnostic) -> Unit

    Append a diagnostic to this error.

    test {
    let e = KdlError::new("x")
    e.push(
    KdlDiagnostic::new("x", 0, 1, Some("boom"), None, None, KdlSeverity::Error),
    )
    assert_false(e.is_empty())
    }

    KdlError::to_display_string

    fn KdlError::to_display_string(self : KdlError) -> String

    Render every diagnostic as a miette-style human-readable report, one after the other (separated by a blank line). Returns the empty string when there are no diagnostics.

    error: unexpected `=` inside a children block --> line 1, col 9 | 1 | server { host="a" } | ^

    test {
    let e = KdlError::new("a b")
    e.push(
    KdlDiagnostic::new(
    "a b",
    0,
    1,
    Some("first"),
    None,
    None,
    KdlSeverity::Error,
    ),
    )
    e.push(
    KdlDiagnostic::new(
    "a b",
    2,
    1,
    Some("second"),
    None,
    None,
    KdlSeverity::Error,
    ),
    )
    let out = e.to_display_string()
    assert_true(out.contains("first"))
    assert_true(out.contains("second"))
    }

    KdlIdentifier

    pub struct KdlIdentifier {
    value : String
    repr : String?
    } derive(Eq,
    Debug
    )

    A node, property or type-annotation name, optionally carrying its original textual representation.

    test {
    let id = KdlIdentifier::new("server")
    assert_eq(id.value(), "server")
    assert_eq(KdlIdentifier::with_repr("a b", "\"a b\"").to_string(), "\"a b\"")
    }

    KdlIdentifier::new

    fn KdlIdentifier::new(value : String) -> KdlIdentifier

    A bare identifier with no original representation.

    test {
    let id = KdlIdentifier::new("server")
    assert_eq(id.value(), "server")
    assert_eq(id.repr(), None)
    }

    KdlIdentifier::repr

    fn KdlIdentifier::repr(self : KdlIdentifier) -> String?

    The custom representation, if any.

    test {
    assert_eq(KdlIdentifier::new("a").repr(), None)
    assert_eq(KdlIdentifier::with_repr("a", "(a)").repr(), Some("(a)"))
    }

    KdlIdentifier::to_string

    fn KdlIdentifier::to_string(self : KdlIdentifier) -> String

    The representation if set, otherwise the plain value.

    test {
    assert_eq(KdlIdentifier::new("a").to_string(), "a")
    assert_eq(KdlIdentifier::with_repr("a b", "\"a b\"").to_string(), "\"a b\"")
    }

    KdlIdentifier::value

    fn KdlIdentifier::value(self : KdlIdentifier) -> String

    The underlying value, ignoring any custom representation.

    test {
    assert_eq(KdlIdentifier::with_repr("a b", "\"a b\"").value(), "a b")
    }

    KdlIdentifier::with_repr

    fn KdlIdentifier::with_repr(value : String, repr : String) -> KdlIdentifier

    An identifier whose serialization keeps a custom representation.

    test {
    let id = KdlIdentifier::with_repr("my node", "\"my node\"")
    assert_eq(id.value(), "my node")
    assert_eq(id.repr(), Some("\"my node\""))
    }

    KdlNode

    pub struct KdlNode {
    ty : KdlIdentifier?
    name : KdlIdentifier
    entries : Array[KdlEntry]
    children : Array[KdlNode]?
    } derive(
    Debug
    )

    A named node with entries (arguments + properties) and optional children.

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("server"), [
    KdlEntry::new_prop(KdlIdentifier::new("port"), KdlValue::Integer(8080L)),
    ])
    assert_eq(node.name_str(), "server")
    assert_eq(node.get_prop("port"), Some(KdlValue::Integer(8080L)))
    }
    impl Eq for KdlNode

    KdlNode::arg_count

    fn KdlNode::arg_count(self : KdlNode) -> Int

    The number of positional (non-property) arguments on this node.

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("n"), [
    KdlEntry::new(KdlValue::Integer(1L)),
    KdlEntry::new_prop(KdlIdentifier::new("k"), KdlValue::Null),
    KdlEntry::new(KdlValue::Integer(2L)),
    ])
    assert_eq(node.arg_count(), 2)
    }

    KdlNode::children_by

    fn KdlNode::children_by(self : KdlNode, name : String) -> Array[KdlNode]

    All child nodes with the given name, in document order.

    test {
    let node = KdlNode::with_children(KdlIdentifier::new("root"), [
    KdlNode::new(KdlIdentifier::new("a")),
    KdlNode::new(KdlIdentifier::new("b")),
    KdlNode::new(KdlIdentifier::new("a")),
    ])
    assert_eq(node.children_by("a").length(), 2)
    assert_eq(node.children_by("z").length(), 0)
    }

    KdlNode::full

    fn KdlNode::full(ty : KdlIdentifier?, name : KdlIdentifier, entries : Array[KdlEntry], children : Array[KdlNode]?) -> KdlNode

    Build a node from all parts: type annotation, name, entries and children.

    test {
    let node = KdlNode::full(
    Some(KdlIdentifier::new("svc")),
    KdlIdentifier::new("server"),
    [KdlEntry::new(KdlValue::String("web"))],
    Some([KdlNode::new(KdlIdentifier::new("child"))]),
    )
    assert_eq(node.name_str(), "server")
    assert_eq(node.get_arg(0), Some(KdlValue::String("web")))
    assert_true(node.get_child("child") is Some(_))
    }

    KdlNode::get_arg

    fn KdlNode::get_arg(self : KdlNode, index : Int) -> KdlValue?

    Get the positional argument at index (0-based).

    Properties (key=value) are skipped; only value arguments are counted.

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("n"), [
    KdlEntry::new(KdlValue::Integer(1L)),
    KdlEntry::new_prop(KdlIdentifier::new("k"), KdlValue::String("v")),
    KdlEntry::new(KdlValue::Integer(2L)),
    ])
    assert_eq(node.get_arg(0), Some(KdlValue::Integer(1L)))
    assert_eq(node.get_arg(1), Some(KdlValue::Integer(2L)))
    assert_eq(node.get_arg(2), None)
    }

    KdlNode::get_child

    fn KdlNode::get_child(self : KdlNode, name : String) -> KdlNode?

    Get the first child node with the given name, if present.

    test {
    let node = KdlNode::with_children(KdlIdentifier::new("parent"), [
    KdlNode::new(KdlIdentifier::new("a")),
    KdlNode::new(KdlIdentifier::new("b")),
    ])
    assert_eq(node.get_child("b").unwrap().name_str(), "b")
    assert_true(node.get_child("c") is None)
    }

    KdlNode::get_prop

    fn KdlNode::get_prop(self : KdlNode, name : String) -> KdlValue?

    Get the value of the property with the given name, if present.

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("server"), [
    KdlEntry::new_prop(
    KdlIdentifier::new("host"),
    KdlValue::String("a.example"),
    ),
    ])
    assert_eq(node.get_prop("host"), Some(KdlValue::String("a.example")))
    assert_eq(node.get_prop("port"), None)
    }

    KdlNode::name_str

    fn KdlNode::name_str(self : KdlNode) -> String

    The node name as a plain string.

    test {
    assert_eq(KdlNode::new(KdlIdentifier::new("server")).name_str(), "server")
    }

    KdlNode::new

    fn KdlNode::new(name : KdlIdentifier) -> KdlNode

    A node with a name and no entries or children.

    test {
    let node = KdlNode::new(KdlIdentifier::new("server"))
    assert_eq(node.name_str(), "server")
    assert_eq(node.arg_count(), 0)
    }

    KdlNode::to_kdl_string

    fn KdlNode::to_kdl_string(self : KdlNode) -> String

    Serialize a node to KDL text (2-space indentation).

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("server"), [
    KdlEntry::new(KdlValue::Integer(1L)),
    ])
    assert_eq(node.to_kdl_string(), "server 1")
    }

    KdlNode::to_kdl_string_formatted

    fn KdlNode::to_kdl_string_formatted(self : KdlNode, indent : Int) -> String

    Serialize a node with a chosen indentation width.

    test {
    let node = KdlNode::with_children(KdlIdentifier::new("p"), [
    KdlNode::new(KdlIdentifier::new("c")),
    ])
    assert_eq(node.to_kdl_string_formatted(4), "p {\n c\n}")
    }

    KdlNode::with_children

    fn KdlNode::with_children(name : KdlIdentifier, children : Array[KdlNode]) -> KdlNode

    A node with child nodes and no entries.

    test {
    let node = KdlNode::with_children(KdlIdentifier::new("parent"), [
    KdlNode::new(KdlIdentifier::new("child")),
    ])
    assert_eq(node.get_child("child").unwrap().name_str(), "child")
    }

    KdlNode::with_entries

    fn KdlNode::with_entries(name : KdlIdentifier, entries : Array[KdlEntry]) -> KdlNode

    A node with entries and no children.

    test {
    let node = KdlNode::with_entries(KdlIdentifier::new("server"), [
    KdlEntry::new_prop(KdlIdentifier::new("port"), KdlValue::Integer(8080L)),
    ])
    assert_eq(node.get_prop("port"), Some(KdlValue::Integer(8080L)))
    }

    KdlPreservedDocument

    pub struct KdlPreservedDocument {
    source : String
    prefix : String
    nodes : Array[KdlPreservedNode]
    trailing : String
    version : Int?
    } derive(
    Debug
    )

    A document in the preserved layer: original source plus per-node retained text, so to_kdl_string round-trips unchanged nodes byte-for-byte.

    test {
    let node = KdlNode::new(KdlIdentifier::new("a"))
    let pn = KdlPreservedNode::new(node, Some(node), "", "a", [], None)
    let doc = KdlPreservedDocument::new("a", "", [pn], "", None)
    assert_eq(doc.to_kdl_string(), "a")
    }

    KdlPreservedDocument::get_version

    fn KdlPreservedDocument::get_version(self : KdlPreservedDocument) -> Int?

    The version marker, if the document declares one.

    test {
    let doc = KdlPreservedDocument::new("a", "", [], "", Some(2))
    assert_eq(doc.get_version(), Some(2))
    }

    KdlPreservedDocument::insert

    fn KdlPreservedDocument::insert(self : KdlPreservedDocument, index : Int, node : KdlNode) -> Unit

    Insert a new node at index (0-based). Insert a new node at index (0-based).

    test {
    let doc = KdlPreservedDocument::new("", "", [], "", None)
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    doc.insert(0, KdlNode::new(KdlIdentifier::new("b")))
    assert_eq(doc.nodes()[0].node().name_str(), "b")
    }

    KdlPreservedDocument::new

    fn KdlPreservedDocument::new(source : String, prefix : String, nodes : Array[KdlPreservedNode], trailing : String, version : Int?) -> KdlPreservedDocument

    Build a preserved document from its parts: original source, prefix, preserved nodes, trailing text and version marker.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "", [pn], "", None)
    assert_eq(doc.nodes().length(), 1)
    assert_eq(doc.source(), "a")
    }

    KdlPreservedDocument::nodes

    The preserved top-level nodes, in document order. The preserved top-level nodes, in document order.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "", [pn], "", None)
    assert_eq(doc.nodes().length(), 1)
    }

    KdlPreservedDocument::prefix

    fn KdlPreservedDocument::prefix(self : KdlPreservedDocument) -> String

    Text before the first node (version marker, leading whitespace). Text before the first node (version marker, leading whitespace).

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "// top\n", [pn], "", None)
    assert_eq(doc.prefix(), "// top\n")
    }

    KdlPreservedDocument::push

    fn KdlPreservedDocument::push(self : KdlPreservedDocument, node : KdlNode) -> Unit

    Append a new node. It is inserted with no original text, so it serializes from the data model. Append a new node. It is inserted with no original text, so it serializes from the data model.

    test {
    let doc = KdlPreservedDocument::new("", "", [], "", None)
    doc.push(KdlNode::new(KdlIdentifier::new("b")))
    assert_eq(doc.nodes().length(), 1)
    assert_false(doc.nodes()[0].is_unchanged())
    }

    KdlPreservedDocument::remove_at

    fn KdlPreservedDocument::remove_at(self : KdlPreservedDocument, index : Int) -> Unit

    Remove the node at index (0-based). Remove the node at index (0-based).

    test {
    let doc = KdlPreservedDocument::new("", "", [], "", None)
    doc.push(KdlNode::new(KdlIdentifier::new("a")))
    doc.push(KdlNode::new(KdlIdentifier::new("b")))
    doc.remove_at(0)
    assert_eq(doc.nodes()[0].node().name_str(), "b")
    }

    KdlPreservedDocument::set_version

    fn KdlPreservedDocument::set_version(self : KdlPreservedDocument, version : Int?) -> Unit

    Set the version marker.

    test {
    let doc = KdlPreservedDocument::new("a", "", [], "", None)
    doc.set_version(Some(1))
    assert_eq(doc.get_version(), Some(1))
    }

    KdlPreservedDocument::source

    fn KdlPreservedDocument::source(self : KdlPreservedDocument) -> String

    The original source text this document was parsed from. The original source text this document was parsed from.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "", [pn], "", None)
    assert_eq(doc.source(), "a")
    }

    KdlPreservedDocument::to_kdl_document

    Down-convert to the plain data model (KdlDocument) so query / schema / decode can be used on an edited preserved document. Down-convert to the plain data model (KdlDocument) so query / schema / decode can be used on an edited preserved document.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "", [pn], "", None)
    let plain = doc.to_kdl_document()
    assert_eq(plain.nodes().length(), 1)
    }

    KdlPreservedDocument::to_kdl_string

    fn KdlPreservedDocument::to_kdl_string(self : KdlPreservedDocument) -> String

    Serialize the document. Unmodified nodes round-trip byte-for-byte (their comments, whitespace and separators are emitted verbatim); modified nodes are rebuilt from the data model while keeping their leading comments. Serialize the document. Unmodified nodes round-trip byte-for-byte (their comments, whitespace and separators are emitted verbatim); modified nodes are rebuilt from the data model while keeping their leading comments.

    test {
    let node = KdlNode::new(KdlIdentifier::new("a"))
    let pn = KdlPreservedNode::new(
    node,
    Some(node),
    "// c\n",
    "a",
    ["// c"],
    None,
    )
    let doc = KdlPreservedDocument::new("// c\na", "", [pn], "", None)
    assert_eq(doc.to_kdl_string(), "// c\na")
    }

    KdlPreservedDocument::trailing

    fn KdlPreservedDocument::trailing(self : KdlPreservedDocument) -> String

    Text after the last node (trailing comments / whitespace). Text after the last node (trailing comments / whitespace).

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let doc = KdlPreservedDocument::new("a", "", [pn], "// end\n", None)
    assert_eq(doc.trailing(), "// end\n")
    }

    KdlPreservedNode

    pub struct KdlPreservedNode {
    node : KdlNode
    orig : KdlNode?
    leading : String
    body : String
    comments : Array[String]
    children : Array[KdlPreservedNode]?
    } derive(
    Debug
    )

    A node in the preserved layer: current data plus the original snapshot, leading comments and body text, so unmodified nodes round-trip verbatim.

    test {
    let node = KdlNode::new(KdlIdentifier::new("a"))
    let pn = KdlPreservedNode::new(node, Some(node), "", "a", [], None)
    assert_true(pn.is_unchanged())
    assert_eq(pn.to_kdl_string(), "a")
    }

    KdlPreservedNode::body

    fn KdlPreservedNode::body(self : KdlPreservedNode) -> String

    The original source text of this node (including its children block). The original body text of this node (excluding leading comments).

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a 1",
    [],
    None,
    )
    assert_eq(pn.body(), "a 1")
    }

    KdlPreservedNode::children

    The preserved children of this node, if it had a children block. The preserved child nodes, if this node has a children block.

    test {
    let child = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("c")),
    None,
    "",
    "c",
    [],
    None,
    )
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("p")),
    None,
    "",
    "p",
    [],
    Some([child]),
    )
    assert_eq(pn.children().unwrap().length(), 1)
    }

    KdlPreservedNode::comments

    fn KdlPreservedNode::comments(self : KdlPreservedNode) -> Array[String]

    The comments that preceded this node in the original source, in order. The individual comment strings preceding this node.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    ["// a", "// b"],
    None,
    )
    assert_eq(pn.comments(), ["// a", "// b"])
    }

    KdlPreservedNode::is_unchanged

    fn KdlPreservedNode::is_unchanged(self : KdlPreservedNode) -> Bool

    True when the current node data is identical to the original parse, i.e. the original source text can be emitted verbatim. True when the current node data is identical to the original parse, i.e. the original source text can be emitted verbatim.

    test {
    let node = KdlNode::new(KdlIdentifier::new("a"))
    let pn = KdlPreservedNode::new(node, Some(node), "", "a", [], None)
    assert_true(pn.is_unchanged())
    assert_false(
    pn.set_node(KdlNode::new(KdlIdentifier::new("b"))).is_unchanged(),
    )
    }

    KdlPreservedNode::leading

    fn KdlPreservedNode::leading(self : KdlPreservedNode) -> String

    The original gap text before this node (comments, whitespace, separators). The original gap text before this node (comments, whitespace, separators).

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "// hi\n",
    "a",
    [],
    None,
    )
    assert_eq(pn.leading(), "// hi\n")
    }

    KdlPreservedNode::new

    fn KdlPreservedNode::new(node : KdlNode, orig : KdlNode?, leading : String, body : String, comments : Array[String], children : Array[KdlPreservedNode]?) -> KdlPreservedNode

    Build a preserved node from its parts: current data, original snapshot, leading comments, original body text, comments and preserved children.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "// c\n",
    "a",
    ["// c"],
    None,
    )
    assert_eq(pn.node().name_str(), "a")
    assert_eq(pn.leading(), "// c\n")
    assert_false(pn.is_unchanged())
    }

    KdlPreservedNode::node

    The current (possibly edited) node data. The current (possibly edited) node data.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    assert_eq(pn.node().name_str(), "a")
    }

    KdlPreservedNode::set_node

    Replace the node data. The original snapshot is kept, so the next to_kdl_string serializes this node from the data model. Replace the node data. The original snapshot is kept, so the next to_kdl_string serializes this node from the data model.

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    Some(KdlNode::new(KdlIdentifier::new("a"))),
    "",
    "a",
    [],
    None,
    )
    let edited = pn.set_node(KdlNode::new(KdlIdentifier::new("b")))
    assert_eq(edited.node().name_str(), "b")
    assert_false(edited.is_unchanged())
    }

    KdlPreservedNode::set_orig

    Replace the original snapshot. Set it to the current node to mark the node as "unchanged" again (subsequent serializations emit the original text). Replace the original snapshot. Set it to the current node to mark the node as "unchanged" again (subsequent serializations emit the original text).

    test {
    let pn = KdlPreservedNode::new(
    KdlNode::new(KdlIdentifier::new("a")),
    None,
    "",
    "a",
    [],
    None,
    )
    let unchanged = pn.set_orig(Some(KdlNode::new(KdlIdentifier::new("a"))))
    assert_true(unchanged.is_unchanged())
    }

    KdlPreservedNode::to_kdl_string

    fn KdlPreservedNode::to_kdl_string(self : KdlPreservedNode) -> String

    The source text of this node, preserving the original formatting when the node is unchanged and rebuilding from the data model when it was edited. The source text of this node, preserving the original formatting when the node is unchanged and rebuilding from the data model when it was edited.

    test {
    let node = KdlNode::new(KdlIdentifier::new("a"))
    let pn = KdlPreservedNode::new(node, Some(node), "", "a", [], None)
    assert_eq(pn.to_kdl_string(), "a")
    }

    KdlSeverity

    pub(all) enum KdlSeverity {
    Error
    Warning
    } derive(Eq,
    Debug
    )

    The severity of a diagnostic.

    test {
    assert_eq(KdlSeverity::Error, KdlSeverity::Error)
    assert_eq(KdlSeverity::Warning, KdlSeverity::Warning)
    }

    KdlValue

    pub(all) enum KdlValue {
    String(String)
    Identifier(String)
    Integer(Int64)
    Float(Double)
    Bool(Bool)
    Null
    } derive(
    Debug
    )

    A KDL value: a string, bare identifier, integer, float, boolean or null.

    test {
    let v = KdlValue::Integer(42L)
    assert_true(v.is_integer())
    assert_eq(v.as_integer(), Some(42L))
    assert_eq(KdlValue::Bool(true).as_bool(), Some(true))
    }
    impl Eq for KdlValue

    KdlValue::as_bool

    fn KdlValue::as_bool(self : KdlValue) -> Bool?

    Return the boolean value if this is a Bool, otherwise None.

    test {
    assert_eq(KdlValue::Bool(true).as_bool(), Some(true))
    assert_eq(KdlValue::Integer(1L).as_bool(), None)
    }

    KdlValue::as_float

    fn KdlValue::as_float(self : KdlValue) -> Double?

    The float value if this is a Float, else None.

    test {
    assert_eq(KdlValue::Float(1.5).as_float(), Some(1.5))
    assert_eq(KdlValue::Integer(1L).as_float(), None)
    }

    KdlValue::as_identifier

    fn KdlValue::as_identifier(self : KdlValue) -> String?

    The content if this is a bare identifier, else None.

    test {
    assert_eq(KdlValue::Identifier("tcp").as_identifier(), Some("tcp"))
    assert_eq(KdlValue::String("tcp").as_identifier(), None)
    }

    KdlValue::as_integer

    fn KdlValue::as_integer(self : KdlValue) -> Int64?

    The integer value if this is an Integer, else None.

    test {
    assert_eq(KdlValue::Integer(42L).as_integer(), Some(42L))
    assert_eq(KdlValue::Bool(true).as_integer(), None)
    }

    KdlValue::as_string

    fn KdlValue::as_string(self : KdlValue) -> String?

    The string content if this is a string or bare identifier, else None.

    test {
    assert_eq(KdlValue::String("x").as_string(), Some("x"))
    assert_eq(KdlValue::Identifier("tcp").as_string(), Some("tcp"))
    assert_eq(KdlValue::Integer(1L).as_string(), None)
    }

    KdlValue::is_bool

    fn KdlValue::is_bool(self : KdlValue) -> Bool

    Whether this is a boolean value.

    test {
    assert_true(KdlValue::Bool(true).is_bool())
    assert_false(KdlValue::Null.is_bool())
    }

    KdlValue::is_float

    fn KdlValue::is_float(self : KdlValue) -> Bool

    Whether this is a float value.

    test {
    assert_true(KdlValue::Float(1.5).is_float())
    assert_false(KdlValue::Integer(1L).is_float())
    }

    KdlValue::is_identifier

    fn KdlValue::is_identifier(self : KdlValue) -> Bool

    Whether this is a bare-identifier value.

    test {
    assert_true(KdlValue::Identifier("tcp").is_identifier())
    assert_false(KdlValue::String("tcp").is_identifier())
    }

    KdlValue::is_integer

    fn KdlValue::is_integer(self : KdlValue) -> Bool

    Whether this is an integer value.

    test {
    assert_true(KdlValue::Integer(42L).is_integer())
    assert_false(KdlValue::Float(1.5).is_integer())
    }

    KdlValue::is_null

    fn KdlValue::is_null(self : KdlValue) -> Bool

    Whether this is a null value.

    test {
    assert_true(KdlValue::Null.is_null())
    assert_false(KdlValue::Bool(false).is_null())
    }

    KdlValue::is_string

    fn KdlValue::is_string(self : KdlValue) -> Bool

    Whether this is a string or bare-identifier value.

    test {
    assert_true(KdlValue::String("x").is_string())
    assert_true(KdlValue::Identifier("tcp").is_string())
    assert_false(KdlValue::Integer(1L).is_string())
    }

    KdlValue::to_kdl_string

    fn KdlValue::to_kdl_string(self : KdlValue) -> String

    Serialize a single value to KDL text.

    test {
    assert_eq(KdlValue::Integer(42L).to_kdl_string(), "42")
    assert_eq(KdlValue::Bool(true).to_kdl_string(), "#true")
    assert_eq(KdlValue::Null.to_kdl_string(), "#null")
    }

    clone_kdl_node

    fn clone_kdl_node(node : KdlNode) -> KdlNode

    Public helper: deep-copy a node tree (used by parse_preserve). Public helper: deep-copy a node tree (used by parse_preserve).

    test {
    let node = KdlNode::with_children(KdlIdentifier::new("p"), [
    KdlNode::new(KdlIdentifier::new("c")),
    ])
    let copy = clone_kdl_node(node)
    assert_eq(copy, node)
    }

    extract_leading_comments

    fn extract_leading_comments(gap : String) -> Array[String]

    Public helper: the comments preceding a chunk of gap text (used by parse_preserve in the parser package). Public helper: the comments preceding a chunk of gap text (used by parse_preserve in the parser package).

    test {
    assert_eq(extract_leading_comments("// a\n// b\n"), ["// a", "// b"])
    assert_eq(extract_leading_comments(""), [])
    }