The MON format is Moth Object Notation as serialised literal data: one root record written in the shared MON notation and restricted to literal values. Every value in a completed document must be a supported literal form.
A MON reader never evaluates Moth expressions. Arithmetic, templates, calls, casts, field projections, variables and constant references are rejected even when the compiler could fold them. Rejection happens before expression evaluation, not after evaluating and inspecting a result.
The standalone Rust crate moth_mon owns the codec. The compiler provides the same API and Rust types through the convenience re-export moth::mon. Full standalone-use examples belong in the crate documentation rather than this format reference.
One root record
A complete document contains exactly one record. Its outer parentheses may be omitted. These forms have the same record meaning:
title = "Strategy",
window = (width = 1280, height = 720),
(
title = "Strategy",
window = (width = 1280, height = 720),
)
A lone scalar, collection or choice is not a document. Put it in a named root field. The explicit empty root is (). Empty and comments-only input denotes an empty root record. Validation still checks every required field.
Use commas between entries at every level, with one optional trailing comma. Newlines are whitespace, not a separator. Root fields create no bindings, scope or references to earlier fields. After an explicit root, only whitespace and comments may remain. Multiple roots and concatenated documents are invalid. The file and in-memory document grammars are identical.
Records, collections and maps
Values nest recursively subject to resource limits and the receiving schema. Supported values are records, ordered collections, maps, quoted strings, characters, booleans, numeric literal data, none, literal choices and qualified nominal record data.
Record fields have unique identifier labels and explicit = value entries. They are named-only and carry no annotations, declaration qualifiers, mutable markers or shorthand initialisers. () is an empty record, never a tuple or unit value.
For every named entry, including implicit and explicit roots, nested records and qualified payloads, the label and = must appear on the same logical line with at least one horizontal whitespace character before =. LF and CR are the only line breaks; CRLF counts as one break. Every other Unicode whitespace character is horizontal whitespace and may separate the label from =. At least one whitespace character must also follow =; the value may start after a newline. A comment cannot replace either required whitespace character, and a line comment cannot bridge the label to an = on a later line. This format tightening rejects missing = spacing and label-to-= line breaks that an earlier reader accepted.
MON collections may contain different literal kinds and different record shapes. The receiving schema enforces its element type. Heterogeneous text changes no Moth collection typing rule and adds no Any type to Moth.
Maps preserve insertion order. Keys use the supported Moth map-key families: String, Bool, Char, I8, I16, I32, I64, U8, U16, U32, U64 and Byte, with each width retaining its own range and comparison. Bare names are references, not key shorthand, and are invalid as MON map keys. The schema checks the declared key and value types. Map entries and collection items cannot be mixed.
Every non-empty map entry requires trivia between its key and = and at least one whitespace character immediately after =. The key-to-= gap accepts whitespace and comments; comments do not replace the required whitespace after =. This format tightening rejects non-empty entries missing spacing on either side. Duplicate keys are rejected rather than keeping the first or last value. Keys compare as decoded values under the receiving key contract, so different escape or numeric spellings cannot evade uniqueness. A key of one declared type never matches another. String and Char remain distinct, and Bool is not a numeric key. Record labels remain identifiers, while map keys are data: a string-keyed map does not become a record.
The empty forms never change kind:
{=} is always an empty map and the spacing exception for non-empty map entries; {} is always an empty collection.- A map schema rejects
{} and a collection schema rejects {=}. Schema context never changes a container's kind.
scores = {"Priya" = 10, "Rob" = 12},
empty_scores = {=},
empty_items = {},
empty_record = (),
Reserved user names
Moth and MON apply the shared name law from Comments and naming to user names. It covers record labels, named arguments and nominal qualifiers. It also covers choice and variant names plus schema field and payload names. Schema preparation and text reading enforce the rule. Validation and encoding also enforce it for programmatic values and defaults. The format rejects invalid names such as __LoOp, _U64, dec01 and dec257. Invalid supplied names report InvalidIdentifier. Preparation projects invalid schema names to InvalidSchema and invalid default names to InvalidDefault.
true, false and none remain literal values, not user names. Quoted String data and string map keys remain unrestricted by reserved-name matching.
Strings and characters
Strings use double quotes and Char uses single quotes. A Char decodes as exactly one Unicode scalar value. String contents are preserved without Unicode normalisation or implicit line-ending conversion. An unescaped newline or CRLF inside a string stays byte-for-byte content, because MON is data, not Moth source.
MON strings accept exactly \\, \", \n, \r, \t and \u{H...}. MON characters accept exactly \\, \', \n, \r, \t and \u{H...}. The Unicode braces hold 1 to 6 ASCII hex digits and accept either case on input; writer output uses uppercase hex. Empty braces, more than six digits, non-hex digits, surrogate values and out-of-range scalars fail. \0, \xNN, fixed-width \uXXXX, an escaped physical newline and every other unknown escape fail.
Templates are producer syntax only and are not accepted string literals in MON. A folded const template and an evaluated runtime template are each an ordinary String that a producer quotes; an unevaluated template is not a serialisable value. Compile time versus runtime concerns the producer and never changes document validity.
Numeric data
A numeric literal keeps its lossless spelling until the destination is known. Whole-number spelling and decimal/exponent spelling remain distinguishable, and numbers are never routed through f64 or display formatting.
The lexical rules are strict. Exponents use lowercase e; uppercase E fails. Unary + fails, and - is accepted only when attached to the literal. _ is allowed only between decimal digits inside the integer, fraction or exponent runs. Malformed, edge and double separators fail, and NaN and infinity have no MON spelling.
Conversion is strict about categories:
- Exact
Integer and every fixed-width integer from I8 to U64 require whole-number spelling. Decimal data such as 3.0 fails such a target even when mathematically integral, and 1e3 fails it too. Byte also requires whole-number spelling and accepts only 0 through 255. Formatting cannot rewrite one category as the other. - Unsigned schemas reject negative spelling, including
-0, and check their declared range. U64 retains the full payload from 0 through 18446744073709551615 without a signed or binary-float intermediate. Programmatic encoding and defaults undergo the same exact-width checks. - Exact
Decimal data with a declared scale from 0 to 256 accepts whole, decimal and exponent forms only when the value is exact after removing trailing fractional zeroes and the effective scale is at most the declared scale. A scale-two target accepts 1.2 but rejects 1.239 without rounding. Exact decimal data is the materialisation path for Dec and DecN schemas, and it rejects inexact values instead of rounding. - The fixed binary floats
F16, F32 and F64 accept whole, decimal and exponent spelling. Each literal rounds directly to its declared precision using nearest, ties-to-even, without a default F64 value followed by narrowing. Non-finite rounded results fail. Subnormals and signed zero remain valid. Encoding round-trips each supported typed value: negative zero writes -0.0 and positive zero writes 0.
The schema owns these categories directly. A schema's declared width or scale is checked during preparation and reused verbatim during decoding and encoding, so a numeric destination never depends on external numeric context. Integer and Decimal remain lossless exact families, while fixed widths round or reject exactly by their declared rule. Large integer and exact decimal data are retained and round-tripped without a second arithmetic runtime. Unsupported concrete adapters fail explicitly rather than narrowing or converting through a binary float.
The public Rust API names destinations with SchemaType::I8 through SchemaType::I64, SchemaType::U8 through SchemaType::U64, SchemaType::F16, SchemaType::F32, SchemaType::F64 and SchemaType::Byte. SchemaType::Integer retains arbitrary-precision whole-number data. SchemaType::Decimal { scale } retains exact decimal data. These Rust data-family names add no Moth source types. MON performs no source inference or numeric default selection and has no numeric-profile API or aliases.
Programmatic values and defaults keep their exact variants. Value::I32(1) cannot satisfy an I64 or F64 schema. Each fixed integer uses its matching Rust integer carrier, while Value::F16, Value::F32 and Value::F64 use f64 carriers. Validation rounds a matching float carrier at that variant's precision and rejects non-finite results. The carrier does not change the schema identity or provide cross-type conversion. For Moth source semantics, see Numeric types and Numeric literals.
moth-lexical owns shared numeric grammar, direct materialisation and formatting. The source compiler and MON schema independently select their receivers. Source expression context never permits MON arithmetic.
Structs and choices
Both nested record forms are accepted:
size = (width = 1280, height = 720),
size = Size(width = 1280, height = 720),
These are alternative examples, not duplicate fields in one document. Anonymous records use named entries. A qualified nominal record literal follows the shared constructor argument rules without invoking user code.
A qualifier is one identifier: Unicode alphabetic or underscore start, Unicode alphanumeric or underscore continuation, case-sensitive. Dotted paths, aliases and registry lookup are invalid. As in Moth source, a qualified variant is one lexical header: write Choice::Variant with no whitespace, line break or comment on either side of ::. The receiving schema determines the expected nominal type. An explicit qualifier is an additional checked assertion, never ignored and never used to select another schema. Matching payload shapes do not make unrelated nominal types interchangeable.
Choice data uses Moth-shaped variants rather than an invented tagged-record mapping:
widgets = {
::Text("Gold"),
Widget::Progress(value = 0.4),
::Ready,
},
A unit variant has no parentheses and a payload variant requires them.
For both nominal and choice payloads, ( must follow the constructor name or variant on the same logical line, with only horizontal whitespace between. A line break or -- comment means the head has no payload; the remaining input fails through ordinary parsing. This intentionally tightens MON's earlier acceptance of payload openers after line breaks or comments. ::Text(...) uses the expected choice from the receiving schema, while an explicit Widget qualifier must name that same expected choice. An unknown or mismatching explicit name fails.
Positional arguments precede named arguments. Target slots are routed once, every required slot is supplied exactly once, and unknown variants, duplicate payload fields, wrong arity and payload type mismatches fail. Choice payload fields have no defaults. Typed encoding checks any supplied qualifier before omitting it, and prefers unqualified named records with named choice payloads.
Schemas, defaults and options
Schemas define ordinary data shapes, field types, nominal identities, choice variants and explicit default values. They do not define a second expression language. Records are closed: every unknown field fails, including a misspelling of a field whose correct name has a default. Maps provide the explicit dynamic-key surface. Each schema declares its own numeric types by explicit width or decimal scale, with the lossless Integer/Decimal family retained.
V1 supplies a small immutable Rust schema description for host callers. The engine defines its save-data contract once and supplies it explicitly. A prepared schema and its defaults are validated when prepared, before any document is processed, and the immutable prepared schema is reused across calls. Schema misuse is a structured failure, not a panic. There are no schema files, remote schema loading, runtime schema editing, registries or predicate DSLs.
Eligibility is derived transitively from the complete concrete schema. Every field, element, map entry and variant payload must have a supported mapping, and an unsupported member makes the enclosing shape ineligible even when the current instance does not use it. Functions, wires, routes, closures, live handles, unresolved resource pieces and deferred computations have no ordinary data encoding. A completed runtime-generated String is eligible. No mandatory serialisation trait, per-type marker, rename or skip attribute, custom codec hook or constructor execution participates in decoding.
Optionality permits none. Only an explicit field default permits omission. A missing optional field without a default is an error. Missing fields, explicit none and empty values remain distinct.
Defaults are prevalidated data, not runtime factories. A default applies only at the exact missing field. A supplied none is validated as none and never replaced by a default. A supplied nested record is validated as that record, not deep-merged with the parent's default record.
Invalid default values report InvalidDefault during preparation, including an exact decimal that cannot fit its declared scale. The same inexact supplied decimal reports NumericScale. Resource-budget failures retain their budget codes in either context.
For a parent field layout with no default, omission fails even when every field inside the Layout schema has a default. Supplying layout = () permits those inner defaults to apply. If layout itself has a default, omission uses that complete value. () remains an empty record at the format level; it becomes a completed default-valued record only when its receiving schema permits every omission.
Normal typed encoding emits all completed fields, including explicit none and values equal to defaults.
Trees, not graphs
The data format represents value trees. Repeated shared source values are encoded at each occurrence, and decoding establishes no preserved alias relationship or allocation identity. Public Value is an owned tree, so cyclic host data cannot be represented by this API. Public SchemaType values form finite owned schema trees rather than named schema references. Each schema describes only its explicit nesting levels, and the codec validates values against those levels and the receiver's limits. Applications can encode graph links as ordinary identifiers and reconstruct them explicitly.
Limits and first errors
The codec consumes complete documents and fails fast. Incremental input, streams and multiple-document framing remain deferred. Finite configurable budgets bound input bytes, nesting, node counts (including one additional node for each map entry), numeric digits, default expansions, decoded bytes and encoded output bytes. The default depth budget is 64; Limits::MAX_SAFE_DEPTH sets a hard ceiling of 64 for configurable max_depth, and schema preparation rejects larger policies. Each counter is checked before the affected allocation or expansion, including default expansion and repeated shared-value expansion. The other defaults are 1 MiB of input, 100,000 nodes, 4,096 numeric digits, 16 MiB of decoded bytes, 16 MiB of output bytes and 10,000 default expansions.
Limits are receiver resource policy, not grammar dialects. A valid document may exceed a receiver's budget, and that outcome is reported distinctly from syntax and schema errors.
Both operations publish only complete successful results. On failure, partial values and output buffers are discarded and no partial public result exists. Each failure carries a stable MonErrorCode, a field or element path and an original-input half-open byte span where available. MonError implements Display and std::error::Error for ordinary Rust reporting and propagation without retaining input text or compiler context. Callers can still inspect the structured code, path, span and detail independently of rendered text.
Deterministic writing
Typed record fields write in schema declaration order. Collection and map order is preserved. Public encode_document and encode_value emit compact output; pretty formatting is private to writer tests and has no public mode. Given the same ordered value, schema and encoder version, output is deterministic, with no promise that all semantically equivalent documents share identical bytes.
Formatting authored text is distinct from typed encoding. It cannot silently fill omitted fields, reorder maps, remove unchecked qualifiers or erase numeric categories.
Resources and versions
MON carries resource identifiers as ordinary strings. Compiler structural resource pieces are resolved to their final characters before encoding, and an unresolved value fails conversion to concrete MON data. V1 performs no path discovery, URL generation, filesystem checks or resource loading, and no string scan reconstructs dependencies.
The receiver supplies the schema. There is no mandatory schema header, reserved universal version field or automatic schema discovery. Applications may declare an ordinary format_version field with explicit migrations. Closed schemas never silently fall back to another version or repair mismatches.