Skip to main content

tabnas_yaml/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3//! A core-subset YAML grammar plugin for the
4//! [`tabnas`](https://github.com/tabnas/parser) parsing engine.
5//!
6//! Unlike most tabnas grammars this one layers on
7//! [`tabnas_jsonic`](https://github.com/tabnas/jsonic) rather than on the
8//! bare engine: YAML's flow collections are relaxed JSON, and the block
9//! forms are added around jsonic's `val` / `map` / `list` / `pair` /
10//! `elem` rules.
11//!
12//! ```
13//! fn main() -> Result<(), Box<dyn std::error::Error>> {
14//!     let value = tabnas_yaml::parse("name: Alice\nitems:\n  - one\n  - two\n")?;
15//!     assert_eq!(
16//!         value.to_string(),
17//!         r#"{"name":"Alice","items":["one","two"]}"#
18//!     );
19//!     Ok(())
20//! }
21//! ```
22
23#![forbid(unsafe_code)]
24// The engine's error type is 664 bytes and every entry point returns it,
25// as the other tabnas crates' entry points do.
26#![allow(clippy::result_large_err)]
27
28use std::cell::RefCell;
29use std::rc::Rc;
30use std::sync::{Arc, OnceLock};
31
32use indexmap::IndexMap;
33use serde_json::json;
34use tabnas::{
35    Context, GrammarSpec, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_NR, TIN_ST, TIN_TX,
36    TIN_VL,
37};
38
39mod lex;
40mod source;
41mod state;
42mod text;
43
44/// Every `rust` fence in the README is compiled and run as a doctest.
45#[cfg(doctest)]
46#[doc = include_str!("../README.md")]
47mod readme_examples {}
48
49/// VERSION is this package's version. It MUST equal `ts/package.json`
50/// "version": the release orchestrator rewrites all three constants, and
51/// `tests/version_test.rs` fails the build if they drift. Mirrors
52/// `const VERSION` in `ts/src/yaml.ts` and `go/yaml.go`.
53pub const VERSION: &str = "0.5.34";
54
55/// The plugin name, which is also the key its options sit under.
56const PLUGIN_NAME: &str = "yaml";
57
58/// The error code for an alias whose anchor does not occur before it.
59/// Its template and hint are in [`options_document`].
60pub(crate) const UNDEFINED_ALIAS: &str = "yaml_undefined_alias";
61
62/// The error code for an alias inside the node its anchor names.
63pub(crate) const RECURSIVE_ALIAS: &str = "yaml_recursive_alias";
64
65/// Set on the instance once the plugin has installed. The install guard
66/// reads it together with the instance's rules ([`grammar_installed`]):
67/// a derived child inherits this decoration before it has any rule of its
68/// own, and a rule of the grammar's name from elsewhere comes without it.
69const INSTALLED: &str = "yaml-installed";
70
71/// Errors this crate returns are the engine's, re-exported so a caller
72/// does not need `tabnas` in scope to name them.
73pub use tabnas::TabnasError as YamlError;
74
75// --- BEGIN EMBEDDED yaml-grammar.jsonic ---
76const GRAMMAR_TEXT: &str = r##"
77# YAML Grammar Definition
78# Parsed by a standard Tabnas instance and passed to tabnas.grammar()
79# Function references (@ prefixed) are resolved against the refs map.
80# State handlers (bo/ao/bc/ac) remain wired in code, since they use
81# closures over per-parse state (anchors, pendingAnchors, etc.).
82
83{
84  # Amend val rule: YAML indent/element-marker handling.
85  rule: val: open: {
86    alts: [
87      # Doc-frame markers between docs mean an empty value here; back up so
88      # the stream rule consumes the marker and starts the next document.
89      { s: '#DS' b: 1 a: '@val-set-null' g: yaml }
90      { s: '#DE' b: 1 a: '@val-set-null' g: yaml }
91      { s: '#DR' b: 1 a: '@val-set-null' g: yaml }
92      # Indent followed by content: push indent rule.
93      { s: '#IN' c: '@val-indent-deeper' p: indent a: '@val-set-in-from-o0' g: yaml }
94      # Same indent followed by element marker: list value at map level.
95      { s: ['#IN' '#EL'] c: '@val-indent-eq-parent' p: yamlBlockList a: '@val-set-in-from-o0' g: yaml }
96      # End of input means empty value.
97      { s: '#ZZ' b: 1 a: '@val-set-null' g: yaml }
98      # Same or lesser indent after a colon means empty value — backtrack.
99      { s: '#IN' b: 1 u: { yamlEmpty: true } g: yaml }
100      # This value is a list: a sequence's entry, or a document's root. A
101      # block sequence cannot start on the line of the key it is the value
102      # of (key: - a), so a pair's value is not one here.
103      { s: '#EL' c: '@val-not-pair-value' p: yamlBlockList a: '@val-set-el-in' g: yaml }
104    ]
105    inject: { append: false }
106  }
107  rule: val: close: {
108    alts: [
109      # Doc-frame markers terminate val; back up for the stream rule.
110      { s: '#DS' b: 1 g: 'yaml,end' }
111      { s: '#DE' b: 1 g: 'yaml,end' }
112      { s: '#DR' b: 1 g: 'yaml,end' }
113      { s: '#IN' b: 1 g: 'yaml,close' }
114    ]
115    inject: { append: false }
116  }
117
118  # Indent rule: start for block content at a given indent.
119  rule: indent: open: [
120    # Key pair => map.
121    { s: ['#KEY' '#CL'] p: map b: 2 g: yaml }
122    # Element marker => block sequence. yamlBlockList, not jsonic's list:
123    # list reads a '[' as its own opening bracket, so a flow sequence as the
124    # first item (k:\n  - [1, 2]) became the block sequence itself, or
125    # failed at the next item (tabnas/yaml#88).
126    { s: '#EL' p: yamlBlockList g: yaml }
127    # Flow collection as a block-mapping value on the FOLLOWING line:
128    #     required:
129    #       [a, b, c]
130    # Valid YAML 1.2, and the inline spelling has always worked. The
131    # indent rule opens at the deeper indent and meets a
132    # flow opener, which only the val rule knows how to read, so hand it back
133    # one token so val sees the bracket or brace itself.
134    { s: '#OS' p: val b: 1 g: yaml }
135    { s: '#OB' p: val b: 1 g: yaml }
136    # Plain value after indent (for nested scalars).
137    { s: '#KEY' a: '@indent-plain-value' g: yaml }
138  ]
139
140  # YAML block list: handles "- " sequences without consuming "[".
141  rule: yamlBlockList: open: [
142    # Element value is a key-value map: - key: val
143    { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
144    # Default: push to val for the element's value.
145    { p: val g: yaml }
146  ]
147  rule: yamlBlockList: close: [
148    # Doc-frame markers terminate list; back up for the stream rule.
149    { s: '#DS' b: 1 g: 'yaml,end' }
150    { s: '#DE' b: 1 g: 'yaml,end' }
151    { s: '#DR' b: 1 g: 'yaml,end' }
152    # Indent followed by element marker: next element at same level.
153    { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
154    # Same or lesser indent: close list.
155    { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
156    # Element marker at top level (no preceding newline).
157    { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
158    { s: '#ZZ' b: 1 g: 'yaml,end' }
159  ]
160
161  # Subsequent elements in a yamlBlockList (via rotation).
162  rule: yamlBlockElem: open: [
163    { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
164    { p: val g: yaml }
165  ]
166  rule: yamlBlockElem: close: [
167    # Doc-frame markers terminate elem; back up for the stream rule.
168    { s: '#DS' b: 1 g: 'yaml,end' }
169    { s: '#DE' b: 1 g: 'yaml,end' }
170    { s: '#DR' b: 1 g: 'yaml,end' }
171    { s: ['#IN' '#EL'] c: '@t0-eq-in' r: yamlBlockElem g: 'yaml,comma' }
172    { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
173    { s: '#EL' r: yamlBlockElem g: 'yaml,comma' }
174    { s: '#ZZ' b: 1 g: 'yaml,end' }
175  ]
176
177  # Amend list rule: close on dedent or same-indent non-element.
178  rule: list: close: {
179    alts: [
180      # Doc-frame markers terminate list; back up for the stream rule.
181      { s: '#DS' b: 1 g: 'yaml,end' }
182      { s: '#DE' b: 1 g: 'yaml,end' }
183      { s: '#DR' b: 1 g: 'yaml,end' }
184      { s: '#IN' c: '@t0-le-in' b: 1 g: 'yaml,close' }
185    ]
186    inject: { append: false }
187  }
188
189  # Amend map rule: same-indent indent continues map with pair.
190  rule: map: open: {
191    alts: [
192      { s: '#IN' c: '@o0-eq-in' r: pair g: yaml }
193    ]
194    inject: { append: false }
195  }
196  rule: map: close: {
197    alts: [
198      # Doc-frame markers terminate map; back up for the stream rule.
199      { s: '#DS' b: 1 g: 'yaml,end' }
200      { s: '#DE' b: 1 g: 'yaml,end' }
201      { s: '#DR' b: 1 g: 'yaml,end' }
202      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
203    ]
204    inject: { append: false }
205  }
206
207  # Amend pair rule: end of input ends pair; dedent closes, same-indent repeats.
208  # Also handle YAML flow-mapping shapes Tabnas doesn't have natively:
209  # - implicit null values: {a, b: c}  — KEY followed directly by CA or CB
210  # - explicit-key marker:  {? k : v}  — leading #QM is consumed
211  rule: pair: open: {
212    alts: [
213      { s: ['#KEY' '#CA'] a: '@implicit-null-pair' b: 1 g: yaml }
214      { s: ['#KEY' '#CB'] a: '@implicit-null-pair' b: 1 g: yaml }
215      { s: ['#QM' '#KEY' '#CL'] p: val u: { pair: true } a: '@qm-pairkey' g: yaml }
216      { s: ['#QM' '#KEY' '#CA'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
217      { s: ['#QM' '#KEY' '#CB'] a: '@qm-implicit-null-pair' b: 1 g: yaml }
218      { s: '#ZZ' b: 1 g: 'yaml,end' }
219    ]
220    inject: { append: false }
221  }
222  rule: pair: close: {
223    alts: [
224      # Doc-frame markers terminate pair; back up for the stream rule.
225      { s: '#DS' b: 1 g: 'yaml,end' }
226      { s: '#DE' b: 1 g: 'yaml,end' }
227      { s: '#DR' b: 1 g: 'yaml,end' }
228      { s: '#IN' c: '@t0-eq-in' r: pair g: 'yaml,comma' }
229      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
230    ]
231    inject: { append: false }
232  }
233
234  # yamlElemMap: a mapping that starts in a sequence entry, "- key: val",
235  # or "[key: val]" in a flow sequence. It only opens the mapping (its
236  # before-open action makes the node) and hands the first pair, unread,
237  # to yamlElemPair, which reads every pair. A pair rule opening on the
238  # open mapping names the member in u.key before it pushes the value's
239  # rule, so a consumer that follows rule events has the key before a
240  # value that is a collection opens. When the rule that opened the
241  # mapping named the first member as well, that consumer was never told
242  # the key, and the first member's value opened ahead of it
243  # (tabnas/yaml#105).
244  rule: yamlElemMap: open: [
245    { s: ['#KEY' '#CL'] r: yamlElemPair b: 2 g: yaml }
246  ]
247
248  # Every pair in a yamlElemMap, the first included.
249  rule: yamlElemPair: open: [
250    { s: ['#KEY' '#CL'] p: val a: '@elem-key' g: yaml }
251  ]
252  rule: yamlElemPair: close: [
253    # Doc-frame markers terminate elem-pair; back up for the stream rule.
254    { s: '#DS' b: 1 g: 'yaml,end' }
255    { s: '#DE' b: 1 g: 'yaml,end' }
256    { s: '#DR' b: 1 g: 'yaml,end' }
257    { s: '#IN' c: '@t0-eq-map-in' r: yamlElemPair g: 'yaml,comma' }
258    { s: '#IN' b: 1 g: 'yaml,close' }
259    { s: '#CA' b: 1 g: 'yaml,comma' }
260    { s: '#CS' b: 1 g: 'yaml,close' }
261    { s: '#CB' b: 1 g: 'yaml,close' }
262    { s: '#ZZ' g: 'yaml,end' }
263  ]
264
265  # Amend elem rule for YAML sequences ("- key: val" at top level of [ ... ]).
266  # Also handle flow-sequence explicit-key entries: [? k : v] is a single-pair
267  # map element. Eat the leading #QM, then back up KEY+CL so yamlElemMap
268  # consumes them as a normal pair.
269  rule: elem: open: {
270    alts: [
271      { s: ['#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
272      { s: ['#QM' '#KEY' '#CL'] p: yamlElemMap b: 2 a: '@set-map-in' g: yaml }
273    ]
274    inject: { append: false }
275  }
276  rule: elem: close: {
277    alts: [
278      # Doc-frame markers terminate elem; back up for the stream rule.
279      { s: '#DS' b: 1 g: 'yaml,end' }
280      { s: '#DE' b: 1 g: 'yaml,end' }
281      { s: '#DR' b: 1 g: 'yaml,end' }
282      { s: ['#IN' '#EL'] c: '@t0-eq-in' r: elem g: 'yaml,comma' }
283      { s: '#IN' c: '@t0-eq-in' b: 1 g: 'yaml,close' }
284      { s: '#IN' c: '@t0-lt-in' b: 1 g: 'yaml,close' }
285      { s: '#EL' r: elem g: 'yaml,comma' }
286    ]
287    inject: { append: false }
288  }
289}
290"##;
291// --- END EMBEDDED yaml-grammar.jsonic ---
292
293/// The options this plugin takes.
294#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
295pub struct YamlOptions {
296    /// When true, a parse returns `{meta, content}` instead of bare
297    /// content. `meta` is a per-document `{directives, explicit, ended}`
298    /// object for a single document, or an array of them for a stream.
299    pub meta: bool,
300    /// The schema a plain scalar resolves by. `None`, the default, also
301    /// reads the YAML 1.1 booleans (`yes`, `no`, `on`, `off`) and jsonic's
302    /// number syntax (`1_000`, `0b11`).
303    pub schema: Option<Schema>,
304}
305
306/// A schema a plain scalar may be resolved by.
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum Schema {
309    /// The YAML 1.2 core schema (YAML 1.2.2, 10.3.2) and no other reading:
310    /// the YAML 1.1 booleans are strings, and a number is only a decimal
311    /// integer or float, a `0o` octal or a `0x` hexadecimal integer.
312    Core,
313}
314
315impl Schema {
316    /// The schema's name in the option bag.
317    fn name(self) -> &'static str {
318        match self {
319            Schema::Core => "core",
320        }
321    }
322}
323
324impl YamlOptions {
325    /// The option bag as the engine's plugin values.
326    fn to_value(self) -> Value {
327        let mut map = IndexMap::new();
328        map.insert("meta".to_string(), Value::Bool(self.meta));
329        if let Some(schema) = self.schema {
330            map.insert(
331                "schema".to_string(),
332                Value::String(schema.name().to_string()),
333            );
334        }
335        Value::object(map)
336    }
337}
338
339/// The schema an option bag names: `None` when it names none, and an
340/// error for a name this plugin does not know, so that a misspelling
341/// cannot leave the default on.
342fn schema_option(options: &Value) -> Result<Option<Schema>, PluginError> {
343    let named = match options {
344        Value::Object(map) => map.get("schema").cloned(),
345        _ => None,
346    };
347    match named {
348        None | Some(Value::Null | Value::Undefined) => Ok(None),
349        Some(Value::String(name)) if name == "core" => Ok(Some(Schema::Core)),
350        Some(other) => Err(PluginError(format!(
351            "yaml: unknown schema {}, expected 'core'",
352            other.to_json()
353        ))),
354    }
355}
356
357/// Whether this parse resolves plain scalars by the core schema alone.
358pub(crate) fn core_schema(context: &Context) -> bool {
359    matches!(
360        context.options.plugin.get(PLUGIN_NAME),
361        Some(Value::Object(map)) if matches!(map.get("schema"), Some(Value::String(name)) if name == "core")
362    )
363}
364
365// ---------------------------------------------------------------------
366// Value helpers
367// ---------------------------------------------------------------------
368
369/// Assign a rule's node: the Rust spelling of TypeScript `r.node = v`.
370///
371/// A pushed or replaced rule SHARES its parent's node cell, so writing
372/// through `rule.node.borrow_mut()` would overwrite the parent's node
373/// too. Assigning installs a fresh cell instead. The cell is borrowed
374/// directly only to mutate a container the rule genuinely shares.
375fn set_node(rule: &mut Rule, value: Value) {
376    rule.node = Rc::new(RefCell::new(value));
377}
378
379fn map_insert(node: &mut Value, key: String, value: Value) {
380    match node {
381        Value::Object(map) => {
382            Arc::make_mut(map).insert(key, value);
383        }
384        Value::MapRef(map) => {
385            Arc::make_mut(map).value.insert(key, value);
386        }
387        _ => {}
388    }
389}
390
391/// Set a member this grammar stores itself, outside the engine's pair
392/// rule: a key with no value in a flow mapping, and a sequence entry's
393/// pair. A key the mapping holds already is combined as jsonic's `pairval`
394/// combines one: through the grammar's `map.merge` when it has one, else
395/// merged deep under `map.extend`, the default, else replaced by the later
396/// value; an earlier null is replaced. So `- a: {b: 1}` and `a: {c: 2}` in
397/// one sequence entry merge as they do at the root, as the canonical
398/// TypeScript stores them.
399fn store_member(rule: &mut Rule, context: &mut Context, key: String, value: Value) {
400    let previous = map_entries(&rule.node.borrow()).and_then(|map| map.get(&key).cloned());
401    let value = match previous {
402        None | Some(Value::Null) | Some(Value::Undefined) => value,
403        Some(previous) => {
404            if let Some(merge) = context.options.map.merge.clone() {
405                merge(previous, value, rule, context)
406            } else if context.options.map.extend {
407                tabnas_jsonic::deep_merge(previous, value)
408            } else {
409                value
410            }
411        }
412    };
413    map_insert(&mut rule.node.borrow_mut(), key, value);
414}
415
416fn map_entries(node: &Value) -> Option<&IndexMap<String, Value>> {
417    match node {
418        Value::Object(map) => Some(map),
419        Value::MapRef(map) => Some(&map.value),
420        _ => None,
421    }
422}
423
424fn list_push(node: &mut Value, value: Value) {
425    match node {
426        Value::Array(items) => Arc::make_mut(items).push(value),
427        Value::ListRef(list) => Arc::make_mut(list).value.push(value),
428        _ => {}
429    }
430}
431
432/// Whether `typeof value === 'object'` would hold in JavaScript, with
433/// `null` excluded as the canonical guards exclude it.
434fn is_container(value: &Value) -> bool {
435    matches!(
436        value,
437        Value::Object(_) | Value::Array(_) | Value::MapRef(_) | Value::ListRef(_) | Value::Text(_)
438    )
439}
440
441/// A copy of an anchored value, as an alias presents it, the canonical
442/// implementation's `copyAnchored`. An alias is the anchored node again
443/// (YAML 1.2.2, 3.2.2.2), so every scalar is kept as it is, a number that
444/// is not finite included, where the JSON round trip the canonical
445/// implementation once copied with wrote one as null; and every container
446/// is rebuilt, so a merge into one alias cannot reach the anchor or another
447/// alias.
448fn deep_copy(value: &Value) -> Value {
449    match value {
450        Value::Object(map) => {
451            let mut out = IndexMap::new();
452            for (key, entry) in map.iter() {
453                out.insert(key.clone(), deep_copy(entry));
454            }
455            Value::object(out)
456        }
457        Value::MapRef(map) => {
458            let mut out = IndexMap::new();
459            for (key, entry) in map.value.iter() {
460                out.insert(key.clone(), deep_copy(entry));
461            }
462            Value::object(out)
463        }
464        Value::Array(items) => Value::array(items.iter().map(deep_copy).collect()),
465        Value::ListRef(list) => Value::array(list.value.iter().map(deep_copy).collect()),
466        Value::Text(text) => Value::String(text.string.clone()),
467        other => other.clone(),
468    }
469}
470
471/// `String(value)` as JavaScript spells it, which is how a non-string key
472/// becomes an object property name.
473pub(crate) fn string_of(value: &Value) -> String {
474    match value {
475        Value::Undefined => "undefined".to_string(),
476        Value::Null => "null".to_string(),
477        Value::Bool(flag) => flag.to_string(),
478        Value::Number(number) => js_number_to_string(*number),
479        Value::String(text) => text.clone(),
480        Value::Text(text) => text.string.clone(),
481        Value::Array(items) => items
482            .iter()
483            .map(|item| match item {
484                Value::Undefined | Value::Null => String::new(),
485                other => string_of(other),
486            })
487            .collect::<Vec<_>>()
488            .join(","),
489        Value::ListRef(list) => string_of(&Value::array(list.value.clone())),
490        Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
491    }
492}
493
494/// `String(number)` as JavaScript spells it: the shortest digit string
495/// that reads back as the same double, in plain decimal while the decimal
496/// point stays inside `(-6, 21]` and in exponent form outside it.
497fn js_number_to_string(number: f64) -> String {
498    if number.is_nan() {
499        return "NaN".to_string();
500    }
501    // Catches -0.0 as well: JavaScript spells both zeros "0".
502    if number == 0.0 {
503        return "0".to_string();
504    }
505    if number < 0.0 {
506        return format!("-{}", js_number_to_string(-number));
507    }
508    if number.is_infinite() {
509        return "Infinity".to_string();
510    }
511    let shortest = format!("{number:e}");
512    let shortest_k = shortest
513        .split_once('e')
514        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
515        .expect("a finite f64 always formats with an exponent");
516    let exponential = format!("{:.*e}", shortest_k - 1, number);
517    let (mantissa, exponent) = exponential
518        .split_once('e')
519        .expect("a finite f64 always formats with an exponent");
520    let digits = mantissa
521        .chars()
522        .filter(|digit| *digit != '.')
523        .collect::<String>();
524    let digits = digits.trim_end_matches('0');
525    let digits = if digits.is_empty() { "0" } else { digits };
526    let k = digits.len() as i32;
527    let n = exponent
528        .parse::<i32>()
529        .expect("a formatted exponent is an integer")
530        + 1;
531    if (k..=21).contains(&n) {
532        let mut text = digits.to_string();
533        text.push_str(&"0".repeat((n - k) as usize));
534        text
535    } else if (1..=21).contains(&n) {
536        let point = n as usize;
537        format!("{}.{}", &digits[..point], &digits[point..])
538    } else if (-5..=0).contains(&n) {
539        format!("0.{}{}", "0".repeat(-n as usize), digits)
540    } else {
541        let sign = if n - 1 < 0 { '-' } else { '+' };
542        let power = (n - 1).abs();
543        if k == 1 {
544            format!("{digits}e{sign}{power}")
545        } else {
546            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
547        }
548    }
549}
550
551/// `Number(text)`, the conversion the unary plus in the canonical scalar
552/// handler performs. `None` stands for `NaN`, which is how a plain scalar
553/// stays text.
554pub(crate) fn js_to_number(text: &str) -> Option<f64> {
555    let trimmed = text.trim_matches(js_space);
556    if trimmed.is_empty() {
557        return Some(0.0);
558    }
559    if let Some(radix) = match trimmed.get(..2) {
560        Some("0x" | "0X") => Some(16u32),
561        Some("0o" | "0O") => Some(8),
562        Some("0b" | "0B") => Some(2),
563        _ => None,
564    } {
565        let digits = &trimmed[2..];
566        if digits.is_empty() || !digits.chars().all(|d| d.is_digit(radix)) {
567            return None;
568        }
569        let mut value = 0.0f64;
570        for digit in digits.chars() {
571            value = value * f64::from(radix) + f64::from(digit.to_digit(radix).unwrap_or(0));
572        }
573        return Some(value);
574    }
575    let (sign, body) = match trimmed.strip_prefix('-') {
576        Some(rest) => (-1.0, rest),
577        None => (1.0, trimmed.strip_prefix('+').unwrap_or(trimmed)),
578    };
579    if body == "Infinity" {
580        return Some(sign * f64::INFINITY);
581    }
582    if !is_decimal_literal(body) {
583        return None;
584    }
585    body.parse::<f64>().ok().map(|value| sign * value)
586}
587
588/// JavaScript's `\s`, which is also its `StrWhiteSpace`: the ASCII
589/// blanks, the Unicode space separators, the two line separators and the
590/// byte-order mark. Rust's own `char::is_whitespace` is the `White_Space`
591/// property, which differs in both directions: it counts U+0085 and it
592/// does not count U+FEFF. Both of those decide a scalar here.
593pub(crate) fn js_space(character: char) -> bool {
594    matches!(
595        character,
596        '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
597            ..='\u{200a}'
598                | '\u{2028}'
599                | '\u{2029}'
600                | '\u{202f}'
601                | '\u{205f}'
602                | '\u{3000}'
603                | '\u{feff}'
604    )
605}
606
607/// The ECMAScript `StrUnsignedDecimalLiteral` shape, which is narrower
608/// than what Rust's own parser accepts: `inf`, `nan` and `1_0` are not
609/// numbers in JavaScript.
610fn is_decimal_literal(body: &str) -> bool {
611    let bytes = body.as_bytes();
612    let mut index = 0;
613    let mut integral = 0;
614    while index < bytes.len() && bytes[index].is_ascii_digit() {
615        index += 1;
616        integral += 1;
617    }
618    let mut fractional = 0;
619    if index < bytes.len() && bytes[index] == b'.' {
620        index += 1;
621        while index < bytes.len() && bytes[index].is_ascii_digit() {
622            index += 1;
623            fractional += 1;
624        }
625    }
626    if integral == 0 && fractional == 0 {
627        return false;
628    }
629    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
630        index += 1;
631        if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
632            index += 1;
633        }
634        let mut exponent = 0;
635        while index < bytes.len() && bytes[index].is_ascii_digit() {
636            index += 1;
637            exponent += 1;
638        }
639        if exponent == 0 {
640            return false;
641        }
642    }
643    index == bytes.len()
644}
645
646/// The number the core schema reads `text` as, or `None` when it reads a
647/// string: a decimal integer or float
648/// (`[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?`), an octal one
649/// (`0o[0-7]+`) or a hexadecimal one (`0x[0-9a-fA-F]+`). `0b11`, `1_000`,
650/// `0X1F`, `-0x30` and `Infinity` are strings under it. Mirrors the
651/// canonical `coreNumber`.
652pub(crate) fn core_number(text: &str) -> Option<f64> {
653    if let Some(digits) = text.strip_prefix("0o") {
654        if !digits.is_empty() && digits.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
655            return Some(text::radix_to_f64(digits, 8));
656        }
657        return None;
658    }
659    if let Some(digits) = text.strip_prefix("0x") {
660        if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_hexdigit()) {
661            return Some(text::radix_to_f64(digits, 16));
662        }
663        return None;
664    }
665    let body = text.strip_prefix(['-', '+']).unwrap_or(text);
666    let bytes = body.as_bytes();
667    let mut index = 0;
668    let digits = |index: &mut usize| {
669        let from = *index;
670        while *index < bytes.len() && bytes[*index].is_ascii_digit() {
671            *index += 1;
672        }
673        *index - from
674    };
675    if bytes.first() == Some(&b'.') {
676        index = 1;
677        if digits(&mut index) == 0 {
678            return None;
679        }
680    } else {
681        if digits(&mut index) == 0 {
682            return None;
683        }
684        if bytes.get(index) == Some(&b'.') {
685            index += 1;
686            digits(&mut index);
687        }
688    }
689    if matches!(bytes.get(index), Some(b'e' | b'E')) {
690        index += 1;
691        if matches!(bytes.get(index), Some(b'-' | b'+')) {
692            index += 1;
693        }
694        if digits(&mut index) == 0 {
695            return None;
696        }
697    }
698    if index != bytes.len() {
699        return None;
700    }
701    js_to_number(text)
702}
703
704/// `parseInt(text, 10)`. The leading run it skips is JavaScript's
705/// whitespace, which is not Rust's: `trim_start` would leave a
706/// byte-order mark in place and strip a next-line character.
707pub(crate) fn parse_int(text: &str) -> f64 {
708    let trimmed = text.trim_start_matches(js_space);
709    let bytes = trimmed.as_bytes();
710    let mut index = 0;
711    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
712        index += 1;
713    }
714    let start = index;
715    while index < bytes.len() && bytes[index].is_ascii_digit() {
716        index += 1;
717    }
718    if index == start {
719        return f64::NAN;
720    }
721    trimmed[..index].parse::<f64>().unwrap_or(f64::NAN)
722}
723
724/// `parseFloat(text)`, skipping the same JavaScript whitespace
725/// `parse_int` skips.
726pub(crate) fn parse_float(text: &str) -> f64 {
727    let trimmed = text.trim_start_matches(js_space);
728    let bytes = trimmed.as_bytes();
729    let mut index = 0;
730    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
731        index += 1;
732    }
733    if trimmed[index..].starts_with("Infinity") {
734        return if bytes.first() == Some(&b'-') {
735            f64::NEG_INFINITY
736        } else {
737            f64::INFINITY
738        };
739    }
740    let mut digits = 0;
741    while index < bytes.len() && bytes[index].is_ascii_digit() {
742        index += 1;
743        digits += 1;
744    }
745    if index < bytes.len() && bytes[index] == b'.' {
746        index += 1;
747        while index < bytes.len() && bytes[index].is_ascii_digit() {
748            index += 1;
749            digits += 1;
750        }
751    }
752    if digits == 0 {
753        return f64::NAN;
754    }
755    let mantissa_end = index;
756    if index < bytes.len() && (bytes[index] == b'e' || bytes[index] == b'E') {
757        let mut probe = index + 1;
758        if probe < bytes.len() && (bytes[probe] == b'+' || bytes[probe] == b'-') {
759            probe += 1;
760        }
761        let exponent_start = probe;
762        while probe < bytes.len() && bytes[probe].is_ascii_digit() {
763            probe += 1;
764        }
765        if probe > exponent_start {
766            index = probe;
767        }
768    }
769    trimmed[..index.max(mantissa_end)]
770        .parse::<f64>()
771        .unwrap_or(f64::NAN)
772}
773
774/// `parseInt(text, 16)`. Like `parse_int` it skips JavaScript's leading
775/// whitespace, takes an optional sign and then the LONGEST PREFIX that
776/// reads as hexadecimal, rather than demanding the whole string: the
777/// digits of a `\x`, `\u` or `\U` escape are a fixed-width window that
778/// routinely holds the closing quote or the rest of the line, and the
779/// canonical handler reads a number out of the window all the same.
780/// `NaN` when the prefix has no digit.
781pub(crate) fn parse_int_16(text: &str) -> f64 {
782    let trimmed = text.trim_start_matches(js_space);
783    let bytes = trimmed.as_bytes();
784    let mut index = 0;
785    let negative = bytes.first() == Some(&b'-');
786    if index < bytes.len() && (bytes[index] == b'+' || bytes[index] == b'-') {
787        index += 1;
788    }
789    // `parseInt` allows the `0x` prefix when the radix is 16.
790    if bytes.len() > index + 1
791        && bytes[index] == b'0'
792        && (bytes[index + 1] == b'x' || bytes[index + 1] == b'X')
793    {
794        index += 2;
795    }
796    let start = index;
797    let mut value = 0f64;
798    while index < bytes.len() && bytes[index].is_ascii_hexdigit() {
799        value = value * 16.0 + f64::from((bytes[index] as char).to_digit(16).expect("hex digit"));
800        index += 1;
801    }
802    if index == start {
803        return f64::NAN;
804    }
805    if negative {
806        -value
807    } else {
808        value
809    }
810}
811
812/// `String.fromCharCode(n)`, whose argument goes through `ToUint16`: a
813/// `NaN` becomes NUL rather than an error, which is why an unreadable
814/// `\x` or `\u` escape is a NUL in the canonical handler.
815pub(crate) fn to_uint16(number: f64) -> u32 {
816    if !number.is_finite() {
817        return 0;
818    }
819    let truncated = number.trunc();
820    let wrapped = truncated.rem_euclid(65536.0);
821    wrapped as u32
822}
823
824/// `String.fromCodePoint(n)`, which THROWS a `RangeError` for anything
825/// that is not a code point. `None` stands for the throw: the canonical
826/// matcher does not catch it, so the token is never produced and the
827/// document is refused.
828pub(crate) fn from_code_point(number: f64) -> Option<u32> {
829    if !number.is_finite() || number.trunc() != number {
830        return None;
831    }
832    if !(0.0..=1_114_111.0).contains(&number) {
833        return None;
834    }
835    Some(number as u32)
836}
837
838/// The plain scalars that are a value and not a string: the YAML 1.2 core
839/// schema's (YAML 1.2.2, 10.3.2), and unless `core` is set the YAML 1.1
840/// booleans too. Mirrors the canonical `VALUES` and `VALUES_CORE`.
841pub(crate) fn yaml_keyword(text: &str, core: bool) -> Option<Value> {
842    Some(match text {
843        "true" | "True" | "TRUE" => Value::Bool(true),
844        "false" | "False" | "FALSE" => Value::Bool(false),
845        "yes" | "Yes" | "YES" | "on" | "On" | "ON" if !core => Value::Bool(true),
846        "no" | "No" | "NO" | "off" | "Off" | "OFF" if !core => Value::Bool(false),
847        "null" | "Null" | "NULL" | "~" => Value::Null,
848        ".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => Value::Number(f64::INFINITY),
849        "-.inf" | "-.Inf" | "-.INF" => Value::Number(f64::NEG_INFINITY),
850        ".nan" | ".NaN" | ".NAN" => Value::Number(f64::NAN),
851        _ => return None,
852    })
853}
854
855// ---------------------------------------------------------------------
856// Grammar references
857// ---------------------------------------------------------------------
858
859/// The value a token carries as a mapping key, resolving an alias marker
860/// against the anchors recorded so far.
861fn extract_key(token: &Token, context: &Context) -> Value {
862    if token.tin == TIN_VL {
863        if let Value::Object(map) = &token.val {
864            if let Some(Value::String(name)) = map.get("__yamlAlias") {
865                return match state::map_get(context, state::ANCHORS, name) {
866                    Some(value) if !matches!(value, Value::Undefined) => value,
867                    _ => Value::String(format!("*{name}")),
868                };
869            }
870        }
871    }
872    if token.tin == TIN_ST || token.tin == TIN_TX {
873        token.val.clone()
874    } else {
875        Value::String(token.src.as_str().to_string())
876    }
877}
878
879fn token_key(rule: &Rule, index: usize, context: &Context) -> Value {
880    let token = if index == 0 { rule.o0() } else { rule.o1() };
881    token.map_or(Value::Undefined, |token| extract_key(token, context))
882}
883
884fn counter(rule: &Rule, name: &str) -> Option<i32> {
885    rule.n.get(name).copied()
886}
887
888fn token_number(value: &Value) -> Option<f64> {
889    match value {
890        Value::Number(number) => Some(*number),
891        _ => None,
892    }
893}
894
895/// The column the mapping of a block sequence's entry starts at, on the
896/// line of the source byte `at`: past the line's indentation and every
897/// `- ` that leads it, as a block scalar's explicit indent counts its key's
898/// column. `- a: 1` starts at 2, `-   a: 1` and `- - a: 1` at 4, and
899/// `- &x a: 1` at 2, where the anchor starts the mapping ahead of its first
900/// key's own token.
901fn entry_column(src: source::Src<'_>, at: usize) -> usize {
902    let at = src.clamp(at);
903    let mut line = src.line_start(at);
904    if line == 0 && src.starts_with(0, lex::BOM_TEXT) {
905        line = lex::BOM_TEXT.len();
906    }
907    let (mut column, mut index) = (0, line);
908    while index < at && src.is(index, b' ') {
909        column += 1;
910        index += 1;
911    }
912    while index < at && src.is(index, b'-') && matches!(src.at(index + 1), 0x20 | 0x09) {
913        column += 2;
914        index += 2;
915        while index < at && src.is(index, b' ') {
916            column += 1;
917            index += 1;
918        }
919    }
920    column
921}
922
923/// The column of the sequence entry's mapping whose pair this value is,
924/// when it is the value of one (`- a: ...`): the mapping's keys stand at
925/// that column, so the value nests only below it, as a block mapping's
926/// value nests only below its key.
927fn entry_map_in(rule: &Rule) -> Option<f64> {
928    let parent = rule.parent_rule.as_ref()?;
929    if parent.name.as_str() != "yamlElemPair" {
930        return None;
931    }
932    match rule.k.get("yamlMapIn") {
933        Some(Value::Number(column)) => Some(*column),
934        _ => None,
935    }
936}
937
938/// The name of the rule that pushed this one.
939fn parent_name(rule: &Rule) -> Option<&str> {
940    rule.parent_rule.as_ref().map(|parent| parent.name.as_str())
941}
942
943/// The name of the anchor an alias marker names: the value of an alias
944/// whose anchor was not recorded when it was read.
945fn alias_name(value: &Value) -> Option<&str> {
946    match value {
947        Value::Object(map) => match map.get("__yamlAlias") {
948            Some(Value::String(name)) => Some(name.as_str()),
949            _ => None,
950        },
951        _ => None,
952    }
953}
954
955/// The token `token`, marked bad, when it is an alias to an anchor whose
956/// node is still open: an alias inside the node it names, which would hold
957/// itself. A rule's action or handler that returns it fails the parse
958/// there, with the code. Mirrors the canonical `recursiveAlias`.
959fn recursive_alias(token: Option<&Token>, context: &Context) -> Option<Token> {
960    let token = token?;
961    if token.tin != TIN_VL {
962        return None;
963    }
964    let name = alias_name(&token.val)?;
965    if !state::anchor_open(context, name) {
966        return None;
967    }
968    let mut bad = token.clone();
969    bad.bad(RECURSIVE_ALIAS);
970    Some(bad)
971}
972
973/// The column of the token a mapping opens on, when that token is a key
974/// and its node is the first thing on its line, and 0 otherwise: a flow
975/// mapping's brace, or a key that follows something on its line
976/// (`--- a: 1`), keeps the indent of 0. The key's node starts at its
977/// properties, so `  &x a: 1` stands at 2 as `  a: 1` does. Mirrors the
978/// canonical `firstKeyColumn`.
979fn first_key_column(context: &mut Context) -> i32 {
980    let Some(token) = context.t0() else {
981        return 0;
982    };
983    if !matches!(token.tin, TIN_TX | TIN_NR | TIN_ST | TIN_VL) {
984        return 0;
985    }
986    let at = token.site.si;
987    let windowed = context.source.is_empty();
988    let kept = source::Kept::load(context, windowed);
989    let touched = std::cell::Cell::new(false);
990    let column = {
991        let src = kept.src(&context.source, &touched);
992        let at = src.clamp(at);
993        let line = lex::line_start_of(src, at);
994        let mut index = line;
995        while index < at && src.is(index, b' ') {
996            index += 1;
997        }
998        let column = src.slice(line, index).len();
999        while index < at && (src.is(index, b'&') || src.is(index, b'!')) {
1000            while index < at && !lex::blank(src.at(index)) {
1001                index += 1;
1002            }
1003            while index < at && lex::blank(src.at(index)) {
1004                index += 1;
1005            }
1006        }
1007        if index == at {
1008            i32::try_from(column).unwrap_or(0)
1009        } else {
1010            0
1011        }
1012    };
1013    kept.store(context);
1014    column
1015}
1016
1017fn t0_number(context: &Context) -> Option<f64> {
1018    context.t0().and_then(|token| token_number(&token.val))
1019}
1020
1021fn register_refs(parser: &mut Tabnas) {
1022    // The two lexer matchers.
1023    parser.imperative_lex_match_ref(lex::MATCHER, lex::yaml_matcher);
1024    parser.imperative_lex_match_ref(text::MATCHER, text::yaml_text);
1025
1026    // Conditions.
1027    parser.alt_condition("@val-indent-deeper", |rule, context| {
1028        let Some(t0) = t0_number(context) else {
1029            return false;
1030        };
1031        if let Some(Value::Number(list_in)) = rule.k.get("yamlListIn") {
1032            if t0 <= *list_in {
1033                return false;
1034            }
1035        }
1036        if entry_map_in(rule).is_some_and(|map_in| t0 <= map_in) {
1037            return false;
1038        }
1039        match rule.k.get("yamlIn") {
1040            Some(Value::Number(parent)) => t0 > *parent,
1041            _ => true,
1042        }
1043    });
1044    // A sequence at the indent of the key it is the value of, its
1045    // mapping's or a sequence entry's: `a:\n- x` and `- a:\n  - x`. The
1046    // key's column is the one that counts. A sequence entry's key stands at
1047    // its mapping's column, not at an enclosing mapping's, and a sequence
1048    // entry's own value has no key: a `-` at an enclosing indent is that
1049    // sequence's next entry.
1050    parser.alt_condition("@val-indent-eq-parent", |rule, context| {
1051        let Some(t0) = t0_number(context) else {
1052            return false;
1053        };
1054        match parent_name(rule) {
1055            Some("yamlElemPair") => {
1056                matches!(rule.k.get("yamlMapIn"), Some(Value::Number(map_in)) if t0 == *map_in)
1057            }
1058            Some("yamlBlockList" | "yamlBlockElem") => false,
1059            _ => matches!(rule.k.get("yamlIn"), Some(Value::Number(parent)) if t0 == *parent),
1060        }
1061    });
1062    // Whether a value may open a block sequence on its own line: not when
1063    // it is the value of a mapping's pair. YAML has no `key: - a`: a block
1064    // sequence starts on the line after its key.
1065    parser.alt_condition("@val-not-pair-value", |rule, _context| {
1066        !matches!(parent_name(rule), Some("pair" | "yamlElemPair"))
1067    });
1068    parser.alt_condition("@t0-eq-in", |rule, context| {
1069        matches!((t0_number(context), counter(rule, "in")),
1070            (Some(t0), Some(indent)) if t0 == f64::from(indent))
1071    });
1072    parser.alt_condition("@t0-le-in", |rule, context| {
1073        matches!((t0_number(context), counter(rule, "in")),
1074            (Some(t0), Some(indent)) if t0 <= f64::from(indent))
1075    });
1076    parser.alt_condition("@t0-lt-in", |rule, context| {
1077        matches!((t0_number(context), counter(rule, "in")),
1078            (Some(t0), Some(indent)) if t0 < f64::from(indent))
1079    });
1080    parser.alt_condition("@o0-eq-in", |rule, _context| {
1081        let open = rule.o0().and_then(|token| token_number(&token.val));
1082        matches!((open, counter(rule, "in")),
1083            (Some(value), Some(indent)) if value == f64::from(indent))
1084    });
1085    parser.alt_condition("@t0-eq-map-in", |rule, context| {
1086        matches!((t0_number(context), rule.k.get("yamlMapIn")),
1087            (Some(t0), Some(Value::Number(indent))) if t0 == *indent)
1088    });
1089
1090    // Actions.
1091    parser.action_with_context("@val-set-in-from-o0", |rule, _context| {
1092        if let Some(value) = rule.o0().and_then(|token| token_number(&token.val)) {
1093            rule.n_mut().insert("in".to_string(), value as i32);
1094        }
1095        Ok(())
1096    });
1097    parser.action_with_context("@val-set-null", |rule, _context| {
1098        set_node(rule, Value::Null);
1099        Ok(())
1100    });
1101    parser.action_with_context("@val-set-el-in", |rule, _context| {
1102        let column = rule.o0().map_or(0, |token| token.site.ci);
1103        rule.n_mut().insert("in".to_string(), column as i32 - 1);
1104        Ok(())
1105    });
1106    // A scalar on the line after its key is the value its token read: a
1107    // number, a boolean or null as well as a string (`a:\n  1` is 1). An
1108    // alias's marker is resolved by the val that pushed this rule.
1109    parser.action_with_context("@indent-plain-value", |rule, _context| {
1110        let node = rule
1111            .o0()
1112            .map_or(Value::Undefined, |token| token.val.clone());
1113        set_node(rule, node);
1114        Ok(())
1115    });
1116    parser.action_with_context("@set-map-in", |rule, context| {
1117        // A block sequence entry's mapping stands at the column its content
1118        // starts at. A flow sequence's pair (`[a: 1]`) keeps
1119        // `r.k.yamlMapIn = r.n.in + 2`, which no indent token reads; with no
1120        // `in` counter that is `undefined + 2`, which is NaN, and NaN never
1121        // equals the indent `@t0-eq-map-in` compares it to. A zero here
1122        // would instead make the comparison true at the outermost indent.
1123        let block = matches!(rule.name.as_str(), "yamlBlockList" | "yamlBlockElem");
1124        let indent = match rule.o0() {
1125            Some(token) if block => {
1126                // The token's line, as the lexer read it: the whole text,
1127                // or from a reader the lines the plugin keeps.
1128                let windowed = context.source.is_empty();
1129                let kept = source::Kept::load(context, windowed);
1130                let touched = std::cell::Cell::new(false);
1131                let column = entry_column(kept.src(&context.source, &touched), token.site.si);
1132                kept.store(context);
1133                column as f64
1134            }
1135            _ => counter(rule, "in").map_or(f64::NAN, |value| f64::from(value + 2)),
1136        };
1137        rule.k_mut()
1138            .insert("yamlMapIn".to_string(), Value::Number(indent));
1139        Ok(())
1140    });
1141    // A key that is an alias to an anchor whose node is still open is
1142    // refused there (`recursive_alias`).
1143    parser.action_with_match_ref("@elem-key", |rule, context, _alt| {
1144        if let Some(bad) = recursive_alias(rule.o0(), context) {
1145            return Ok(Some(bad));
1146        }
1147        let key = token_key(rule, 0, context);
1148        rule.u_mut().insert("key".to_string(), key);
1149        Ok(None)
1150    });
1151    parser.action_with_match_ref("@implicit-null-pair", |rule, context, _alt| {
1152        if let Some(bad) = recursive_alias(rule.o0(), context) {
1153            return Ok(Some(bad));
1154        }
1155        let key = token_key(rule, 0, context);
1156        rule.u_mut().insert("key".to_string(), key.clone());
1157        store_member(rule, context, string_of(&key), Value::Null);
1158        Ok(None)
1159    });
1160    parser.action_with_match_ref("@qm-pairkey", |rule, context, _alt| {
1161        if let Some(bad) = recursive_alias(rule.o1(), context) {
1162            return Ok(Some(bad));
1163        }
1164        let key = token_key(rule, 1, context);
1165        rule.u_mut().insert("key".to_string(), key);
1166        Ok(None)
1167    });
1168    parser.action_with_match_ref("@qm-implicit-null-pair", |rule, context, _alt| {
1169        if let Some(bad) = recursive_alias(rule.o1(), context) {
1170            return Ok(Some(bad));
1171        }
1172        let key = token_key(rule, 1, context);
1173        rule.u_mut().insert("key".to_string(), key.clone());
1174        store_member(rule, context, string_of(&key), Value::Null);
1175        Ok(None)
1176    });
1177
1178    // The stream rule's actions.
1179    parser.action_with_context("@yaml-apply-directive", |rule, context| {
1180        apply_directive(rule, context);
1181        Ok(())
1182    });
1183    parser.action_with_context("@yaml-mark-explicit", |_rule, context| {
1184        ensure_meta(context);
1185        set_meta_flag(context, "explicit", true);
1186        Ok(())
1187    });
1188    parser.action_with_context("@yaml-accum-doc", |rule, context| {
1189        accumulate_document(rule, context);
1190        Ok(())
1191    });
1192    parser.action_with_context("@yaml-accum-and-directive", |rule, context| {
1193        accumulate_document(rule, context);
1194        apply_directive(rule, context);
1195        Ok(())
1196    });
1197    parser.action_with_context("@yaml-finalize-stream", |rule, context| {
1198        finalize_stream(rule, context);
1199        Ok(())
1200    });
1201}
1202
1203// ---------------------------------------------------------------------
1204// The stream rule's bookkeeping
1205// ---------------------------------------------------------------------
1206
1207fn ensure_meta(context: &mut Context) {
1208    if context.u.get(state::CUR_META).is_none() {
1209        let mut meta = IndexMap::new();
1210        meta.insert("directives".to_string(), Value::array(Vec::new()));
1211        meta.insert("explicit".to_string(), Value::Bool(false));
1212        meta.insert("ended".to_string(), Value::Bool(false));
1213        context
1214            .u
1215            .insert(state::CUR_META.to_string(), Value::object(meta));
1216    }
1217}
1218
1219fn set_meta_flag(context: &mut Context, field: &str, value: bool) {
1220    ensure_meta(context);
1221    state::map_set(
1222        context,
1223        state::CUR_META,
1224        field.to_string(),
1225        Value::Bool(value),
1226    );
1227}
1228
1229fn flush_meta(context: &mut Context, ended: bool) {
1230    ensure_meta(context);
1231    if ended {
1232        set_meta_flag(context, "ended", true);
1233    }
1234    let meta = context
1235        .u
1236        .shift_remove(state::CUR_META)
1237        .unwrap_or(Value::Undefined);
1238    state::list_push(context, state::METAS, meta);
1239}
1240
1241fn apply_directive(rule: &mut Rule, context: &mut Context) {
1242    let source = rule.o0().map_or(String::new(), |token| {
1243        let src = token.src.as_str();
1244        if src.is_empty() {
1245            match &token.val {
1246                Value::String(text) => text.clone(),
1247                _ => String::new(),
1248            }
1249        } else {
1250            src.to_string()
1251        }
1252    });
1253    if let Some((handle, prefix)) = tag_directive(&source) {
1254        state::map_set(context, state::TAG_HANDLES, handle, Value::String(prefix));
1255    }
1256    ensure_meta(context);
1257    let mut directives = match state::map_get(context, state::CUR_META, "directives") {
1258        Some(Value::Array(items)) => (*items).clone(),
1259        _ => Vec::new(),
1260    };
1261    directives.push(Value::String(source));
1262    state::map_set(
1263        context,
1264        state::CUR_META,
1265        "directives".to_string(),
1266        Value::array(directives),
1267    );
1268}
1269
1270/// `%TAG <handle> <prefix>`, the only directive that changes a parse.
1271/// The canonical pattern is `^%TAG\s+(\S+)\s+(\S+)`, so the separator
1272/// is JavaScript's whitespace: `is_whitespace` and `split_whitespace`
1273/// would read a next-line character as a separator and a byte-order mark
1274/// as part of a field.
1275fn tag_directive(source: &str) -> Option<(String, String)> {
1276    let rest = source.strip_prefix("%TAG")?;
1277    if !rest.starts_with(js_space) {
1278        return None;
1279    }
1280    let mut fields = rest.split(js_space).filter(|field| !field.is_empty());
1281    let handle = fields.next()?;
1282    let prefix = fields.next()?;
1283    Some((handle.to_string(), prefix.to_string()))
1284}
1285
1286fn child_document(rule: &Rule) -> Option<Value> {
1287    (!rule.child_node.is_undefined()).then(|| rule.child_node.clone())
1288}
1289
1290fn accumulate_document(rule: &mut Rule, context: &mut Context) {
1291    let value = child_document(rule).unwrap_or(Value::Null);
1292    state::list_push(context, state::DOCS, value);
1293    // The close token says whether this document ended with `...`.
1294    let ended = rule.c0().is_some_and(|token| token.name.as_ref() == "#DE");
1295    flush_meta(context, ended);
1296}
1297
1298fn finalize_stream(rule: &mut Rule, context: &mut Context) {
1299    if let Some(value) = child_document(rule) {
1300        state::list_push(context, state::DOCS, value);
1301        flush_meta(context, false);
1302    } else if context.u.get(state::CUR_META).is_some() {
1303        // The final document was opened explicitly but its value
1304        // coalesced away: a bare `---` at end of stream, or the trailing
1305        // empty document of `---\n---\n---`. Restore the null the other
1306        // empty documents are given.
1307        state::list_push(context, state::DOCS, Value::Null);
1308        flush_meta(context, false);
1309    }
1310
1311    let documents = state::list_all(context, state::DOCS);
1312    let content = match documents.len() {
1313        0 => Value::Undefined,
1314        1 => documents[0].clone(),
1315        _ => Value::array(documents),
1316    };
1317
1318    let want_meta = matches!(
1319        context
1320            .options
1321            .plugin
1322            .get(PLUGIN_NAME)
1323            .and_then(|options| match options {
1324                Value::Object(map) => map.get("meta").cloned(),
1325                _ => None,
1326            }),
1327        Some(Value::Bool(true))
1328    );
1329
1330    let result = if want_meta {
1331        let metas = state::list_all(context, state::METAS);
1332        let meta = match metas.len() {
1333            0 => Value::Undefined,
1334            1 => metas[0].clone(),
1335            _ => Value::array(metas),
1336        };
1337        let mut wrapper = IndexMap::new();
1338        wrapper.insert("meta".to_string(), meta);
1339        wrapper.insert("content".to_string(), content);
1340        Value::object(wrapper)
1341    } else {
1342        content
1343    };
1344
1345    // A rotation through `r: stream` shares the start rule's node cell,
1346    // which is the parse root, so writing THROUGH the cell is the Rust
1347    // spelling of the canonical `ctx.root().node = result`.
1348    *rule.node.borrow_mut() = result;
1349}
1350
1351// ---------------------------------------------------------------------
1352// Rule lifecycle
1353// ---------------------------------------------------------------------
1354
1355fn wire_rules(parser: &mut Tabnas) {
1356    parser.define_rule("val", |spec| {
1357        spec.add_ao(|rule, context| {
1358            let pending = state::list_take(context, state::PENDING_ANCHORS);
1359            if !pending.is_empty() {
1360                // Only whether the open node was a scalar is ever read back,
1361                // so a container is recorded as `Undefined`: a clone of an
1362                // inherited container is a second handle on the parent's
1363                // accumulator (see below).
1364                let open_node = match &*rule.node.borrow() {
1365                    node if is_container(node) => Value::Undefined,
1366                    node => node.clone(),
1367                };
1368                name_anchors(rule, &pending, &open_node);
1369                for anchor in &pending {
1370                    if let Value::Object(entry) = anchor {
1371                        if let Some(Value::String(name)) = entry.get("n") {
1372                            state::hold_anchor(context, name, 1.0);
1373                        }
1374                    }
1375                }
1376                rule.u_mut()
1377                    .insert("yamlAnchors".to_string(), Value::array(pending));
1378                rule.u_mut()
1379                    .insert("yamlAnchorOpenNode".to_string(), open_node);
1380                // The arrays inside the anchored value are kept, behind a
1381                // stream that empties them, until the anchor is recorded
1382                // at this val's close ([`state::PRUNE_HOLD`]).
1383                state::hold_pruning(context, 1.0);
1384            }
1385            // A YAML alt that opens on `#IN` or `#EL` (pushing `indent` or
1386            // `yamlBlockList`, or backing up for an empty value) leaves this val's node as the cell
1387            // it inherited from its parent: the parent MAP when the value is
1388            // a pair's and starts on the next line. jsonic's val before-close
1389            // stashes a clone of that node (`u.openval`), a second `Arc` on
1390            // the map the pair is about to insert into, so every insert
1391            // copied the whole map and a mapping of N such values parsed in
1392            // O(N^2). jsonic's own alts reset the node when they open; these
1393            // do the same. The value is the child's either way.
1394            // The empty-value alt (`#IN`, backed up) is the same shape: the
1395            // val ends with no value, and the stash held the map while the
1396            // pair inserted that absence.
1397            let yaml_alt = matches!(
1398                rule.o0().map(|token| token.name.as_ref()),
1399                Some("#EL" | "#IN")
1400            );
1401            if yaml_alt && is_container(&rule.node.borrow()) {
1402                set_node(rule, Value::Undefined);
1403            }
1404        });
1405        spec.add_bc(|rule, _context| {
1406            if matches!(rule.u.get("yamlEmpty"), Some(Value::Bool(true))) {
1407                set_node(rule, Value::Undefined);
1408            }
1409        });
1410        spec.add_ac_with_state(Arc::new(|rule, context, _next, _out| {
1411            Ok(close_val(rule, context))
1412        }));
1413    });
1414
1415    parser.define_rule("indent", |spec| {
1416        spec.add_bc(|rule, _context| {
1417            if !rule.child_node.is_undefined() {
1418                let child = rule.child_node.clone();
1419                set_node(rule, child);
1420            }
1421        });
1422    });
1423
1424    parser.define_rule("yamlBlockList", |spec| {
1425        spec.add_bo(|rule, _context| {
1426            // A fresh cell, as `r.node = []` installs a fresh array.
1427            // Every rotation of this rule shares the cell it installs, so
1428            // the elements all land in one list, which is what the
1429            // canonical port passes along in `k.yamlBlockArr`.
1430            set_node(rule, Value::array(Vec::new()));
1431            set_indent_key(rule, "yamlListIn");
1432        });
1433        spec.add_bc(|rule, _context| {
1434            let value = if rule.child_node.is_undefined() {
1435                Value::Null
1436            } else {
1437                rule.child_node.clone()
1438            };
1439            list_push(&mut rule.node.borrow_mut(), value);
1440        });
1441    });
1442
1443    parser.define_rule("yamlBlockElem", |spec| {
1444        spec.add_bc(|rule, _context| {
1445            let value = if rule.child_node.is_undefined() {
1446                Value::Null
1447            } else {
1448                rule.child_node.clone()
1449            };
1450            list_push(&mut rule.node.borrow_mut(), value);
1451        });
1452    });
1453
1454    parser.define_rule("list", |spec| {
1455        spec.add_bo(|rule, _context| {
1456            set_indent_key(rule, "yamlListIn");
1457            // A YAML block sequence reaches `list` through the indent
1458            // rule's `#EL` alternate, with no `[` and no implicit-list
1459            // promotion, so neither of jsonic's array builders runs and
1460            // the node is still the inherited parent container. Allocate
1461            // the array here so the element pushes land in a list.
1462            if rule
1463                .parent_rule
1464                .as_ref()
1465                .is_some_and(|parent| parent.name.as_ref() == "indent")
1466            {
1467                set_node(rule, Value::array(Vec::new()));
1468            }
1469        });
1470    });
1471
1472    // A quoted `<<` key is an ordinary key: YAML resolves only a plain
1473    // `<<` to the merge key (the merge type is YAML 1.1's, and a quoted
1474    // scalar is always a string). The pair notes a quoted one on the
1475    // mapping's node cell, which every pair of a mapping shares, and the
1476    // map leaves that mapping unmerged, as the canonical port does.
1477    parser.define_rule("pair", |spec| {
1478        spec.add_ao_with_state(Arc::new(|rule, context, _next, _out| {
1479            let key = match rule.o0() {
1480                Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1481                other => other,
1482            };
1483            if let Some(bad) = recursive_alias(key, context) {
1484                return Ok(Some(bad));
1485            }
1486            hold_merge(rule, context);
1487            Ok(None)
1488        }));
1489        spec.add_bc(|rule, context| {
1490            note_literal_merge_key(rule, context);
1491        });
1492        spec.add_ac(|rule, context| {
1493            release_merge(rule, context);
1494        });
1495    });
1496
1497    parser.define_rule("map", |spec| {
1498        spec.add_bo(|rule, context| {
1499            if counter(rule, "in").is_none() {
1500                // No indent token came before this mapping: it is a
1501                // document's root, or a flow mapping. A root block mapping
1502                // stands at the column of its first key, which need not be
1503                // 0 (YAML 1.2.2, 9.1.1: a document's root node is indented
1504                // by -1, so any column is deeper).
1505                let column = first_key_column(context);
1506                rule.n_mut().insert("in".to_string(), column);
1507            }
1508            set_indent_key(rule, "yamlIn");
1509        });
1510        spec.add_ac(|rule, context| {
1511            if !state::map_take(context, state::LITERAL_MERGE, &cell_address(rule)) {
1512                // Each key a merge brings is named in the map's counters
1513                // as `<<key`, whose value is the number of the source it
1514                // came from, so the map's close pass names every key it
1515                // merged and where it took it: a host that reads the rule
1516                // passes (YAML's transducer part) writes those members of
1517                // those sources, and no other, as the mapping's last, as
1518                // `mergeMember` does in the canonical source.
1519                for (key, source) in apply_merge_keys(rule) {
1520                    rule.n_mut().insert(format!("<<{key}"), source);
1521                }
1522            }
1523        });
1524    });
1525
1526    // `yamlElemMap` only makes the map: its open alternate hands every
1527    // pair, the first included, to `yamlElemPair` (see the grammar), so it
1528    // never reaches a close phase and stores nothing itself.
1529    parser.define_rule("yamlElemMap", |spec| {
1530        spec.add_bo(|rule, _context| {
1531            set_node(rule, Value::object(IndexMap::new()));
1532        });
1533    });
1534
1535    parser.define_rule("yamlElemPair", |spec| {
1536        spec.add_bc(|rule, context| {
1537            store_elem_pair(rule, context);
1538        });
1539    });
1540}
1541
1542/// The val rule's after-close: an alias whose anchor was not yet recorded
1543/// when it was read is resolved, or refused when its anchor's node is
1544/// still open; and the anchors this val claimed are recorded, their nodes
1545/// now closed. A token returned is a refusal.
1546fn close_val(rule: &mut Rule, context: &mut Context) -> Option<Token> {
1547    let alias = alias_name(&rule.node.borrow()).map(str::to_string);
1548    if let Some(name) = alias {
1549        if state::anchor_open(context, &name) {
1550            // The alias's own token: this val's, or its indent child's when
1551            // the alias stands on the line after its key.
1552            let node = rule.node.borrow().clone();
1553            let own = rule.o0().filter(|token| token.val == node).cloned();
1554            let child = rule
1555                .child_rule
1556                .as_ref()
1557                .and_then(|child| child.o.first().filter(|token| token.val == node).cloned());
1558            let mut token = own.or(child).or_else(|| rule.o0().cloned())?;
1559            token.bad(RECURSIVE_ALIAS);
1560            return Some(token);
1561        }
1562        let resolved =
1563            state::map_get(context, state::ANCHORS, &name).map_or(Value::Undefined, |value| {
1564                if is_container(&value) {
1565                    deep_copy(&value)
1566                } else {
1567                    value
1568                }
1569            });
1570        set_node(rule, resolved);
1571    }
1572
1573    let Some(Value::Array(anchors)) = rule.u.get("yamlAnchors").cloned() else {
1574        return None;
1575    };
1576    let open_node = rule
1577        .u
1578        .get("yamlAnchorOpenNode")
1579        .cloned()
1580        .unwrap_or(Value::Undefined);
1581    let node = rule.node.borrow().clone();
1582    for anchor in anchors.iter() {
1583        let Value::Object(entry) = anchor else {
1584            continue;
1585        };
1586        let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
1587        let Some(Value::String(name)) = entry.get("n") else {
1588            continue;
1589        };
1590        // An inline anchor that named a scalar keeps that scalar: the
1591        // container this val ended up holding belongs to a later, deeper
1592        // value.
1593        if inline
1594            && !matches!(open_node, Value::Undefined | Value::Null)
1595            && !is_container(&open_node)
1596            && is_container(&node)
1597        {
1598            continue;
1599        }
1600        let value = if is_container(&node) {
1601            deep_copy(&node)
1602        } else {
1603            node.clone()
1604        };
1605        state::map_set(context, state::ANCHORS, name.clone(), value);
1606    }
1607    // The node has closed: an alias after it names a finished node.
1608    for anchor in anchors.iter() {
1609        if let Value::Object(entry) = anchor {
1610            if let Some(Value::String(name)) = entry.get("n") {
1611                state::hold_anchor(context, name, -1.0);
1612            }
1613        }
1614    }
1615    // Recorded: the hold this val raised at its open is released.
1616    state::hold_pruning(context, -1.0);
1617    None
1618}
1619
1620/// `r.k.<name> = r.n.in`, including when there is no `in` counter: the
1621/// canonical assignment writes `undefined` there, and every reader takes
1622/// that as "no enclosing indent". Writing a zero instead would make a
1623/// block sequence at the outermost indent look nested inside itself.
1624fn set_indent_key(rule: &mut Rule, name: &str) {
1625    let indent =
1626        counter(rule, "in").map_or(Value::Undefined, |value| Value::Number(f64::from(value)));
1627    rule.k_mut().insert(name.to_string(), indent);
1628}
1629
1630fn store_elem_pair(rule: &mut Rule, context: &mut Context) {
1631    let Some(key) = rule.u.get("key").cloned() else {
1632        return;
1633    };
1634    if matches!(key, Value::Null | Value::Undefined) {
1635        return;
1636    }
1637    // A pair whose value never arrived (`- a:` before the next entry) is
1638    // a null member, as `a:` at the root is: the canonical implementation
1639    // stores null for it, as the Go port does, and
1640    // `test/spec/sequence-of-mappings.tsv` pins the member.
1641    let child = if rule.child_node.is_undefined() {
1642        Value::Null
1643    } else {
1644        rule.child_node.clone()
1645    };
1646    store_member(rule, context, string_of(&key), child);
1647}
1648
1649/// Name, in the val's counters, each anchor it claims that its close may
1650/// record as its node: the counter `&name`, whose value is the val's own
1651/// instance number, and the counter `yamlAnchored`, of the same value,
1652/// which marks the val. A host that reads the rule passes (YAML's
1653/// transducer part) knows the anchored val as the one whose `yamlAnchored`
1654/// is its own `i`, keeps the events of its value, and writes them again at
1655/// an alias of a name. An inline anchor on a val that opened on a scalar
1656/// records that scalar or nothing (the val's after-close), so it is not
1657/// named. Mirrors `nameAnchors` in the canonical source.
1658fn name_anchors(rule: &mut Rule, anchors: &[Value], open_node: &Value) {
1659    let scalar = !matches!(open_node, Value::Undefined | Value::Null) && !is_container(open_node);
1660    // A parse of more rules than an `i32` counts names no anchor, so an
1661    // alias of one past them is refused rather than written wrong.
1662    let Ok(instance) = i32::try_from(rule.i) else {
1663        return;
1664    };
1665    for anchor in anchors {
1666        let Value::Object(entry) = anchor else {
1667            continue;
1668        };
1669        let inline = matches!(entry.get("i"), Some(Value::Bool(true)));
1670        let Some(Value::String(name)) = entry.get("n") else {
1671            continue;
1672        };
1673        if inline && scalar {
1674            continue;
1675        }
1676        rule.n_mut().insert(format!("&{name}"), instance);
1677        rule.n_mut().insert("yamlAnchored".to_string(), instance);
1678    }
1679}
1680
1681/// A plain `<<` holds a streaming host's pruning ([`state::PRUNE_HOLD`])
1682/// from its pair's open to its close: the map's after-close merges the
1683/// sources the `<<` value lists, and a sequence of them, emptied behind
1684/// the stream when its rule closed, would merge nothing.
1685fn hold_merge(rule: &mut Rule, context: &mut Context) {
1686    let token = match rule.o0() {
1687        Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1688        other => other,
1689    };
1690    let plain = token.is_some_and(|token| token.tin != TIN_ST);
1691    if plain && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
1692        rule.u_mut()
1693            .insert("yamlMergeHold".to_string(), Value::Bool(true));
1694        state::hold_pruning(context, 1.0);
1695    }
1696}
1697
1698/// The hold [`hold_merge`] raised, released as the merge key's pair closes.
1699fn release_merge(rule: &mut Rule, context: &mut Context) {
1700    if matches!(rule.u.get("yamlMergeHold"), Some(Value::Bool(true))) {
1701        rule.u_mut()
1702            .insert("yamlMergeHold".to_string(), Value::Bool(false));
1703        state::hold_pruning(context, -1.0);
1704    }
1705}
1706
1707/// Note a quoted `<<` key on the mapping it belongs to: the key a pair
1708/// names is `<<`, and its token is a quoted scalar's (`#ST`), the token
1709/// after the `?` of an explicit key in a flow mapping.
1710fn note_literal_merge_key(rule: &Rule, context: &mut Context) {
1711    let token = match rule.o0() {
1712        Some(token) if token.name.as_ref() == "#QM" => rule.o1(),
1713        other => other,
1714    };
1715    let quoted = token.is_some_and(|token| token.tin == TIN_ST);
1716    if quoted && matches!(rule.u.get("key"), Some(Value::String(key)) if key == "<<") {
1717        state::map_set(
1718            context,
1719            state::LITERAL_MERGE,
1720            cell_address(rule),
1721            Value::Bool(true),
1722        );
1723    }
1724}
1725
1726/// The address of a rule's node cell. A mapping's pairs share its cell,
1727/// and the cell lives as long as the parse that built it, so the address
1728/// names the mapping.
1729fn cell_address(rule: &Rule) -> String {
1730    format!("{:p}", Rc::as_ptr(&rule.node))
1731}
1732
1733/// Resolve a `<<` merge key in place: the merged entries are appended
1734/// after the explicit ones, and an explicit key always wins. It answers
1735/// the keys it merged, in the order it merged them, each with the number
1736/// of the source it came from: 1 for the mapping a `<<` names, and for a
1737/// sequence, the place of the mapping among the sequence's mappings,
1738/// counted from 1.
1739fn apply_merge_keys(rule: &mut Rule) -> Vec<(String, i32)> {
1740    let mut merged = Vec::new();
1741    let mut node = rule.node.borrow_mut();
1742    let Some(entries) = map_entries(&node) else {
1743        return merged;
1744    };
1745    let Some(merge) = entries.get("<<").cloned() else {
1746        return merged;
1747    };
1748    let sources = match &merge {
1749        Value::Array(items) => (**items).clone(),
1750        Value::ListRef(list) => list.value.clone(),
1751        other => vec![other.clone()],
1752    };
1753    match &mut *node {
1754        Value::Object(map) => {
1755            Arc::make_mut(map).shift_remove("<<");
1756        }
1757        Value::MapRef(map) => {
1758            Arc::make_mut(map).value.shift_remove("<<");
1759        }
1760        _ => {}
1761    }
1762    let mut number = 0;
1763    for source in sources {
1764        let Some(source_entries) = map_entries(&source) else {
1765            continue;
1766        };
1767        number += 1;
1768        let additions: Vec<(String, Value)> = source_entries
1769            .iter()
1770            .filter(|(key, _)| {
1771                map_entries(&node).is_some_and(|entries| !entries.contains_key(*key))
1772            })
1773            .map(|(key, value)| (key.clone(), value.clone()))
1774            .collect();
1775        for (key, value) in additions {
1776            merged.push((key.clone(), number));
1777            map_insert(&mut node, key, value);
1778        }
1779    }
1780    merged
1781}
1782
1783// ---------------------------------------------------------------------
1784// Installation
1785// ---------------------------------------------------------------------
1786
1787/// The lexer and option overlay this plugin needs, plus the `stream`
1788/// rule, which the canonical implementation also declares in code rather
1789/// than in the shared grammar file.
1790fn options_document() -> serde_json::Value {
1791    json!({
1792        "rule": {
1793            "stream": {
1794                "open": [
1795                    // A directive line: apply it, then look again.
1796                    { "s": "#DR", "a": "@yaml-apply-directive", "r": "stream", "g": "yaml" },
1797                    // An explicit document start: push val for its content.
1798                    { "s": "#DS", "a": "@yaml-mark-explicit", "p": "val", "g": "yaml" },
1799                    // A `...` with no document open terminates nothing, so
1800                    // it produces no document. Consume it and look again.
1801                    { "s": "#DE", "r": "stream", "g": "yaml" },
1802                    // End of source: close immediately.
1803                    { "s": "#ZZ", "b": 1, "g": "yaml" },
1804                    // The implicit first document.
1805                    { "p": "val", "g": "yaml" }
1806                ],
1807                "close": [
1808                    { "s": "#ZZ", "a": "@yaml-finalize-stream", "g": "yaml" },
1809                    { "s": "#DR", "a": "@yaml-accum-and-directive", "r": "stream", "g": "yaml" },
1810                    { "s": "#DE", "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" },
1811                    { "s": "#DS", "b": 1, "a": "@yaml-accum-doc", "r": "stream", "g": "yaml" }
1812                ]
1813            }
1814        },
1815        "options": {
1816            // A bare colon is not a YAML token; `: ` is, and the matcher
1817            // emits it.
1818            "fixed": { "token": { "#CL": null } },
1819            // A colon still ends unquoted text.
1820            "ender": ":",
1821            // YAML's quoting is not the engine's: both forms are lexed by
1822            // the YAML matcher, and a backtick is not a quote at all.
1823            "string": { "chars": "" },
1824            "lex": {
1825                "match": {
1826                    // Below the first built-in band, so YAML syntax is
1827                    // seen before the fixed-token matcher.
1828                    "yaml": { "order": 5e5, "make": "@yaml-matcher" },
1829                    // Between the number matcher and the text matcher,
1830                    // which is where `options.text.check` runs.
1831                    "yamlText": { "order": 7.5e6, "make": "@yaml-text" }
1832                }
1833            },
1834            // A document stream is the entry point, and it opens into the
1835            // shared `val` rule.
1836            "rule": { "start": "stream" },
1837            // This plugin's own error codes, with the templates and hints
1838            // the engine fills from the bad token. Each is declared in every
1839            // runtime and listed in tabnas.plugin.json.
1840            "error": {
1841                "yaml_undefined_alias": "undefined alias: {src}",
1842                "yaml_recursive_alias": "recursive alias: {src}",
1843                "yaml_tab_indent": "tab in indentation"
1844            },
1845            "hint": {
1846                "yaml_undefined_alias": "\nThe alias {src} names no anchor that occurs before it in the document.\nAn anchor is written &name on the node it names, and an alias can only\nname an anchor defined earlier.",
1847                "yaml_recursive_alias": "\nThe alias {src} names the anchor of a node it is inside, so the node\nwould hold itself. This parser gives a tree, which cannot. Anchor the\npart that repeats, and name that from outside it.",
1848                "yaml_tab_indent": "\nA tab stands in this line's indentation, before a mapping key or a\nsequence entry. YAML indents block structure with spaces alone, so the\nline's depth cannot be read. Indent the line with spaces."
1849            }
1850        }
1851    })
1852}
1853
1854/// jsonic's numbers are doubles, so `b: 2` arrives as `2.0`; the
1855/// alternate decoder reads an integer field as an integer. Put every
1856/// whole number back into integer form.
1857fn integral_numbers(value: serde_json::Value) -> serde_json::Value {
1858    match value {
1859        serde_json::Value::Number(number) => match number.as_f64() {
1860            Some(float) if float.fract() == 0.0 && float.abs() < 9.0e15 => json!(float as i64),
1861            _ => serde_json::Value::Number(number),
1862        },
1863        serde_json::Value::Array(items) => {
1864            serde_json::Value::Array(items.into_iter().map(integral_numbers).collect())
1865        }
1866        serde_json::Value::Object(fields) => serde_json::Value::Object(
1867            fields
1868                .into_iter()
1869                .map(|(key, value)| (key, integral_numbers(value)))
1870                .collect(),
1871        ),
1872        other => other,
1873    }
1874}
1875
1876/// The grammar document, parsed from the embedded jsonic text exactly as
1877/// the TypeScript and Go ports parse their copies of it.
1878fn grammar_document() -> Result<serde_json::Value, PluginError> {
1879    let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
1880        .map_err(|error| PluginError(format!("yaml: cannot parse the grammar text: {error}")))?;
1881    let document = integral_numbers(parsed.to_json());
1882    if document
1883        .get("rule")
1884        .and_then(serde_json::Value::as_object)
1885        .is_none()
1886    {
1887        return Err(PluginError(
1888            "yaml: the grammar text has no `rule` table".to_string(),
1889        ));
1890    }
1891    Ok(document)
1892}
1893
1894/// Install YAML on a jsonic-enabled `parser`.
1895///
1896/// ```
1897/// fn main() -> Result<(), Box<dyn std::error::Error>> {
1898///     let mut parser = tabnas_jsonic::make();
1899///     tabnas_yaml::yaml(&mut parser, &tabnas_yaml::YamlOptions::default())?;
1900///     assert_eq!(parser.parse("a: 1")?.to_string(), r#"{"a":1}"#);
1901///     Ok(())
1902/// }
1903/// ```
1904pub fn yaml(parser: &mut Tabnas, options: &YamlOptions) -> Result<(), PluginError> {
1905    // Guard against a second install on the same instance, which would
1906    // install the grammar twice. A derived child must not be caught by
1907    // it: `Tabnas::derive` copies the parent's decorations onto the child
1908    // before it re-runs the plugins, as the canonical TypeScript does, so
1909    // the child carries the mark and none of the grammar
1910    // (tabnas/parser#244). The guard therefore asks for both, the mark
1911    // this plugin set and a rule only this grammar installs: a child has
1912    // the mark alone and installs again, and an instance carrying a rule
1913    // of that name from elsewhere has the rule alone and goes on to the
1914    // checks below.
1915    if parser.decoration::<bool>(INSTALLED).is_some() && grammar_installed(parser) {
1916        return Ok(());
1917    }
1918    // This plugin reshapes jsonic's rules rather than declaring a whole
1919    // grammar, so an instance without them earns a clear refusal now
1920    // instead of a grammar that can parse nothing later.
1921    if !parser.rule_names().iter().any(|name| name == "val") {
1922        return Err(PluginError(
1923            "yaml: the jsonic grammar is not installed on this instance; \
1924             install tabnas_jsonic first"
1925                .to_string(),
1926        ));
1927    }
1928    parser.decorate(INSTALLED, true);
1929    parser.set_plugin_options(PLUGIN_NAME, options.to_value());
1930
1931    // The tokens the matcher emits by name, allocated before any grammar
1932    // names them.
1933    for name in ["#IN", "#EL", "#QM", "#DS", "#DE", "#DR"] {
1934        parser.token(name);
1935    }
1936
1937    register_refs(parser);
1938
1939    let spec = GrammarSpec::from_value(options_document())
1940        .map_err(|error| PluginError(format!("yaml: invalid option document: {error}")))?;
1941    parser
1942        .grammar(&spec)
1943        .map_err(|error| PluginError(format!("yaml: cannot apply the options: {error}")))?;
1944
1945    let spec = GrammarSpec::from_value(grammar_document()?)
1946        .map_err(|error| PluginError(format!("yaml: invalid grammar document: {error}")))?;
1947    parser
1948        .grammar(&spec)
1949        .map_err(|error| PluginError(format!("yaml: cannot apply the grammar: {error}")))?;
1950
1951    wire_rules(parser);
1952
1953    // Replaces jsonic's guard, which counts only jsonic's own containers
1954    // (see `DEPTH_GUARD`). A guard rather than the parse budget, which is
1955    // one slot a caller's `parse_budget` replaces: the limit holds
1956    // whatever budget the caller sets.
1957    parser.parse_guard(DEPTH_GUARD, within_depth_limit);
1958    Ok(())
1959}
1960
1961/// Whether this grammar's rules are on `parser`, judged by a rule only it
1962/// installs: `yamlBlockList`, the block sequence, from the grammar
1963/// document. Read with the [`INSTALLED`] mark: a derived child starts
1964/// with no rules of its own and earns the grammar again, and a second
1965/// `yaml` call on one instance returns early.
1966fn grammar_installed(parser: &Tabnas) -> bool {
1967    parser
1968        .rule_names()
1969        .iter()
1970        .any(|name| name == "yamlBlockList")
1971}
1972
1973/// How many containers a parse may hold before it is refused, with the
1974/// engine's `cancel` code: jsonic's number, so a flow collection, which
1975/// is jsonic's, is bounded where it always was.
1976///
1977/// The engine parses iteratively, but displaying, converting or dropping
1978/// a `Value` walks the tree with the call stack, so an unbounded document
1979/// ends the caller's process rather than returning an error: a compact
1980/// block sequence 64,000 levels deep parsed, and then overflowed a 2 MiB
1981/// stack when it was dropped. TypeScript and Go have no limit, which
1982/// `../DIVERGENCE.md` records.
1983const DEPTH_LIMIT: usize = 127;
1984
1985/// The name the depth check is installed under, as a parse guard.
1986///
1987/// It is the name jsonic installs its own check under, so this one
1988/// replaces it. jsonic's counts its `map` and `list` rules, which is all a
1989/// flow collection or an indented block collection uses, but a compact
1990/// block sequence (`- - - x`) nests through YAML's own rules, and under
1991/// jsonic's check it went unbounded.
1992const DEPTH_GUARD: &str = "depth";
1993
1994/// Whether a rule of this name holds a container: jsonic's `map` and
1995/// `list`, and YAML's own block collections. A block sequence opens as
1996/// `yamlBlockList` and, after its first entry, is replaced by
1997/// `yamlBlockElem`; a mapping that starts in a sequence entry opens as
1998/// `yamlElemMap` and is replaced by `yamlElemPair` before its first pair.
1999/// Each replacement shares the container's cell and takes its place on
2000/// the stack, so a container is counted once under whichever name it has
2001/// reached. jsonic's `pair` and `elem`, and `indent`, hold none.
2002fn is_container_rule(name: &str) -> bool {
2003    matches!(
2004        name,
2005        "map" | "list" | "yamlBlockList" | "yamlBlockElem" | "yamlElemMap" | "yamlElemPair"
2006    )
2007}
2008
2009/// How many containers are open: those on the rule stack, and the rule
2010/// the loop is working on, which the engine hands over apart from them.
2011///
2012/// Counted afresh at each step. Every level holds a container and a few
2013/// other rules, so the stack a step walks is bounded by the limit itself.
2014fn depth(context: &Context) -> usize {
2015    let ancestors = context
2016        .rule_stack
2017        .iter()
2018        .filter(|rule| is_container_rule(&rule.name))
2019        .count();
2020    let current = usize::from(
2021        context
2022            .rule
2023            .as_ref()
2024            .is_some_and(|rule| is_container_rule(&rule.name)),
2025    );
2026    ancestors + current
2027}
2028
2029/// The depth guard: [`DEPTH_LIMIT`] containers parse, the next one is
2030/// refused.
2031fn within_depth_limit(context: &Context) -> bool {
2032    depth(context) <= DEPTH_LIMIT
2033}
2034
2035/// The plugin form of [`yaml`], for [`Tabnas::use_plugin`]. Installed
2036/// this way the grammar is re-applied to derived instances, as every
2037/// native plugin is.
2038///
2039/// ```
2040/// fn main() -> Result<(), Box<dyn std::error::Error>> {
2041///     let mut parser = tabnas_jsonic::make();
2042///     parser.use_plugin(tabnas_yaml::plugin(), None)?;
2043///     assert_eq!(parser.parse("- a\n- b")?.to_string(), r#"["a","b"]"#);
2044///     Ok(())
2045/// }
2046/// ```
2047pub fn plugin() -> Plugin {
2048    Plugin::new(PLUGIN_NAME, |parser, options| {
2049        let meta = matches!(
2050            match options {
2051                Value::Object(map) => map.get("meta").cloned(),
2052                _ => None,
2053            },
2054            Some(Value::Bool(true))
2055        );
2056        let schema = schema_option(options)?;
2057        yaml(parser, &YamlOptions { meta, schema })
2058    })
2059    .with_defaults(YamlOptions::default().to_value())
2060}
2061
2062/// Build a YAML parser with caller options.
2063///
2064/// ```
2065/// fn main() -> Result<(), Box<dyn std::error::Error>> {
2066///     let parser = tabnas_yaml::make_with(tabnas_yaml::YamlOptions { meta: true, ..Default::default() });
2067///     let value = parser.parse("---\na: 1\n...")?;
2068///     assert_eq!(
2069///         value.to_string(),
2070///         r#"{"meta":{"directives":[],"explicit":true,"ended":true},"content":{"a":1}}"#
2071///     );
2072///     Ok(())
2073/// }
2074/// ```
2075#[must_use]
2076pub fn make_with(options: YamlOptions) -> Tabnas {
2077    let mut parser = tabnas_jsonic::make();
2078    parser
2079        .use_plugin(plugin(), Some(options.to_value()))
2080        .expect("the yaml grammar documents are fixed and valid");
2081    // Read a reader a window at a time (admin ADR-30): the plugin's
2082    // matcher and text check read the source through the window, asking
2083    // the engine to cut again over a wider one where a scan reaches its
2084    // end, and keep the lines before the cursor that their backward scans
2085    // read (`source.rs`); jsonic's base cuts its tokens with the engine's
2086    // own matchers. Set on the parser this crate makes whole, not in
2087    // [`plugin`], which a host may install beneath matchers of its own.
2088    parser
2089        .set_options(|options| options.lex.window = true)
2090        .expect("lex.window sets");
2091    parser
2092}
2093
2094/// Build a YAML parser with the default options.
2095///
2096/// ```
2097/// fn main() -> Result<(), Box<dyn std::error::Error>> {
2098///     let parser = tabnas_yaml::make();
2099///     assert_eq!(parser.parse("a:\n  b: 1")?.to_string(), r#"{"a":{"b":1}}"#);
2100///     Ok(())
2101/// }
2102/// ```
2103#[must_use]
2104pub fn make() -> Tabnas {
2105    make_with(YamlOptions::default())
2106}
2107
2108/// Parse a YAML source string with the shared default parser.
2109///
2110/// The parser is built once, on first use, and reused after that, as the
2111/// other two runtimes do. Reuse is safe: [`Tabnas::parse`] takes `&self`
2112/// and builds a fresh parse context per call, and every piece of
2113/// per-parse state this grammar keeps lives in that context.
2114///
2115/// ```
2116/// fn main() -> Result<(), Box<dyn std::error::Error>> {
2117///     let value = tabnas_yaml::parse("- 1\n- 2\n")?;
2118///     assert_eq!(value.to_string(), "[1,2]");
2119///     Ok(())
2120/// }
2121/// ```
2122pub fn parse(src: &str) -> Result<Value, YamlError> {
2123    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
2124    DEFAULT.get_or_init(make).parse(src)
2125}
2126
2127/// One optional alchemy translation source and its explicit entry point.
2128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2129pub struct TranslationPart {
2130    /// The definition a host calls after linking the source.
2131    pub entry: &'static str,
2132    /// The source text, or `None` for an entry supplied by alchemy.
2133    pub source: Option<&'static str>,
2134}
2135
2136/// The package-local structural translation interface.
2137#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2138pub struct TranslationParts {
2139    /// The complete `tabnas.plugin.json` text.
2140    pub manifest: &'static str,
2141    /// An optional lift from the grammar's events to its first read shape.
2142    pub lift: Option<TranslationPart>,
2143    /// An optional embedding of a plain tree in the format's schema, with its reverse.
2144    pub embed: Option<TranslationPart>,
2145    /// An optional render from the write shape to text.
2146    pub render: Option<TranslationPart>,
2147    /// An optional transducer: the format's JSON events from its parser's
2148    /// rule passes, for a host that reads parser events.
2149    pub transduce: Option<TranslationPart>,
2150}
2151
2152const TRANSLATION: TranslationParts = TranslationParts {
2153    manifest: include_str!("../translate/manifest.json"),
2154    lift: None,
2155    embed: None,
2156    render: Some(TranslationPart {
2157        entry: "yaml-render",
2158        source: Some(include_str!("../translate/render.alc")),
2159    }),
2160    transduce: Some(TranslationPart {
2161        entry: "yaml-transduce",
2162        source: Some(include_str!("../translate/transduce.alc")),
2163    }),
2164};
2165
2166/// Return YAML's immutable translation parts.
2167#[must_use]
2168pub const fn translate() -> Option<TranslationParts> {
2169    Some(TRANSLATION)
2170}
2171
2172/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
2173/// it. Its `translate` object is what a host that translates reads: the
2174/// shape YAML is read as and written from (`tree`), the file that holds
2175/// the render, the sentences that say what the render does not keep, and
2176/// the file that holds the transducer part (`transduce`), the document's
2177/// JSON events from the grammar's rule passes under its default options,
2178/// through which a host that reads parser events reads a document. The
2179/// crate embeds its own copies, `translate/manifest.json` and
2180/// `translate/transduce.alc`, since a packaged crate holds nothing outside
2181/// `rs/`; `tests/translate_test.rs` holds each copy to its file.
2182///
2183/// ```
2184/// assert!(tabnas_yaml::manifest_text().contains("\"translate\""));
2185/// ```
2186pub fn manifest_text() -> &'static str {
2187    TRANSLATION.manifest
2188}
2189
2190/// YAML's render, `alchemy/render.alc`, the file the manifest's
2191/// `translate.render` names: a library of alchemy definitions, with no
2192/// `export`, whose entry point `yaml-render` writes a tree's events as one
2193/// YAML document. A host links it with its own program. The crate embeds
2194/// its own copy, `translate/render.alc`, held to the file as the
2195/// manifest's is.
2196///
2197/// ```
2198/// assert!(tabnas_yaml::render_text().contains("def yaml-render [input]"));
2199/// ```
2200pub fn render_text() -> &'static str {
2201    match TRANSLATION.render {
2202        Some(part) => part.source.unwrap_or_default(),
2203        None => "",
2204    }
2205}