Skip to main content

tabnas_toml/
lib.rs

1// Copyright (c) 2021-2026 Richard Rodger, MIT License
2
3// The engine's error carries a code, position, hint and a formatted
4// report, so it is large by design and `Result<_, TabnasError>` trips
5// clippy's `result_large_err`. The engine allows the lint at its own crate
6// root for the same reason; boxing here would make `parse` return a
7// different shape from `Tabnas::parse` and from the other two ports.
8#![allow(clippy::result_large_err)]
9
10//! The TOML grammar plugin for the `tabnas` parsing engine.
11//!
12//! It parses [TOML](https://toml.io) into plain values: bare, quoted and
13//! dotted keys, `[table]` headers, `[[array-of-tables]]`, inline tables,
14//! arrays, basic, literal and multi-line strings, integers and floats
15//! including `inf` and `nan`, booleans, and date and time values.
16//!
17//! It is not standalone. It layers on the relaxed-JSON base grammar from
18//! [`tabnas_jsonic`] (the `val` / `map` / `list` / `pair` / `elem` rules),
19//! sets `rule.start` to `toml` and excludes the jsonic alternates, then
20//! adds the TOML rules, a custom string matcher and context-aware date and
21//! time matchers on top.
22//!
23//! ```
24//! let value = tabnas_toml::parse("title = \"TOML\"\n[owner]\nname = \"Tom\"")?;
25//! assert_eq!(
26//!     value.to_string(),
27//!     r#"{"title":"TOML","owner":{"name":"Tom"}}"#
28//! );
29//! # Ok::<(), tabnas_toml::TomlError>(())
30//! ```
31//!
32//! TypeScript is canonical: `ts/src/toml.ts` defines behaviour, and the
33//! grammar itself is authored once in `toml-grammar.jsonic` and embedded
34//! into every runtime. The shared fixtures in `test/spec/*.tsv` are the
35//! parity contract across TypeScript, Go and Rust.
36
37use std::cell::RefCell;
38use std::rc::Rc;
39use std::sync::OnceLock;
40
41use serde_json::{json, Map, Value as Json};
42use tabnas::{
43    Context, GrammarError, GrammarSpec, Plugin, PluginError, RuleSnapshot, RuleState, Tabnas,
44    Value, ValueDef,
45};
46
47mod datematcher;
48mod daterange;
49mod node;
50mod refs;
51mod strmatcher;
52mod values;
53
54pub use tabnas::TabnasError as TomlError;
55pub use values::{toml_time, TomlTime, LOCAL_DATE, LOCAL_DATE_TIME, LOCAL_TIME, OFFSET_DATE_TIME};
56
57/// This crate's version. It MUST equal `ts/package.json` "version": the
58/// release orchestrator rewrites both, and `tests/version_test.rs` fails
59/// the build if they drift. Mirrors `VERSION` in `ts/src/toml.ts` and
60/// `const VERSION` in `go/toml.go`.
61pub const VERSION: &str = "0.5.23";
62
63/// The README's Rust examples run as doctests, so a stale one fails the
64/// gate rather than misleading the reader. Its `toml` and `bash` fences
65/// are skipped; rustdoc runs only the `rust` ones.
66#[cfg(doctest)]
67#[doc = include_str!("../README.md")]
68mod readme_examples {}
69
70// --- BEGIN EMBEDDED toml-grammar.jsonic ---
71pub(crate) const GRAMMAR_TEXT: &str = r#"
72# TOML Grammar Definition
73# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
74# Function references (@ prefixed) are resolved against the refs map.
75# Regex references (@/pattern/flags) are resolved to RegExp instances.
76
77{
78  options: rule: { start: toml exclude: jsonic }
79  options: lex: {
80    emptyResult: {}
81    match: string: make: '@make-toml-string-matcher'
82  }
83  options: fixed: token: { '#CL': '=' '#DOT': '.' }
84  options: match: {
85    token: { '#ID': '@/^[a-zA-Z0-9_-]+/' }
86    value: {
87      isodate: {
88        match: '@/^\\d\\d\\d\\d-\\d\\d-\\d\\d([Tt ]\\d\\d:\\d\\d(:\\d\\d(\\.\\d+)?)?([Zz]|[-+]\\d\\d:\\d\\d)?)?/'
89        val: '@isodate-val'
90      }
91      localtime: {
92        match: '@/^\\d\\d:\\d\\d(:\\d\\d(\\.\\d+)?)?/'
93        val: '@localtime-val'
94      }
95    }
96  }
97  options: tokenSet: {
98    KEY: ['#ST' '#ID' null null]
99  }
100  options: comment: def: { slash: null multi: null }
101
102  rule: toml: open: [
103    { s: ['#ST #NR #ID' '#CL'] p: table b: 2 }
104    { s: ['#OS' '#ST #NR #ID'] p: table b: 2 }
105    { s: ['#OS' '#OS'] p: table b: 2 }
106    { s: ['#ST #NR #ID' '#DOT'] p: table b: 2 }
107    { s: '#ZZ' }
108  ]
109
110  rule: table: {
111    open: [
112      { s: ['#ST #NR #ID' '#CL'] p: map b: 2 }
113      { s: ['#OS' '#ST #NR #ID'] r: table b: 1 }
114      { s: ['#OS' '#OS'] r: table n: { table_array: 1 } }
115      {
116        s: ['#ST #NR #ID' '#DOT']
117        c: '@table-top-dive-cond'
118        p: dive
119        b: 2
120        u: { top_dive: true }
121      }
122      {
123        s: ['#ST #NR #ID' '#DOT']
124        r: table
125        c: '@lte-table-dive'
126        n: { table_dive: 1 }
127        a: '@table-dive-start'
128        g: 'dive,start'
129      }
130      {
131        s: ['#ST #NR #ID' '#DOT']
132        r: table
133        n: { table_dive: 1 }
134        a: '@table-dive-mid'
135        g: 'dive'
136      }
137      {
138        s: ['#ST #NR #ID' '#CS']
139        c: '@lte-table-dive'
140        p: '@table-end-p'
141        r: '@table-end-r'
142        a: '@table-key-cs-head'
143      }
144      {
145        s: ['#ST #NR #ID' '#CS']
146        p: '@table-end-p'
147        r: '@table-end-r'
148        a: '@table-key-cs-tail'
149        g: 'dive,end'
150      }
151      {
152        s: '#CS'
153        p: map
154        c: '@lte-table-array-1'
155        a: '@table-cs-push'
156      }
157    ]
158    close: [
159      { s: ['#OS' '#OS'] r: table b: 2 g: end }
160      { s: ['#OS' '#ST #NR #ID'] r: table b: 1 g: end }
161      { s: '#ZZ' g: end }
162    ]
163  }
164
165  rule: map: {
166    open: [
167      { s: '#OS' b: 1 }
168      {
169        s: ['#ST #NR #ID' '#CL']
170        c: '@map-is-table-parent'
171        p: pair
172        b: 2
173      }
174      { s: ['#OB' '#ST #NR #ID'] b: 1 p: pair }
175      { s: ['#ST #NR #ID' '#DOT'] p: dive b: 2 }
176      { s: '#ZZ' }
177    ]
178    close: [
179      { s: '#OS' b: 1 g: end }
180      { s: '#ZZ' g: end }
181    ]
182  }
183
184  rule: pair: {
185    open: [
186      {
187        s: ['#ST #NR #ID' '#CL']
188        p: val
189        u: { pair: true }
190        a: '@pair-key-set'
191      }
192      { s: ['#ST #NR #ID' '#DOT'] p: dive b: 2 }
193    ]
194    close: [
195      { s: ['#ST #NR #ID'] b: 1 r: pair g: comma }
196      { s: ['#CA' '#ST #NR #ID'] b: 1 r: pair g: comma }
197      { s: ['#OS'] b: 1 g: end }
198      { s: ['#CA' '#CB'] c: '@lte-pk' b: 1 g: close }
199    ]
200  }
201
202  rule: val: close: [
203    { s: ['#ST #NR #ID'] b: 1 g: end }
204    { s: ['#OS'] b: 1 g: end }
205  ]
206
207  rule: elem: close: [
208    { s: ['#CA' '#CS'] b: 1 g: comma }
209  ]
210
211  # A dotted key is a replace loop, as a dotted header is: each segment
212  # ending in a dot re-enters dive in the same frame (r), so rule depth
213  # stays what one segment needs however long the key, and only the value
214  # nests. The loop at the close takes the next dotted key without
215  # returning to the pair, and begins it from the table that holds both.
216  rule: dive: {
217    open: [
218      {
219        s: ['#ST #NR #ID' '#DOT']
220        r: dive
221        a: '@dive-key-dot'
222      }
223      {
224        s: ['#ST #NR #ID' '#CL']
225        p: val
226        u: { dive_end: true }
227      }
228    ]
229    close: [
230      {
231        s: ['#ST #NR #ID' '#DOT']
232        b: 2
233        r: dive
234      }
235      {}
236    ]
237  }
238}
239"#;
240// --- END EMBEDDED toml-grammar.jsonic ---
241
242/// The plugin's name, as the engine records it.
243const PLUGIN_NAME: &str = "toml";
244
245/// Parser options. Reserved for future use, as `TomlOptions` is in both
246/// other ports.
247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
248pub struct TomlOptions;
249
250/// The lexer orders custom matchers against the builtin bands. All four of
251/// these sit below the `match` band at 1e6, so they are consulted before
252/// the value and token matchers, and the leading BOM before any of them.
253const BOM_ORDER: f64 = 500_000.0;
254const STRING_ORDER: f64 = 900_000.0;
255const ISODATE_ORDER: f64 = 950_000.0;
256const LOCALTIME_ORDER: f64 = 950_001.0;
257
258/// Parse the embedded grammar with a standard jsonic instance, exactly as
259/// the TypeScript and Go ports do, and answer it as a JSON document the
260/// engine's grammar loader takes.
261fn grammar_document() -> Result<Json, GrammarError> {
262    let parsed = tabnas_jsonic::make()
263        .parse(GRAMMAR_TEXT)
264        .map_err(|error| GrammarError(format!("Grammar: parse grammar text: {error}")))?;
265    let mut document = parsed.to_json();
266    integerize(&mut document);
267    let Some(root) = document.as_object_mut() else {
268        return Err(GrammarError(
269            "Grammar: the grammar text is not a map".into(),
270        ));
271    };
272    let options = root
273        .entry("options".to_string())
274        .or_insert_with(|| Json::Object(Map::new()));
275    let Some(options) = options.as_object_mut() else {
276        return Err(GrammarError("Grammar: options is not a map".into()));
277    };
278
279    adjust_token_sets(options);
280    adjust_value_matchers(options);
281    adjust_lex_matchers(options);
282    adjust_messages(options);
283
284    Ok(document)
285}
286
287/// Every number in a jsonic parse result is an `f64`, so `b: 2` arrives as
288/// `2.0` and the grammar loader, which wants a non-negative INTEGER for a
289/// backtrack count, refuses it. Fold every fractionless float back to an
290/// integer across the whole document. The Go port does the same, one field
291/// at a time, in `mapToAlt`.
292///
293/// Nothing in a grammar document means a float where an integer would do:
294/// the numeric fields are backtrack counts, counter deltas, rule depths
295/// and matcher orders.
296fn integerize(value: &mut Json) {
297    match value {
298        Json::Number(number) => {
299            if let Some(float) = number.as_f64() {
300                #[allow(clippy::cast_possible_truncation)]
301                if float.is_finite() && 0.0 == float.fract() && float.abs() < 9.0e15 {
302                    *value = Json::from(float as i64);
303                }
304            }
305        }
306        Json::Array(items) => items.iter_mut().for_each(integerize),
307        Json::Object(entries) => entries.values_mut().for_each(integerize),
308        _ => {}
309    }
310}
311
312/// `tokenSet: { KEY: ['#ST' '#ID' null null] }`. The canonical token-set
313/// form pads a set to four slots with nulls; this engine's loader takes
314/// the members alone and rejects a null entry, so the padding is dropped.
315/// Same set either way: a null slot names no token.
316fn adjust_token_sets(options: &mut Map<String, Json>) {
317    let Some(sets) = options.get_mut("tokenSet").and_then(Json::as_object_mut) else {
318        return;
319    };
320    for members in sets.values_mut() {
321        if let Some(list) = members.as_array_mut() {
322            list.retain(|member| member.is_string());
323        }
324    }
325}
326
327/// Respell the grammar's `match.value` date and time patterns with ASCII
328/// digit classes.
329///
330/// The shared grammar text writes them with `\d`, which is right for the
331/// two runtimes that read it: JavaScript compiles them without the `u`
332/// flag and Go's RE2 has no Unicode `\d` at all, so in both `\d` is
333/// `0-9`. The `regex` crate reads `\d` as the whole Unicode `Nd`
334/// category, so the same text compiled here matches `٢٠٢٤-٠١-٠١` and
335/// turns it into a `local-date` value, where both other runtimes leave it
336/// as ordinary text.
337///
338/// The canonical port replaces these two matchers outright once the
339/// document is in, and so, in effect, does this one: the native matchers
340/// in [`datematcher`] are ordered ahead of the value band. But the
341/// grammar's own declarations stay installed here, and a value-band
342/// matcher is still consulted when the native one declines, so they have
343/// to agree with it rather than merely be shadowed by it. Taking the
344/// pattern from the native matcher itself is what keeps the two in step.
345fn adjust_value_matchers(options: &mut Map<String, Json>) {
346    let Some(values) = options
347        .get_mut("match")
348        .and_then(Json::as_object_mut)
349        .and_then(|matchers| matchers.get_mut("value"))
350        .and_then(Json::as_object_mut)
351    else {
352        return;
353    };
354    for (name, ascii) in [
355        ("isodate", datematcher::isodate_re().as_str()),
356        ("localtime", datematcher::localtime_re().as_str()),
357    ] {
358        let Some(entry) = values.get_mut(name).and_then(Json::as_object_mut) else {
359            continue;
360        };
361        // Only a regex reference is respelled. A `@name` function
362        // reference means the grammar has moved on and the substitution
363        // would no longer be describing the same thing.
364        if entry
365            .get("match")
366            .and_then(Json::as_str)
367            .is_some_and(|reference| reference.starts_with("@/"))
368        {
369            entry.insert("match".to_string(), json!(format!("@/{ascii}/")));
370        }
371    }
372}
373
374/// The grammar declares `lex.match.string.make` with no order, because the
375/// canonical engine's string matcher is a named builtin that this
376/// REPLACES. Here the builtin bands are fixed and a custom matcher is
377/// placed among them by order, so the string matcher is given one that
378/// puts it ahead of every band that could claim a quote.
379///
380/// The BOM and the two date matchers are added here rather than to the
381/// grammar text, because the text is shared with two ports that install
382/// their own equivalents natively.
383fn adjust_lex_matchers(options: &mut Map<String, Json>) {
384    let lex = options
385        .entry("lex".to_string())
386        .or_insert_with(|| Json::Object(Map::new()));
387    let Some(lex) = lex.as_object_mut() else {
388        return;
389    };
390    let matchers = lex
391        .entry("match".to_string())
392        .or_insert_with(|| Json::Object(Map::new()));
393    let Some(matchers) = matchers.as_object_mut() else {
394        return;
395    };
396
397    if let Some(string) = matchers.get_mut("string").and_then(Json::as_object_mut) {
398        string.insert("order".to_string(), json!(STRING_ORDER));
399    }
400    matchers.insert(
401        "bom".to_string(),
402        json!({ "order": BOM_ORDER, "make": "@bom-matcher" }),
403    );
404    matchers.insert(
405        "tomlisodate".to_string(),
406        json!({ "order": ISODATE_ORDER, "make": "@isodate-match" }),
407    );
408    matchers.insert(
409        "tomllocaltime".to_string(),
410        json!({ "order": LOCALTIME_ORDER, "make": "@localtime-match" }),
411    );
412}
413
414/// A code with no template renders as "unknown error: toml_key_conflict",
415/// which tells the author nothing. Kept in step with the TypeScript port's
416/// registration, so a document rejected by both is rejected in the same
417/// words.
418fn adjust_messages(options: &mut Map<String, Json>) {
419    options.insert(
420        "error".to_string(),
421        json!({
422            "toml_key_conflict": "cannot define {key}, {why}",
423            "invalid_datetime": "date or time is out of range",
424        }),
425    );
426    options.insert(
427        "hint".to_string(),
428        json!({
429            "toml_key_conflict": "\nTOML does not allow a key to be redefined, and a key that already holds a\nvalue is not a table you can add to. This usually means the same name was\nused twice: a key given a second value, a table or table-array header over a\nkey that already holds a value, a header written a second time, a header for\na table that a dotted key or an inline table had already defined, or the same\nname twice inside one inline table.",
430            "invalid_datetime": "\nThe value has the shape of a date or time, but one of its components is out\nof range: month 1-12, day 1 to the length of that month, hour 0-23, minute\nand second 0-59 (a second may be 60, for a leap second), and the same limits\nagain for a +hh:mm offset. February is checked against the actual year, so\n2100-02-29 is rejected - 2100 is not a leap year.",
431        }),
432    );
433}
434
435/// How many levels a document may nest before the parse is refused, with
436/// the engine's `cancel` code: 127 levels parse, the 128th is refused.
437///
438/// A level is a container the value being built sits in: the document's
439/// root table, a table or an array of tables along a header's or a dotted
440/// key's path, an inline table, an array. Every one counts, however the
441/// parse reaches it, and a key inside an inline table counts on from the
442/// keys outside it. The number is jsonic's, which `tabnas-json` and
443/// `serde_json` use too. jsonic's own check counts its `map` and `list`
444/// rules, which here are every inline table, every array and the body of
445/// every table, and never the tables a header or a dotted key nests
446/// through: under it a key of 10,000 segments parsed, building a value
447/// 10,000 deep (tabnas/toml#78). So an inline table or an array in the
448/// root table is bounded where jsonic's check bounded it, and one under a
449/// header or a dotted key now has that header's or key's tables counted
450/// above it.
451///
452/// The engine parses iteratively, but displaying, converting or dropping a
453/// `Value` walks the tree with the call stack, so an unbounded document
454/// ends the caller's process rather than returning an error. TypeScript
455/// and Go have no limit, which `../test/divergent.tsv` records.
456///
457/// A caller that wants the depth anyway lifts the guard with
458/// `parser.remove_parse_guard(DEPTH_GUARD)`. That lifts every bound, and
459/// not only the one this guard adds: the guard replaced jsonic's check
460/// under the same name, so nothing is left to stop an inline table or an
461/// array either, and a document of any depth parses. The caller then
462/// displays and drops the value on a stack that can take it.
463pub const DEPTH_LIMIT: usize = 127;
464
465/// The name the depth check is installed under, as a parse guard, and the
466/// name `Tabnas::remove_parse_guard` takes to lift it.
467///
468/// It is the name jsonic installs its own check under, so this one
469/// replaces it, as YAML's does: jsonic's counts its `map` and `list`
470/// rules, which is every inline table and array, but a header and a
471/// dotted key nest through `table` and `dive`, which it does not see. So
472/// removing this guard removes jsonic's bound with it, and leaves none
473/// (see [`DEPTH_LIMIT`]). A guard rather than the parse budget, because
474/// the budget is one slot a caller's `parse_budget` replaces, and a guard
475/// holds whatever budget the caller sets. A parse a grammar's guard
476/// cancels is reported by the fleet's tools as the input's fault, naming
477/// the guard.
478pub const DEPTH_GUARD: &str = "depth";
479
480/// How deep the value being built is nested at this point of the parse:
481/// the root table, what the rules on the rule stack add to it
482/// ([`levels_on_stack`]), and what the rule the loop is working on adds
483/// ([`current_levels`]).
484///
485/// The root table is counted first, because no rule stands for it on its
486/// own: a document's keys live in a `map` rule the root `table` pushes, or
487/// in a `dive` it pushes straight away when the first key is dotted.
488fn depth(context: &Context) -> usize {
489    let below = context.rule_stack.last();
490    let current = context
491        .rule
492        .as_ref()
493        .map_or(0, |rule| current_levels(rule, below));
494    1 + levels_on_stack(context) + current
495}
496
497/// The levels the rules on the rule stack add, carried from one step to
498/// the next.
499///
500/// The guard runs at every step, and walking the whole stack each time
501/// cost a step as much as the stack is deep: 2,000 lines of arrays or
502/// inline tables nested 120 deep took 20 to 28 percent longer to parse
503/// than under jsonic's guard, which keeps its count this way
504/// (tabnas/jsonic#91). The engine changes the stack only at the top: a
505/// pop truncates it and a push appends the new rule's snapshot, and the
506/// rules below the top stay as they were (the engine checks this in
507/// debug builds). What a frame adds depends on it and on the frame below
508/// it alone ([`frame_levels`]), and a rule's ancestors are fixed for as
509/// long as it lives, so the levels at or below a stack position are known
510/// once the rule at that position is. The count is kept for each position
511/// with the id of the rule there, which is unique within a parse, and a
512/// step recounts only from the first position whose rule has changed,
513/// usually the top. A callback that writes into `context.rule_stack`
514/// below the top is not followed.
515fn levels_on_stack(context: &Context) -> usize {
516    let stack = &context.rule_stack;
517    STACK_COUNT.with(|count| {
518        let mut count = count.borrow_mut();
519        let here = std::ptr::from_ref(context) as usize;
520        if count.context != here || 1 == context.iteration || context.iteration < count.iteration {
521            count.context = here;
522            count.frames.clear();
523        }
524        count.iteration = context.iteration;
525        let top = count.frames.len().min(stack.len());
526        let mut kept = top;
527        while kept > 0 && count.frames[kept - 1].0 != stack[kept - 1].i {
528            kept -= 1;
529        }
530        #[cfg(test)]
531        {
532            count.examined += (top - kept) + 1 + (stack.len() - kept);
533        }
534        count.frames.truncate(kept);
535        let mut levels = count.frames.last().map_or(0, |&(_, at)| at);
536        for position in kept..stack.len() {
537            let below = position.checked_sub(1).map(|under| &stack[under]);
538            levels += frame_levels(&stack[position], below);
539            count.frames.push((stack[position].i, levels));
540        }
541        levels
542    })
543}
544
545/// The count [`levels_on_stack`] keeps from one step to the next.
546struct StackCount {
547    /// The context the count describes, by address.
548    context: usize,
549    /// The last step counted. A parse's steps go up from 1, so a first
550    /// step, or one lower than the last, is a new parse in the same place;
551    /// the same step again is the same step, asked twice.
552    iteration: usize,
553    /// For each stack position, the id of the rule there and the levels
554    /// the rules at or below it add.
555    frames: Vec<(usize, usize)>,
556    /// Frames looked at, all told: what a step costs, for the tests.
557    #[cfg(test)]
558    examined: usize,
559}
560
561thread_local! {
562    // Per thread, as a parse runs on one; a nested parse on the same
563    // thread has a context of its own and starts the count afresh.
564    static STACK_COUNT: RefCell<StackCount> = const {
565        RefCell::new(StackCount {
566            context: 0,
567            iteration: 0,
568            frames: Vec::new(),
569            #[cfg(test)]
570            examined: 0,
571        })
572    };
573}
574
575/// The levels a rule on the rule stack adds, given the rule below it.
576///
577/// A `map` or `list` is a container: a table's body, an inline table, an
578/// array. A `table` on the stack has its body open, and its path, kept in
579/// its `u` bag, is exact, arrays of tables included; its body is a `map`
580/// INSIDE the table at the end of that path, not a level of its own, so a
581/// `map` directly above a `table` adds nothing (the root's body included,
582/// at path length zero).
583///
584/// A `dive` on the stack is a dotted key waiting for its value, and its
585/// path counts the tables the key has descended through from the table it
586/// is in: the cell of the table body or inline table that holds the key,
587/// or the root table's when the root table pushed the dive itself. So
588/// every key still open counts, and a key in an inline table that is the
589/// value of another key counts on from that key, however the parse
590/// reached it. A counter cannot say the same: the dive's close loop takes
591/// the next dotted key in the same frame and has to begin it from the
592/// table it is in, and a counter the loop reset lost the tables of every
593/// key further out with it. A dotted key on a new line of an inline table
594/// once counted from zero that way.
595fn frame_levels(rule: &Rc<RuleSnapshot>, below: Option<&Rc<RuleSnapshot>>) -> usize {
596    match rule.name.as_ref() {
597        "map" => usize::from(below.is_none_or(|below| "table" != below.name.as_ref())),
598        "list" => 1,
599        "table" | "dive" => node::snapshot_path(Some(rule)).len(),
600        _ => 0,
601    }
602}
603
604/// The levels the rule the loop is working on adds, given the top of the
605/// rule stack. The engine hands that rule over apart from the stack, and
606/// at the start of its step, before any of its actions have run.
607///
608/// A `table` that is the current rule is still reading its header, one
609/// segment per replacement, and a replacement inherits counters but not
610/// `u`, so its path says nothing yet: there the `table_dive` counter, the
611/// segments entered so far, plus the one being read, say how deep the
612/// header has got, so a header is refused at the segment that passes the
613/// limit and never builds a value past it. A `dive` that is still open
614/// has not run `@dive-bo`, which records its path, yet: it stands where
615/// the segment it replaced left off when it continues a key, and has
616/// descended through nothing when it begins one. So a dotted key is
617/// refused at the segment past the limit too.
618fn current_levels(rule: &Rc<RuleSnapshot>, below: Option<&Rc<RuleSnapshot>>) -> usize {
619    match rule.name.as_ref() {
620        "table" => {
621            let entered = rule.n.get("table_dive").copied().unwrap_or(0);
622            1 + usize::try_from(entered).unwrap_or(0)
623        }
624        "dive" if RuleState::Open == rule.state => {
625            let previous = rule.prev_rule.as_ref();
626            if refs::continues_key(previous) {
627                node::snapshot_path(previous).len()
628            } else {
629                0
630            }
631        }
632        _ => frame_levels(rule, below),
633    }
634}
635
636/// The depth guard: [`DEPTH_LIMIT`] levels parse, the next one is refused.
637fn within_depth_limit(context: &Context) -> bool {
638    depth(context) <= DEPTH_LIMIT
639}
640
641/// Install the TOML grammar on an instance that already carries the
642/// jsonic base grammar.
643///
644/// ```
645/// fn main() -> Result<(), Box<dyn std::error::Error>> {
646///     let mut parser = tabnas_jsonic::make();
647///     tabnas_toml::toml(&mut parser)?;
648///     assert_eq!(parser.parse("a = 1")?.to_string(), r#"{"a":1}"#);
649///     Ok(())
650/// }
651/// ```
652pub fn toml(parser: &mut Tabnas) -> Result<(), GrammarError> {
653    refs::register(parser);
654    register_native_matchers(parser);
655
656    let document = grammar_document()?;
657    let spec = GrammarSpec::from_value(document)?;
658    parser.grammar(&spec)?;
659
660    // Replaces jsonic's guard, which counts only jsonic's own containers
661    // (see `DEPTH_GUARD`).
662    parser.parse_guard(DEPTH_GUARD, within_depth_limit);
663
664    // After the document, because it is the document that installs the
665    // option tree these replace part of.
666    register_special_floats(parser)?;
667    Ok(())
668}
669
670/// The three matchers this port implements natively rather than in the
671/// shared grammar text.
672fn register_native_matchers(parser: &mut Tabnas) {
673    parser.imperative_lex_match_ref("@bom-matcher", datematcher::bom_matcher);
674    parser.imperative_lex_match_ref("@isodate-match", datematcher::isodate_matcher);
675    parser.imperative_lex_match_ref("@localtime-match", datematcher::localtime_matcher);
676}
677
678/// TOML's `nan` and `inf` keyword values, added alongside the standard
679/// `true` / `false` / `null`.
680///
681/// Not in the grammar document, for two reasons. The literals cannot
682/// round-trip through a jsonic parse of the grammar text: they come back
683/// as the strings. And a keyword definition takes a literal `val`, never a
684/// function reference, so there is no `@`-name for a number JSON cannot
685/// spell. Both other ports patch them in code for the same reason.
686/// Assigning the definitions REPLACES the engine's defaults, so
687/// `true` / `false` / `null` are restated.
688fn register_special_floats(parser: &mut Tabnas) -> Result<(), GrammarError> {
689    parser
690        .set_options(|options| {
691            let definitions = &mut options.value.definitions;
692            definitions.clear();
693            for (source, value) in [
694                ("true", Value::Bool(true)),
695                ("false", Value::Bool(false)),
696                ("null", Value::Null),
697                ("nan", Value::Number(f64::NAN)),
698                ("+nan", Value::Number(f64::NAN)),
699                ("-nan", Value::Number(f64::NAN)),
700                ("inf", Value::Number(f64::INFINITY)),
701                ("+inf", Value::Number(f64::INFINITY)),
702                ("-inf", Value::Number(f64::NEG_INFINITY)),
703            ] {
704                definitions.insert(
705                    source.to_string(),
706                    ValueDef {
707                        val: Some(value),
708                        matcher: None,
709                        transform: None,
710                        consume: false,
711                    },
712                );
713            }
714        })
715        .map_err(|error| GrammarError(format!("Grammar: value definitions: {error}")))?;
716    Ok(())
717}
718
719/// The plugin form of [`toml`], for [`Tabnas::use_plugin`]. Installed this
720/// way the grammar is re-applied to derived instances, as every native
721/// plugin is.
722pub fn plugin() -> Plugin {
723    Plugin::new(PLUGIN_NAME, |parser, _options| {
724        toml(parser).map_err(|error| PluginError(error.0))
725    })
726    .with_defaults(Value::object(indexmap::IndexMap::new()))
727}
728
729/// Build a TOML parser: a jsonic instance with this plugin installed, the
730/// counterpart of the TypeScript `make()` and the Go `MakeJsonic()`, with
731/// `lex.window` declared, so that [`Tabnas::parse_reader`] reads a reader a
732/// window at a time rather than whole (admin ADR-30).
733///
734/// ```
735/// fn main() -> Result<(), Box<dyn std::error::Error>> {
736///     let parser = tabnas_toml::make();
737///     assert_eq!(parser.parse("[a]\nx = 1")?.to_string(), r#"{"a":{"x":1}}"#);
738///     Ok(())
739/// }
740/// ```
741pub fn make() -> Tabnas {
742    make_with(TomlOptions)
743}
744
745/// Build a TOML parser with plugin options. `TomlOptions` carries nothing
746/// yet, in every port; the entry point exists so that adding one is not a
747/// breaking change.
748pub fn make_with(_options: TomlOptions) -> Tabnas {
749    let mut parser = tabnas_jsonic::make();
750    parser
751        .use_plugin(plugin(), None)
752        .expect("the toml grammar document is fixed and valid");
753    // The plugin's own matchers, its strings, its dates and times and the
754    // leading byte order mark, read the source through the lexer's window
755    // and fill it where a scan reaches its end; jsonic's base reads through
756    // it too (jsonic 0.7.11); and no action reads the source. So a parse
757    // from a reader may hold a window of the source rather than all of it
758    // (`Tabnas::parse_reader`). Set on the parser this crate makes whole,
759    // not in [`toml`] or [`plugin`], which a host may install beneath
760    // matchers of its own.
761    parser
762        .set_options(|options| options.lex.window = true)
763        .expect("lex.window sets");
764    parser
765}
766
767/// Parse a TOML document with a shared default parser.
768///
769/// Building the grammar dominates a parse, so the no-options path reuses
770/// one instance. Parsing builds a fresh context per call and only reads
771/// instance state, so the shared instance is safe for concurrent use.
772///
773/// ```
774/// fn main() -> Result<(), Box<dyn std::error::Error>> {
775///     let value = tabnas_toml::parse("[[products]]\nname = \"Hammer\"")?;
776///     assert_eq!(value.to_string(), r#"{"products":[{"name":"Hammer"}]}"#);
777///     Ok(())
778/// }
779/// ```
780pub fn parse(src: &str) -> Result<Value, TomlError> {
781    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
782    DEFAULT.get_or_init(make).parse(src)
783}
784
785/// The grammar text this crate embeds, for the test that compares it with
786/// the file on disk.
787#[doc(hidden)]
788pub fn grammar_text() -> &'static str {
789    GRAMMAR_TEXT
790}
791
792/// One optional alchemy translation source and its explicit entry point.
793#[derive(Clone, Copy, Debug, Eq, PartialEq)]
794pub struct TranslationPart {
795    /// The definition a host calls after linking the source.
796    pub entry: &'static str,
797    /// The source text, or `None` for an entry supplied by alchemy.
798    pub source: Option<&'static str>,
799}
800
801/// The package-local structural translation interface.
802#[derive(Clone, Copy, Debug, Eq, PartialEq)]
803pub struct TranslationParts {
804    /// The complete `tabnas.plugin.json` text.
805    pub manifest: &'static str,
806    /// An optional lift from the grammar's events to its first read shape.
807    pub lift: Option<TranslationPart>,
808    /// An optional embedding of a plain tree in the format's schema, with its reverse.
809    pub embed: Option<TranslationPart>,
810    /// An optional render from the write shape to text.
811    pub render: Option<TranslationPart>,
812    /// An optional transducer: the format's JSON events from its parser's
813    /// rule passes, for a host that reads parser events.
814    pub transduce: Option<TranslationPart>,
815}
816
817const TRANSLATION: TranslationParts = TranslationParts {
818    manifest: include_str!("../translate/manifest.json"),
819    lift: None,
820    embed: None,
821    render: Some(TranslationPart {
822        entry: "toml-render",
823        source: Some(include_str!("../translate/render.alc")),
824    }),
825    transduce: Some(TranslationPart {
826        entry: "toml-transduce",
827        source: Some(include_str!("../translate/transduce.alc")),
828    }),
829};
830
831/// Return TOML's immutable translation parts.
832#[must_use]
833pub const fn translate() -> Option<TranslationParts> {
834    Some(TRANSLATION)
835}
836
837/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
838/// it. Its `translate` object is what a host that translates reads: the
839/// shape TOML is read as and written from (`tree`), the file that holds
840/// the render, the sentences that say what the render does not keep, and
841/// the file that holds the transducer part (`transduce`), the document's
842/// JSON events from the grammar's rule passes under its default options,
843/// through which a host that reads parser events reads a document.
844/// The crate embeds its own copies, `translate/manifest.json` and
845/// `translate/transduce.alc`, since a packaged crate holds nothing outside
846/// `rs/`; `tests/translate_test.rs` holds each copy to its file.
847///
848/// ```
849/// assert!(tabnas_toml::manifest_text().contains("\"translate\""));
850/// ```
851pub fn manifest_text() -> &'static str {
852    TRANSLATION.manifest
853}
854
855/// TOML's render, `alchemy/render.alc`, the file the manifest's
856/// `translate.render` names: a library of alchemy definitions, with no
857/// `export`, whose entry point `toml-render` writes a tree's events as one
858/// TOML document. A host links it with its own program. The crate embeds
859/// its own copy, `translate/render.alc`, held to the file as the
860/// manifest's is.
861///
862/// ```
863/// assert!(tabnas_toml::render_text().contains("def toml-render [input]"));
864/// ```
865pub fn render_text() -> &'static str {
866    match TRANSLATION.render {
867        Some(part) => part.source.unwrap_or_default(),
868        None => "",
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use std::sync::atomic::{AtomicUsize, Ordering};
875    use std::sync::{Arc, Mutex};
876
877    use super::*;
878
879    /// [`depth`] with the stack walked afresh, as it was counted before
880    /// the count was kept from step to step.
881    fn walked(context: &Context) -> usize {
882        let mut levels = 1;
883        let mut below = None;
884        for rule in &context.rule_stack {
885            levels += frame_levels(rule, below);
886            below = Some(rule);
887        }
888        let current = context
889            .rule
890            .as_ref()
891            .map_or(0, |rule| current_levels(rule, below));
892        levels + current
893    }
894
895    fn segments(n: usize) -> String {
896        vec!["a"; n].join(".")
897    }
898
899    #[test]
900    fn the_kept_count_is_the_walked_count_at_every_step() {
901        // The engine turns a panic in a guard into a parse error, so a
902        // difference is written down and asserted after the parses. The
903        // check replaces the crate's own guard, so the count is kept once
904        // per step, as it is in use.
905        let differences = Arc::new(Mutex::new(Vec::new()));
906        let steps = Arc::new(AtomicUsize::new(0));
907        let (seen, stepped) = (differences.clone(), steps.clone());
908        let mut parser = make();
909        parser.parse_guard(DEPTH_GUARD, move |context| {
910            let (kept, walked) = (depth(context), walked(context));
911            if kept != walked {
912                seen.lock().unwrap().push((context.iteration, kept, walked));
913            }
914            stepped.fetch_add(1, Ordering::Relaxed);
915            kept <= DEPTH_LIMIT
916        });
917        let nested = |open: &str, inner: &str, close: &str, n: usize| {
918            format!("{}{inner}{}", open.repeat(n), close.repeat(n))
919        };
920        let sources = [
921            "a = 1".to_string(),
922            "a = 1\nb.c = 2\nd.e.f = 3".to_string(),
923            "a.b = 1\nc.d = 2".to_string(),
924            "[a.b]\nc = 1\n[[d.e]]\nf = {g = [1, {h.i = 2}]}\n[[d.e]]\nj.k = 3".to_string(),
925            "[[a]]\n[[a.b]]\n[[a.b.c]]\nx = 1".to_string(),
926            "k.k = {p.q = 1\nr.s = {t.u = 2\nv.w = 3}}".to_string(),
927            "x = [{p.q = 1\na.b.c = 2}, [[3]]]".to_string(),
928            "a = \"unterminated".to_string(),
929            "a = 1\n[a]".to_string(),
930            "a = ]".to_string(),
931            format!("{} = 1", segments(127)),
932            format!("{} = 1", segments(128)),
933            format!("[{}]\nx = 1", segments(127)),
934            format!("x = {}", nested("[", "", "]", 127)),
935            format!("x = {}", nested("{a = ", "1", "}", 130)),
936            format!("{} = {{p.q = 1\n{} = 1}}", segments(100), segments(28)),
937            nested(&format!("{} = {{p.q = 1\n", segments(25)), "z = 1", "}", 6),
938        ];
939        // Twice over, so each parse also follows one that ended, some of
940        // them in an error, on the same thread.
941        for source in sources.iter().chain(sources.iter()) {
942            let _ = parser.parse(source);
943        }
944        let steps = steps.load(Ordering::Relaxed);
945        assert!(steps > 3_000, "{steps} steps");
946        assert_eq!(*differences.lock().unwrap(), Vec::new());
947    }
948
949    #[test]
950    fn a_step_counts_what_changed_not_the_whole_stack() {
951        // Arrays 120 deep put about 360 rules on the stack: a `val`, a
952        // `list` and an `elem` a level. Counting all of them at every
953        // step looked at a hundred frames a step or more, and the kept
954        // count looks at one or two. The work is counted rather than
955        // timed: in a debug build the engine checks every buried frame at
956        // every step, which would swamp a timing.
957        let steps = Arc::new(AtomicUsize::new(0));
958        let walk = Arc::new(AtomicUsize::new(0));
959        let (stepped, walked) = (steps.clone(), walk.clone());
960        let mut parser = make();
961        parser.parse_guard(DEPTH_GUARD, move |context| {
962            stepped.fetch_add(1, Ordering::Relaxed);
963            walked.fetch_add(context.rule_stack.len(), Ordering::Relaxed);
964            within_depth_limit(context)
965        });
966        let levels = 120;
967        let src = format!("x = {}1{}", "[".repeat(levels), "]".repeat(levels));
968        let examined = || STACK_COUNT.with(|count| count.borrow().examined);
969        let before = examined();
970        parser.parse(&src).expect("parses");
971        let work = examined() - before;
972        let steps = steps.load(Ordering::Relaxed);
973        let walk = walk.load(Ordering::Relaxed);
974        assert!(steps > 2 * levels, "{steps} steps");
975        assert!(
976            walk > levels / 2 * steps,
977            "a shallow stack: {walk} frames in {steps} steps"
978        );
979        assert!(
980            work <= 3 * steps,
981            "{work} frames looked at in {steps} steps"
982        );
983    }
984}