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.24";
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: the counterpart of the
1002/// canonical `make(options)` and Go's `MakeJsonic`.
1003///
1004/// Infallible by design: the grammar document is a fixed literal and the
1005/// jsonic base is installed one line earlier, so a failure here is a bug
1006/// in this crate rather than anything a caller did. The Go `MakeJsonic`
1007/// panics for the same reason.
1008///
1009/// It also declares `lex.window`, so that [`Tabnas::parse_reader`] reads a
1010/// reader a window at a time rather than whole (admin ADR-30). The string
1011/// check reads the source only through the lexer's window and `fill`;
1012/// hoover's blocks fill as it does (hoover 0.3.15);
1013/// the multiline value matcher reads only the window and ends a value
1014/// there, a token the engine cuts again; jsonic's base and the comment,
1015/// line and string matchers are the engine's own; and the actions read
1016/// only the tokens. The window is declared here, on the parser this crate
1017/// makes whole, and not in [`plugin`] or [`ini`], which a host may install
1018/// beneath matchers of its own.
1019///
1020/// ```
1021/// let options = tabnas_ini::IniOptions::default().with_inline_comments();
1022/// let parser = tabnas_ini::make_with(&options);
1023/// assert_eq!(parser.parse("a = x ; note")?.to_string(), r#"{"a":"x"}"#);
1024/// # Ok::<(), tabnas_ini::IniError>(())
1025/// ```
1026pub fn make_with(options: &IniOptions) -> Tabnas {
1027    let mut parser = tabnas_jsonic::make();
1028    parser
1029        .use_plugin(plugin(options.clone()), None)
1030        .expect("the INI grammar document is fixed, and the jsonic base is installed");
1031    parser
1032        .set_options(|options| options.lex.window = true)
1033        .expect("lex.window sets");
1034    parser
1035}
1036
1037/// Parse an INI source string with the shared default parser.
1038///
1039/// The engine is built once, on first use, and reused after that. Both
1040/// other runtimes do the same (`sync.Once` in `go/ini.go`, a lazily
1041/// assigned module variable in the TypeScript tests), and reuse is safe
1042/// here for the same reason it is there: [`Tabnas::parse`] takes `&self`
1043/// and builds a fresh parse context per call, and `Tabnas` is `Send +
1044/// Sync`, so concurrent callers share one installed grammar instead of
1045/// each rebuilding it.
1046///
1047/// ```
1048/// let value = tabnas_ini::parse("a = 1\n[s]\nb = 2")?;
1049/// assert_eq!(value.to_string(), r#"{"a":"1","s":{"b":"2"}}"#);
1050/// # Ok::<(), tabnas_ini::IniError>(())
1051/// ```
1052pub fn parse(src: &str) -> Result<Value, IniError> {
1053    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
1054    DEFAULT.get_or_init(make).parse(src)
1055}
1056
1057/// Parse an INI source string with caller options.
1058///
1059/// Every call builds a fresh parser, because the options decide the
1060/// hoover blocks and the lexer matchers and so cannot be shared. Reach
1061/// for [`make_with`] when parsing more than once with one option set.
1062///
1063/// ```
1064/// let options = tabnas_ini::IniOptions::default().with_multiline();
1065/// let value = tabnas_ini::parse_with("a = one \\\ntwo", &options)?;
1066/// assert_eq!(value.to_string(), r#"{"a":"one two"}"#);
1067/// # Ok::<(), tabnas_ini::IniError>(())
1068/// ```
1069pub fn parse_with(src: &str, options: &IniOptions) -> Result<Value, IniError> {
1070    make_with(options).parse(src)
1071}
1072
1073// ---------------------------------------------------------------------
1074// The translation parts
1075// ---------------------------------------------------------------------
1076
1077/// One optional alchemy translation source and its explicit entry point.
1078#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1079pub struct TranslationPart {
1080    /// The definition a host calls after linking the source.
1081    pub entry: &'static str,
1082    /// The source text, or `None` for an entry supplied by alchemy.
1083    pub source: Option<&'static str>,
1084}
1085
1086/// The package-local structural translation interface.
1087#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1088pub struct TranslationParts {
1089    /// The complete `tabnas.plugin.json` text.
1090    pub manifest: &'static str,
1091    /// An optional lift from the grammar's events to its first read shape.
1092    pub lift: Option<TranslationPart>,
1093    /// An optional embedding of a plain tree in the format's schema, with its reverse.
1094    pub embed: Option<TranslationPart>,
1095    /// An optional render from the write shape to text.
1096    pub render: Option<TranslationPart>,
1097    /// An optional transducer: the format's JSON events from its parser's
1098    /// rule passes, for a host that reads parser events.
1099    pub transduce: Option<TranslationPart>,
1100}
1101
1102const TRANSLATION: TranslationParts = TranslationParts {
1103    manifest: include_str!("../translate/manifest.json"),
1104    lift: None,
1105    embed: None,
1106    render: Some(TranslationPart {
1107        entry: "ini-render",
1108        source: Some(include_str!("../translate/render.alc")),
1109    }),
1110    transduce: Some(TranslationPart {
1111        entry: "ini-transduce",
1112        source: Some(include_str!("../translate/transduce.alc")),
1113    }),
1114};
1115
1116/// Return INI's immutable translation parts.
1117#[must_use]
1118pub const fn translate() -> Option<TranslationParts> {
1119    Some(TRANSLATION)
1120}
1121
1122/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
1123/// it. Its `translate` object is what a host that translates reads: the
1124/// shape INI is read as and written from (`tree`), the root its render
1125/// needs (`object`), the file that holds the render, the sentences that
1126/// say what the render does not keep, and the file that holds the
1127/// transducer part (`transduce`), the document's JSON events from the
1128/// grammar's rule passes under its default options, through which a host
1129/// that reads parser events reads a document.
1130/// The crate embeds its own copies, `translate/manifest.json` and
1131/// `translate/transduce.alc`, since a packaged crate holds nothing outside
1132/// `rs/`; `tests/translate_test.rs` holds each copy to its file.
1133///
1134/// ```
1135/// assert!(tabnas_ini::manifest_text().contains("\"translate\""));
1136/// ```
1137pub fn manifest_text() -> &'static str {
1138    TRANSLATION.manifest
1139}
1140
1141/// INI's render, `alchemy/render.alc`, the file the manifest's
1142/// `translate.render` names: a library of alchemy definitions, with no
1143/// `export`, whose entry point `ini-render` writes a tree's events as one
1144/// INI document. A host links it with its own program. The crate embeds
1145/// its own copy, `translate/render.alc`, held to the file as the
1146/// manifest's is.
1147///
1148/// ```
1149/// assert!(tabnas_ini::render_text().contains("def ini-render [input]"));
1150/// ```
1151pub fn render_text() -> &'static str {
1152    match TRANSLATION.render {
1153        Some(part) => part.source.unwrap_or_default(),
1154        None => "",
1155    }
1156}
1157
1158// ---------------------------------------------------------------------
1159// Lexer hooks
1160// ---------------------------------------------------------------------
1161
1162/// Register the in-value probe and the four `check` hooks, and hand
1163/// back the cell the string check reads its quote characters from.
1164fn register_lex_hooks(
1165    parser: &mut Tabnas,
1166    resolved: &Resolved,
1167) -> Arc<OnceLock<StringCheckConfig>> {
1168    // The probe. It matches nothing; it only records where the parser
1169    // is, for the checks below. See the thread-local block above.
1170    parser.imperative_lex_match_ref(PROBE_REF, |_lexer, rule, _context| {
1171        IN_VAL.with(|flag| flag.set(in_val_rule(rule)));
1172        IN_VALUE.with(|flag| flag.set(in_value_position(rule)));
1173        None
1174    });
1175
1176    // Line matching is skipped inside a `val` rule, so a newline does
1177    // not end a value the hoover block is still gathering.
1178    parser.imperative_lex_check_ref(LINE_CHECK_REF, |_lexer| {
1179        if IN_VAL.with(Cell::get) {
1180            LexCheckResult::Skip
1181        } else {
1182            LexCheckResult::Continue
1183        }
1184    });
1185
1186    // A comment marker is only a comment when it starts a LINE. Inside
1187    // a value (`k = ;x`) the comment matcher would otherwise beat
1188    // hoover's endofline block and eat the rest of the line, after which
1189    // the value rule silently swallowed the NEXT line's pair. Declining
1190    // here lets the value lexers see the marker: with inline comments
1191    // off it becomes a literal, and with them on hoover terminates the
1192    // value at the marker and the comment is lexed normally once the
1193    // value rule has closed.
1194    parser.imperative_lex_check_ref(COMMENT_CHECK_REF, |_lexer| {
1195        if IN_VALUE.with(Cell::get) {
1196            LexCheckResult::Skip
1197        } else {
1198            LexCheckResult::Continue
1199        }
1200    });
1201
1202    // A value keyword is only a keyword when it is the WHOLE value:
1203    // `k = true` is the boolean, `k = true, false` is the string
1204    // `true, false`. The text matcher runs before hoover and emits a
1205    // `#VL` for a keyword that merely STARTS the value, so
1206    // `k = true, false` silently became `true` and `k = null x` even
1207    // grew a spurious `x` key. Declining in value position hands the
1208    // whole line to hoover, which does the same keyword lookup on the
1209    // complete, trimmed value.
1210    parser.imperative_lex_check_ref(TEXT_CHECK_REF, |_lexer| {
1211        if IN_VALUE.with(Cell::get) {
1212            LexCheckResult::Skip
1213        } else {
1214            LexCheckResult::Continue
1215        }
1216    });
1217
1218    // A quoted value only counts as quoted when the quotes wrap the
1219    // WHOLE value: `k = "a b"` is the string `a b`, but `k = "a"b` is
1220    // the literal text `"a"b`. Without this the string matcher consumed
1221    // just `"a"`, hoover then lexed the trailing `b` as a fresh key, and
1222    // the document silently gained a property that was never written. An
1223    // unterminated quote is left to the string matcher, which abandons
1224    // it and lets hoover take the raw line.
1225    let config: Arc<OnceLock<StringCheckConfig>> = Arc::new(OnceLock::new());
1226    let for_check = Arc::clone(&config);
1227    let inline = Arc::new(resolved.clone());
1228    parser.imperative_lex_check_ref(STRING_CHECK_REF, move |lexer: &mut Lexer<'_>| {
1229        let Some(string_config) = for_check.get() else {
1230            return LexCheckResult::Continue;
1231        };
1232        // A quoted key is the engine's string matcher's to read. In a parse
1233        // from a reader the matcher declines a string the window ends
1234        // inside, and the engine cuts the token again over a wider window,
1235        // even where a later matcher's fill has read the source to its end
1236        // (tabnas/parser#326, from tabnas-parser 0.12.17), so hoover's key
1237        // block never takes a quoted key's line whole.
1238        if !IN_VALUE.with(Cell::get) {
1239            return LexCheckResult::Continue;
1240        }
1241        if string_quote_wraps_value(lexer, string_config, &inline) {
1242            LexCheckResult::Continue
1243        } else {
1244            LexCheckResult::Skip
1245        }
1246    });
1247
1248    config
1249}
1250
1251/// Does the quote at the cursor close on this line with nothing but
1252/// whitespace (and, when enabled, an inline comment) after it?
1253///
1254/// `true` also when there is no quote at all, so the string matcher runs
1255/// as usual; the caller only declines on a genuine trailing-text case.
1256///
1257/// The line is read from the text the lexer holds: the whole source, or
1258/// in a parse from a reader a window of it (`lex.window`, admin ADR-30),
1259/// which [`Lexer::window`] gives from the cursor on. A line the window
1260/// ends inside is read again over a window asked for twice what it holds
1261/// ([`Lexer::fill`]); where the window does not grow, the source ends
1262/// there, and the end of the window is the end of the line. In a whole
1263/// text `fill` only answers.
1264fn string_quote_wraps_value(
1265    lexer: &mut Lexer<'_>,
1266    config: &StringCheckConfig,
1267    resolved: &Resolved,
1268) -> bool {
1269    let mut exhausted = !lexer.windowed();
1270    loop {
1271        let rest = lexer.window();
1272        if let Some(answer) = quote_wraps_value(rest, config, resolved, exhausted) {
1273            return answer;
1274        }
1275        let ahead = rest.len();
1276        let read = rest.chars().count();
1277        lexer.fill(read.saturating_mul(2).max(read + 1));
1278        if lexer.window().len() <= ahead {
1279            exhausted = true;
1280        }
1281    }
1282}
1283
1284/// [`string_quote_wraps_value`] over `remaining`, the text the lexer holds
1285/// from the cursor on. Unless `exhausted`, `None` where the answer needs
1286/// more of the line than `remaining` holds.
1287fn quote_wraps_value(
1288    remaining: &str,
1289    config: &StringCheckConfig,
1290    resolved: &Resolved,
1291    exhausted: bool,
1292) -> Option<bool> {
1293    // Read forward lazily, never into a buffer. This hook runs at every
1294    // value, and the rest of the document is what it can see: collecting
1295    // that made a document of n pairs cost n^2, with 16,000 pairs taking
1296    // three seconds where the same count of bare keys took a fifth of a
1297    // second. Nothing here looks past the end of the line.
1298    let mut characters = remaining.chars();
1299    let Some(quote) = characters.next() else {
1300        return if exhausted { Some(true) } else { None };
1301    };
1302    if !config.quotes.contains(&quote) {
1303        return Some(true);
1304    }
1305
1306    // Find the closing quote on this line. An escape takes the character
1307    // after it with it, so `"a\"b"` closes at the LAST quote.
1308    let after_quote = loop {
1309        let Some(character) = characters.next() else {
1310            return if exhausted { Some(true) } else { None };
1311        };
1312        if character == config.escape_char {
1313            characters.next();
1314            continue;
1315        }
1316        if character == quote {
1317            break characters.as_str();
1318        }
1319        if character == '\n' {
1320            return Some(true);
1321        }
1322    };
1323
1324    // Only whitespace, and when enabled an inline comment, may follow.
1325    let tail = after_quote.trim_start_matches([' ', '\t']);
1326    let spaced = tail.len() < after_quote.len();
1327    let next = tail.chars().next();
1328    if !exhausted && (tail.is_empty() || "\r" == tail) {
1329        return None;
1330    }
1331    let at_line_end = match next {
1332        None | Some('\n') => true,
1333        Some('\r') => tail.starts_with("\r\n"),
1334        _ => false,
1335    };
1336    let at_inline_comment = resolved.inline_active
1337        && next.is_some_and(|character| resolved.is_inline_char(character))
1338        && (!resolved.esc_whitespace || spaced);
1339
1340    Some(at_line_end || at_inline_comment)
1341}
1342
1343// ---------------------------------------------------------------------
1344// hoover
1345// ---------------------------------------------------------------------
1346
1347fn install_hoover(parser: &mut Tabnas, resolved: &Resolved) -> Result<(), IniPluginError> {
1348    // When inline comments are active without whitespace mode, the
1349    // comment characters terminate a hoovered span. With whitespace mode
1350    // on, the custom value matcher does the detection instead.
1351    let inline_in_fixed = resolved.inline_active && !resolved.esc_whitespace;
1352
1353    let mut eol_end: Vec<String> = vec!["\n".into(), "\r\n".into()];
1354    if inline_in_fixed {
1355        eol_end.extend(resolved.inline_char_str.iter().cloned());
1356    }
1357    eol_end.push(String::new());
1358
1359    let mut key_end: Vec<String> = vec!["=".into(), "\n".into(), "\r\n".into()];
1360    if inline_in_fixed {
1361        key_end.extend(resolved.inline_char_str.iter().cloned());
1362    }
1363    key_end.push(String::new());
1364
1365    let mut eol_escape: HashMap<String, String> = HashMap::new();
1366    eol_escape.insert("\\".into(), "\\".into());
1367    let mut key_escape = eol_escape.clone();
1368    if resolved.inline_active && resolved.esc_backslash {
1369        for ch in &resolved.inline_char_str {
1370            eol_escape.insert(ch.clone(), ch.clone());
1371            key_escape.insert(ch.clone(), ch.clone());
1372        }
1373    }
1374
1375    let endofline = Block {
1376        name: "endofline".into(),
1377        start: Some(StartSpec {
1378            fixed: None,
1379            consume: Consume::All,
1380            rule: Some(HooverRuleSpec {
1381                parent: Some(HooverRuleFilter::include(&["pair", "elem"])),
1382                ..Default::default()
1383            }),
1384        }),
1385        end: EndSpec {
1386            fixed: eol_end,
1387            consume: Consume::Only(vec!["\n".into(), "\r\n".into()]),
1388        },
1389        token: None,
1390        escape_char: Some('\\'),
1391        escape: eol_escape,
1392        allow_unknown_escape: Some(true),
1393        preserve_escape_char: true,
1394        trim: true,
1395    };
1396
1397    let key = Block {
1398        name: "key".into(),
1399        start: Some(StartSpec {
1400            fixed: None,
1401            consume: Consume::All,
1402            rule: Some(HooverRuleSpec {
1403                current: Some(HooverRuleFilter::exclude(&["dive"])),
1404                state: Some("oc".into()),
1405                ..Default::default()
1406            }),
1407        }),
1408        end: EndSpec {
1409            fixed: key_end,
1410            consume: Consume::Never,
1411        },
1412        token: Some("#HK".into()),
1413        // No escape character, as in the canonical port: the map below
1414        // is inert without one, and a backslash in a key is literal.
1415        escape_char: None,
1416        escape: key_escape,
1417        allow_unknown_escape: None,
1418        preserve_escape_char: false,
1419        trim: true,
1420    };
1421
1422    let divekey = Block {
1423        name: "divekey".into(),
1424        start: Some(StartSpec {
1425            fixed: None,
1426            consume: Consume::All,
1427            rule: Some(HooverRuleSpec {
1428                current: Some(HooverRuleFilter::include(&["dive"])),
1429                ..Default::default()
1430            }),
1431        }),
1432        end: EndSpec {
1433            // A section header lives on one line: a newline terminates
1434            // the path segment, so an unterminated header (`[a` with no
1435            // `]`) is a parse error instead of a section name that
1436            // silently swallows following lines up to the next `]`.
1437            //
1438            // The empty string is hoover's end-of-input delimiter.
1439            // Without it a header that runs to the end of the source
1440            // leaves the block committed but unterminated, which hoover
1441            // reports as a generic `invalid_text` bad token, raised by
1442            // the lexer before any alternate is consulted, so the
1443            // grammar never gets to say what actually went wrong. Ending
1444            // at the end of input emits the segment token instead and
1445            // lets the dive rule's close state raise
1446            // `unterminated_section`, which is the real diagnosis.
1447            fixed: vec![
1448                "]".into(),
1449                ".".into(),
1450                "\n".into(),
1451                "\r\n".into(),
1452                String::new(),
1453            ],
1454            consume: Consume::Never,
1455        },
1456        token: Some("#DK".into()),
1457        escape_char: Some('\\'),
1458        escape: HashMap::from([
1459            ("]".to_string(), "]".to_string()),
1460            (".".to_string(), ".".to_string()),
1461            ("\\".to_string(), "\\".to_string()),
1462        ]),
1463        allow_unknown_escape: Some(true),
1464        // Same rule as the value block: an escape that is not one of the
1465        // three above keeps both characters, so `[C:\path]` stays
1466        // `C:\path` rather than losing the backslash.
1467        preserve_escape_char: true,
1468        trim: true,
1469    };
1470
1471    hoover(
1472        parser,
1473        HooverOptions::new(vec![endofline, key, divekey]).with_lex_order(HOOVER_ORDER),
1474    )?;
1475    Ok(())
1476}
1477
1478// ---------------------------------------------------------------------
1479// The declared-section set
1480// ---------------------------------------------------------------------
1481
1482// Per PARSE state, so it lives on the context's `u` bag rather than in
1483// the instance. The canonical TypeScript and Go ports keep it in a
1484// closure variable shared by every parse, which is safe only because
1485// neither runtime parses one instance from two threads. A `Tabnas` is
1486// `Send + Sync` and `parse` shares one instance, so here it has to be
1487// per parse or two concurrent documents would declare each other's
1488// sections.
1489const DECLARED: &str = "ini_declared";
1490
1491fn declared_clear(context: &mut Context) {
1492    context.u.insert(DECLARED.to_string(), empty_object());
1493}
1494
1495fn declared_has(context: &Context, key: &str) -> bool {
1496    match context.u.get(DECLARED) {
1497        // Membership is read WITHOUT cloning the entry: `object_get`
1498        // hands back a copy, which on a container is a second owner and
1499        // makes the next write copy the whole map.
1500        Some(Value::Object(entries)) => entries.contains_key(key),
1501        _ => false,
1502    }
1503}
1504
1505fn declared_add(context: &mut Context, key: String) {
1506    // Take the set out of the bag rather than cloning it. `insert`
1507    // returns the previous value, so the set has one owner while it is
1508    // written to and the write is in place; reading it with `get` and
1509    // cloning made a document of many sections copy the whole set once
1510    // per section.
1511    let mut set = context
1512        .u
1513        .insert(DECLARED.to_string(), Value::Undefined)
1514        .filter(is_object)
1515        .unwrap_or_else(empty_object);
1516    object_insert(&mut set, key, Value::Bool(true));
1517    context.u.insert(DECLARED.to_string(), set);
1518}
1519
1520/// Walk `dive` from `root`, creating a plain object at each missing
1521/// segment, and hand back the value the section starts from.
1522///
1523/// `override_last` replaces the final segment's object outright, which
1524/// is what `section.duplicate: 'override'` means.
1525///
1526/// Iterative, not recursive. A container here is a value rather than a
1527/// reference, so the path has to be taken apart on the way down and put
1528/// back together on the way up, and doing that with the call stack
1529/// aborted the process on a section header thousands of segments deep.
1530/// The depth guard below bounds the vectors; the shape does not depend
1531/// on it.
1532fn open_section(root: &mut Value, dive: &[String], override_last: bool) -> Value {
1533    if !is_object(root) {
1534        *root = empty_object();
1535    }
1536    let mut levels: Vec<Value> = Vec::with_capacity(dive.len() + 1);
1537    levels.push(std::mem::replace(root, Value::Undefined));
1538    for (index, key) in dive.iter().enumerate() {
1539        let last = index + 1 == dive.len();
1540        let parent = levels.last_mut().expect("a level is always on the stack");
1541        let child = match object_take(parent, key) {
1542            Some(value) if is_object(&value) && !(last && override_last) => value,
1543            _ => empty_object(),
1544        };
1545        levels.push(child);
1546    }
1547
1548    let mut current = levels.pop().expect("one level per segment plus the root");
1549    let section = current.clone();
1550    for key in dive.iter().rev() {
1551        let mut parent = levels.pop().expect("one level per segment plus the root");
1552        object_insert(&mut parent, key.clone(), current);
1553        current = parent;
1554    }
1555    *root = current;
1556    section
1557}
1558
1559/// Write a finished section back into `root` at `dive`. Iterative, for
1560/// the reason [`open_section`] is.
1561fn close_section(root: &mut Value, dive: &[String], section: Value) {
1562    if dive.is_empty() {
1563        return;
1564    }
1565    if !is_object(root) {
1566        *root = empty_object();
1567    }
1568    let mut levels: Vec<Value> = Vec::with_capacity(dive.len());
1569    levels.push(std::mem::replace(root, Value::Undefined));
1570    for key in &dive[..dive.len() - 1] {
1571        let parent = levels.last_mut().expect("a level is always on the stack");
1572        let child = match object_take(parent, key) {
1573            Some(value) if is_object(&value) => value,
1574            _ => empty_object(),
1575        };
1576        levels.push(child);
1577    }
1578
1579    let mut current = section;
1580    for key in dive.iter().rev() {
1581        let mut parent = levels.pop().expect("one level per segment");
1582        object_insert(&mut parent, key.clone(), current);
1583        current = parent;
1584    }
1585    *root = current;
1586}
1587
1588/// How deep the parse is: the `map`, `list` and `dive` rules on the
1589/// stack, plus the rule the loop is working on, which the engine hands
1590/// over separately. Counted from the rule NAMES rather than
1591/// `rule_stack.len()`, because the stack holds about three rules per
1592/// container level and a length-based limit would encode that ratio.
1593fn depth(context: &Context) -> usize {
1594    let is_level = |name: &str| name == "map" || name == "list" || name == "dive";
1595    let ancestors = context
1596        .rule_stack
1597        .iter()
1598        .filter(|rule| is_level(&rule.name))
1599        .count();
1600    let current = usize::from(
1601        context
1602            .rule
1603            .as_ref()
1604            .is_some_and(|rule| is_level(&rule.name)),
1605    );
1606    ancestors + current
1607}
1608
1609/// The depth guard: [`DEPTH_LIMIT`] levels parse, the next one is
1610/// refused with the engine's `cancel` code.
1611fn within_depth_limit(context: &Context) -> bool {
1612    depth(context) <= DEPTH_LIMIT
1613}
1614
1615/// The name the depth check is installed under, as a parse guard: the
1616/// name jsonic's own check uses, so this one replaces it.
1617const DEPTH_GUARD: &str = "depth";
1618
1619// ---------------------------------------------------------------------
1620// The grammar's function references
1621// ---------------------------------------------------------------------
1622
1623/// The path this table is writing into, kept apart from `dive`.
1624///
1625/// `dive` on a table's `u` means "the header that opened the NEXT
1626/// table", because the next table reads it through `r.prev.u.dive`.
1627/// Recording the path under that name would make every table inherit
1628/// its predecessor's section.
1629const INI_PATH: &str = "ini_path";
1630
1631fn register_refs(parser: &mut Tabnas, resolved: &Resolved) {
1632    // --- state actions, wired by the @rule-phase convention ---
1633
1634    parser.state_action_ref("@ini-bo", |rule, context| {
1635        set_node(rule, empty_object());
1636        declared_clear(context);
1637        Ok(())
1638    });
1639
1640    let for_table_bo = Arc::new(resolved.clone());
1641    parser.state_action_ref("@table-bo", move |rule, context| {
1642        table_before_open(rule, context, &for_table_bo)
1643    });
1644
1645    parser.state_action_ref("@table-bc", table_before_close);
1646
1647    // Carry the completed child's dive path up. The canonical
1648    // TypeScript pushes onto an array the parent already holds, so the
1649    // parent sees the growth for free; a Rust rule cannot write its
1650    // parent's `u` bag, so each level reads its child's instead. The Go
1651    // port added `@dive-bc` for the same reason.
1652    parser.state_action_ref("@dive-bc", |rule, _context| {
1653        if let Some(dive) = rule
1654            .child_rule
1655            .as_ref()
1656            .and_then(|child| dive_of(child.u.get("dive")))
1657        {
1658            rule.u_mut().insert("dive".into(), dive_value(&dive));
1659        }
1660        Ok(())
1661    });
1662
1663    // --- alternate actions ---
1664
1665    parser.action_with_context("@table-close-dive", |rule, _context| {
1666        if let Some(dive) = rule
1667            .child_rule
1668            .as_ref()
1669            .and_then(|child| dive_of(child.u.get("dive")))
1670        {
1671            rule.u_mut().insert("dive".into(), dive_value(&dive));
1672        }
1673        Ok(())
1674    });
1675
1676    parser.action_with_context("@dive-push", |rule, _context| {
1677        let mut dive = rule
1678            .parent_rule
1679            .as_ref()
1680            .and_then(|parent| dive_of(parent.u.get("dive")))
1681            .unwrap_or_default();
1682        if let Some(existing) = dive_of(rule.u.get("dive")) {
1683            dive = existing;
1684        }
1685        let segment = rule.o0().map(token_string).unwrap_or_default();
1686        dive.push(segment);
1687        rule.u_mut().insert("dive".into(), dive_value(&dive));
1688        Ok(())
1689    });
1690
1691    parser.action_with_context("@pair-key-eq", pair_key_eq);
1692    parser.subscribe_lex(mark_array_key);
1693
1694    parser.action_with_context("@pair-key-bool", |rule, _context| {
1695        // The canonical `'string' === typeof key`, which is NOT the same
1696        // as "the token's text". A line holding nothing but a value
1697        // keyword (`true` on its own) carries the BOOLEAN on its token,
1698        // because hoover and the text matcher both resolve a keyword
1699        // that is the whole span, so TypeScript declares no key at all
1700        // and answers `{}`. Measured, with the checkouts beside this
1701        // repository: TypeScript `{}`, Go `{"true":true}`. TypeScript is
1702        // canonical, so this port follows it and not the sibling.
1703        let Some(key) = rule.o0().and_then(bool_key) else {
1704            return Ok(());
1705        };
1706        if let Some(parent) = rule
1707            .parent_rule
1708            .as_ref()
1709            .map(|parent| Rc::clone(&parent.node))
1710        {
1711            object_insert(&mut parent.borrow_mut(), key, Value::Bool(true));
1712        }
1713        Ok(())
1714    });
1715
1716    parser.action_with_context("@val-empty", |rule, _context| {
1717        set_node(rule, Value::String(String::new()));
1718        Ok(())
1719    });
1720
1721    // --- conditions ---
1722
1723    parser.alt_condition("@is-table-parent", |rule, _context| {
1724        rule.parent_rule
1725            .as_ref()
1726            .is_some_and(|parent| parent.name.as_str() == "table")
1727    });
1728
1729    parser.alt_condition("@is-table-grandparent", |rule, _context| {
1730        rule.parent_rule
1731            .as_ref()
1732            .and_then(|parent| parent.parent_rule.clone())
1733            .is_some_and(|grandparent| grandparent.name.as_str() == "table")
1734    });
1735
1736    parser.alt_condition("@is-duplicate-section", |rule, _context| {
1737        rule.u.contains_key("dupsec")
1738    });
1739
1740    // --- error alternates ---
1741
1742    // The duplicate itself. The dotted path is not any single token's
1743    // source, so it rides along as the `{section}` detail the message
1744    // template reads.
1745    parser.alt_error("@duplicate-section", |rule, context| {
1746        let mut token = alt_err_token(rule, context)?;
1747        let section = match rule.u.get("dupsec") {
1748            Some(Value::String(path)) => path.clone(),
1749            _ => String::new(),
1750        };
1751        token.bad_with_details(
1752            "duplicate_section",
1753            [("section".to_string(), Value::String(section))],
1754        );
1755        Some(token)
1756    });
1757
1758    // The section header ran out before its closing bracket, at a
1759    // newline or at the end of input. The dive rule opened on the `#DK`
1760    // segment token, so that token carries both the text for the
1761    // message and the position to point at.
1762    parser.alt_error("@dive-unterminated", |rule, context| {
1763        let mut token = alt_err_token(rule, context)?;
1764        token.bad("unterminated_section");
1765        Some(token)
1766    });
1767
1768    // Unreachable while `#CL` is removed from the fixed tokens, as it is
1769    // here and in the Go port. Registered because the grammar names it.
1770    parser.alt_error("@pair-close-err", |rule, _context| rule.c1().cloned());
1771}
1772
1773fn table_before_open(
1774    rule: &mut Rule,
1775    context: &mut Context,
1776    resolved: &Resolved,
1777) -> Result<(), ActionError> {
1778    // r.node = r.parent.node: the table writes into the document root
1779    // until a section header moves it.
1780    let Some(root) = rule
1781        .parent_rule
1782        .as_ref()
1783        .map(|parent| Rc::clone(&parent.node))
1784    else {
1785        return Ok(());
1786    };
1787    rule.node = Rc::clone(&root);
1788
1789    let Some(dive) = rule
1790        .prev_rule
1791        .as_ref()
1792        .and_then(|prev| dive_of(prev.u.get("dive")))
1793        .filter(|dive| !dive.is_empty())
1794    else {
1795        return Ok(());
1796    };
1797
1798    // A null character separates the segments, so a dot inside a key
1799    // cannot collide with the separator.
1800    let section_key = dive.join("\u{0}");
1801    let is_duplicate = declared_has(context, &section_key);
1802
1803    if is_duplicate && resolved.dup_section == Duplicate::Error {
1804        // Flag the rule and let this rule's error ALTERNATE raise the
1805        // coded error (see the grammar's table:open). Raising here is
1806        // not portable: Go discards a state action's return value, and
1807        // an error published on the context from a before-open hook is
1808        // overwritten when the alternates are matched.
1809        rule.u_mut()
1810            .insert("dupsec".into(), Value::String(dive.join(".")));
1811        return Ok(());
1812    }
1813
1814    let override_last = is_duplicate && resolved.dup_section == Duplicate::Override;
1815    let section = open_section(&mut root.borrow_mut(), &dive, override_last);
1816
1817    rule.u_mut().insert(INI_PATH.into(), dive_value(&dive));
1818    set_node(rule, section);
1819    declared_add(context, section_key);
1820    Ok(())
1821}
1822
1823fn table_before_close(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1824    // Object.assign(r.node, r.child.node). The child `map` and `dive`
1825    // rules SHARE this rule's node cell, so the merge is a copy of a map
1826    // onto itself: no change in any runtime, and in this one an
1827    // expensive one, because `child_node` is a second owner of the same
1828    // `Arc` and the first write copies the whole map. A document of
1829    // 5,000 sections paid that once per section. Skipping it when the
1830    // cells are the same object is what the canonical `Object.assign(x,
1831    // x)` does for free. The merge is kept for a child that genuinely
1832    // allocates its own node.
1833    let child_is_self = rule
1834        .child_rule
1835        .as_ref()
1836        .is_some_and(|child| Rc::ptr_eq(&child.node, &rule.node));
1837    if child_is_self {
1838        // Drop this rule's copy of its child's node as well. It is a
1839        // second owner of the same container, and the next write to the
1840        // document would copy the whole thing to get around it. Nothing
1841        // reads a `table` rule's child node after this point.
1842        rule.child_node = Value::Undefined;
1843    } else if let Value::Object(entries) = rule.child_node.clone() {
1844        let mut node = rule.node.borrow_mut();
1845        if is_object(&node) {
1846            for (key, value) in entries.iter() {
1847                object_insert(&mut node, key.clone(), value.clone());
1848            }
1849        }
1850    }
1851
1852    // Write the finished section back into the document root. The
1853    // canonical ports hold a live reference to the section object and
1854    // never need this; a Rust container is a value, so the tree is
1855    // reassembled on the way out.
1856    let Some(dive) = dive_of(rule.u.get(INI_PATH)) else {
1857        return Ok(());
1858    };
1859    let Some(root) = rule
1860        .parent_rule
1861        .as_ref()
1862        .map(|parent| Rc::clone(&parent.node))
1863    else {
1864        return Ok(());
1865    };
1866    let section = rule.node.borrow().clone();
1867    close_section(&mut root.borrow_mut(), &dive, section);
1868    Ok(())
1869}
1870
1871/// The lexer's mark on an array key, `k[]`, quoted or not: a transducer
1872/// part reading the rule passes (`alchemy/transduce.alc`) sees a token's
1873/// value but cannot strip a suffix, so in key position (anywhere but
1874/// inside a value) a key token whose string ends in `[]` past the
1875/// brackets carries the name before them in a one-element array. The
1876/// pair actions read it back, and a bare `k[]` line keeps declaring the
1877/// key `k[]`. The canonical TypeScript tests `2 < key.length` in UTF-16
1878/// code units, which any string ending in `[]` with a byte before them
1879/// meets alike.
1880fn mark_array_key(token: &mut Token, rule: &mut Rule, _context: &mut Context) {
1881    if rule.name.as_str() == "val" && rule.state == RuleState::Open {
1882        return;
1883    }
1884    let name = token.name.as_str();
1885    if name != "#HK" && name != "#ST" {
1886        return;
1887    }
1888    let text = match &token.val {
1889        Value::String(text) => text.as_str(),
1890        Value::Text(text) => text.string.as_str(),
1891        _ => return,
1892    };
1893    if text.len() > 2 && text.ends_with("[]") {
1894        let stripped = text[..text.len() - 2].to_string();
1895        token.val = Value::array(vec![Value::String(stripped)]);
1896    }
1897}
1898
1899/// The name the lexer marked an array key with ([`mark_array_key`]), when
1900/// the token carries one.
1901fn array_key_name(token: &Token) -> Option<String> {
1902    match &token.val {
1903        Value::Array(items) if items.len() == 1 => match &items[0] {
1904            Value::String(name) => Some(name.clone()),
1905            _ => None,
1906        },
1907        _ => None,
1908    }
1909}
1910
1911/// A key token's name, and whether the lexer marked it as an array key.
1912fn key_of(token: &Token) -> (String, bool) {
1913    match array_key_name(token) {
1914        Some(name) => (name, true),
1915        None => (token_string(token), false),
1916    }
1917}
1918
1919fn pair_key_eq(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
1920    // An array key, `k[]`, arrives from the lexer as its name in a
1921    // one-element array (`mark_array_key`).
1922    let (key, array_key) = rule.o0().map(key_of).unwrap_or_default();
1923
1924    // An array key adds to the array under its own spelling first, `k[]`,
1925    // which a `k[][] =` line made, then to the one under its name.
1926    if array_key {
1927        let spelt = format!("{key}[]");
1928        if matches!(
1929            object_get(&rule.node.borrow(), &spelt),
1930            Some(Value::Array(_))
1931        ) {
1932            rule.u_mut().insert("key".into(), Value::String(spelt));
1933            rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1934            return Ok(());
1935        }
1936    }
1937    let existing = object_get(&rule.node.borrow(), &key);
1938
1939    if matches!(existing, Some(Value::Array(_))) {
1940        rule.u_mut().insert("key".into(), Value::String(key));
1941        rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1942        return Ok(());
1943    }
1944
1945    if array_key {
1946        let array = match existing {
1947            Some(value) if !value.is_undefined() => Value::array(vec![value]),
1948            _ => Value::array(Vec::new()),
1949        };
1950        object_insert(&mut rule.node.borrow_mut(), key.clone(), array);
1951        rule.u_mut().insert("key".into(), Value::String(key));
1952        rule.u_mut().insert("ini_array".into(), Value::Bool(true));
1953        return Ok(());
1954    }
1955
1956    rule.u_mut().insert("key".into(), Value::String(key));
1957    rule.u_mut().insert("pair".into(), Value::Bool(true));
1958    Ok(())
1959}
1960
1961// ---------------------------------------------------------------------
1962// The val rule
1963// ---------------------------------------------------------------------
1964
1965/// Is this alternate the one that starts a list on `[`?
1966///
1967/// INI spells a section header `[a]`, so the JSON core's list alternate
1968/// has to go or `[a]` would open an array. It is identified by its group
1969/// tags rather than its position, because the position moves whenever
1970/// the layers below add an alternate. The tags are compared as a SET:
1971/// the canonical TypeScript joins them as `json,list` and this engine
1972/// stores them as `list,json`, and the alternate is the same one.
1973fn is_json_list_alt(alt: &AltSpec) -> bool {
1974    let mut tags: Vec<&str> = alt
1975        .g
1976        .split(',')
1977        .map(str::trim)
1978        .filter(|tag| !tag.is_empty())
1979        .collect();
1980    tags.sort_unstable();
1981    tags == ["json", "list"]
1982}
1983
1984fn install_val_rule(parser: &mut Tabnas, _resolved: &Resolved) {
1985    let os = parser.token("#OS");
1986    let cs = parser.token("#CS");
1987    let eq = parser.token("#EQ");
1988    let dot = parser.token("#DOT");
1989    let zz = parser.token("#ZZ");
1990    let st = parser.token("#ST");
1991
1992    parser.define_rule("val", move |spec| {
1993        // Clear the node this rule inherits from its parent, which is
1994        // the enclosing map. jsonic's own value alternates do it with
1995        // `@reset$`; the alternate hoover prepends for its `#HV` token
1996        // carries no action, so an INI value would keep the map.
1997        //
1998        // Not tidiness: jsonic's val before-close stashes the inherited
1999        // node in the rule's `u` bag, which holds a second handle on
2000        // that map for as long as the value rule lives, and the next key
2001        // written into it then copies the whole map through
2002        // `Arc::make_mut`. A document of n pairs cost n^2 without this
2003        // (4000 pairs took 2.2 seconds, 20,000 exhausted memory). The Go
2004        // port resets the node in its own `val` before-open hook.
2005        spec.add_bo(|rule, _context| set_node(rule, Value::Undefined));
2006
2007        let kept: Vec<AltSpec> = std::mem::take(&mut spec.open)
2008            .into_iter()
2009            .filter(|alt| !is_json_list_alt(alt))
2010            .collect();
2011
2012        // Since `[`, `]`, `=` and `.` are fixed tokens they are lexed
2013        // before hoover gets to run, so a value that STARTS with one of
2014        // them never reaches the endofline block. Concatenate the fixed
2015        // token's source with the rest of the value instead. All four
2016        // are alternatives for one slot, the TypeScript
2017        // `['#OS #CS #EQ #DOT']`.
2018        let mut open = vec![
2019            AltSpec {
2020                s: vec![vec![os, cs, eq, dot]],
2021                r: Some("val".to_string()),
2022                u: HashMap::from([("ini_prev".to_string(), Value::Bool(true))]),
2023                ..Default::default()
2024            },
2025            // End of input: an empty value.
2026            AltSpec {
2027                s: vec![vec![zz]],
2028                a: vec!["@val-empty".to_string()],
2029                ..Default::default()
2030            },
2031        ];
2032        open.extend(kept);
2033        spec.open = open;
2034
2035        spec.add_ac(move |rule, _context| val_after_close(rule, st));
2036    });
2037}
2038
2039/// The value `JSON.parse` gives a number literal too large for a double,
2040/// which is the one document `serde_json` refuses where `JSON.parse`
2041/// succeeds.
2042///
2043/// `JSON.parse("1e400")` is `Infinity` and `JSON.parse("-1e400")` is
2044/// `-Infinity`, because the specification rounds an unrepresentable
2045/// magnitude to the nearest double. `serde_json` reports
2046/// `number out of range` instead, and the caller then kept the source
2047/// text, so `a = '1e400'` was the STRING `"1e400"` in this port and the
2048/// number `Infinity` in the canonical one. A literal too SMALL to
2049/// represent is not affected: both readers round `1e-400` to zero.
2050///
2051/// `Some` only for a whole document that is one JSON number and whose
2052/// value is not finite. Anything else, including a number that overflows
2053/// INSIDE an array or an object, is left to the caller, which keeps the
2054/// text; `DIVERGENCE.md` records that remaining gap.
2055fn overflowed_json_number(text: &str) -> Option<f64> {
2056    // The JSON whitespace set, which `JSON.parse` also allows around a
2057    // top-level value.
2058    let trimmed = text.trim_matches([' ', '\t', '\n', '\r']);
2059    if !is_json_number(trimmed) {
2060        return None;
2061    }
2062    // A valid JSON number `serde_json` rejected can only be one it could
2063    // not fit in a double, so the parse below succeeds and is infinite.
2064    // Testing for that rather than assuming it keeps this arm from
2065    // quietly claiming any other failure.
2066    trimmed
2067        .parse::<f64>()
2068        .ok()
2069        .filter(|value| value.is_infinite())
2070}
2071
2072/// Whether the whole of `text` is a JSON number literal (RFC 8259
2073/// section 6). Rust's own float parser is wider than that grammar: it
2074/// takes `inf`, `NaN`, `+1`, `1.` and `.5`, none of which `JSON.parse`
2075/// accepts, so the grammar is checked here rather than inferred from a
2076/// successful parse.
2077fn is_json_number(text: &str) -> bool {
2078    let mut chars = text.chars().peekable();
2079    if chars.peek() == Some(&'-') {
2080        chars.next();
2081    }
2082    match chars.next() {
2083        // A leading zero admits no further integer digits.
2084        Some('0') => {}
2085        Some(digit) if digit.is_ascii_digit() => {
2086            while chars.peek().is_some_and(char::is_ascii_digit) {
2087                chars.next();
2088            }
2089        }
2090        _ => return false,
2091    }
2092    if chars.peek() == Some(&'.') {
2093        chars.next();
2094        if !chars.peek().is_some_and(char::is_ascii_digit) {
2095            return false;
2096        }
2097        while chars.peek().is_some_and(char::is_ascii_digit) {
2098            chars.next();
2099        }
2100    }
2101    if matches!(chars.peek(), Some('e' | 'E')) {
2102        chars.next();
2103        if matches!(chars.peek(), Some('+' | '-')) {
2104            chars.next();
2105        }
2106        if !chars.peek().is_some_and(char::is_ascii_digit) {
2107            return false;
2108        }
2109        while chars.peek().is_some_and(char::is_ascii_digit) {
2110            chars.next();
2111        }
2112    }
2113    chars.next().is_none()
2114}
2115
2116/// Rewrite every UNPAIRED surrogate escape in JSON source text to a
2117/// `�` escape, or `None` when there is none to rewrite.
2118///
2119/// `JSON.parse` accepts a lone surrogate: a JavaScript string is UTF-16,
2120/// so `"\ud800"` is a perfectly ordinary one-code-unit string. A Rust
2121/// `String` is scalar values and cannot hold one at all, so `serde_json`
2122/// refuses the document outright and the caller then kept the JSON
2123/// SOURCE as the value: `a = '["\ud800"]'` stopped being an array.
2124///
2125/// Substituting the replacement character keeps the TYPE and the SHAPE
2126/// of the value, which is the larger half of the canonical result, and
2127/// is what Go's `encoding/json` does here, so the two ports that cannot
2128/// hold a lone surrogate agree. The one character that differs is
2129/// recorded in `../DIVERGENCE.md`.
2130///
2131/// Scanned as bytes, which is safe because every character this looks at
2132/// (`"`, `\`, `u` and the hex digits) is ASCII, and because the only
2133/// slices taken start and end on one of them. An escape other than
2134/// `\uXXXX` takes the WHOLE next character with it, so a multi-byte one
2135/// cannot leave the cursor inside a character.
2136fn replace_lone_surrogates(text: &str) -> Option<String> {
2137    /// The code unit a `\uXXXX` escape at `at` names.
2138    fn escaped_unit(bytes: &[u8], at: usize) -> Option<u16> {
2139        if bytes.get(at) != Some(&b'\\') || bytes.get(at + 1) != Some(&b'u') {
2140            return None;
2141        }
2142        let digits = bytes.get(at + 2..at + 6)?;
2143        digits.iter().try_fold(0u16, |unit, byte| {
2144            let digit = (*byte as char).to_digit(16)?;
2145            Some(unit * 16 + digit as u16)
2146        })
2147    }
2148    const HIGH: std::ops::Range<u16> = 0xD800..0xDC00;
2149    const LOW: std::ops::Range<u16> = 0xDC00..0xE000;
2150
2151    let bytes = text.as_bytes();
2152    let mut repaired = String::new();
2153    let mut copied = 0usize;
2154    let mut index = 0usize;
2155    let mut in_string = false;
2156    let mut replaced = false;
2157    while index < bytes.len() {
2158        match bytes[index] {
2159            b'"' => {
2160                in_string = !in_string;
2161                index += 1;
2162            }
2163            b'\\' if in_string => match escaped_unit(bytes, index) {
2164                Some(unit)
2165                    if HIGH.contains(&unit)
2166                        && escaped_unit(bytes, index + 6)
2167                            .is_some_and(|next| LOW.contains(&next)) =>
2168                {
2169                    index += 12;
2170                }
2171                Some(unit) if HIGH.contains(&unit) || LOW.contains(&unit) => {
2172                    repaired.push_str(&text[copied..index]);
2173                    repaired.push_str("\\ufffd");
2174                    index += 6;
2175                    copied = index;
2176                    replaced = true;
2177                }
2178                Some(_) => index += 6,
2179                // Any other escape, whose escaped character may be
2180                // several bytes long.
2181                None => {
2182                    index += 1;
2183                    index += text[index..]
2184                        .chars()
2185                        .next()
2186                        .map_or(0, char::len_utf8)
2187                        .max(1);
2188                }
2189            },
2190            _ => index += 1,
2191        }
2192    }
2193
2194    replaced.then(|| {
2195        repaired.push_str(&text[copied..]);
2196        repaired
2197    })
2198}
2199
2200fn val_after_close(rule: &mut Rule, st: tabnas::Tin) {
2201    // A single-quoted value carries JSON: `k = '{"a":1}'` is the object.
2202    // An invalid document is kept as the string it already is.
2203    let single_quoted = rule
2204        .o0()
2205        .is_some_and(|token| token.tin == st && token.src.as_str().starts_with('\''));
2206    if single_quoted {
2207        let text = match &*rule.node.borrow() {
2208            Value::String(text) => Some(text.clone()),
2209            Value::Text(text) => Some(text.string.clone()),
2210            _ => None,
2211        };
2212        if let Some(text) = text {
2213            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) {
2214                set_node(rule, Value::from_json(&parsed));
2215            } else if let Some(number) = overflowed_json_number(&text) {
2216                set_node(rule, Value::Number(number));
2217            } else if let Some(repaired) = replace_lone_surrogates(&text) {
2218                // A lone surrogate is the other thing `JSON.parse`
2219                // accepts and `serde_json` refuses. Re-read the repaired
2220                // text rather than assuming it now parses: the document
2221                // may be invalid for some further reason, and then the
2222                // value stays the string it already is.
2223                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&repaired) {
2224                    set_node(rule, Value::from_json(&parsed));
2225                }
2226            }
2227        }
2228    }
2229
2230    // A value can start with more than one fixed token (`a = ==x`), and
2231    // each one replaced the val rule with a fresh one. Only the LAST val
2232    // in that chain runs this hook, so walk the whole chain: every link
2233    // contributes its token source, and every link's node is updated,
2234    // including the first, which is the rule the pair rule reads its
2235    // child node from. Stopping at the first link instead left that node
2236    // unset, and the pair then took the parent map as its value,
2237    // producing a circular result.
2238    if rule
2239        .prev_rule
2240        .as_ref()
2241        .is_some_and(|prev| prev.u.contains_key("ini_prev"))
2242    {
2243        let mut text = js_string(&rule.node.borrow());
2244        let mut cursor = rule.prev_rule.clone();
2245        while let Some(link) = cursor {
2246            if !link.u.contains_key("ini_prev") {
2247                break;
2248            }
2249            let source = link
2250                .o
2251                .first()
2252                .map(|token| token.src.as_str().to_string())
2253                .unwrap_or_default();
2254            text = format!("{source}{text}");
2255            // The canonical `p.node = r.node` (ts/src/ini.ts:530,
2256            // go/ini.go:1033), which this port had never carried. The
2257            // write goes THROUGH the cell rather than replacing it:
2258            // `link.node` is the very `Rc<RefCell<Value>>` the engine
2259            // froze as the parent's child link when the pair rule pushed
2260            // the FIRST val of this chain, so only a write into that cell
2261            // reaches the node the pair later reads. `set_node` swaps the
2262            // `Rc` instead, which leaves the frozen handle untouched.
2263            *link.node.borrow_mut() = Value::String(text.clone());
2264            cursor = link.prev_rule.clone();
2265        }
2266        set_node(rule, Value::String(text));
2267    }
2268
2269    // Deliberately NOT an `else` of the block above: an array entry
2270    // whose value starts with a fixed token (`k[] = [x`) needs both the
2271    // concatenation AND the push, or the entry is silently dropped.
2272    let Some(parent) = rule.parent_rule.clone() else {
2273        return;
2274    };
2275    if !parent.u.contains_key("ini_array") {
2276        return;
2277    }
2278    let Some(Value::String(key)) = parent.u.get("key").cloned() else {
2279        return;
2280    };
2281    // The array is read back off the parent's node rather than out of
2282    // its `u` bag: a Rust rule cannot write its parent's bag, and a
2283    // container here is a value rather than a reference, so the grown
2284    // array has to be stored back where the document will find it.
2285    let value = rule.node.borrow().clone();
2286    let mut node = parent.node.borrow_mut();
2287    let mut items = match object_get(&node, &key) {
2288        Some(Value::Array(items)) => (*items).clone(),
2289        _ => Vec::new(),
2290    };
2291    items.push(value);
2292    object_insert(&mut node, key, Value::array(items));
2293}
2294
2295// ---------------------------------------------------------------------
2296// The custom value matcher
2297// ---------------------------------------------------------------------
2298
2299/// The lexer configuration the value matcher reads: the `value.lex` flag
2300/// and the `value.def` table, so a keyword is resolved exactly as
2301/// hoover's endofline block resolves the values it lexes itself.
2302struct ValueConfig {
2303    lex: bool,
2304    definitions: HashMap<String, Value>,
2305}
2306
2307impl ValueConfig {
2308    fn from_options(options: &Options) -> Self {
2309        Self {
2310            lex: options.value.lex,
2311            definitions: options
2312                .value
2313                .definitions
2314                .iter()
2315                .map(|(source, definition)| {
2316                    (
2317                        source.clone(),
2318                        definition.val.clone().unwrap_or(Value::Undefined),
2319                    )
2320                })
2321                .collect(),
2322        }
2323    }
2324
2325    fn resolve(&self, text: &str) -> Value {
2326        if self.lex {
2327            if let Some(value) = self.definitions.get(text) {
2328                return value.clone();
2329            }
2330        }
2331        Value::String(text.to_string())
2332    }
2333}
2334
2335/// Register the custom value matcher.
2336///
2337/// It is needed when multiline continuation is on, or when inline
2338/// comments are active with whitespace-prefix detection, and it runs at
2339/// [`MULTILINE_ORDER`], just below hoover, so it sees a value first.
2340fn register_multiline(parser: &mut Tabnas, resolved: &Resolved) {
2341    let resolved = Arc::new(resolved.clone());
2342    parser.lex_match_factory_ref(MULTILINE_REF, move |options: &Options| {
2343        let config = Arc::new(ValueConfig::from_options(options));
2344        let resolved = Arc::clone(&resolved);
2345        let matcher: ImperativeLexMatcher = Arc::new(
2346            move |lexer: &mut Lexer<'_>, rule: &mut Rule, _context: &mut Context| {
2347                multiline_match(lexer, rule, &resolved, &config)
2348            },
2349        );
2350        Some(matcher)
2351    });
2352}
2353
2354fn multiline_match(
2355    lexer: &mut Lexer<'_>,
2356    rule: &Rule,
2357    resolved: &Resolved,
2358    config: &ValueConfig,
2359) -> Option<Token> {
2360    // Only in value context during a rule's open state, the same gate
2361    // hoover's endofline block applies.
2362    let parent_is_pair = rule.parent_rule.as_ref().is_some_and(|parent| {
2363        let name = parent.name.as_str();
2364        name == "pair" || name == "elem"
2365    });
2366    if !parent_is_pair || rule.state != RuleState::Open {
2367        return None;
2368    }
2369
2370    // Read forward lazily, never into a buffer. This matcher runs at
2371    // every value and what it can see is the rest of the document, so
2372    // collecting that first would make a document of n values cost n
2373    // squared. `rest` is always a character boundary: every step below
2374    // advances by whole characters.
2375    //
2376    // The value is read from `Lexer::window`, the text the lexer holds from
2377    // the cursor on: the whole source, or in a parse from a reader
2378    // (`lex.window`, admin ADR-30) a window of it. Every scan below that
2379    // reaches the window's end ends the value there: a continuation, a CRLF
2380    // or an escape whose second character the window does not hold is
2381    // taken as text, and a line end the window ends after is consumed. The
2382    // token then ends at the window's end, which the engine cuts again over
2383    // a window twice as far ahead while the source has more, so the value
2384    // ends where the whole text ends it.
2385    let source = lexer.window();
2386    let mut rest = source;
2387    let mut text = String::new();
2388
2389    while let Some(c) = rest.chars().next() {
2390        // An inline comment character ends the value.
2391        if resolved.inline_active && resolved.is_inline_char(c) {
2392            if resolved.esc_whitespace {
2393                // Only a comment when whitespace comes first.
2394                if matches!(text.chars().last(), Some(' ') | Some('\t')) {
2395                    break;
2396                }
2397                text.push(c);
2398                rest = &rest[c.len_utf8()..];
2399                continue;
2400            }
2401            break;
2402        }
2403
2404        // A continuation character before a newline joins the lines.
2405        if resolved.continuation == Some(c) {
2406            let after = &rest[c.len_utf8()..];
2407            if let Some(next) = after
2408                .strip_prefix('\n')
2409                .or_else(|| after.strip_prefix("\r\n"))
2410            {
2411                rest = next.trim_start_matches([' ', '\t']);
2412                continue;
2413            }
2414        }
2415
2416        // A newline ends the value, unless the next line is indented and
2417        // indent continuation is on. A lone carriage return is ordinary
2418        // text, as it is in the canonical port.
2419        if '\n' == c || rest.starts_with("\r\n") {
2420            let after = if '\r' == c { &rest[2..] } else { &rest[1..] };
2421            if resolved.indent && after.starts_with([' ', '\t']) {
2422                rest = after.trim_start_matches([' ', '\t']);
2423                text.push(' ');
2424                continue;
2425            }
2426            rest = after;
2427            break;
2428        }
2429
2430        // Escapes.
2431        if '\\' == c {
2432            let after = &rest[1..];
2433            if let Some(next) = after.chars().next() {
2434                if resolved.inline_active && resolved.esc_backslash && resolved.is_inline_char(next)
2435                {
2436                    text.push(next);
2437                    rest = &after[next.len_utf8()..];
2438                    continue;
2439                }
2440                if '\\' == next {
2441                    text.push('\\');
2442                    rest = &after[1..];
2443                    continue;
2444                }
2445            }
2446        }
2447
2448        text.push(c);
2449        rest = &rest[c.len_utf8()..];
2450    }
2451
2452    // Resolve the value keywords on the WHOLE trimmed value, exactly as
2453    // hoover's endofline block does for the values it lexes itself.
2454    let value = config.resolve(tabnas_hoover::js_trim(&text));
2455
2456    // Owned, which releases the borrow of the lexer's source before the
2457    // cursor is moved. It is what the token carries in any case.
2458    let consumed: String = source[..source.len() - rest.len()].to_string();
2459    let advance = consumed.chars().count();
2460
2461    let point = lexer.point();
2462    lexer.advance_chars(advance);
2463    let tin = lexer.token_tin("#HV");
2464    let mut token = lexer.token("#HV", tin, value, consumed, point);
2465    token
2466        .use_data_mut()
2467        .insert("block".to_string(), Value::String("endofline".to_string()));
2468    Some(token)
2469}