Skip to main content

tabnas_ini/
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
6// crate root for the same reason, and so do tabnas-json and
7// tabnas-jsonic; boxing here instead would make `parse` return a
8// different shape from `Tabnas::parse` and from the other two ports.
9#![allow(clippy::result_large_err)]
10
11//! An INI grammar plugin for the `tabnas` parsing engine.
12//!
13//! INI is the oldest configuration format still in daily use, and the
14//! least specified: every implementation is a dialect. This one layers
15//! on the relaxed-JSON grammar from
16//! [`tabnas-jsonic`](https://github.com/tabnas/jsonic) and lexes keys,
17//! values and section-header segments with
18//! [`tabnas-hoover`](https://github.com/tabnas/hoover).
19//!
20//! ```text
21//! [server]
22//! host = localhost
23//! port = 8080
24//!
25//! => {"server":{"host":"localhost","port":"8080"}}
26//! ```
27//!
28//! This is the Rust port; the TypeScript package (`ts/src/ini.ts`) is
29//! canonical and the Go port (`go/ini.go`) is the nearer structural
30//! model. The three are held together by the shared `test/spec/*.tsv`
31//! fixtures, which every runtime discovers and runs.
32
33use std::cell::{Cell, RefCell};
34use std::collections::HashMap;
35use std::rc::Rc;
36use std::sync::{Arc, OnceLock};
37
38use indexmap::IndexMap;
39use serde_json::json;
40use tabnas::{
41    ActionError, AltSpec, Context, GrammarError, GrammarSpec, ImperativeLexMatcher, LexCheckResult,
42    Lexer, Options, Plugin, PluginError, Rule, RuleState, Tabnas, Token, Value,
43};
44use tabnas_hoover::{
45    hoover, Block, Consume, EndSpec, HooverOptions, HooverRuleFilter, HooverRuleSpec, StartSpec,
46};
47
48/// The README's Rust examples run as doctests, so a stale one fails the
49/// gate rather than misleading the reader. Its `text`, `toml` and `bash`
50/// fences are skipped; rustdoc runs only the `rust` ones.
51#[cfg(doctest)]
52#[doc = include_str!("../README.md")]
53mod readme_examples {}
54
55/// This crate's version. It MUST equal `ts/package.json` "version": the
56/// release orchestrator rewrites both, and `tests/version_test.rs` fails
57/// the build if they drift. Mirrors `VERSION` in `ts/src/ini.ts` and
58/// `const VERSION` in `go/ini.go`.
59pub const VERSION: &str = "0.5.21";
60
61/// The engine's error, re-exported under this crate's name.
62pub use tabnas::TabnasError as IniError;
63
64// --- BEGIN EMBEDDED ini-grammar.jsonic ---
65const GRAMMAR_TEXT: &str = r#"
66# INI Grammar Definition
67# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
68# Function references (@ prefixed) are resolved against the refs map
69
70{
71  options: rule: { start: ini exclude: jsonic }
72  options: lex: { emptyResult: {} }
73  options: fixed: token: { '#EQ': '=' '#DOT': '.' '#OB': null '#CB': null '#CL': null }
74  options: line: { check: '@line-check' }
75  options: number: { lex: false }
76  options: string: { lex: true chars: QUOTE_CHARS abandon: true }
77  options: text: { lex: false }
78  # Declared error codes. The CODE is the cross-runtime contract; the message
79  # text is not (see AGENTS.md). Both runtimes read this one block, so the two
80  # catalogues cannot drift. Keys stay alphabetical: admin's descriptor
81  # generator compares the TS and Go extractions and sorts only one side.
82  options: error: {
83    duplicate_section: 'duplicate section header: [{section}]'
84    unterminated_section: 'unterminated section header: [{src}'
85  }
86  # A hint for each declared code, keyed alike. Without one the engine falls
87  # back to its hint for an UNKNOWN code, which tells the reader the error is
88  # probably a bug in jsonic or a plugin -- wrong for both of these.
89  options: hint: {
90    duplicate_section: 'The section [{section}] is declared more than once, and the\nsection.duplicate option is error. Combine the two sections, or set\nsection.duplicate to merge or override to allow a repeated header.'
91    unterminated_section: 'A section header must be closed with ] on the same line, as in\n[name] or [a.b].'
92  }
93  options: comment: def: {
94    hash: { eatline: true }
95    slash: null
96    multi: null
97    semi: { line: true start: ';' lex: true eatline: true }
98  }
99
100  rule: ini: open: [
101    { s: '#OS' p: table b: 1 }
102    { s: ['#HK #ST #VL' '#EQ'] p: table b: 2 }
103    { s: ['#HV' '#OS'] p: table b: 2 }
104    { s: ['#HK #ST #VL'] p: table b: 1 }
105    { s: '#ZZ' }
106  ]
107
108  rule: table: open: [
109    # Raised when the table's own before-open handler saw a section path it
110    # had already declared and section.duplicate is 'error'. It flags the
111    # rule rather than raising there, because a state action cannot raise a
112    # coded error in both runtimes: TS can return a bad token from bo, Go
113    # discards the return value, and a ctx error set in bo is overwritten by
114    # alternate matching. An error ALTERNATE is the path both runtimes share.
115    { c: '@is-duplicate-section' e: '@duplicate-section' }
116    { s: '#OS' p: dive }
117    { s: ['#HK #ST #VL' '#EQ'] p: map b: 2 }
118    { s: ['#HV' '#OS'] p: map b: 2 }
119    { s: ['#HK #ST #VL'] p: map b: 1 }
120    { s: '#CS' p: map }
121    { s: '#ZZ' }
122  ]
123  rule: table: close: [
124    { s: '#OS' r: table b: 1 g: end }
125    { s: '#CS' r: table a: '@table-close-dive' g: close }
126    { s: '#ZZ' g: end }
127  ]
128
129  rule: dive: open: [
130    { s: ['#DK' '#DOT'] a: '@dive-push' p: dive }
131    { s: '#DK' a: '@dive-push' }
132    # The root header, []: the closing bracket where the first segment is
133    # due. It names no section, so the dive records no path, and the table
134    # that follows writes into the root again, wherever the document is.
135    # Only the first segment's place takes it (the dive the table pushed):
136    # after a dot, as in [a.], the bracket is still unexpected.
137    { s: '#CS' c: '@is-table-parent' b: 1 }
138  ]
139  rule: dive: close: [
140    { s: '#CS' b: 1 g: close }
141    # A section header lives on one line, so anything other than the closing
142    # bracket here means the header was never closed. Unconditional (no s
143    # key), so it matches only after the '#CS' alternate above has been
144    # tried, and raises unterminated_section rather than the engine's
145    # generic 'unexpected'.
146    { e: '@dive-unterminated' }
147  ]
148
149  rule: map: open: {
150    alts: [
151      { s: ['#HK #ST #VL' '#EQ'] c: '@is-table-parent' p: pair b: 2 }
152      { s: ['#HK #ST #VL'] c: '@is-table-parent' p: pair b: 1 }
153    ]
154    inject: { append: true }
155  }
156  rule: map: close: [
157    { s: '#OS' b: 1 g: end }
158    { s: '#ZZ' g: end }
159  ]
160
161  rule: pair: open: [
162    { s: ['#HK #ST #VL' '#EQ'] c: '@is-table-grandparent' p: val a: '@pair-key-eq' }
163    { s: ['#HK #ST #VL'] c: '@is-table-grandparent' a: '@pair-key-bool' }
164  ]
165  rule: pair: close: [
166    { s: ['#HK #ST #VL' '#CL'] c: '@is-table-grandparent' e: '@pair-close-err' }
167    { s: ['#HK #ST #VL'] b: 1 r: pair g: comma }
168    { s: '#OS' b: 1 g: end }
169  ]
170}
171"#;
172// --- END EMBEDDED ini-grammar.jsonic ---
173
174/// The quote characters INI values may be wrapped in. The grammar text
175/// carries the placeholder `QUOTE_CHARS`, which every runtime replaces
176/// with this before installing the document, exactly as the TypeScript
177/// `grammarDef.options.string.chars` assignment does.
178const QUOTE_CHARS: &str = "'\"";
179
180/// The hoover matcher band. Lower than nothing else here; the custom
181/// multiline matcher sits just below it so it sees a value first.
182const HOOVER_ORDER: f64 = 8.5e6;
183const MULTILINE_ORDER: f64 = 8.4e6;
184
185/// The in-value probe's band. Below 1e6, so it runs before every
186/// built-in matcher family and therefore before any `check` hook.
187const PROBE_ORDER: f64 = 0.5e6;
188
189const PROBE_REF: &str = "@ini-inval-probe";
190const MULTILINE_REF: &str = "@ini-multiline";
191const LINE_CHECK_REF: &str = "@line-check";
192const COMMENT_CHECK_REF: &str = "@ini-comment-check";
193const TEXT_CHECK_REF: &str = "@ini-text-check";
194const STRING_CHECK_REF: &str = "@ini-string-check";
195
196/// The plugin name, and the namespace `use_plugin` files its option bag
197/// under.
198pub const PLUGIN_NAME: &str = "ini";
199
200/// The deepest a document may nest before the parse is refused with the
201/// engine's `cancel` code.
202///
203/// The engine parses iteratively, but displaying, converting or dropping
204/// a `Value` walks the tree with the call stack, and a section header a
205/// few thousand segments deep ended the process: an abort, not an error.
206/// The TypeScript and Go ports have no limit, so the refusal is a
207/// recorded divergence (`../DIVERGENCE.md`). The number is the one
208/// `tabnas-jsonic` and `tabnas-json` use, so every crate in the family
209/// bounds nesting alike; `dive` is counted beside `map` and `list`,
210/// because a section header is where an INI document nests.
211pub const DEPTH_LIMIT: usize = 127;
212
213// ---------------------------------------------------------------------
214// Options
215// ---------------------------------------------------------------------
216
217/// How a repeated section header is treated.
218#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
219pub enum Duplicate {
220    /// Combine the keys of every occurrence; the last value wins for a
221    /// repeated key. The default.
222    #[default]
223    Merge,
224    /// The last occurrence replaces the earlier ones entirely.
225    Override,
226    /// A repeated header is rejected with the `duplicate_section` code.
227    Error,
228}
229
230/// Multiline value continuation.
231///
232/// `Some(MultilineOptions::default())` is the TypeScript `multiline:
233/// true`: backslash continuation on, indent continuation off. `None` is
234/// multiline off.
235#[derive(Clone, Debug, Default, PartialEq, Eq)]
236pub struct MultilineOptions {
237    /// The character that, before a newline, continues the value. `None`
238    /// means the default `\`; `Some("")` disables it, which is the
239    /// TypeScript `continuation: false`.
240    pub continuation: Option<String>,
241    /// When true, a line starting with whitespace continues the previous
242    /// value even with no continuation character.
243    pub indent: Option<bool>,
244}
245
246/// Section header handling.
247#[derive(Clone, Debug, Default, PartialEq, Eq)]
248pub struct SectionOptions {
249    /// How a repeated section header is treated.
250    pub duplicate: Duplicate,
251}
252
253/// Comment handling. Line comments are always on; this controls the
254/// inline ones.
255#[derive(Clone, Debug, Default, PartialEq, Eq)]
256pub struct CommentOptions {
257    /// Inline comment behaviour.
258    pub inline: Option<InlineCommentOptions>,
259}
260
261/// Inline comment behaviour.
262#[derive(Clone, Debug, Default, PartialEq, Eq)]
263pub struct InlineCommentOptions {
264    /// Whether inline comments are active. Default: false.
265    pub active: Option<bool>,
266    /// The characters that start an inline comment. Default: `#` and `;`.
267    pub chars: Option<Vec<String>>,
268    /// How a literal comment character is written in a value.
269    pub escape: Option<InlineEscapeOptions>,
270}
271
272/// Escape mechanisms for a literal comment character inside a value.
273#[derive(Clone, Debug, Default, PartialEq, Eq)]
274pub struct InlineEscapeOptions {
275    /// Allow `\;` and `\#` to produce a literal `;` and `#`. Default: true.
276    pub backslash: Option<bool>,
277    /// Require whitespace before a comment character for it to start a
278    /// comment. Default: false.
279    pub whitespace: Option<bool>,
280}
281
282/// The INI plugin options.
283///
284/// Every field is optional and every default matches the canonical
285/// TypeScript `IniOptions`.
286#[derive(Clone, Debug, Default, PartialEq, Eq)]
287pub struct IniOptions {
288    /// Multiline value continuation. `None` is off.
289    pub multiline: Option<MultilineOptions>,
290    /// Section header handling.
291    pub section: Option<SectionOptions>,
292    /// Comment handling.
293    pub comment: Option<CommentOptions>,
294}
295
296impl IniOptions {
297    /// Options with every default in force, the same instance
298    /// `IniOptions::default()` gives.
299    pub fn new() -> Self {
300        Self::default()
301    }
302
303    /// Turn multiline continuation on with its defaults, the TypeScript
304    /// `multiline: true`.
305    pub fn with_multiline(mut self) -> Self {
306        self.multiline = Some(MultilineOptions::default());
307        self
308    }
309
310    /// Turn inline comments on with their defaults.
311    pub fn with_inline_comments(mut self) -> Self {
312        let inline = self
313            .comment
314            .get_or_insert_with(CommentOptions::default)
315            .inline
316            .get_or_insert_with(InlineCommentOptions::default);
317        inline.active = Some(true);
318        self
319    }
320
321    /// Set how a repeated section header is treated.
322    pub fn with_duplicate(mut self, duplicate: Duplicate) -> Self {
323        self.section = Some(SectionOptions { duplicate });
324        self
325    }
326}
327
328/// Every option with its default applied, computed once per install.
329/// Mirrors the Go `resolved` struct and the TypeScript closure locals.
330#[derive(Clone, Debug)]
331struct Resolved {
332    multiline: bool,
333    /// `None` when continuation is disabled.
334    continuation: Option<char>,
335    indent: bool,
336    dup_section: Duplicate,
337    inline_active: bool,
338    inline_chars: Vec<char>,
339    inline_char_str: Vec<String>,
340    esc_backslash: bool,
341    esc_whitespace: bool,
342}
343
344impl Resolved {
345    fn is_inline_char(&self, c: char) -> bool {
346        self.inline_chars.contains(&c)
347    }
348}
349
350/// The single UTF-16 code unit an option string names, or `None` when
351/// the string is not exactly one.
352///
353/// Both places this is used compare one code unit of the SOURCE against
354/// each whole option string: the canonical continuation test is
355/// `c === continuation`, and the canonical comment test is
356/// `commentCharSet.has(c)`, with `c` a `src[i]`. A string of any other
357/// length can never be equal to one, so the feature it configures is
358/// simply off, and an astral character (two code units in JavaScript)
359/// is off with it. Taking the first character instead made
360/// `continuation: "~~"` continue a line ending in one `~`, and made
361/// `chars: ["##"]` cut a value at the first `#`.
362fn one_code_unit(text: &str) -> Option<char> {
363    let mut characters = text.chars();
364    let first = characters.next()?;
365    (characters.next().is_none() && first.len_utf16() == 1).then_some(first)
366}
367
368fn resolve(options: &IniOptions) -> Resolved {
369    let mut resolved = Resolved {
370        multiline: false,
371        continuation: None,
372        indent: false,
373        dup_section: Duplicate::Merge,
374        inline_active: false,
375        inline_chars: vec!['#', ';'],
376        inline_char_str: vec!["#".to_string(), ";".to_string()],
377        esc_backslash: true,
378        esc_whitespace: false,
379    };
380
381    if let Some(multiline) = &options.multiline {
382        resolved.multiline = true;
383        resolved.continuation = match multiline.continuation.as_deref() {
384            None => Some('\\'),
385            Some(text) => one_code_unit(text),
386        };
387        resolved.indent = multiline.indent.unwrap_or(false);
388    }
389
390    if let Some(section) = &options.section {
391        resolved.dup_section = section.duplicate;
392    }
393
394    if let Some(inline) = options.comment.as_ref().and_then(|c| c.inline.as_ref()) {
395        resolved.inline_active = inline.active.unwrap_or(false);
396        // `None` is "the caller said nothing", and only that takes the
397        // default. An EMPTY list is a choice: the canonical
398        // `_options.comment?.inline?.chars ?? ['#', ';']` defaults on
399        // absence alone, so `chars: []` leaves no inline comment
400        // character at all and `a=x;y` keeps its semicolon.
401        if let Some(chars) = inline.chars.as_ref() {
402            // The WHOLE string is what hoover's `end.fixed` and its
403            // escape map compare, exactly as the canonical
404            // `eolEndFixed.push(...inlineComment.chars)` does, so a
405            // marker of any length still terminates a hoovered span.
406            resolved.inline_char_str = chars.clone();
407            // The custom value matcher and the string check compare ONE
408            // code unit instead (`commentCharSet.has(c)` and
409            // `inlineComment.chars.includes(src[tI])`, both against a
410            // `src[i]`), so an entry that is not exactly one UTF-16 code
411            // unit can never start a comment there. Taking the first
412            // character instead truncated `chars: ["##"]` to `#` and cut
413            // `a=x ## note` short, and promoted an astral marker the
414            // canonical set can never hold a single unit of.
415            resolved.inline_chars = chars
416                .iter()
417                .filter_map(|text| one_code_unit(text))
418                .collect();
419        }
420        if let Some(escape) = &inline.escape {
421            resolved.esc_backslash = escape.backslash.unwrap_or(true);
422            resolved.esc_whitespace = escape.whitespace.unwrap_or(false);
423        }
424    }
425
426    resolved
427}
428
429// ---------------------------------------------------------------------
430// The in-value probe
431// ---------------------------------------------------------------------
432
433// The four `check` hooks the canonical port installs all ask the same
434// question: where is the parser, right now? The TypeScript hooks read
435// `lex.ctx.rule`, and the Go ones read `lex.Ctx.Rule`. The Rust engine
436// hands a check only the live `Lexer`, which carries no rule, so the
437// answer is recorded one step earlier instead: a custom matcher in the
438// band BELOW every built-in family (see `PROBE_ORDER`) receives the
439// rule, writes what it sees here, and matches nothing. Every check that
440// runs afterwards, in the same `next_token` call on the same thread,
441// reads it back.
442//
443// Thread-local rather than instance state because a `Tabnas` is shared
444// across threads by `parse`, and because the flags are written and read
445// inside one lexer call: nothing outlives the token being lexed.
446thread_local! {
447    /// The lexer is inside a `val` rule, of any state or parent. This is
448    /// the question `@line-check` asks.
449    static IN_VAL: Cell<bool> = const { Cell::new(false) };
450    /// The lexer is inside the OPEN `val` rule of a `key = value` pair,
451    /// the TypeScript `inValue(lex)`.
452    static IN_VALUE: Cell<bool> = const { Cell::new(false) };
453}
454
455fn in_val_rule(rule: &Rule) -> bool {
456    rule.name.as_str() == "val"
457}
458
459fn in_value_position(rule: &Rule) -> bool {
460    in_val_rule(rule)
461        && rule.state == RuleState::Open
462        && rule.parent_rule.as_ref().is_some_and(|parent| {
463            let name = parent.name.as_str();
464            name == "pair" || name == "elem"
465        })
466}
467
468/// What the string check needs from the resolved configuration. Captured
469/// after the grammar document is installed, because the document is what
470/// sets `string.chars`.
471#[derive(Debug, Default)]
472struct StringCheckConfig {
473    quotes: Vec<char>,
474    escape_char: char,
475}
476
477// ---------------------------------------------------------------------
478// Value helpers
479// ---------------------------------------------------------------------
480
481/// Assign a rule's node.
482///
483/// A pushed or replaced rule SHARES its parent's `Rc<RefCell<Value>>`,
484/// so writing through `rule.node.borrow_mut()` would overwrite the
485/// parent's node too. An assignment, `r.node = ...` in the canonical
486/// TypeScript, installs a fresh cell instead, which is what this does.
487fn set_node(rule: &mut Rule, value: Value) {
488    rule.node = Rc::new(RefCell::new(value));
489}
490
491/// The JavaScript `String(value)` of a parsed value, for the fixed-token
492/// concatenation in the `val` after-close hook and for a key whose token
493/// carries a non-string value.
494///
495/// A composite reaches this only from the fixed-token concatenation, and
496/// only ever as what the JSON reader made of a single-quoted value:
497/// `a = ='[1,2]'` is the array `[1, 2]` with a `=` in front of its
498/// `String()`. So the two composite arms are the ones ECMA-262 applies
499/// to an ordinary array and an ordinary object.
500///
501/// Rendering the composite as JSON instead is the defect this replaces.
502/// It put `=[1.0,2.0]` where the canonical implementation puts `=1,2`,
503/// and `={"b":1.0}` where it puts `=[object Object]`.
504fn js_string(value: &Value) -> String {
505    match value {
506        Value::String(text) => text.clone(),
507        Value::Text(text) => text.string.clone(),
508        Value::Undefined => "undefined".to_string(),
509        Value::Null => "null".to_string(),
510        Value::Bool(flag) => flag.to_string(),
511        Value::Number(number) => js_number_to_string(*number),
512        Value::Array(items) => js_array_string(items),
513        // `Object.prototype.toString`. The object came from the JSON
514        // reader, so it carries the ordinary prototype and its
515        // `String()` is this constant. A jsonic object, allocated with
516        // no prototype, would throw a `TypeError` instead, and cannot
517        // reach here: INI nulls the `#OB` token, so no value in this
518        // dialect opens a map.
519        _ => "[object Object]".to_string(),
520    }
521}
522
523/// `Array.prototype.toString`, which is `join(',')` with no separator
524/// argument (ECMA-262 23.1.3.17 and 23.1.3.34): the elements are joined
525/// with a comma, `null` and `undefined` contribute the empty string, and
526/// every other element is converted by the rules above. A nested array
527/// therefore flattens, so `[1,[2,3]]` is `1,2,3` and `[]` is empty.
528///
529/// The empty string for a null belongs to `join`, not to `String`: a
530/// null VALUE is still `"null"`, and only a null ELEMENT disappears.
531///
532/// The recursion needs no depth bound. These values come from
533/// `serde_json`, whose reader refuses to nest past 128, and a parsed
534/// value is a tree, so the walk always terminates.
535fn js_array_string(items: &[Value]) -> String {
536    let mut joined = String::new();
537    for (index, item) in items.iter().enumerate() {
538        if 0 < index {
539            joined.push(',');
540        }
541        match item {
542            Value::Null | Value::Undefined => {}
543            other => joined.push_str(&js_string(other)),
544        }
545    }
546    joined
547}
548
549/// A double as JavaScript spells it: ECMA-262 6.1.6.1.20.
550///
551/// Neither Rust's shortest float formatter nor Go's
552/// `FormatFloat('f', -1, 64)` is that algorithm. Both break an exact
553/// decimal midpoint away from zero where the specification takes the
554/// even digit, and neither switches to exponent form at 1e21 or 1e-7.
555/// This is the implementation the other tabnas Rust ports carry, copied
556/// rather than rewritten.
557///
558/// `number.lex` is off in INI, so a double can only arrive here from a
559/// single-quoted value the JSON reader claimed, but that is enough for a
560/// document to notice the difference.
561fn js_number_to_string(number: f64) -> String {
562    if number.is_nan() {
563        return "NaN".to_string();
564    }
565    // Catches -0.0 as well: JavaScript spells both zeros "0".
566    if number == 0.0 {
567        return "0".to_string();
568    }
569    if number < 0.0 {
570        return format!("-{}", js_number_to_string(-number));
571    }
572    if number.is_infinite() {
573        return "Infinity".to_string();
574    }
575
576    // The specification wants the shortest digit string `s` that
577    // round-trips (length `k`), and `n`, the position of the decimal
578    // point relative to it. Rust's `{:e}` yields digits of exactly that
579    // shortest length.
580    let shortest = format!("{number:e}");
581    let shortest_k = shortest
582        .split_once('e')
583        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
584        .expect("a finite f64 always formats with an exponent");
585
586    // Re-render to that same length to settle a tie. Where two digit
587    // strings of length `k` are equally close to `number`, the
588    // specification takes the one ending in an even digit; Rust's
589    // shortest form does not, but its exactly-rounded fixed-precision
590    // form does.
591    let exponential = format!("{:.*e}", shortest_k - 1, number);
592    let (mantissa, exponent) = exponential
593        .split_once('e')
594        .expect("a finite f64 always formats with an exponent");
595    // Rounding can leave trailing zeros (and, on a carry, one digit too
596    // many); dropping them keeps `s` shortest, which is what `k` means.
597    let digits = mantissa
598        .chars()
599        .filter(|digit| *digit != '.')
600        .collect::<String>();
601    let digits = digits.trim_end_matches('0');
602    let digits = if digits.is_empty() { "0" } else { digits };
603    let k = digits.len() as i32;
604    let n = exponent
605        .parse::<i32>()
606        .expect("a formatted exponent is an integer")
607        + 1;
608
609    // The four cases of the specification, in its order. The range
610    // bounds are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
611    if (k..=21).contains(&n) {
612        // Integral, with n - k trailing zeros to restore.
613        let mut text = digits.to_string();
614        text.push_str(&"0".repeat((n - k) as usize));
615        text
616    } else if (1..=21).contains(&n) {
617        let point = n as usize;
618        format!("{}.{}", &digits[..point], &digits[point..])
619    } else if (-5..=0).contains(&n) {
620        format!("0.{}{}", "0".repeat(-n as usize), digits)
621    } else {
622        // Exponent form. `n - 1` is never 0 here, so the sign is never
623        // "+0".
624        let sign = if n - 1 < 0 { '-' } else { '+' };
625        let power = (n - 1).abs();
626        if k == 1 {
627            format!("{digits}e{sign}{power}")
628        } else {
629            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
630        }
631    }
632}
633
634fn object_get(value: &Value, key: &str) -> Option<Value> {
635    match value {
636        Value::Object(entries) => entries.get(key).cloned(),
637        Value::MapRef(map) => map.value.get(key).cloned(),
638        _ => None,
639    }
640}
641
642fn object_insert(value: &mut Value, key: String, entry: Value) {
643    match value {
644        Value::Object(entries) => {
645            Arc::make_mut(entries).insert(key, entry);
646        }
647        Value::MapRef(map) => {
648            Arc::make_mut(map).value.insert(key, entry);
649        }
650        _ => {
651            let mut entries = IndexMap::new();
652            entries.insert(key, entry);
653            *value = Value::object(entries);
654        }
655    }
656}
657
658/// Take the value at `key` OUT of a container, leaving the key in place
659/// with no value.
660///
661/// The slot is kept rather than removed so the key holds its position:
662/// an `IndexMap` remembers insertion order, and a remove-then-insert
663/// would move a section to the end of its parent every time it was
664/// reopened.
665///
666/// Taking rather than cloning is what keeps a document of many sections
667/// linear. A container is an `Arc`, so a clone leaves two owners and the
668/// next write copies the whole map; a document of 5,000 sections then
669/// copied a 5,000-key root once per section.
670fn object_take(node: &mut Value, key: &str) -> Option<Value> {
671    match node {
672        Value::Object(entries) => Arc::make_mut(entries)
673            .get_mut(key)
674            .map(|slot| std::mem::replace(slot, Value::Undefined)),
675        Value::MapRef(map) => Arc::make_mut(map)
676            .value
677            .get_mut(key)
678            .map(|slot| std::mem::replace(slot, Value::Undefined)),
679        _ => None,
680    }
681}
682
683fn is_object(value: &Value) -> bool {
684    matches!(value, Value::Object(_) | Value::MapRef(_))
685}
686
687fn empty_object() -> Value {
688    Value::object(IndexMap::new())
689}
690
691/// The string a token contributes as a key: its decoded value when it
692/// has one, otherwise its source. Mirrors the Go `tokenString`.
693fn token_string(token: &Token) -> String {
694    if token.is_no_token() {
695        return String::new();
696    }
697    match &token.val {
698        Value::String(text) => text.clone(),
699        Value::Text(text) => text.string.clone(),
700        Value::Undefined => token.src.as_str().to_string(),
701        other => js_string(other),
702    }
703}
704
705/// The key a BARE line declares, or `None` when its token carries no
706/// string at all.
707///
708/// The canonical `@pair-key-bool` reads `r.o0.val` and sets the key only
709/// when `'string' === typeof key`, so a line holding a value keyword and
710/// nothing else declares nothing: both value lexers resolve a keyword
711/// that is the whole span, and the token then carries a boolean or null.
712/// A bare `k[]` line, whose token the lexer marked as an array key
713/// ([`mark_array_key`]), declares the key `k[]`, brackets and all.
714fn bool_key(token: &Token) -> Option<String> {
715    if let Some(name) = array_key_name(token) {
716        return Some(format!("{name}[]"));
717    }
718    match &token.val {
719        Value::String(text) if !text.is_empty() => Some(text.clone()),
720        Value::Text(text) if !text.string.is_empty() => Some(text.string.clone()),
721        _ => None,
722    }
723}
724
725/// Pick the token an error alternate should mark.
726///
727/// An alternate with no token sequence matches zero tokens, so the
728/// rule's open slot holds nothing from the source and the lookahead
729/// token is the one that actually stopped the parse. The canonical
730/// TypeScript reads `r.o0` then `ctx.t0`, and the Go port adds the
731/// NOTOKEN sentinel as a last resort.
732///
733/// All three fallbacks are here, and the last one is reached more often
734/// in this port than in the others: the engine fills its lookahead
735/// buffer to the length the alternate under test asks for, and an
736/// alternate with no token sequence asks for none, so `context.t0()` is
737/// empty exactly where the other two runtimes have a positionless token
738/// in it. A FRESH sentinel is built rather than the rule's, so marking
739/// it cannot scribble on a shared object, and the diagnostic it renders
740/// is the one TypeScript and Go render: the code, the message with its
741/// `{section}` detail, and the start of the source.
742fn alt_err_token(rule: &Rule, context: &Context) -> Option<Token> {
743    if rule.os() > 0 {
744        if let Some(token) = rule.o0().filter(|token| !token.is_no_token()) {
745            return Some(token.clone());
746        }
747    }
748    context.t0().cloned().or_else(|| Some(Token::no_token()))
749}
750
751/// The dive path recorded on a rule's `u` bag, as a vector of segments.
752fn dive_of(bag: Option<&Value>) -> Option<Vec<String>> {
753    match bag? {
754        Value::Array(items) => Some(items.iter().map(js_string).collect()),
755        _ => None,
756    }
757}
758
759fn dive_value(dive: &[String]) -> Value {
760    Value::array(dive.iter().cloned().map(Value::String).collect())
761}
762
763// ---------------------------------------------------------------------
764// The grammar document
765// ---------------------------------------------------------------------
766
767/// Turn every whole-valued double in a parsed grammar into a JSON
768/// integer. See the call site for why.
769fn integralize(value: &mut serde_json::Value) {
770    match value {
771        serde_json::Value::Number(number) => {
772            if let Some(float) = number.as_f64() {
773                if float.fract() == 0.0 && float.abs() < 9.007_199_254_740_992e15 {
774                    *value = serde_json::Value::from(float as i64);
775                }
776            }
777        }
778        serde_json::Value::Array(items) => items.iter_mut().for_each(integralize),
779        serde_json::Value::Object(entries) => {
780            entries.values_mut().for_each(integralize);
781        }
782        _ => {}
783    }
784}
785
786/// Parse the embedded grammar text and turn it into the JSON document
787/// the engine installs.
788///
789/// The grammar is AUTHORED in jsonic, so it can carry the comments that
790/// explain it, and every runtime parses it with a stock jsonic instance
791/// before installing it: TypeScript in `new Tabnas().use(jsonic).parse`,
792/// Go in `jsonic.Make().Parse`, and this. One grammar, three readers.
793fn grammar_document(resolved: &Resolved) -> Result<serde_json::Value, GrammarError> {
794    static PARSED: OnceLock<Result<serde_json::Value, String>> = OnceLock::new();
795    let parsed = PARSED
796        .get_or_init(|| {
797            tabnas_jsonic::make()
798                .parse(GRAMMAR_TEXT)
799                .map(|value| value.to_json())
800                .map_err(|error| error.to_string())
801        })
802        .clone()
803        .map_err(GrammarError)?;
804
805    let mut document = parsed;
806    // jsonic parses every number as a double, and `1` then reaches the
807    // engine as the JSON `1.0`, which its integer fields refuse. The
808    // other two runtimes never see this: JavaScript has one number type
809    // and Go's decoder hands back a float the conversion code rounds.
810    // Round whole doubles back to integers so `b: 1` means what it says.
811    integralize(&mut document);
812    let options = document
813        .get_mut("options")
814        .and_then(serde_json::Value::as_object_mut)
815        .ok_or_else(|| GrammarError("tabnas-ini: the grammar has no `options` table".into()))?;
816
817    // The grammar text carries `QUOTE_CHARS` as a placeholder, exactly
818    // as the TypeScript and Go ports do, and every runtime substitutes
819    // the real characters before installing the document.
820    options
821        .entry("string")
822        .or_insert_with(|| json!({}))
823        .as_object_mut()
824        .ok_or_else(|| GrammarError("tabnas-ini: options.string must be a table".into()))?
825        .insert("chars".into(), json!(QUOTE_CHARS));
826
827    // The three checks the canonical port installs through
828    // `options.config.modify` callbacks. The Rust engine has no
829    // load-time config modifier that can hold a live closure reachable
830    // from a lexer check, so they are declared here as ordinary
831    // serialized `check` references, beside the `line.check` the grammar
832    // text already names. Same hooks, same order, named rather than
833    // assigned.
834    for (family, reference) in [
835        ("comment", COMMENT_CHECK_REF),
836        ("text", TEXT_CHECK_REF),
837        ("string", STRING_CHECK_REF),
838    ] {
839        options
840            .entry(family)
841            .or_insert_with(|| json!({}))
842            .as_object_mut()
843            .ok_or_else(|| GrammarError(format!("tabnas-ini: options.{family} must be a table")))?
844            .insert("check".into(), json!(reference));
845    }
846
847    // The in-value probe, and the custom value matcher when the options
848    // call for one. Both are ordinary serialized matcher entries.
849    let mut matchers = json!({
850        "iniprobe": { "order": PROBE_ORDER, "make": PROBE_REF },
851    });
852    if resolved.multiline || (resolved.inline_active && resolved.esc_whitespace) {
853        matchers.as_object_mut().expect("a literal object").insert(
854            "multiline".into(),
855            json!({ "order": MULTILINE_ORDER, "make": MULTILINE_REF }),
856        );
857    }
858    options
859        .entry("lex")
860        .or_insert_with(|| json!({}))
861        .as_object_mut()
862        .ok_or_else(|| GrammarError("tabnas-ini: options.lex must be a table".into()))?
863        .insert("match".into(), matchers);
864
865    Ok(document)
866}
867
868// ---------------------------------------------------------------------
869// The plugin
870// ---------------------------------------------------------------------
871
872/// Install the INI grammar on an engine that ALREADY carries jsonic.
873///
874/// Order matters: jsonic supplies the `val`, `map` and `pair` rules this
875/// grammar extends, and hoover refuses an engine with no `val`. Applying
876/// jsonic here when it is absent would silently accept the wrong order,
877/// so the missing-grammar case is reported instead.
878///
879/// ```
880/// let mut parser = tabnas_jsonic::make();
881/// tabnas_ini::ini(&mut parser, &tabnas_ini::IniOptions::default())?;
882/// let value = parser.parse("a = 1")?;
883/// assert_eq!(value.to_string(), r#"{"a":"1"}"#);
884/// # Ok::<(), Box<dyn std::error::Error>>(())
885/// ```
886pub fn ini(parser: &mut Tabnas, options: &IniOptions) -> Result<(), IniPluginError> {
887    let resolved = Arc::new(resolve(options));
888
889    if !parser.rule_names().iter().any(|name| name == "val") {
890        return Err(IniPluginError(
891            "tabnas-ini: the jsonic grammar must be installed first: call \
892             tabnas_jsonic::jsonic(&mut parser) before tabnas_ini::ini(..), or use make()"
893                .into(),
894        ));
895    }
896
897    let string_config = register_lex_hooks(parser, &resolved);
898    register_multiline(parser, &resolved);
899    install_hoover(parser, &resolved)?;
900    register_refs(parser, &resolved);
901
902    let document = grammar_document(&resolved)?;
903    let spec = GrammarSpec::from_value(document)?;
904    parser.grammar(&spec)?;
905
906    // The string check reads `string.chars` and the escape character off
907    // the resolved configuration, and the document above is what sets
908    // them, so the snapshot is taken here rather than at registration.
909    let config = parser.config();
910    let _ = string_config.set(StringCheckConfig {
911        quotes: config.string.chars.chars().collect(),
912        escape_char: config.string.escape_char,
913    });
914
915    install_val_rule(parser, &resolved);
916
917    // A parse guard, under the name jsonic installs its own under, so it
918    // replaces jsonic's: that one counts `map` and `list`, and this one
919    // adds `dive`, which is where an INI document nests, and is otherwise
920    // identical. A guard rather than the budget, which is one slot a
921    // caller's `parse_budget` replaced in place, taking the limit with it.
922    parser.parse_guard(DEPTH_GUARD, within_depth_limit);
923
924    // INI has no array syntax: `val` is restricted to scalars and maps
925    // above, leaving jsonic's `list` and `elem` rules unreachable.
926    // Remove them so the grammar -- and its railroad diagram -- holds
927    // only the rules INI actually uses.
928    for name in ["list", "elem"] {
929        parser.remove_rule(name);
930    }
931
932    Ok(())
933}
934
935/// The plugin form of [`ini`], for [`Tabnas::use_plugin`].
936///
937/// The options are typed, so they travel in this closure rather than in
938/// the engine's serialized plugin bag, exactly as
939/// `tabnas_hoover::plugin` and `tabnas_directive::plugin` do. Installed
940/// this way the grammar is re-applied to derived instances.
941///
942/// ```
943/// let mut parser = tabnas_jsonic::make();
944/// parser.use_plugin(tabnas_ini::plugin(tabnas_ini::IniOptions::default()), None)?;
945/// assert_eq!(parser.parse("a=1")?.to_string(), r#"{"a":"1"}"#);
946/// # Ok::<(), Box<dyn std::error::Error>>(())
947/// ```
948pub fn plugin(options: IniOptions) -> Plugin {
949    Plugin::new(PLUGIN_NAME, move |parser, _bag| {
950        ini(parser, &options).map_err(|error| PluginError(error.0))
951    })
952}
953
954/// A failure to install the plugin: a missing base grammar, a hoover
955/// block the host refuses, or a grammar document the engine rejects.
956#[derive(Debug, Clone, PartialEq, Eq)]
957pub struct IniPluginError(pub String);
958
959impl std::fmt::Display for IniPluginError {
960    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
961        formatter.write_str(&self.0)
962    }
963}
964
965impl std::error::Error for IniPluginError {}
966
967impl From<GrammarError> for IniPluginError {
968    fn from(error: GrammarError) -> Self {
969        IniPluginError(error.0)
970    }
971}
972
973impl From<PluginError> for IniPluginError {
974    fn from(error: PluginError) -> Self {
975        IniPluginError(error.0)
976    }
977}
978
979impl From<tabnas_hoover::HooverError> for IniPluginError {
980    fn from(error: tabnas_hoover::HooverError) -> Self {
981        IniPluginError(error.0)
982    }
983}
984
985// ---------------------------------------------------------------------
986// Construction
987// ---------------------------------------------------------------------
988
989/// Build an INI parser with the default options.
990///
991/// ```
992/// let parser = tabnas_ini::make();
993/// let value = parser.parse("[a]\nb = c")?;
994/// assert_eq!(value.to_string(), r#"{"a":{"b":"c"}}"#);
995/// # Ok::<(), tabnas_ini::IniError>(())
996/// ```
997pub fn make() -> Tabnas {
998    make_with(&IniOptions::default())
999}
1000
1001/// Build an INI parser with caller options.
1002///
1003/// Infallible by design: the grammar document is a fixed literal and the
1004/// jsonic base is installed one line earlier, so a failure here is a bug
1005/// in this crate rather than anything a caller did. The Go `MakeJsonic`
1006/// panics for the same reason.
1007///
1008/// ```
1009/// let options = tabnas_ini::IniOptions::default().with_inline_comments();
1010/// let parser = tabnas_ini::make_with(&options);
1011/// assert_eq!(parser.parse("a = x ; note")?.to_string(), r#"{"a":"x"}"#);
1012/// # Ok::<(), tabnas_ini::IniError>(())
1013/// ```
1014pub fn make_with(options: &IniOptions) -> Tabnas {
1015    let mut parser = tabnas_jsonic::make();
1016    parser
1017        .use_plugin(plugin(options.clone()), None)
1018        .expect("the INI grammar document is fixed, and the jsonic base is installed");
1019    parser
1020}
1021
1022/// Parse an INI source string with the shared default parser.
1023///
1024/// The engine is built once, on first use, and reused after that. Both
1025/// other runtimes do the same (`sync.Once` in `go/ini.go`, a lazily
1026/// assigned module variable in the TypeScript tests), and reuse is safe
1027/// here for the same reason it is there: [`Tabnas::parse`] takes `&self`
1028/// and builds a fresh parse context per call, and `Tabnas` is `Send +
1029/// Sync`, so concurrent callers share one installed grammar instead of
1030/// each rebuilding it.
1031///
1032/// ```
1033/// let value = tabnas_ini::parse("a = 1\n[s]\nb = 2")?;
1034/// assert_eq!(value.to_string(), r#"{"a":"1","s":{"b":"2"}}"#);
1035/// # Ok::<(), tabnas_ini::IniError>(())
1036/// ```
1037pub fn parse(src: &str) -> Result<Value, IniError> {
1038    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
1039    DEFAULT.get_or_init(make).parse(src)
1040}
1041
1042/// Parse an INI source string with caller options.
1043///
1044/// Every call builds a fresh parser, because the options decide the
1045/// hoover blocks and the lexer matchers and so cannot be shared. Reach
1046/// for [`make_with`] when parsing more than once with one option set.
1047///
1048/// ```
1049/// let options = tabnas_ini::IniOptions::default().with_multiline();
1050/// let value = tabnas_ini::parse_with("a = one \\\ntwo", &options)?;
1051/// assert_eq!(value.to_string(), r#"{"a":"one two"}"#);
1052/// # Ok::<(), tabnas_ini::IniError>(())
1053/// ```
1054pub fn parse_with(src: &str, options: &IniOptions) -> Result<Value, IniError> {
1055    make_with(options).parse(src)
1056}
1057
1058// ---------------------------------------------------------------------
1059// The translation parts
1060// ---------------------------------------------------------------------
1061
1062/// One optional alchemy translation source and its explicit entry point.
1063#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1064pub struct TranslationPart {
1065    /// The definition a host calls after linking the source.
1066    pub entry: &'static str,
1067    /// The source text, or `None` for an entry supplied by alchemy.
1068    pub source: Option<&'static str>,
1069}
1070
1071/// The package-local structural translation interface.
1072#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1073pub struct TranslationParts {
1074    /// The complete `tabnas.plugin.json` text.
1075    pub manifest: &'static str,
1076    /// An optional lift from the grammar's events to its first read shape.
1077    pub lift: Option<TranslationPart>,
1078    /// An optional embedding of a plain tree in the format's schema, with its reverse.
1079    pub embed: Option<TranslationPart>,
1080    /// An optional render from the write shape to text.
1081    pub render: Option<TranslationPart>,
1082    /// An optional transducer: the format's JSON events from its parser's
1083    /// rule passes, for a host that reads parser events.
1084    pub transduce: Option<TranslationPart>,
1085}
1086
1087const TRANSLATION: TranslationParts = TranslationParts {
1088    manifest: include_str!("../translate/manifest.json"),
1089    lift: None,
1090    embed: None,
1091    render: Some(TranslationPart {
1092        entry: "ini-render",
1093        source: Some(include_str!("../translate/render.alc")),
1094    }),
1095    transduce: Some(TranslationPart {
1096        entry: "ini-transduce",
1097        source: Some(include_str!("../translate/transduce.alc")),
1098    }),
1099};
1100
1101/// Return INI's immutable translation parts.
1102#[must_use]
1103pub const fn translate() -> Option<TranslationParts> {
1104    Some(TRANSLATION)
1105}
1106
1107/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
1108/// it. Its `translate` object is what a host that translates reads: the
1109/// shape INI is read as and written from (`tree`), the root its render
1110/// needs (`object`), the file that holds the render, the sentences that
1111/// say what the render does not keep, and the file that holds the
1112/// transducer part (`transduce`), the document's JSON events from the
1113/// grammar's rule passes under its default options, through which a host
1114/// that reads parser events reads a document.
1115/// The crate embeds its own copies, `translate/manifest.json` and
1116/// `translate/transduce.alc`, since a packaged crate holds nothing outside
1117/// `rs/`; `tests/translate_test.rs` holds each copy to its file.
1118///
1119/// ```
1120/// assert!(tabnas_ini::manifest_text().contains("\"translate\""));
1121/// ```
1122pub fn manifest_text() -> &'static str {
1123    TRANSLATION.manifest
1124}
1125
1126/// INI's render, `alchemy/render.alc`, the file the manifest's
1127/// `translate.render` names: a library of alchemy definitions, with no
1128/// `export`, whose entry point `ini-render` writes a tree's events as one
1129/// INI document. A host links it with its own program. The crate embeds
1130/// its own copy, `translate/render.alc`, held to the file as the
1131/// manifest's is.
1132///
1133/// ```
1134/// assert!(tabnas_ini::render_text().contains("def ini-render [input]"));
1135/// ```
1136pub fn render_text() -> &'static str {
1137    match TRANSLATION.render {
1138        Some(part) => part.source.unwrap_or_default(),
1139        None => "",
1140    }
1141}
1142
1143// ---------------------------------------------------------------------
1144// Lexer hooks
1145// ---------------------------------------------------------------------
1146
1147/// Register the in-value probe and the four `check` hooks, and hand
1148/// back the cell the string check reads its quote characters from.
1149fn register_lex_hooks(
1150    parser: &mut Tabnas,
1151    resolved: &Resolved,
1152) -> Arc<OnceLock<StringCheckConfig>> {
1153    // The probe. It matches nothing; it only records where the parser
1154    // is, for the checks below. See the thread-local block above.
1155    parser.imperative_lex_match_ref(PROBE_REF, |_lexer, rule, _context| {
1156        IN_VAL.with(|flag| flag.set(in_val_rule(rule)));
1157        IN_VALUE.with(|flag| flag.set(in_value_position(rule)));
1158        None
1159    });
1160
1161    // Line matching is skipped inside a `val` rule, so a newline does
1162    // not end a value the hoover block is still gathering.
1163    parser.imperative_lex_check_ref(LINE_CHECK_REF, |_lexer| {
1164        if IN_VAL.with(Cell::get) {
1165            LexCheckResult::Skip
1166        } else {
1167            LexCheckResult::Continue
1168        }
1169    });
1170
1171    // A comment marker is only a comment when it starts a LINE. Inside
1172    // a value (`k = ;x`) the comment matcher would otherwise beat
1173    // hoover's endofline block and eat the rest of the line, after which
1174    // the value rule silently swallowed the NEXT line's pair. Declining
1175    // here lets the value lexers see the marker: with inline comments
1176    // off it becomes a literal, and with them on hoover terminates the
1177    // value at the marker and the comment is lexed normally once the
1178    // value rule has closed.
1179    parser.imperative_lex_check_ref(COMMENT_CHECK_REF, |_lexer| {
1180        if IN_VALUE.with(Cell::get) {
1181            LexCheckResult::Skip
1182        } else {
1183            LexCheckResult::Continue
1184        }
1185    });
1186
1187    // A value keyword is only a keyword when it is the WHOLE value:
1188    // `k = true` is the boolean, `k = true, false` is the string
1189    // `true, false`. The text matcher runs before hoover and emits a
1190    // `#VL` for a keyword that merely STARTS the value, so
1191    // `k = true, false` silently became `true` and `k = null x` even
1192    // grew a spurious `x` key. Declining in value position hands the
1193    // whole line to hoover, which does the same keyword lookup on the
1194    // complete, trimmed value.
1195    parser.imperative_lex_check_ref(TEXT_CHECK_REF, |_lexer| {
1196        if IN_VALUE.with(Cell::get) {
1197            LexCheckResult::Skip
1198        } else {
1199            LexCheckResult::Continue
1200        }
1201    });
1202
1203    // A quoted value only counts as quoted when the quotes wrap the
1204    // WHOLE value: `k = "a b"` is the string `a b`, but `k = "a"b` is
1205    // the literal text `"a"b`. Without this the string matcher consumed
1206    // just `"a"`, hoover then lexed the trailing `b` as a fresh key, and
1207    // the document silently gained a property that was never written. An
1208    // unterminated quote is left to the string matcher, which abandons
1209    // it and lets hoover take the raw line.
1210    let config: Arc<OnceLock<StringCheckConfig>> = Arc::new(OnceLock::new());
1211    let for_check = Arc::clone(&config);
1212    let inline = Arc::new(resolved.clone());
1213    parser.imperative_lex_check_ref(STRING_CHECK_REF, move |lexer: &mut Lexer<'_>| {
1214        if !IN_VALUE.with(Cell::get) {
1215            return LexCheckResult::Continue;
1216        }
1217        let Some(string_config) = for_check.get() else {
1218            return LexCheckResult::Continue;
1219        };
1220        if string_quote_wraps_value(lexer, string_config, &inline) {
1221            LexCheckResult::Continue
1222        } else {
1223            LexCheckResult::Skip
1224        }
1225    });
1226
1227    config
1228}
1229
1230/// Does the quote at the cursor close on this line with nothing but
1231/// whitespace (and, when enabled, an inline comment) after it?
1232///
1233/// `true` also when there is no quote at all, so the string matcher runs
1234/// as usual; the caller only declines on a genuine trailing-text case.
1235fn string_quote_wraps_value(
1236    lexer: &Lexer<'_>,
1237    config: &StringCheckConfig,
1238    resolved: &Resolved,
1239) -> bool {
1240    // Read forward lazily, never into a buffer. This hook runs at every
1241    // value, and the rest of the document is what it can see: collecting
1242    // that made a document of n pairs cost n^2, with 16,000 pairs taking
1243    // three seconds where the same count of bare keys took a fifth of a
1244    // second. Nothing here looks past the end of the line.
1245    let remaining = lexer.remaining();
1246    let mut characters = remaining.chars();
1247    let Some(quote) = characters.next() else {
1248        return true;
1249    };
1250    if !config.quotes.contains(&quote) {
1251        return true;
1252    }
1253
1254    // Find the closing quote on this line. An escape takes the character
1255    // after it with it, so `"a\"b"` closes at the LAST quote.
1256    let after_quote = loop {
1257        let Some(character) = characters.next() else {
1258            return true;
1259        };
1260        if character == config.escape_char {
1261            characters.next();
1262            continue;
1263        }
1264        if character == quote {
1265            break characters.as_str();
1266        }
1267        if character == '\n' {
1268            return true;
1269        }
1270    };
1271
1272    // Only whitespace, and when enabled an inline comment, may follow.
1273    let tail = after_quote.trim_start_matches([' ', '\t']);
1274    let spaced = tail.len() < after_quote.len();
1275    let next = tail.chars().next();
1276    let at_line_end = match next {
1277        None | Some('\n') => true,
1278        Some('\r') => tail.starts_with("\r\n"),
1279        _ => false,
1280    };
1281    let at_inline_comment = resolved.inline_active
1282        && next.is_some_and(|character| resolved.is_inline_char(character))
1283        && (!resolved.esc_whitespace || spaced);
1284
1285    at_line_end || at_inline_comment
1286}
1287
1288// ---------------------------------------------------------------------
1289// hoover
1290// ---------------------------------------------------------------------
1291
1292fn install_hoover(parser: &mut Tabnas, resolved: &Resolved) -> Result<(), IniPluginError> {
1293    // When inline comments are active without whitespace mode, the
1294    // comment characters terminate a hoovered span. With whitespace mode
1295    // on, the custom value matcher does the detection instead.
1296    let inline_in_fixed = resolved.inline_active && !resolved.esc_whitespace;
1297
1298    let mut eol_end: Vec<String> = vec!["\n".into(), "\r\n".into()];
1299    if inline_in_fixed {
1300        eol_end.extend(resolved.inline_char_str.iter().cloned());
1301    }
1302    eol_end.push(String::new());
1303
1304    let mut key_end: Vec<String> = vec!["=".into(), "\n".into(), "\r\n".into()];
1305    if inline_in_fixed {
1306        key_end.extend(resolved.inline_char_str.iter().cloned());
1307    }
1308    key_end.push(String::new());
1309
1310    let mut eol_escape: HashMap<String, String> = HashMap::new();
1311    eol_escape.insert("\\".into(), "\\".into());
1312    let mut key_escape = eol_escape.clone();
1313    if resolved.inline_active && resolved.esc_backslash {
1314        for ch in &resolved.inline_char_str {
1315            eol_escape.insert(ch.clone(), ch.clone());
1316            key_escape.insert(ch.clone(), ch.clone());
1317        }
1318    }
1319
1320    let endofline = Block {
1321        name: "endofline".into(),
1322        start: Some(StartSpec {
1323            fixed: None,
1324            consume: Consume::All,
1325            rule: Some(HooverRuleSpec {
1326                parent: Some(HooverRuleFilter::include(&["pair", "elem"])),
1327                ..Default::default()
1328            }),
1329        }),
1330        end: EndSpec {
1331            fixed: eol_end,
1332            consume: Consume::Only(vec!["\n".into(), "\r\n".into()]),
1333        },
1334        token: None,
1335        escape_char: Some('\\'),
1336        escape: eol_escape,
1337        allow_unknown_escape: Some(true),
1338        preserve_escape_char: true,
1339        trim: true,
1340    };
1341
1342    let key = Block {
1343        name: "key".into(),
1344        start: Some(StartSpec {
1345            fixed: None,
1346            consume: Consume::All,
1347            rule: Some(HooverRuleSpec {
1348                current: Some(HooverRuleFilter::exclude(&["dive"])),
1349                state: Some("oc".into()),
1350                ..Default::default()
1351            }),
1352        }),
1353        end: EndSpec {
1354            fixed: key_end,
1355            consume: Consume::Never,
1356        },
1357        token: Some("#HK".into()),
1358        // No escape character, as in the canonical port: the map below
1359        // is inert without one, and a backslash in a key is literal.
1360        escape_char: None,
1361        escape: key_escape,
1362        allow_unknown_escape: None,
1363        preserve_escape_char: false,
1364        trim: true,
1365    };
1366
1367    let divekey = Block {
1368        name: "divekey".into(),
1369        start: Some(StartSpec {
1370            fixed: None,
1371            consume: Consume::All,
1372            rule: Some(HooverRuleSpec {
1373                current: Some(HooverRuleFilter::include(&["dive"])),
1374                ..Default::default()
1375            }),
1376        }),
1377        end: EndSpec {
1378            // A section header lives on one line: a newline terminates
1379            // the path segment, so an unterminated header (`[a` with no
1380            // `]`) is a parse error instead of a section name that
1381            // silently swallows following lines up to the next `]`.
1382            //
1383            // The empty string is hoover's end-of-input delimiter.
1384            // Without it a header that runs to the end of the source
1385            // leaves the block committed but unterminated, which hoover
1386            // reports as a generic `invalid_text` bad token, raised by
1387            // the lexer before any alternate is consulted, so the
1388            // grammar never gets to say what actually went wrong. Ending
1389            // at the end of input emits the segment token instead and
1390            // lets the dive rule's close state raise
1391            // `unterminated_section`, which is the real diagnosis.
1392            fixed: vec![
1393                "]".into(),
1394                ".".into(),
1395                "\n".into(),
1396                "\r\n".into(),
1397                String::new(),
1398            ],
1399            consume: Consume::Never,
1400        },
1401        token: Some("#DK".into()),
1402        escape_char: Some('\\'),
1403        escape: HashMap::from([
1404            ("]".to_string(), "]".to_string()),
1405            (".".to_string(), ".".to_string()),
1406            ("\\".to_string(), "\\".to_string()),
1407        ]),
1408        allow_unknown_escape: Some(true),
1409        // Same rule as the value block: an escape that is not one of the
1410        // three above keeps both characters, so `[C:\path]` stays
1411        // `C:\path` rather than losing the backslash.
1412        preserve_escape_char: true,
1413        trim: true,
1414    };
1415
1416    hoover(
1417        parser,
1418        HooverOptions::new(vec![endofline, key, divekey]).with_lex_order(HOOVER_ORDER),
1419    )?;
1420    Ok(())
1421}
1422
1423// ---------------------------------------------------------------------
1424// The declared-section set
1425// ---------------------------------------------------------------------
1426
1427// Per PARSE state, so it lives on the context's `u` bag rather than in
1428// the instance. The canonical TypeScript and Go ports keep it in a
1429// closure variable shared by every parse, which is safe only because
1430// neither runtime parses one instance from two threads. A `Tabnas` is
1431// `Send + Sync` and `parse` shares one instance, so here it has to be
1432// per parse or two concurrent documents would declare each other's
1433// sections.
1434const DECLARED: &str = "ini_declared";
1435
1436fn declared_clear(context: &mut Context) {
1437    context.u.insert(DECLARED.to_string(), empty_object());
1438}
1439
1440fn declared_has(context: &Context, key: &str) -> bool {
1441    match context.u.get(DECLARED) {
1442        // Membership is read WITHOUT cloning the entry: `object_get`
1443        // hands back a copy, which on a container is a second owner and
1444        // makes the next write copy the whole map.
1445        Some(Value::Object(entries)) => entries.contains_key(key),
1446        _ => false,
1447    }
1448}
1449
1450fn declared_add(context: &mut Context, key: String) {
1451    // Take the set out of the bag rather than cloning it. `insert`
1452    // returns the previous value, so the set has one owner while it is
1453    // written to and the write is in place; reading it with `get` and
1454    // cloning made a document of many sections copy the whole set once
1455    // per section.
1456    let mut set = context
1457        .u
1458        .insert(DECLARED.to_string(), Value::Undefined)
1459        .filter(is_object)
1460        .unwrap_or_else(empty_object);
1461    object_insert(&mut set, key, Value::Bool(true));
1462    context.u.insert(DECLARED.to_string(), set);
1463}
1464
1465/// Walk `dive` from `root`, creating a plain object at each missing
1466/// segment, and hand back the value the section starts from.
1467///
1468/// `override_last` replaces the final segment's object outright, which
1469/// is what `section.duplicate: 'override'` means.
1470///
1471/// Iterative, not recursive. A container here is a value rather than a
1472/// reference, so the path has to be taken apart on the way down and put
1473/// back together on the way up, and doing that with the call stack
1474/// aborted the process on a section header thousands of segments deep.
1475/// The depth guard below bounds the vectors; the shape does not depend
1476/// on it.
1477fn open_section(root: &mut Value, dive: &[String], override_last: bool) -> Value {
1478    if !is_object(root) {
1479        *root = empty_object();
1480    }
1481    let mut levels: Vec<Value> = Vec::with_capacity(dive.len() + 1);
1482    levels.push(std::mem::replace(root, Value::Undefined));
1483    for (index, key) in dive.iter().enumerate() {
1484        let last = index + 1 == dive.len();
1485        let parent = levels.last_mut().expect("a level is always on the stack");
1486        let child = match object_take(parent, key) {
1487            Some(value) if is_object(&value) && !(last && override_last) => value,
1488            _ => empty_object(),
1489        };
1490        levels.push(child);
1491    }
1492
1493    let mut current = levels.pop().expect("one level per segment plus the root");
1494    let section = current.clone();
1495    for key in dive.iter().rev() {
1496        let mut parent = levels.pop().expect("one level per segment plus the root");
1497        object_insert(&mut parent, key.clone(), current);
1498        current = parent;
1499    }
1500    *root = current;
1501    section
1502}
1503
1504/// Write a finished section back into `root` at `dive`. Iterative, for
1505/// the reason [`open_section`] is.
1506fn close_section(root: &mut Value, dive: &[String], section: Value) {
1507    if dive.is_empty() {
1508        return;
1509    }
1510    if !is_object(root) {
1511        *root = empty_object();
1512    }
1513    let mut levels: Vec<Value> = Vec::with_capacity(dive.len());
1514    levels.push(std::mem::replace(root, Value::Undefined));
1515    for key in &dive[..dive.len() - 1] {
1516        let parent = levels.last_mut().expect("a level is always on the stack");
1517        let child = match object_take(parent, key) {
1518            Some(value) if is_object(&value) => value,
1519            _ => empty_object(),
1520        };
1521        levels.push(child);
1522    }
1523
1524    let mut current = section;
1525    for key in dive.iter().rev() {
1526        let mut parent = levels.pop().expect("one level per segment");
1527        object_insert(&mut parent, key.clone(), current);
1528        current = parent;
1529    }
1530    *root = current;
1531}
1532
1533/// How deep the parse is: the `map`, `list` and `dive` rules on the
1534/// stack, plus the rule the loop is working on, which the engine hands
1535/// over separately. Counted from the rule NAMES rather than
1536/// `rule_stack.len()`, because the stack holds about three rules per
1537/// container level and a length-based limit would encode that ratio.
1538fn depth(context: &Context) -> usize {
1539    let is_level = |name: &str| name == "map" || name == "list" || name == "dive";
1540    let ancestors = context
1541        .rule_stack
1542        .iter()
1543        .filter(|rule| is_level(&rule.name))
1544        .count();
1545    let current = usize::from(
1546        context
1547            .rule
1548            .as_ref()
1549            .is_some_and(|rule| is_level(&rule.name)),
1550    );
1551    ancestors + current
1552}
1553
1554/// The depth guard: [`DEPTH_LIMIT`] levels parse, the next one is
1555/// refused with the engine's `cancel` code.
1556fn within_depth_limit(context: &Context) -> bool {
1557    depth(context) <= DEPTH_LIMIT
1558}
1559
1560/// The name the depth check is installed under, as a parse guard: the
1561/// name jsonic's own check uses, so this one replaces it.
1562const DEPTH_GUARD: &str = "depth";
1563
1564// ---------------------------------------------------------------------
1565// The grammar's function references
1566// ---------------------------------------------------------------------
1567
1568/// The path this table is writing into, kept apart from `dive`.
1569///
1570/// `dive` on a table's `u` means "the header that opened the NEXT
1571/// table", because the next table reads it through `r.prev.u.dive`.
1572/// Recording the path under that name would make every table inherit
1573/// its predecessor's section.
1574const INI_PATH: &str = "ini_path";
1575
1576fn register_refs(parser: &mut Tabnas, resolved: &Resolved) {
1577    // --- state actions, wired by the @rule-phase convention ---
1578
1579    parser.state_action_ref("@ini-bo", |rule, context| {
1580        set_node(rule, empty_object());
1581        declared_clear(context);
1582        Ok(())
1583    });
1584
1585    let for_table_bo = Arc::new(resolved.clone());
1586    parser.state_action_ref("@table-bo", move |rule, context| {
1587        table_before_open(rule, context, &for_table_bo)
1588    });
1589
1590    parser.state_action_ref("@table-bc", table_before_close);
1591
1592    // Carry the completed child's dive path up. The canonical
1593    // TypeScript pushes onto an array the parent already holds, so the
1594    // parent sees the growth for free; a Rust rule cannot write its
1595    // parent's `u` bag, so each level reads its child's instead. The Go
1596    // port added `@dive-bc` for the same reason.
1597    parser.state_action_ref("@dive-bc", |rule, _context| {
1598        if let Some(dive) = rule
1599            .child_rule
1600            .as_ref()
1601            .and_then(|child| dive_of(child.u.get("dive")))
1602        {
1603            rule.u_mut().insert("dive".into(), dive_value(&dive));
1604        }
1605        Ok(())
1606    });
1607
1608    // --- alternate actions ---
1609
1610    parser.action_with_context("@table-close-dive", |rule, _context| {
1611        if let Some(dive) = rule
1612            .child_rule
1613            .as_ref()
1614            .and_then(|child| dive_of(child.u.get("dive")))
1615        {
1616            rule.u_mut().insert("dive".into(), dive_value(&dive));
1617        }
1618        Ok(())
1619    });
1620
1621    parser.action_with_context("@dive-push", |rule, _context| {
1622        let mut dive = rule
1623            .parent_rule
1624            .as_ref()
1625            .and_then(|parent| dive_of(parent.u.get("dive")))
1626            .unwrap_or_default();
1627        if let Some(existing) = dive_of(rule.u.get("dive")) {
1628            dive = existing;
1629        }
1630        let segment = rule.o0().map(token_string).unwrap_or_default();
1631        dive.push(segment);
1632        rule.u_mut().insert("dive".into(), dive_value(&dive));
1633        Ok(())
1634    });
1635
1636    parser.action_with_context("@pair-key-eq", pair_key_eq);
1637    parser.subscribe_lex(mark_array_key);
1638
1639    parser.action_with_context("@pair-key-bool", |rule, _context| {
1640        // The canonical `'string' === typeof key`, which is NOT the same
1641        // as "the token's text". A line holding nothing but a value
1642        // keyword (`true` on its own) carries the BOOLEAN on its token,
1643        // because hoover and the text matcher both resolve a keyword
1644        // that is the whole span, so TypeScript declares no key at all
1645        // and answers `{}`. Measured, with the checkouts beside this
1646        // repository: TypeScript `{}`, Go `{"true":true}`. TypeScript is
1647        // canonical, so this port follows it and not the sibling.
1648        let Some(key) = rule.o0().and_then(bool_key) else {
1649            return Ok(());
1650        };
1651        if let Some(parent) = rule
1652            .parent_rule
1653            .as_ref()
1654            .map(|parent| Rc::clone(&parent.node))
1655        {
1656            object_insert(&mut parent.borrow_mut(), key, Value::Bool(true));
1657        }
1658        Ok(())
1659    });
1660
1661    parser.action_with_context("@val-empty", |rule, _context| {
1662        set_node(rule, Value::String(String::new()));
1663        Ok(())
1664    });
1665
1666    // --- conditions ---
1667
1668    parser.alt_condition("@is-table-parent", |rule, _context| {
1669        rule.parent_rule
1670            .as_ref()
1671            .is_some_and(|parent| parent.name.as_str() == "table")
1672    });
1673
1674    parser.alt_condition("@is-table-grandparent", |rule, _context| {
1675        rule.parent_rule
1676            .as_ref()
1677            .and_then(|parent| parent.parent_rule.clone())
1678            .is_some_and(|grandparent| grandparent.name.as_str() == "table")
1679    });
1680
1681    parser.alt_condition("@is-duplicate-section", |rule, _context| {
1682        rule.u.contains_key("dupsec")
1683    });
1684
1685    // --- error alternates ---
1686
1687    // The duplicate itself. The dotted path is not any single token's
1688    // source, so it rides along as the `{section}` detail the message
1689    // template reads.
1690    parser.alt_error("@duplicate-section", |rule, context| {
1691        let mut token = alt_err_token(rule, context)?;
1692        let section = match rule.u.get("dupsec") {
1693            Some(Value::String(path)) => path.clone(),
1694            _ => String::new(),
1695        };
1696        token.bad_with_details(
1697            "duplicate_section",
1698            [("section".to_string(), Value::String(section))],
1699        );
1700        Some(token)
1701    });
1702
1703    // The section header ran out before its closing bracket, at a
1704    // newline or at the end of input. The dive rule opened on the `#DK`
1705    // segment token, so that token carries both the text for the
1706    // message and the position to point at.
1707    parser.alt_error("@dive-unterminated", |rule, context| {
1708        let mut token = alt_err_token(rule, context)?;
1709        token.bad("unterminated_section");
1710        Some(token)
1711    });
1712
1713    // Unreachable while `#CL` is removed from the fixed tokens, as it is
1714    // here and in the Go port. Registered because the grammar names it.
1715    parser.alt_error("@pair-close-err", |rule, _context| rule.c1().cloned());
1716}
1717
1718fn table_before_open(
1719    rule: &mut Rule,
1720    context: &mut Context,
1721    resolved: &Resolved,
1722) -> Result<(), ActionError> {
1723    // r.node = r.parent.node: the table writes into the document root
1724    // until a section header moves it.
1725    let Some(root) = rule
1726        .parent_rule
1727        .as_ref()
1728        .map(|parent| Rc::clone(&parent.node))
1729    else {
1730        return Ok(());
1731    };
1732    rule.node = Rc::clone(&root);
1733
1734    let Some(dive) = rule
1735        .prev_rule
1736        .as_ref()
1737        .and_then(|prev| dive_of(prev.u.get("dive")))
1738        .filter(|dive| !dive.is_empty())
1739    else {
1740        return Ok(());
1741    };
1742
1743    // A null character separates the segments, so a dot inside a key
1744    // cannot collide with the separator.
1745    let section_key = dive.join("\u{0}");
1746    let is_duplicate = declared_has(context, &section_key);
1747
1748    if is_duplicate && resolved.dup_section == Duplicate::Error {
1749        // Flag the rule and let this rule's error ALTERNATE raise the
1750        // coded error (see the grammar's table:open). Raising here is
1751        // not portable: Go discards a state action's return value, and
1752        // an error published on the context from a before-open hook is
1753        // overwritten when the alternates are matched.
1754        rule.u_mut()
1755            .insert("dupsec".into(), Value::String(dive.join(".")));
1756        return Ok(());
1757    }
1758
1759    let override_last = is_duplicate && resolved.dup_section == Duplicate::Override;
1760    let section = open_section(&mut root.borrow_mut(), &dive, override_last);
1761
1762    rule.u_mut().insert(INI_PATH.into(), dive_value(&dive));
1763    set_node(rule, section);
1764    declared_add(context, section_key);
1765    Ok(())
1766}
1767
1768fn table_before_close(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1769    // Object.assign(r.node, r.child.node). The child `map` and `dive`
1770    // rules SHARE this rule's node cell, so the merge is a copy of a map
1771    // onto itself: no change in any runtime, and in this one an
1772    // expensive one, because `child_node` is a second owner of the same
1773    // `Arc` and the first write copies the whole map. A document of
1774    // 5,000 sections paid that once per section. Skipping it when the
1775    // cells are the same object is what the canonical `Object.assign(x,
1776    // x)` does for free. The merge is kept for a child that genuinely
1777    // allocates its own node.
1778    let child_is_self = rule
1779        .child_rule
1780        .as_ref()
1781        .is_some_and(|child| Rc::ptr_eq(&child.node, &rule.node));
1782    if child_is_self {
1783        // Drop this rule's copy of its child's node as well. It is a
1784        // second owner of the same container, and the next write to the
1785        // document would copy the whole thing to get around it. Nothing
1786        // reads a `table` rule's child node after this point.
1787        rule.child_node = Value::Undefined;
1788    } else if let Value::Object(entries) = rule.child_node.clone() {
1789        let mut node = rule.node.borrow_mut();
1790        if is_object(&node) {
1791            for (key, value) in entries.iter() {
1792                object_insert(&mut node, key.clone(), value.clone());
1793            }
1794        }
1795    }
1796
1797    // Write the finished section back into the document root. The
1798    // canonical ports hold a live reference to the section object and
1799    // never need this; a Rust container is a value, so the tree is
1800    // reassembled on the way out.
1801    let Some(dive) = dive_of(rule.u.get(INI_PATH)) else {
1802        return Ok(());
1803    };
1804    let Some(root) = rule
1805        .parent_rule
1806        .as_ref()
1807        .map(|parent| Rc::clone(&parent.node))
1808    else {
1809        return Ok(());
1810    };
1811    let section = rule.node.borrow().clone();
1812    close_section(&mut root.borrow_mut(), &dive, section);
1813    Ok(())
1814}
1815
1816/// The lexer's mark on an array key, `k[]`, quoted or not: a transducer
1817/// part reading the rule passes (`alchemy/transduce.alc`) sees a token's
1818/// value but cannot strip a suffix, so in key position (anywhere but
1819/// inside a value) a key token whose string ends in `[]` past the
1820/// brackets carries the name before them in a one-element array. The
1821/// pair actions read it back, and a bare `k[]` line keeps declaring the
1822/// key `k[]`. The canonical TypeScript tests `2 < key.length` in UTF-16
1823/// code units, which any string ending in `[]` with a byte before them
1824/// meets alike.
1825fn mark_array_key(token: &mut Token, rule: &mut Rule, _context: &mut Context) {
1826    if rule.name.as_str() == "val" && rule.state == RuleState::Open {
1827        return;
1828    }
1829    let name = token.name.as_str();
1830    if name != "#HK" && name != "#ST" {
1831        return;
1832    }
1833    let text = match &token.val {
1834        Value::String(text) => text.as_str(),
1835        Value::Text(text) => text.string.as_str(),
1836        _ => return,
1837    };
1838    if text.len() > 2 && text.ends_with("[]") {
1839        let stripped = text[..text.len() - 2].to_string();
1840        token.val = Value::array(vec![Value::String(stripped)]);
1841    }
1842}
1843
1844/// The name the lexer marked an array key with ([`mark_array_key`]), when
1845/// the token carries one.
1846fn array_key_name(token: &Token) -> Option<String> {
1847    match &token.val {
1848        Value::Array(items) if items.len() == 1 => match &items[0] {
1849            Value::String(name) => Some(name.clone()),
1850            _ => None,
1851        },
1852        _ => None,
1853    }
1854}
1855
1856/// A key token's name, and whether the lexer marked it as an array key.
1857fn key_of(token: &Token) -> (String, bool) {
1858    match array_key_name(token) {
1859        Some(name) => (name, true),
1860        None => (token_string(token), false),
1861    }
1862}
1863
1864fn pair_key_eq(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1865    // An array key, `k[]`, arrives from the lexer as its name in a
1866    // one-element array (`mark_array_key`).
1867    let (key, array_key) = rule.o0().map(key_of).unwrap_or_default();
1868
1869    // An array key adds to the array under its own spelling first, `k[]`,
1870    // which a `k[][] =` line made, then to the one under its name.
1871    if array_key {
1872        let spelt = format!("{key}[]");
1873        if matches!(
1874            object_get(&rule.node.borrow(), &spelt),
1875            Some(Value::Array(_))
1876        ) {
1877            rule.u_mut().insert("key".into(), Value::String(spelt));
1878            rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1879            return Ok(());
1880        }
1881    }
1882    let existing = object_get(&rule.node.borrow(), &key);
1883
1884    if matches!(existing, Some(Value::Array(_))) {
1885        rule.u_mut().insert("key".into(), Value::String(key));
1886        rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1887        return Ok(());
1888    }
1889
1890    if array_key {
1891        let array = match existing {
1892            Some(value) if !value.is_undefined() => Value::array(vec![value]),
1893            _ => Value::array(Vec::new()),
1894        };
1895        object_insert(&mut rule.node.borrow_mut(), key.clone(), array);
1896        rule.u_mut().insert("key".into(), Value::String(key));
1897        rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1898        return Ok(());
1899    }
1900
1901    rule.u_mut().insert("key".into(), Value::String(key));
1902    rule.u_mut().insert("pair".into(), Value::Bool(true));
1903    Ok(())
1904}
1905
1906// ---------------------------------------------------------------------
1907// The val rule
1908// ---------------------------------------------------------------------
1909
1910/// Is this alternate the one that starts a list on `[`?
1911///
1912/// INI spells a section header `[a]`, so the JSON core's list alternate
1913/// has to go or `[a]` would open an array. It is identified by its group
1914/// tags rather than its position, because the position moves whenever
1915/// the layers below add an alternate. The tags are compared as a SET:
1916/// the canonical TypeScript joins them as `json,list` and this engine
1917/// stores them as `list,json`, and the alternate is the same one.
1918fn is_json_list_alt(alt: &AltSpec) -> bool {
1919    let mut tags: Vec<&str> = alt
1920        .g
1921        .split(',')
1922        .map(str::trim)
1923        .filter(|tag| !tag.is_empty())
1924        .collect();
1925    tags.sort_unstable();
1926    tags == ["json", "list"]
1927}
1928
1929fn install_val_rule(parser: &mut Tabnas, _resolved: &Resolved) {
1930    let os = parser.token("#OS");
1931    let cs = parser.token("#CS");
1932    let eq = parser.token("#EQ");
1933    let dot = parser.token("#DOT");
1934    let zz = parser.token("#ZZ");
1935    let st = parser.token("#ST");
1936
1937    parser.define_rule("val", move |spec| {
1938        // Clear the node this rule inherits from its parent, which is
1939        // the enclosing map. jsonic's own value alternates do it with
1940        // `@reset$`; the alternate hoover prepends for its `#HV` token
1941        // carries no action, so an INI value would keep the map.
1942        //
1943        // Not tidiness: jsonic's val before-close stashes the inherited
1944        // node in the rule's `u` bag, which holds a second handle on
1945        // that map for as long as the value rule lives, and the next key
1946        // written into it then copies the whole map through
1947        // `Arc::make_mut`. A document of n pairs cost n^2 without this
1948        // (4000 pairs took 2.2 seconds, 20,000 exhausted memory). The Go
1949        // port resets the node in its own `val` before-open hook.
1950        spec.add_bo(|rule, _context| set_node(rule, Value::Undefined));
1951
1952        let kept: Vec<AltSpec> = std::mem::take(&mut spec.open)
1953            .into_iter()
1954            .filter(|alt| !is_json_list_alt(alt))
1955            .collect();
1956
1957        // Since `[`, `]`, `=` and `.` are fixed tokens they are lexed
1958        // before hoover gets to run, so a value that STARTS with one of
1959        // them never reaches the endofline block. Concatenate the fixed
1960        // token's source with the rest of the value instead. All four
1961        // are alternatives for one slot, the TypeScript
1962        // `['#OS #CS #EQ #DOT']`.
1963        let mut open = vec![
1964            AltSpec {
1965                s: vec![vec![os, cs, eq, dot]],
1966                r: Some("val".to_string()),
1967                u: HashMap::from([("ini_prev".to_string(), Value::Bool(true))]),
1968                ..Default::default()
1969            },
1970            // End of input: an empty value.
1971            AltSpec {
1972                s: vec![vec![zz]],
1973                a: vec!["@val-empty".to_string()],
1974                ..Default::default()
1975            },
1976        ];
1977        open.extend(kept);
1978        spec.open = open;
1979
1980        spec.add_ac(move |rule, _context| val_after_close(rule, st));
1981    });
1982}
1983
1984/// The value `JSON.parse` gives a number literal too large for a double,
1985/// which is the one document `serde_json` refuses where `JSON.parse`
1986/// succeeds.
1987///
1988/// `JSON.parse("1e400")` is `Infinity` and `JSON.parse("-1e400")` is
1989/// `-Infinity`, because the specification rounds an unrepresentable
1990/// magnitude to the nearest double. `serde_json` reports
1991/// `number out of range` instead, and the caller then kept the source
1992/// text, so `a = '1e400'` was the STRING `"1e400"` in this port and the
1993/// number `Infinity` in the canonical one. A literal too SMALL to
1994/// represent is not affected: both readers round `1e-400` to zero.
1995///
1996/// `Some` only for a whole document that is one JSON number and whose
1997/// value is not finite. Anything else, including a number that overflows
1998/// INSIDE an array or an object, is left to the caller, which keeps the
1999/// text; `DIVERGENCE.md` records that remaining gap.
2000fn overflowed_json_number(text: &str) -> Option<f64> {
2001    // The JSON whitespace set, which `JSON.parse` also allows around a
2002    // top-level value.
2003    let trimmed = text.trim_matches([' ', '\t', '\n', '\r']);
2004    if !is_json_number(trimmed) {
2005        return None;
2006    }
2007    // A valid JSON number `serde_json` rejected can only be one it could
2008    // not fit in a double, so the parse below succeeds and is infinite.
2009    // Testing for that rather than assuming it keeps this arm from
2010    // quietly claiming any other failure.
2011    trimmed
2012        .parse::<f64>()
2013        .ok()
2014        .filter(|value| value.is_infinite())
2015}
2016
2017/// Whether the whole of `text` is a JSON number literal (RFC 8259
2018/// section 6). Rust's own float parser is wider than that grammar: it
2019/// takes `inf`, `NaN`, `+1`, `1.` and `.5`, none of which `JSON.parse`
2020/// accepts, so the grammar is checked here rather than inferred from a
2021/// successful parse.
2022fn is_json_number(text: &str) -> bool {
2023    let mut chars = text.chars().peekable();
2024    if chars.peek() == Some(&'-') {
2025        chars.next();
2026    }
2027    match chars.next() {
2028        // A leading zero admits no further integer digits.
2029        Some('0') => {}
2030        Some(digit) if digit.is_ascii_digit() => {
2031            while chars.peek().is_some_and(char::is_ascii_digit) {
2032                chars.next();
2033            }
2034        }
2035        _ => return false,
2036    }
2037    if chars.peek() == Some(&'.') {
2038        chars.next();
2039        if !chars.peek().is_some_and(char::is_ascii_digit) {
2040            return false;
2041        }
2042        while chars.peek().is_some_and(char::is_ascii_digit) {
2043            chars.next();
2044        }
2045    }
2046    if matches!(chars.peek(), Some('e' | 'E')) {
2047        chars.next();
2048        if matches!(chars.peek(), Some('+' | '-')) {
2049            chars.next();
2050        }
2051        if !chars.peek().is_some_and(char::is_ascii_digit) {
2052            return false;
2053        }
2054        while chars.peek().is_some_and(char::is_ascii_digit) {
2055            chars.next();
2056        }
2057    }
2058    chars.next().is_none()
2059}
2060
2061/// Rewrite every UNPAIRED surrogate escape in JSON source text to a
2062/// `�` escape, or `None` when there is none to rewrite.
2063///
2064/// `JSON.parse` accepts a lone surrogate: a JavaScript string is UTF-16,
2065/// so `"\ud800"` is a perfectly ordinary one-code-unit string. A Rust
2066/// `String` is scalar values and cannot hold one at all, so `serde_json`
2067/// refuses the document outright and the caller then kept the JSON
2068/// SOURCE as the value: `a = '["\ud800"]'` stopped being an array.
2069///
2070/// Substituting the replacement character keeps the TYPE and the SHAPE
2071/// of the value, which is the larger half of the canonical result, and
2072/// is what Go's `encoding/json` does here, so the two ports that cannot
2073/// hold a lone surrogate agree. The one character that differs is
2074/// recorded in `../DIVERGENCE.md`.
2075///
2076/// Scanned as bytes, which is safe because every character this looks at
2077/// (`"`, `\`, `u` and the hex digits) is ASCII, and because the only
2078/// slices taken start and end on one of them. An escape other than
2079/// `\uXXXX` takes the WHOLE next character with it, so a multi-byte one
2080/// cannot leave the cursor inside a character.
2081fn replace_lone_surrogates(text: &str) -> Option<String> {
2082    /// The code unit a `\uXXXX` escape at `at` names.
2083    fn escaped_unit(bytes: &[u8], at: usize) -> Option<u16> {
2084        if bytes.get(at) != Some(&b'\\') || bytes.get(at + 1) != Some(&b'u') {
2085            return None;
2086        }
2087        let digits = bytes.get(at + 2..at + 6)?;
2088        digits.iter().try_fold(0u16, |unit, byte| {
2089            let digit = (*byte as char).to_digit(16)?;
2090            Some(unit * 16 + digit as u16)
2091        })
2092    }
2093    const HIGH: std::ops::Range<u16> = 0xD800..0xDC00;
2094    const LOW: std::ops::Range<u16> = 0xDC00..0xE000;
2095
2096    let bytes = text.as_bytes();
2097    let mut repaired = String::new();
2098    let mut copied = 0usize;
2099    let mut index = 0usize;
2100    let mut in_string = false;
2101    let mut replaced = false;
2102    while index < bytes.len() {
2103        match bytes[index] {
2104            b'"' => {
2105                in_string = !in_string;
2106                index += 1;
2107            }
2108            b'\\' if in_string => match escaped_unit(bytes, index) {
2109                Some(unit)
2110                    if HIGH.contains(&unit)
2111                        && escaped_unit(bytes, index + 6)
2112                            .is_some_and(|next| LOW.contains(&next)) =>
2113                {
2114                    index += 12;
2115                }
2116                Some(unit) if HIGH.contains(&unit) || LOW.contains(&unit) => {
2117                    repaired.push_str(&text[copied..index]);
2118                    repaired.push_str("\\ufffd");
2119                    index += 6;
2120                    copied = index;
2121                    replaced = true;
2122                }
2123                Some(_) => index += 6,
2124                // Any other escape, whose escaped character may be
2125                // several bytes long.
2126                None => {
2127                    index += 1;
2128                    index += text[index..]
2129                        .chars()
2130                        .next()
2131                        .map_or(0, char::len_utf8)
2132                        .max(1);
2133                }
2134            },
2135            _ => index += 1,
2136        }
2137    }
2138
2139    replaced.then(|| {
2140        repaired.push_str(&text[copied..]);
2141        repaired
2142    })
2143}
2144
2145fn val_after_close(rule: &mut Rule, st: tabnas::Tin) {
2146    // A single-quoted value carries JSON: `k = '{"a":1}'` is the object.
2147    // An invalid document is kept as the string it already is.
2148    let single_quoted = rule
2149        .o0()
2150        .is_some_and(|token| token.tin == st && token.src.as_str().starts_with('\''));
2151    if single_quoted {
2152        let text = match &*rule.node.borrow() {
2153            Value::String(text) => Some(text.clone()),
2154            Value::Text(text) => Some(text.string.clone()),
2155            _ => None,
2156        };
2157        if let Some(text) = text {
2158            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) {
2159                set_node(rule, Value::from_json(&parsed));
2160            } else if let Some(number) = overflowed_json_number(&text) {
2161                set_node(rule, Value::Number(number));
2162            } else if let Some(repaired) = replace_lone_surrogates(&text) {
2163                // A lone surrogate is the other thing `JSON.parse`
2164                // accepts and `serde_json` refuses. Re-read the repaired
2165                // text rather than assuming it now parses: the document
2166                // may be invalid for some further reason, and then the
2167                // value stays the string it already is.
2168                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&repaired) {
2169                    set_node(rule, Value::from_json(&parsed));
2170                }
2171            }
2172        }
2173    }
2174
2175    // A value can start with more than one fixed token (`a = ==x`), and
2176    // each one replaced the val rule with a fresh one. Only the LAST val
2177    // in that chain runs this hook, so walk the whole chain: every link
2178    // contributes its token source, and every link's node is updated,
2179    // including the first, which is the rule the pair rule reads its
2180    // child node from. Stopping at the first link instead left that node
2181    // unset, and the pair then took the parent map as its value,
2182    // producing a circular result.
2183    if rule
2184        .prev_rule
2185        .as_ref()
2186        .is_some_and(|prev| prev.u.contains_key("ini_prev"))
2187    {
2188        let mut text = js_string(&rule.node.borrow());
2189        let mut cursor = rule.prev_rule.clone();
2190        while let Some(link) = cursor {
2191            if !link.u.contains_key("ini_prev") {
2192                break;
2193            }
2194            let source = link
2195                .o
2196                .first()
2197                .map(|token| token.src.as_str().to_string())
2198                .unwrap_or_default();
2199            text = format!("{source}{text}");
2200            // The canonical `p.node = r.node` (ts/src/ini.ts:530,
2201            // go/ini.go:1033), which this port had never carried. The
2202            // write goes THROUGH the cell rather than replacing it:
2203            // `link.node` is the very `Rc<RefCell<Value>>` the engine
2204            // froze as the parent's child link when the pair rule pushed
2205            // the FIRST val of this chain, so only a write into that cell
2206            // reaches the node the pair later reads. `set_node` swaps the
2207            // `Rc` instead, which leaves the frozen handle untouched.
2208            *link.node.borrow_mut() = Value::String(text.clone());
2209            cursor = link.prev_rule.clone();
2210        }
2211        set_node(rule, Value::String(text));
2212    }
2213
2214    // Deliberately NOT an `else` of the block above: an array entry
2215    // whose value starts with a fixed token (`k[] = [x`) needs both the
2216    // concatenation AND the push, or the entry is silently dropped.
2217    let Some(parent) = rule.parent_rule.clone() else {
2218        return;
2219    };
2220    if !parent.u.contains_key("ini_array") {
2221        return;
2222    }
2223    let Some(Value::String(key)) = parent.u.get("key").cloned() else {
2224        return;
2225    };
2226    // The array is read back off the parent's node rather than out of
2227    // its `u` bag: a Rust rule cannot write its parent's bag, and a
2228    // container here is a value rather than a reference, so the grown
2229    // array has to be stored back where the document will find it.
2230    let value = rule.node.borrow().clone();
2231    let mut node = parent.node.borrow_mut();
2232    let mut items = match object_get(&node, &key) {
2233        Some(Value::Array(items)) => (*items).clone(),
2234        _ => Vec::new(),
2235    };
2236    items.push(value);
2237    object_insert(&mut node, key, Value::array(items));
2238}
2239
2240// ---------------------------------------------------------------------
2241// The custom value matcher
2242// ---------------------------------------------------------------------
2243
2244/// The lexer configuration the value matcher reads: the `value.lex` flag
2245/// and the `value.def` table, so a keyword is resolved exactly as
2246/// hoover's endofline block resolves the values it lexes itself.
2247struct ValueConfig {
2248    lex: bool,
2249    definitions: HashMap<String, Value>,
2250}
2251
2252impl ValueConfig {
2253    fn from_options(options: &Options) -> Self {
2254        Self {
2255            lex: options.value.lex,
2256            definitions: options
2257                .value
2258                .definitions
2259                .iter()
2260                .map(|(source, definition)| {
2261                    (
2262                        source.clone(),
2263                        definition.val.clone().unwrap_or(Value::Undefined),
2264                    )
2265                })
2266                .collect(),
2267        }
2268    }
2269
2270    fn resolve(&self, text: &str) -> Value {
2271        if self.lex {
2272            if let Some(value) = self.definitions.get(text) {
2273                return value.clone();
2274            }
2275        }
2276        Value::String(text.to_string())
2277    }
2278}
2279
2280/// Register the custom value matcher.
2281///
2282/// It is needed when multiline continuation is on, or when inline
2283/// comments are active with whitespace-prefix detection, and it runs at
2284/// [`MULTILINE_ORDER`], just below hoover, so it sees a value first.
2285fn register_multiline(parser: &mut Tabnas, resolved: &Resolved) {
2286    let resolved = Arc::new(resolved.clone());
2287    parser.lex_match_factory_ref(MULTILINE_REF, move |options: &Options| {
2288        let config = Arc::new(ValueConfig::from_options(options));
2289        let resolved = Arc::clone(&resolved);
2290        let matcher: ImperativeLexMatcher = Arc::new(
2291            move |lexer: &mut Lexer<'_>, rule: &mut Rule, _context: &mut Context| {
2292                multiline_match(lexer, rule, &resolved, &config)
2293            },
2294        );
2295        Some(matcher)
2296    });
2297}
2298
2299fn multiline_match(
2300    lexer: &mut Lexer<'_>,
2301    rule: &Rule,
2302    resolved: &Resolved,
2303    config: &ValueConfig,
2304) -> Option<Token> {
2305    // Only in value context during a rule's open state, the same gate
2306    // hoover's endofline block applies.
2307    let parent_is_pair = rule.parent_rule.as_ref().is_some_and(|parent| {
2308        let name = parent.name.as_str();
2309        name == "pair" || name == "elem"
2310    });
2311    if !parent_is_pair || rule.state != RuleState::Open {
2312        return None;
2313    }
2314
2315    // Read forward lazily, never into a buffer. This matcher runs at
2316    // every value and what it can see is the rest of the document, so
2317    // collecting that first would make a document of n values cost n
2318    // squared. `rest` is always a character boundary: every step below
2319    // advances by whole characters.
2320    let source = lexer.remaining();
2321    let mut rest = source;
2322    let mut text = String::new();
2323
2324    while let Some(c) = rest.chars().next() {
2325        // An inline comment character ends the value.
2326        if resolved.inline_active && resolved.is_inline_char(c) {
2327            if resolved.esc_whitespace {
2328                // Only a comment when whitespace comes first.
2329                if matches!(text.chars().last(), Some(' ') | Some('\t')) {
2330                    break;
2331                }
2332                text.push(c);
2333                rest = &rest[c.len_utf8()..];
2334                continue;
2335            }
2336            break;
2337        }
2338
2339        // A continuation character before a newline joins the lines.
2340        if resolved.continuation == Some(c) {
2341            let after = &rest[c.len_utf8()..];
2342            if let Some(next) = after
2343                .strip_prefix('\n')
2344                .or_else(|| after.strip_prefix("\r\n"))
2345            {
2346                rest = next.trim_start_matches([' ', '\t']);
2347                continue;
2348            }
2349        }
2350
2351        // A newline ends the value, unless the next line is indented and
2352        // indent continuation is on. A lone carriage return is ordinary
2353        // text, as it is in the canonical port.
2354        if '\n' == c || rest.starts_with("\r\n") {
2355            let after = if '\r' == c { &rest[2..] } else { &rest[1..] };
2356            if resolved.indent && after.starts_with([' ', '\t']) {
2357                rest = after.trim_start_matches([' ', '\t']);
2358                text.push(' ');
2359                continue;
2360            }
2361            rest = after;
2362            break;
2363        }
2364
2365        // Escapes.
2366        if '\\' == c {
2367            let after = &rest[1..];
2368            if let Some(next) = after.chars().next() {
2369                if resolved.inline_active && resolved.esc_backslash && resolved.is_inline_char(next)
2370                {
2371                    text.push(next);
2372                    rest = &after[next.len_utf8()..];
2373                    continue;
2374                }
2375                if '\\' == next {
2376                    text.push('\\');
2377                    rest = &after[1..];
2378                    continue;
2379                }
2380            }
2381        }
2382
2383        text.push(c);
2384        rest = &rest[c.len_utf8()..];
2385    }
2386
2387    // Resolve the value keywords on the WHOLE trimmed value, exactly as
2388    // hoover's endofline block does for the values it lexes itself.
2389    let value = config.resolve(tabnas_hoover::js_trim(&text));
2390
2391    // Owned, which releases the borrow of the lexer's source before the
2392    // cursor is moved. It is what the token carries in any case.
2393    let consumed: String = source[..source.len() - rest.len()].to_string();
2394    let advance = consumed.chars().count();
2395
2396    let point = lexer.point();
2397    lexer.advance_chars(advance);
2398    let tin = lexer.token_tin("#HV");
2399    let mut token = lexer.token("#HV", tin, value, consumed, point);
2400    token
2401        .use_data_mut()
2402        .insert("block".to_string(), Value::String("endofline".to_string()));
2403    Some(token)
2404}