Skip to main content

tabnas_expr/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Pratt expression-operator plugin for the
4//! [tabnas](https://github.com/tabnas/parser) parser engine, layered on the
5//! [jsonic](https://github.com/tabnas/jsonic) relaxed-JSON base grammar.
6//!
7//! The algorithm is Pratt parsing, and draws heavily from the explanation
8//! written by Aleksey Kladov at
9//! <https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html>.
10//! See [`prattify`] for the core.
11//!
12//! Expressions parse into LISP-style S-expressions: an array whose first
13//! element describes the operator and whose remaining elements are the
14//! operand terms, so `1+2*3` becomes `["+", 1, ["*", 2, 3]]` once the
15//! operator descriptions are reduced to their source text. A caller
16//! supplied evaluator can reduce the tree to a value during the parse.
17//!
18//! TypeScript is canonical: `ts/src/expr.ts` defines the behaviour, the
19//! option names, the defaults and the order of alternates. The shared
20//! fixtures in `test/spec/*.tsv` are the parity contract across
21//! TypeScript, Go and Rust.
22//!
23//! ```
24//! fn main() -> Result<(), Box<dyn std::error::Error>> {
25//!     let value = tabnas_expr::parse("a:1+2*3")?;
26//!     assert_eq!(tabnas_expr::simplify(&value).to_string(),
27//!                r#"{"a":["+",1,["*",2,3]]}"#);
28//!     Ok(())
29//! }
30//! ```
31//!
32//! # Folding a finished tree
33//!
34//! A key operator ([`OpDef::key()`]) is an operation spelled as a map, a
35//! `$ref` say, recognised by the map's shape when [`fold`] walks a
36//! finished document and reduces each occurrence through a resolver, with
37//! the rest of the tree in reach through its [`Site`]. One fold can reduce
38//! the token operators too, on the live expression nodes inside
39//! [`parse_scope`]; a realized operator array is plain data to it.
40//!
41//! # Untrusted input
42//!
43//! A parsed expression is data, never instructions. This plugin reads
44//! expression text of unknown provenance and returns S-expressions for a
45//! caller supplied evaluator to reduce, and that hand-off is where hostile
46//! input could become execution. Treat every operand and operator as
47//! untrusted text, and never let a document select which evaluator or
48//! operator implementation runs.
49
50// The engine's error type is large by design (it carries the whole
51// rendered report), and the engine allows this lint at its own crate root
52// for the same reason.
53#![allow(clippy::result_large_err)]
54
55use std::cell::{Cell, RefCell};
56use std::collections::HashMap;
57use std::fmt;
58use std::rc::Rc;
59use std::sync::{Arc, OnceLock};
60
61use indexmap::IndexMap;
62
63use tabnas::{
64    AltMatch, AltSpec, Context, ListRef, Plugin, PluginError, Rule, RuleSnapshot, RuleSpec, Tabnas,
65    TabnasError, Tin, Token, Value, TIN_CA, TIN_CB, TIN_CL, TIN_CS, TIN_NR, TIN_OB, TIN_OS, TIN_ST,
66    TIN_TX, TIN_VL, TIN_ZZ,
67};
68
69/// VERSION is this crate's version. It MUST equal `ts/package.json`
70/// "version" and the `version` field in `rs/Cargo.toml`: the release
71/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
72/// the build if they drift. Mirrors `VERSION` in `ts/src/expr.ts` and
73/// `const VERSION` in `go/expr.go`.
74pub const VERSION: &str = "0.6.0";
75
76/// The name this plugin registers under.
77pub const PLUGIN_NAME: &str = "Expr";
78
79/// The README's Rust examples run as doctests, so a stale one fails the
80/// gate rather than misleading the reader. Its `toml` and `bash` fences
81/// are skipped; rustdoc runs only the `rust` ones.
82#[cfg(doctest)]
83#[doc = include_str!("../README.md")]
84mod readme_examples {}
85
86/// The error a failed parse produces, re-exported so callers need not
87/// depend on the engine crate directly.
88pub use tabnas::TabnasError as ExprError;
89
90// The tree layer: key operators and the fold over a finished tree.
91mod tree;
92
93pub use tree::{
94    fold, key_op_of, make_key_map, FoldCycle, FoldDynamic, FoldEntry, FoldError, FoldEvaluate,
95    FoldHit, FoldOptions, FoldReport, Inherit, KeyMap, Load, Path, Positions, Recognise, Seg, Site,
96    FOLD_CYCLE, FOLD_DEPTH, FOLD_INHERIT, FOLD_KEY, FOLD_MAX_STACK, FOLD_OPTION,
97};
98
99/// JavaScript's `Number.MIN_SAFE_INTEGER`, the binding power an operator
100/// with no declared `left` takes: it binds loosest on the left.
101pub const MIN_SAFE_INTEGER: i64 = -9_007_199_254_740_991;
102
103/// JavaScript's `Number.MAX_SAFE_INTEGER`, the binding power an operator
104/// with no declared `right` takes: it binds tightest on the right.
105pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
106
107// ---------------------------------------------------------------------------
108// Operator model
109// ---------------------------------------------------------------------------
110
111/// Paren preval configuration: whether a value may precede the opening
112/// paren (`foo(1)`, `a[1]`), whether one is required, and which values are
113/// allowed to.
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct PrevalDef {
116    pub active: bool,
117    pub required: bool,
118    pub allow: Option<Vec<String>>,
119}
120
121/// A paren operator's content: whether it may be empty, and whether it is
122/// a list of terms separated by commas.
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
124pub struct ContentDef {
125    /// The content may not be empty: `()` is refused, while a call that
126    /// admits none stays `f()`.
127    pub required: bool,
128    /// The content is a list of terms separated by commas, as a call's
129    /// arguments are, and each is a term of the operator (`f(a, b)` is
130    /// `[f, a, b]` under a call), so an infix operator on `,` does not
131    /// apply directly inside it.
132    pub separated: bool,
133}
134
135/// A cast's test of a group's content: whether the group before an
136/// operand, `(int)` in `(int)a`, is a cast. It sees the content as the
137/// parse built it, an expression node or a value. The Rust spelling of the
138/// canonical `accept`.
139#[derive(Clone)]
140pub struct Accept(Arc<dyn Fn(&Value) -> bool + Send + Sync>);
141
142impl Accept {
143    /// Wrap a test of a group's content.
144    pub fn new(test: impl Fn(&Value) -> bool + Send + Sync + 'static) -> Self {
145        Accept(Arc::new(test))
146    }
147
148    /// Whether the test accepts this content.
149    pub fn accepts(&self, term: &Value) -> bool {
150        (self.0)(term)
151    }
152}
153
154impl fmt::Debug for Accept {
155    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
156        formatter.write_str("Accept(<function>)")
157    }
158}
159
160/// Two tests are equal when they are the same function.
161impl PartialEq for Accept {
162    fn eq(&self, other: &Self) -> bool {
163        Arc::ptr_eq(&self.0, &other.0)
164    }
165}
166
167/// One entry of the `op` option map: the definition of an operator.
168///
169/// `src` carries one source string for a prefix, suffix or infix
170/// operator and two for a ternary (`["?", ":"]`); a paren operator uses
171/// `osrc` and `csrc` instead. A key operator's `src` is the member name
172/// that marks a site, `$ref` say.
173#[derive(Debug, Clone, PartialEq)]
174pub struct OpDef {
175    pub src: Vec<String>,
176    pub osrc: String,
177    pub csrc: String,
178    pub left: Option<i64>,
179    pub right: Option<i64>,
180    pub prefix: bool,
181    pub suffix: bool,
182    pub infix: bool,
183    pub ternary: bool,
184    pub paren: bool,
185    pub preval: Option<PrevalDef>,
186    /// Custom operator data, handed back to an evaluator as `op.use`.
187    pub use_data: Value,
188    /// A STRUCTURAL operator: an occurrence is a map that owns the member
189    /// named by `src`, recognised by its shape when a tree is folded
190    /// ([`fold`]), never by a token. No fixed token is registered for it,
191    /// so the base grammar keeps the key position, and no binding power
192    /// applies: its two terms are fixed by the shape, the member's value
193    /// and the map of the other members.
194    pub key: bool,
195    /// A key operator a fold recognises and reports but never evaluates,
196    /// such as `$dynamicRef`, whose meaning depends on a scope the parser
197    /// does not have. Its map folds as a plain map.
198    pub dynamic: bool,
199    /// A paren operator's content: see [`ContentDef`].
200    pub content: ContentDef,
201    /// An infix operator on `,` that gives way to the separator: wherever
202    /// an enclosing context separates on `,` (a list, a map, or a paren
203    /// whose content is separated) the comma separates, and only elsewhere
204    /// is it this operator. A group is such an elsewhere, even inside a
205    /// call.
206    pub separator: bool,
207    /// A CAST: a prefix operator whose token is a group (`(int)` in
208    /// `(int)a`) that `accept` accepts. `osrc` and `csrc` name the group,
209    /// which a paren operator of the table on the same opener and closer
210    /// parses; `right` is the cast's binding power, as a prefix's; `src`,
211    /// by default `osrc` and `csrc` together, is what [`simplify`] writes.
212    /// The operation's terms are the group's content and the operand. A
213    /// group `accept` refuses stays a group, or a call, and a cast without
214    /// `accept` accepts nothing.
215    pub cast: bool,
216    /// A cast's test of the group's content: see [`Accept`].
217    pub accept: Option<Accept>,
218}
219
220impl Default for OpDef {
221    fn default() -> Self {
222        OpDef {
223            src: Vec::new(),
224            osrc: String::new(),
225            csrc: String::new(),
226            left: None,
227            right: None,
228            prefix: false,
229            suffix: false,
230            infix: false,
231            ternary: false,
232            paren: false,
233            preval: None,
234            use_data: Value::Undefined,
235            key: false,
236            dynamic: false,
237            content: ContentDef::default(),
238            separator: false,
239            cast: false,
240            accept: None,
241        }
242    }
243}
244
245impl OpDef {
246    /// An infix operator with the given source and binding powers.
247    pub fn infix(src: impl Into<String>, left: i64, right: i64) -> Self {
248        OpDef {
249            src: vec![src.into()],
250            infix: true,
251            left: Some(left),
252            right: Some(right),
253            ..Default::default()
254        }
255    }
256
257    /// A prefix operator with the given source and right binding power.
258    pub fn prefix(src: impl Into<String>, right: i64) -> Self {
259        OpDef {
260            src: vec![src.into()],
261            prefix: true,
262            right: Some(right),
263            ..Default::default()
264        }
265    }
266
267    /// A suffix operator with the given source and left binding power.
268    pub fn suffix(src: impl Into<String>, left: i64) -> Self {
269        OpDef {
270            src: vec![src.into()],
271            suffix: true,
272            left: Some(left),
273            ..Default::default()
274        }
275    }
276
277    /// A ternary operator with its two source strings.
278    pub fn ternary(first: impl Into<String>, second: impl Into<String>) -> Self {
279        OpDef {
280            src: vec![first.into(), second.into()],
281            ternary: true,
282            ..Default::default()
283        }
284    }
285
286    /// A paren operator with its opening and closing source strings.
287    ///
288    /// Two paren operators may share an opener: a group, whose preval is
289    /// inactive, and a call or a subscript, whose preval is active. A value
290    /// before the opener selects the preval operator and no value the
291    /// group, so `(e)` and `e()` reach an evaluator as different
292    /// operators. Of two of one kind on an opener the later declared
293    /// applies, and an opener with no group uses an operator whose preval
294    /// is active and not required for both forms. The default `plain` is
295    /// left out of a table that has another paren operator on `(` and
296    /// `)`, unless the options change it.
297    pub fn paren(osrc: impl Into<String>, csrc: impl Into<String>) -> Self {
298        OpDef {
299            osrc: osrc.into(),
300            csrc: csrc.into(),
301            paren: true,
302            ..Default::default()
303        }
304    }
305
306    /// A key operator: a map that owns the member `src` is an occurrence
307    /// of it when a tree is folded.
308    pub fn key(src: impl Into<String>) -> Self {
309        OpDef {
310            src: vec![src.into()],
311            key: true,
312            ..Default::default()
313        }
314    }
315
316    /// A dynamic key operator: recognised and reported by a fold, never
317    /// evaluated.
318    pub fn dynamic_key(src: impl Into<String>) -> Self {
319        OpDef {
320            dynamic: true,
321            ..OpDef::key(src)
322        }
323    }
324
325    /// A cast on the group `osrc` `csrc`, with the binding power `right`,
326    /// whose content `accept` tests: see [`OpDef::cast`](OpDef#structfield.cast).
327    pub fn cast(
328        osrc: impl Into<String>,
329        csrc: impl Into<String>,
330        right: i64,
331        accept: impl Fn(&Value) -> bool + Send + Sync + 'static,
332    ) -> Self {
333        OpDef {
334            osrc: osrc.into(),
335            csrc: csrc.into(),
336            right: Some(right),
337            cast: true,
338            accept: Some(Accept::new(accept)),
339            ..Default::default()
340        }
341    }
342
343    /// Give a paren operator a preval configuration.
344    pub fn with_preval(mut self, preval: PrevalDef) -> Self {
345        self.preval = Some(preval);
346        self
347    }
348
349    /// Give a preval paren a binding power, compared like a suffix's with
350    /// the operator whose operand precedes it: where the paren binds no
351    /// tighter, it takes that operator's expression (`a.b[1]` is
352    /// `(a.b)[1]`). Unset, the paren binds to the value just before it.
353    pub fn with_left(mut self, left: i64) -> Self {
354        self.left = Some(left);
355        self
356    }
357
358    /// Give a paren operator a content configuration: see [`ContentDef`].
359    pub fn with_content(mut self, content: ContentDef) -> Self {
360        self.content = content;
361        self
362    }
363
364    /// Make an infix operator on `,` give way to separators: see
365    /// [`OpDef::separator`](OpDef#structfield.separator).
366    pub fn with_separator(mut self) -> Self {
367        self.separator = true;
368        self
369    }
370
371    /// Attach custom operator data, handed back to an evaluator.
372    pub fn with_use(mut self, use_data: Value) -> Self {
373        self.use_data = use_data;
374        self
375    }
376}
377
378/// The full operator description carried by a parsed expression and handed
379/// to an evaluator.
380#[derive(Debug, Clone, PartialEq)]
381pub struct Op {
382    pub name: String,
383    pub src: String,
384    pub left: i64,
385    pub right: i64,
386    pub use_data: Value,
387    pub prefix: bool,
388    pub suffix: bool,
389    pub infix: bool,
390    pub ternary: bool,
391    pub paren: bool,
392    pub terms: usize,
393    pub tkn: String,
394    pub tin: Tin,
395    pub osrc: String,
396    pub csrc: String,
397    pub otkn: String,
398    pub otin: Tin,
399    pub ctkn: String,
400    pub ctin: Tin,
401    pub preval: PrevalDef,
402    /// Which of a ternary's two source strings this operator is, as the
403    /// canonical `use.ternary.opI`. `None` for every other operator.
404    pub ternary_index: Option<usize>,
405    /// A key operator, recognised by a map's shape when a tree is folded:
406    /// see [`OpDef::key()`] and [`fold`].
407    pub key: bool,
408    /// A key operator a fold reports and never evaluates: see
409    /// [`OpDef::dynamic`].
410    pub dynamic: bool,
411    /// A paren operator's content: see [`ContentDef`].
412    pub content: ContentDef,
413    /// An infix operator on `,` that gives way to separators: see
414    /// [`OpDef::separator`](OpDef#structfield.separator).
415    pub separator: bool,
416    /// A cast, whose token is a group: see
417    /// [`OpDef::cast`](OpDef#structfield.cast).
418    pub cast: bool,
419    /// A cast's test of the group's content.
420    pub accept: Option<Accept>,
421}
422
423impl Default for Op {
424    fn default() -> Self {
425        Op {
426            name: String::new(),
427            src: String::new(),
428            left: MIN_SAFE_INTEGER,
429            right: MAX_SAFE_INTEGER,
430            use_data: Value::Undefined,
431            prefix: false,
432            suffix: false,
433            infix: false,
434            ternary: false,
435            paren: false,
436            terms: 0,
437            tkn: String::new(),
438            tin: -1,
439            osrc: String::new(),
440            csrc: String::new(),
441            otkn: String::new(),
442            otin: -1,
443            ctkn: String::new(),
444            ctin: -1,
445            preval: PrevalDef::default(),
446            ternary_index: None,
447            key: false,
448            dynamic: false,
449            content: ContentDef::default(),
450            separator: false,
451            cast: false,
452            accept: None,
453        }
454    }
455}
456
457impl Op {
458    /// The serialized operator description, with the canonical lower-case
459    /// key names. `token` is the occurrence's own token, so it is supplied
460    /// separately rather than carried on the shared description.
461    fn to_value(&self, token: Option<&Token>) -> Value {
462        let mut map: IndexMap<String, Value> = IndexMap::new();
463        map.insert("src".into(), Value::String(self.src.clone()));
464        map.insert("left".into(), number(self.left));
465        map.insert("right".into(), number(self.right));
466        map.insert("name".into(), Value::String(self.name.clone()));
467        map.insert("infix".into(), Value::Bool(self.infix));
468        map.insert("prefix".into(), Value::Bool(self.prefix));
469        map.insert("suffix".into(), Value::Bool(self.suffix));
470        map.insert("ternary".into(), Value::Bool(self.ternary));
471        map.insert("tkn".into(), Value::String(self.tkn.clone()));
472        map.insert("tin".into(), Value::Number(f64::from(self.tin)));
473        map.insert("terms".into(), Value::Number(self.terms as f64));
474        map.insert("use".into(), self.use_value());
475        map.insert("paren".into(), Value::Bool(self.paren));
476        map.insert("osrc".into(), Value::String(self.osrc.clone()));
477        map.insert("csrc".into(), Value::String(self.csrc.clone()));
478        map.insert("otkn".into(), Value::String(self.otkn.clone()));
479        map.insert("ctkn".into(), Value::String(self.ctkn.clone()));
480        map.insert("otin".into(), Value::Number(f64::from(self.otin)));
481        map.insert("ctin".into(), Value::Number(f64::from(self.ctin)));
482        map.insert("preval".into(), self.preval_value());
483        // In the canonical key order: TypeScript's operator builder lists
484        // `content`, `separator` and `cast` after `preval`, then `key` and
485        // `dynamic`, and `token` last. A cast's `accept` is a function,
486        // which JSON leaves out.
487        let mut content: IndexMap<String, Value> = IndexMap::new();
488        content.insert("required".into(), Value::Bool(self.content.required));
489        content.insert("separated".into(), Value::Bool(self.content.separated));
490        map.insert("content".into(), Value::object(content));
491        map.insert("separator".into(), Value::Bool(self.separator));
492        map.insert("cast".into(), Value::Bool(self.cast));
493        map.insert("key".into(), Value::Bool(self.key));
494        map.insert("dynamic".into(), Value::Bool(self.dynamic));
495        map.insert("token".into(), token_value(token));
496        Value::object(map)
497    }
498
499    fn use_value(&self) -> Value {
500        let mut used: IndexMap<String, Value> = match &self.use_data {
501            Value::Object(entries) => (**entries).clone(),
502            _ => IndexMap::new(),
503        };
504        if let Some(index) = self.ternary_index {
505            let mut ternary: IndexMap<String, Value> = IndexMap::new();
506            ternary.insert("opI".into(), Value::Number(index as f64));
507            used.insert("ternary".into(), Value::object(ternary));
508        }
509        Value::object(used)
510    }
511
512    fn preval_value(&self) -> Value {
513        let mut preval: IndexMap<String, Value> = IndexMap::new();
514        preval.insert("active".into(), Value::Bool(self.preval.active));
515        preval.insert("required".into(), Value::Bool(self.preval.required));
516        if let Some(allow) = &self.preval.allow {
517            preval.insert(
518                "allow".into(),
519                Value::array(allow.iter().cloned().map(Value::String).collect()),
520            );
521        }
522        Value::object(preval)
523    }
524}
525
526/// A binding power as a `Value`. The powers are integers on a scale whose
527/// ends are JavaScript's safe-integer bounds, and every one of them is
528/// exactly representable as an `f64`.
529fn number(value: i64) -> Value {
530    Value::Number(value as f64)
531}
532
533/// The occurrence token an operator carries, under the canonical key
534/// names, so that an evaluator can report where a term came from.
535fn token_value(token: Option<&Token>) -> Value {
536    let Some(token) = token else {
537        return Value::object(IndexMap::new());
538    };
539    let mut map: IndexMap<String, Value> = IndexMap::new();
540    map.insert("isToken".into(), Value::Bool(true));
541    map.insert("name".into(), Value::String(token.name.as_str().into()));
542    map.insert("tin".into(), Value::Number(f64::from(token.tin)));
543    map.insert("src".into(), Value::String(token.src.as_str().into()));
544    map.insert("len".into(), Value::Number(token.len as f64));
545    map.insert("sI".into(), Value::Number(token.site.pos as f64));
546    map.insert("rI".into(), Value::Number(token.site.ri as f64));
547    map.insert("cI".into(), Value::Number(token.site.ci as f64));
548    Value::object(map)
549}
550
551// ---------------------------------------------------------------------------
552// Options
553// ---------------------------------------------------------------------------
554
555/// The site an evaluator is called from: the rule the reduction belongs to
556/// and the live parse context, and neither when [`evaluation`] is called on
557/// a finished tree.
558///
559/// The rule is a snapshot rather than the live rule, because the canonical
560/// port hands the evaluator the PARENT of the rule that is closing, which
561/// this engine exposes as a snapshot. Its state, its `u` flags and its node
562/// cell are all reachable through it.
563pub struct EvalSite<'a> {
564    rule: Option<Rc<RuleSnapshot>>,
565    context: Option<&'a mut Context>,
566    token: Option<Token>,
567}
568
569impl<'a> EvalSite<'a> {
570    /// A site with no live parse behind it.
571    pub fn detached() -> Self {
572        EvalSite {
573            rule: None,
574            context: None,
575            token: None,
576        }
577    }
578
579    /// A site inside a parse.
580    pub fn new(rule: Option<Rc<RuleSnapshot>>, context: &'a mut Context) -> Self {
581        EvalSite {
582            rule,
583            context: Some(context),
584            token: None,
585        }
586    }
587
588    /// The rule the reduction belongs to, when there is one.
589    pub fn rule(&self) -> Option<&RuleSnapshot> {
590        self.rule.as_deref()
591    }
592
593    /// The token this OCCURRENCE of the operator was matched from.
594    ///
595    /// The `Op` an evaluator receives is the shared description, one per
596    /// entry in the operator table, so it cannot say which occurrence is
597    /// being reduced. The canonical `makeOp` attaches the token to its
598    /// copy of the description for exactly that reason; this port keeps
599    /// the token beside the node instead, and hands it over here. The
600    /// position is the engine's `Site` triple: `token.site.pos`, `.ri`
601    /// (row) and `.ci` (column).
602    ///
603    /// It is `None` when the node was built without one, which is what
604    /// [`prattify`] called directly produces.
605    pub fn token(&self) -> Option<&Token> {
606        self.token.as_ref()
607    }
608
609    /// The live parse context, when there is one.
610    pub fn context(&mut self) -> Option<&mut Context> {
611        self.context.as_deref_mut()
612    }
613
614    /// Whether the rule carries a `u` flag set to `true`. The
615    /// `paren_preval` flag is what tells an evaluator that a paren
616    /// operator's first term is the preceding value.
617    pub fn flag(&self, name: &str) -> bool {
618        self.rule
619            .as_ref()
620            .is_some_and(|rule| matches!(rule.u.get(name), Some(Value::Bool(true))))
621    }
622
623    /// Reborrow, so a recursive reduction passes the same site down. The
624    /// token is not carried: it belongs to one occurrence, and the nested
625    /// reduction sets the one it is reducing.
626    fn reborrow(&mut self) -> EvalSite<'_> {
627        EvalSite {
628            rule: self.rule.clone(),
629            context: self.context.as_deref_mut(),
630            token: None,
631        }
632    }
633}
634
635/// Resolve the value of an operation. The Rust spelling of the canonical
636/// `Evaluate` callback: it takes the operator and its already reduced
637/// terms, and returns the value the expression stands for.
638pub type Evaluate = Arc<dyn Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync>;
639
640/// Options for the plugin.
641///
642/// `op` is an insertion-ordered map, and the order matters: two operators
643/// claiming the same source string resolve to the same token, and the
644/// later entry wins, exactly as it does in the canonical TypeScript. A
645/// `None` entry deletes an operator the defaults provide.
646#[derive(Clone, Default)]
647pub struct ExprOptions {
648    pub op: IndexMap<String, Option<OpDef>>,
649    pub evaluate: Option<Evaluate>,
650    /// Values side by side, with nothing between them, inside an
651    /// expression or a paren group make an implicit list, as jsonic makes
652    /// one (`f(a b)` is a call of `[a, b]`). With `Some(false)` they are
653    /// refused, with the engine's `unexpected`. A document's own implicit
654    /// list, outside any expression, and the items of a list or a map are
655    /// unchanged. `None` reads as `true`.
656    pub juxtapose: Option<bool>,
657}
658
659impl fmt::Debug for ExprOptions {
660    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
661        formatter
662            .debug_struct("ExprOptions")
663            .field("op", &self.op)
664            .field("evaluate", &self.evaluate.as_ref().map(|_| "<function>"))
665            .field("juxtapose", &self.juxtapose)
666            .finish()
667    }
668}
669
670impl ExprOptions {
671    /// Options carrying no operators of their own; the defaults still
672    /// apply.
673    pub fn new() -> Self {
674        Self::default()
675    }
676
677    /// Add or replace one operator definition.
678    pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
679        self.op.insert(name.into(), Some(def));
680        self
681    }
682
683    /// Delete a default operator, the Rust spelling of `plain: null`.
684    pub fn without_op(mut self, name: impl Into<String>) -> Self {
685        self.op.insert(name.into(), None);
686        self
687    }
688
689    /// Whether values side by side make an implicit list: see
690    /// [`ExprOptions::juxtapose`].
691    pub fn with_juxtapose(mut self, juxtapose: bool) -> Self {
692        self.juxtapose = Some(juxtapose);
693        self
694    }
695
696    /// Set the evaluator that reduces each expression as it closes.
697    pub fn with_evaluate(
698        mut self,
699        evaluate: impl Fn(&mut EvalSite<'_>, &Op, &[Value]) -> Value + Send + Sync + 'static,
700    ) -> Self {
701        self.evaluate = Some(Arc::new(evaluate));
702        self
703    }
704
705    /// Read the operator table, and `juxtapose`, out of a serialized option
706    /// bag, as the engine hands it to a plugin. Unreadable entries are
707    /// ignored, the way the canonical plugin ignores what it cannot use.
708    pub fn from_value(options: &Value) -> Self {
709        let mut resolved = ExprOptions::new();
710        if let Some(Value::Bool(juxtapose)) = object_get(options, "juxtapose") {
711            resolved.juxtapose = Some(*juxtapose);
712        }
713        let Some(op) = object_get(options, "op") else {
714            return resolved;
715        };
716        let Value::Object(entries) = op else {
717            return resolved;
718        };
719        for (name, def) in entries.iter() {
720            match def {
721                Value::Object(_) => {
722                    resolved
723                        .op
724                        .insert(name.clone(), Some(op_def_from_value(def)));
725                }
726                // `plain: null` deletes a default operator.
727                _ => {
728                    resolved.op.insert(name.clone(), None);
729                }
730            }
731        }
732        resolved
733    }
734}
735
736fn object_get<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
737    match value {
738        Value::Object(map) => map.get(key),
739        Value::MapRef(map) => map.value.get(key),
740        _ => None,
741    }
742}
743
744fn value_bool(value: Option<&Value>) -> bool {
745    matches!(value, Some(Value::Bool(true)))
746}
747
748fn value_i64(value: Option<&Value>) -> Option<i64> {
749    match value {
750        Some(Value::Number(number)) => Some(*number as i64),
751        _ => None,
752    }
753}
754
755fn value_string(value: Option<&Value>) -> String {
756    match value {
757        Some(Value::String(text)) => text.clone(),
758        Some(Value::Text(text)) => text.string.clone(),
759        _ => String::new(),
760    }
761}
762
763fn op_def_from_value(def: &Value) -> OpDef {
764    let mut out = OpDef {
765        osrc: value_string(object_get(def, "osrc")),
766        csrc: value_string(object_get(def, "csrc")),
767        left: value_i64(object_get(def, "left")),
768        right: value_i64(object_get(def, "right")),
769        prefix: value_bool(object_get(def, "prefix")),
770        suffix: value_bool(object_get(def, "suffix")),
771        infix: value_bool(object_get(def, "infix")),
772        ternary: value_bool(object_get(def, "ternary")),
773        paren: value_bool(object_get(def, "paren")),
774        use_data: object_get(def, "use").cloned().unwrap_or(Value::Undefined),
775        key: value_bool(object_get(def, "key")),
776        dynamic: value_bool(object_get(def, "dynamic")),
777        separator: value_bool(object_get(def, "separator")),
778        // A cast's `accept` is a function, which no serialized option bag
779        // carries: give one with `OpDef::cast`.
780        cast: value_bool(object_get(def, "cast")),
781        ..Default::default()
782    };
783    if let Some(content) = object_get(def, "content") {
784        out.content = ContentDef {
785            required: value_bool(object_get(content, "required")),
786            separated: value_bool(object_get(content, "separated")),
787        };
788    }
789    match object_get(def, "src") {
790        Some(Value::String(src)) => out.src = vec![src.clone()],
791        Some(Value::Array(srcs)) => {
792            out.src = srcs
793                .iter()
794                .map(|src| value_string(Some(src)))
795                .collect::<Vec<_>>()
796        }
797        _ => {}
798    }
799    out.preval = match object_get(def, "preval") {
800        None | Some(Value::Undefined) | Some(Value::Null) => None,
801        Some(Value::Bool(active)) => Some(PrevalDef {
802            active: *active,
803            required: false,
804            allow: None,
805        }),
806        Some(preval) => Some(PrevalDef {
807            // True by default when a preval object is specified at all.
808            active: match object_get(preval, "active") {
809                None | Some(Value::Undefined) | Some(Value::Null) => true,
810                Some(Value::Bool(active)) => *active,
811                Some(_) => true,
812            },
813            required: value_bool(object_get(preval, "required")),
814            allow: match object_get(preval, "allow") {
815                Some(Value::Array(allow)) => Some(
816                    allow
817                        .iter()
818                        .map(|entry| value_string(Some(entry)))
819                        .collect::<Vec<_>>(),
820                ),
821                _ => None,
822            },
823        }),
824    };
825    out
826}
827
828// Default operator precedence: the "binding power" scale.
829//
830// Binding powers are compared only by ORDER, never by magnitude (every
831// comparison in `prattify` is a `<` or `<=`): a higher number binds
832// tighter. Associativity is set by left against right. Left below right is
833// left-associative (`a-b-c` is `(a-b)-c`); left above right is
834// right-associative. An unset left or right falls back to
835// [`MIN_SAFE_INTEGER`] or [`MAX_SAFE_INTEGER`], which is why prefix
836// operators give only `right` and parens give neither.
837//
838// The defaults occupy a compact low block on a base-1000000 ladder,
839// leaving the whole range above the built-ins open for client operators.
840// Tiers are 1000000 apart; the +100000 on `right` is the
841// left-associativity offset, so a tier occupies a 100000-wide band inside
842// its 1000000-wide slot and adjacent tiers can never overlap:
843//
844//    <1000000  looser client operators (assignment, ternary, logical)
845//     1000000  sequence and comma
846//     2000000  addition and subtraction                  built-in
847//     3000000  multiplication, division, remainder       built-in
848//     4000000  unary prefix                              built-in, tightest
849//     5000000+ free for tighter client operators
850/// The default operator table, as the plugin declares it to the engine.
851pub fn defaults() -> Value {
852    let mut ops: IndexMap<String, Value> = IndexMap::new();
853    ops.insert("positive".into(), prefix_value("+", 4_000_000));
854    ops.insert("negative".into(), prefix_value("-", 4_000_000));
855    // NOTE: all of these are left-associative, as left is below right.
856    // Example: 2+3+4 is (2+3)+4.
857    ops.insert("addition".into(), infix_value("+", 2_000_000, 2_100_000));
858    ops.insert("subtraction".into(), infix_value("-", 2_000_000, 2_100_000));
859    ops.insert(
860        "multiplication".into(),
861        infix_value("*", 3_000_000, 3_100_000),
862    );
863    ops.insert("division".into(), infix_value("/", 3_000_000, 3_100_000));
864    ops.insert("remainder".into(), infix_value("%", 3_000_000, 3_100_000));
865    ops.insert("plain".into(), paren_value("(", ")"));
866
867    let mut map: IndexMap<String, Value> = IndexMap::new();
868    map.insert("op".into(), Value::object(ops));
869    Value::object(map)
870}
871
872fn prefix_value(src: &str, right: i64) -> Value {
873    let mut def: IndexMap<String, Value> = IndexMap::new();
874    def.insert("prefix".into(), Value::Bool(true));
875    def.insert("right".into(), number(right));
876    def.insert("src".into(), Value::String(src.into()));
877    Value::object(def)
878}
879
880fn infix_value(src: &str, left: i64, right: i64) -> Value {
881    let mut def: IndexMap<String, Value> = IndexMap::new();
882    def.insert("infix".into(), Value::Bool(true));
883    def.insert("left".into(), number(left));
884    def.insert("right".into(), number(right));
885    def.insert("src".into(), Value::String(src.into()));
886    Value::object(def)
887}
888
889fn paren_value(osrc: &str, csrc: &str) -> Value {
890    let mut def: IndexMap<String, Value> = IndexMap::new();
891    def.insert("paren".into(), Value::Bool(true));
892    def.insert("osrc".into(), Value::String(osrc.into()));
893    def.insert("csrc".into(), Value::String(csrc.into()));
894    Value::object(def)
895}
896
897/// The default operator table as typed options.
898fn default_ops() -> IndexMap<String, Option<OpDef>> {
899    ExprOptions::from_value(&defaults()).op
900}
901
902/// Merge caller options over the defaults with the canonical semantics: a
903/// name the defaults already carry is deep-merged and moves to the end of
904/// the table, a new name is appended, and a `None` entry deletes.
905fn resolve_options(options: &ExprOptions) -> IndexMap<String, Option<OpDef>> {
906    let defaults = default_ops();
907    let mut resolved = defaults.clone();
908    for (name, def) in &options.op {
909        resolved.shift_remove(name);
910        match def {
911            Some(def) => {
912                resolved.insert(name.clone(), Some(def.clone()));
913            }
914            None => {
915                resolved.insert(name.clone(), None);
916            }
917        }
918    }
919
920    // The default grouping paren yields to the table's own: `plain`, as
921    // the defaults define it, is left out when another paren operator
922    // opens with `(` and closes with `)`. Otherwise it would be that
923    // opener's group beside a call the table declares there, which a
924    // table that gave its call the group's job too (one paren operator
925    // whose preval is active and not required) never asked for. A `plain`
926    // the options change is theirs, and stays.
927    if let Some(Some(plain)) = resolved.get("plain") {
928        let claimed = Some(&Some(plain.clone())) == defaults.get("plain")
929            && resolved.iter().any(|(name, def)| {
930                "plain" != name
931                    && def.as_ref().is_some_and(|def| {
932                        def.paren && def.osrc == plain.osrc && def.csrc == plain.csrc
933                    })
934            });
935        if claimed {
936            resolved.shift_remove("plain");
937        }
938    }
939    resolved
940}
941
942// ---------------------------------------------------------------------------
943// The expression node arena
944// ---------------------------------------------------------------------------
945//
946// The canonical algorithm rewrites expression nodes IN PLACE, so that every
947// rule holding a node observes the rewrite: that is what keeps the overall
948// AST intact while an expression is still being assembled. JavaScript gets
949// that from array identity and the Go port buys it with a `*ListRef` box.
950//
951// The engine's `Value` is a copy-on-write tree with no interior mutability,
952// so a rewrite through one holder would be invisible to the others. Nodes
953// therefore live in a per-thread arena and the value that travels through
954// the parse is a HANDLE: a `ListRef` carrying the node's identity under
955// `meta.expr`. Cloning a handle shares the identity, which is exactly the
956// property the algorithm needs, and [`realize`] turns a finished tree of
957// handles into plain values at the parse boundary.
958//
959// A handle is a `ListRef` rather than a string because the base grammar's
960// value coalescing asks whether a node is a container, and the canonical
961// expression node -- a JavaScript array -- is one.
962
963/// One expression node: the operator, the token that introduced this
964/// occurrence, and the operand terms.
965///
966/// The operator is optional because the canonical port rewrites a
967/// completed ternary into a one-element LIST in place, keeping the node's
968/// identity so that every holder sees the list. A node with no operator is
969/// exactly that: a plain array of its terms.
970#[derive(Debug, Clone)]
971struct ExprNode {
972    op: Option<Arc<Op>>,
973    token: Option<Token>,
974    terms: Vec<Value>,
975    /// The node at the top of the expression this one belongs to, or this
976    /// node itself.
977    ///
978    /// The Pratt core only ever grows a tree DOWNWARD from its root: a
979    /// looser operator rewrites the root node in place, keeping its
980    /// identity, and a tighter one builds a new node under it. So the
981    /// root a node was created under stays its root for the life of the
982    /// expression, and recording it is what lets a rule holding a
983    /// sub-expression hand the whole expression back.
984    root: u64,
985    /// How many nodes the expression under this root holds, counted only
986    /// on a root. A tree is never deeper than it is large, so this bounds
987    /// its depth: see [`NODE_LIMIT`].
988    size: usize,
989}
990
991#[derive(Default)]
992struct Arena {
993    nodes: HashMap<u64, ExprNode>,
994    next_id: u64,
995    /// Parses currently running on this thread through this crate's own
996    /// entry points. While one is in flight the arena must not be cleared.
997    active: usize,
998}
999
1000thread_local! {
1001    static ARENA: RefCell<Arena> = RefCell::new(Arena::default());
1002    /// Set when an expression outgrows [`NODE_LIMIT`]. The parse budget
1003    /// reads it and cancels the parse.
1004    static OVER_LIMIT: Cell<bool> = const { Cell::new(false) };
1005}
1006
1007/// The `meta` key a handle carries its node identity under.
1008const EXPR_META: &str = "expr";
1009
1010/// The most nodes one expression may hold.
1011///
1012/// The engine walks a value with the CALL STACK to display it, convert it
1013/// to JSON or drop it, so a deeply nested result aborts the process rather
1014/// than failing: a flat sum of a few thousand terms builds a tree as deep
1015/// as it is long, and an abort is not something a caller can catch. An
1016/// expression past this size is refused with the engine's `cancel` code
1017/// instead, which is a recorded divergence (`../DIVERGENCE.md`):
1018/// TypeScript raises a JavaScript `RangeError` of its own a few thousand
1019/// terms later, and Go grows its stacks and keeps going. The number is
1020/// the one the jsonic base grammar already applies to nested containers,
1021/// so a document cannot nest deeper than this anyway.
1022pub const NODE_LIMIT: usize = 127;
1023
1024/// The deepest rule stack a parse may reach.
1025///
1026/// [`NODE_LIMIT`] bounds an expression that is being BUILT, and an
1027/// unterminated one builds nothing: `((((` with no closer pushes a rule
1028/// frame per level and never reaches the limit, and the engine's cost per
1029/// step grows with the stack, so the parse turned quadratic. The base
1030/// grammar bounds its own nesting for the same reason, and the deepest
1031/// document it accepts, 127 nested containers, measures 378 frames, so
1032/// this one sits well above anything it lets through. Past it a parse is
1033/// refused with the engine's `cancel` code.
1034pub const RULE_LIMIT: usize = 1024;
1035
1036/// Read a handle's node identity.
1037fn node_id(value: &Value) -> Option<u64> {
1038    let Value::ListRef(list) = value else {
1039        return None;
1040    };
1041    match list.meta.get(EXPR_META) {
1042        Some(Value::Number(id)) => Some(*id as u64),
1043        _ => None,
1044    }
1045}
1046
1047/// Whether a value is an expression node, the port of the canonical
1048/// `isOp`.
1049pub fn is_op(value: &Value) -> bool {
1050    op_of(value).is_some()
1051}
1052
1053/// The number of elements a node presents, the canonical `node.length`:
1054/// the operator plus its terms for an expression, and the terms alone for
1055/// a node rewritten into a plain list.
1056fn node_length(value: &Value) -> usize {
1057    if let Some(length) = with_node(value, |entry| {
1058        entry.terms.len() + usize::from(entry.op.is_some())
1059    }) {
1060        return length;
1061    }
1062    match value {
1063        Value::Array(entries) => entries.len(),
1064        Value::ListRef(list) => list.value.len(),
1065        _ => 0,
1066    }
1067}
1068
1069fn is_op_kind(value: &Value, kind: fn(&Op) -> bool) -> bool {
1070    op_of(value).is_some_and(|op| kind(&op))
1071}
1072
1073fn is_paren_op(value: &Value) -> bool {
1074    is_op_kind(value, |op| op.paren)
1075}
1076
1077fn is_ternary_op(value: &Value) -> bool {
1078    is_op_kind(value, |op| op.ternary)
1079}
1080
1081/// The operator heading an expression node.
1082pub fn op_of(value: &Value) -> Option<Arc<Op>> {
1083    let id = node_id(value)?;
1084    ARENA.with(|arena| {
1085        arena
1086            .borrow()
1087            .nodes
1088            .get(&id)
1089            .and_then(|node| node.op.clone())
1090    })
1091}
1092
1093/// The operand terms of an expression node.
1094pub fn terms_of(value: &Value) -> Option<Vec<Value>> {
1095    let id = node_id(value)?;
1096    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.terms.clone()))
1097}
1098
1099/// Allocate a node and return its handle. `under` is the expression the
1100/// node belongs to, when it is built inside one.
1101fn new_node_under(
1102    op: Option<Arc<Op>>,
1103    token: Option<Token>,
1104    terms: Vec<Value>,
1105    under: Option<&Value>,
1106) -> Value {
1107    let inherited = under.and_then(root_id);
1108    let terms_taken = terms.clone();
1109    let id = ARENA.with(|arena| {
1110        let mut arena = arena.borrow_mut();
1111        arena.next_id += 1;
1112        let id = arena.next_id;
1113        arena.nodes.insert(
1114            id,
1115            ExprNode {
1116                op,
1117                token,
1118                terms,
1119                root: inherited.unwrap_or(id),
1120                size: 1,
1121            },
1122        );
1123        id
1124    });
1125    let handle = handle_for(id);
1126    if under.is_some() {
1127        grow(&handle, 1);
1128    }
1129    adopt_all(&handle, &terms_taken);
1130    handle
1131}
1132
1133fn new_node(op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) -> Value {
1134    new_node_under(op, token, terms, None)
1135}
1136
1137/// Count `count` more nodes against the expression `node` belongs to, and
1138/// record it when the expression has outgrown [`NODE_LIMIT`].
1139fn grow(node: &Value, count: usize) {
1140    let Some(root) = root_id(node) else {
1141        return;
1142    };
1143    let over = ARENA.with(|arena| {
1144        let mut arena = arena.borrow_mut();
1145        match arena.nodes.get_mut(&root) {
1146            Some(entry) => {
1147                entry.size += count;
1148                entry.size > NODE_LIMIT
1149            }
1150            None => false,
1151        }
1152    });
1153    if over {
1154        OVER_LIMIT.with(|flag| flag.set(true));
1155    }
1156}
1157
1158/// The size of the expression a node belongs to.
1159fn expression_size(node: &Value) -> usize {
1160    let Some(root) = root_id(node) else {
1161        return 0;
1162    };
1163    ARENA.with(|arena| {
1164        arena
1165            .borrow()
1166            .nodes
1167            .get(&root)
1168            .map_or(0, |entry| entry.size)
1169    })
1170}
1171
1172/// Account for a term taken into an expression. A term that is itself an
1173/// expression brings its whole tree with it, unless it already belongs to
1174/// this one.
1175fn adopt(container: &Value, term: &Value) {
1176    let (Some(into), Some(from)) = (root_id(container), root_id(term)) else {
1177        return;
1178    };
1179    if into == from {
1180        return;
1181    }
1182    grow(container, expression_size(term));
1183}
1184
1185fn adopt_all(container: &Value, terms: &[Value]) {
1186    for term in terms {
1187        adopt(container, term);
1188    }
1189}
1190
1191/// The handle for a node identity. Two handles carrying the same identity
1192/// are the same node, whichever one a rule is holding.
1193fn handle_for(id: u64) -> Value {
1194    let mut meta: IndexMap<String, Value> = IndexMap::new();
1195    meta.insert(EXPR_META.into(), Value::Number(id as f64));
1196    Value::ListRef(Arc::new(ListRef {
1197        value: Vec::new(),
1198        implicit: false,
1199        child: None,
1200        meta,
1201    }))
1202}
1203
1204/// The identity of the expression a node belongs to.
1205fn root_id(value: &Value) -> Option<u64> {
1206    let id = node_id(value)?;
1207    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(|node| node.root))
1208}
1209
1210/// The whole expression a node belongs to.
1211fn root_node(value: &Value) -> Value {
1212    match root_id(value) {
1213        Some(id) => handle_for(id),
1214        None => value.clone(),
1215    }
1216}
1217
1218fn with_node<R>(value: &Value, read: impl FnOnce(&ExprNode) -> R) -> Option<R> {
1219    let id = node_id(value)?;
1220    ARENA.with(|arena| arena.borrow().nodes.get(&id).map(read))
1221}
1222
1223fn with_node_mut<R>(value: &Value, write: impl FnOnce(&mut ExprNode) -> R) -> Option<R> {
1224    let id = node_id(value)?;
1225    ARENA.with(|arena| arena.borrow_mut().nodes.get_mut(&id).map(write))
1226}
1227
1228/// The port of the canonical `updateExprNode`: rewrite a node in place,
1229/// keeping its identity, and truncate it to the supplied terms.
1230fn update_expr_node(node: &Value, op: Option<Arc<Op>>, token: Option<Token>, terms: Vec<Value>) {
1231    adopt_all(node, &terms);
1232    with_node_mut(node, |entry| {
1233        entry.op = op;
1234        entry.token = token;
1235        entry.terms = terms;
1236    });
1237}
1238
1239/// The port of the canonical `dupNode`: a shallow copy, sharing the terms
1240/// with the original but carrying its own identity.
1241fn dup_node(node: &Value) -> Value {
1242    let Some((op, token, terms)) = with_node(node, |entry| {
1243        (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1244    }) else {
1245        return node.clone();
1246    };
1247    new_node_under(op, token, terms, Some(node))
1248}
1249
1250/// `expr[index]` where index 1 is the first term: absent slots read as
1251/// `Undefined`, as a sparse JavaScript array does.
1252fn term_at(node: &Value, index: usize) -> Value {
1253    with_node(node, |entry| {
1254        entry
1255            .terms
1256            .get(index.saturating_sub(1))
1257            .cloned()
1258            .unwrap_or(Value::Undefined)
1259    })
1260    .unwrap_or(Value::Undefined)
1261}
1262
1263/// `expr[index] = value`, extending the node when the slot is past its
1264/// end, as assigning past a JavaScript array's length does.
1265fn set_term(node: &Value, index: usize, value: Value) {
1266    adopt(node, &value);
1267    with_node_mut(node, |entry| {
1268        let slot = index.saturating_sub(1);
1269        while entry.terms.len() <= slot {
1270            entry.terms.push(Value::Undefined);
1271        }
1272        entry.terms[slot] = value;
1273    });
1274}
1275
1276/// `expr.push(value)`.
1277fn push_term(node: &Value, value: Value) {
1278    adopt(node, &value);
1279    with_node_mut(node, |entry| entry.terms.push(value));
1280}
1281
1282/// The number of terms a node carries, the canonical `node.length - 1`.
1283fn term_count(node: &Value) -> usize {
1284    with_node(node, |entry| entry.terms.len()).unwrap_or(0)
1285}
1286
1287/// Refuse a handle whose node the arena no longer holds.
1288///
1289/// A node leaves the arena only when a parse releases it wholesale, so a
1290/// handle that names a missing one is a value that outlived the scope its
1291/// nodes were live in: taken out of [`parse_scope`], or read straight off
1292/// [`Tabnas::parse`] and kept across the next parse on this thread. Node
1293/// identities never repeat, so the handle cannot have been captured by a
1294/// later parse either: the expression it headed is simply gone.
1295///
1296/// This is loud on purpose. Reporting the missing node as an empty array
1297/// let a walk finish and hand back a well-formed value that had silently
1298/// lost the whole expression, which is worse than either a correct answer
1299/// or no answer: nothing downstream could tell the two apart.
1300fn released_handle(id: u64) -> ! {
1301    panic!(
1302        "tabnas-expr: expression node {id} has been released. The value \
1303         holding this handle outlived its parse: realize it with \
1304         `tabnas_expr::realize` inside the `parse_scope` closure, or before \
1305         the next parse on this thread, and let the realized value escape \
1306         instead."
1307    )
1308}
1309
1310/// Drop every node this thread's arena holds.
1311///
1312/// The arena is per-thread and is released when the outermost parse
1313/// through this crate's own entry points returns, or at the start of the
1314/// next parse on the thread when a caller drives the engine directly. Its
1315/// high-water mark is therefore one parse's expression nodes.
1316fn release_arena() {
1317    ARENA.with(|arena| {
1318        let mut arena = arena.borrow_mut();
1319        if 0 == arena.active {
1320            arena.nodes.clear();
1321            EVALUATED.with(|set| set.borrow_mut().clear());
1322            OVER_LIMIT.with(|flag| flag.set(false));
1323        }
1324    });
1325}
1326
1327/// Hold the arena open for the duration of one parse, and release it when
1328/// the outermost one returns.
1329struct ArenaGuard;
1330
1331impl ArenaGuard {
1332    fn enter() -> Self {
1333        ARENA.with(|arena| arena.borrow_mut().active += 1);
1334        OVER_LIMIT.with(|flag| flag.set(false));
1335        ArenaGuard
1336    }
1337}
1338
1339impl Drop for ArenaGuard {
1340    fn drop(&mut self) {
1341        ARENA.with(|arena| {
1342            let mut arena = arena.borrow_mut();
1343            arena.active = arena.active.saturating_sub(1);
1344            if 0 == arena.active {
1345                arena.nodes.clear();
1346                EVALUATED.with(|set| set.borrow_mut().clear());
1347                OVER_LIMIT.with(|flag| flag.set(false));
1348            }
1349        });
1350    }
1351}
1352
1353// ---------------------------------------------------------------------------
1354// Realizing and simplifying a parsed tree
1355// ---------------------------------------------------------------------------
1356
1357/// Replace every expression handle in a parsed value with the plain array
1358/// the canonical port returns: the operator description followed by the
1359/// operand terms.
1360///
1361/// A parse through [`parse`], [`parse_with`] or [`parse_simplified`] is
1362/// realized already. A caller driving a [`Tabnas`] instance directly calls
1363/// this on the result.
1364pub fn realize(value: &Value) -> Value {
1365    let mut open: Vec<u64> = Vec::new();
1366    realize_seen(value, &mut open)
1367}
1368
1369fn realize_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1370    match value {
1371        Value::ListRef(list) => {
1372            let Some(id) = node_id(value) else {
1373                let mut out = (**list).clone();
1374                out.value = out
1375                    .value
1376                    .iter()
1377                    .map(|entry| realize_seen(entry, open))
1378                    .collect();
1379                return Value::ListRef(Arc::new(out));
1380            };
1381            // A rewrite can leave a node reachable from itself; the
1382            // canonical simplifier reports the same way rather than
1383            // recursing forever.
1384            if open.contains(&id) {
1385                return Value::String("[CIRCLE]".into());
1386            }
1387            let Some((op, token, terms)) = with_node(value, |entry| {
1388                (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1389            }) else {
1390                released_handle(id)
1391            };
1392            open.push(id);
1393            let mut out = Vec::with_capacity(terms.len() + 1);
1394            if let Some(op) = &op {
1395                out.push(op.to_value(token.as_ref()));
1396            }
1397            for term in &terms {
1398                out.push(realize_seen(term, open));
1399            }
1400            open.pop();
1401            Value::array(out)
1402        }
1403        Value::Array(entries) => Value::array(
1404            entries
1405                .iter()
1406                .map(|entry| realize_seen(entry, open))
1407                .collect(),
1408        ),
1409        Value::Object(entries) => Value::object(
1410            entries
1411                .iter()
1412                .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1413                .collect(),
1414        ),
1415        Value::MapRef(map) => {
1416            let mut out = (**map).clone();
1417            out.value = out
1418                .value
1419                .iter()
1420                .map(|(key, entry)| (key.clone(), realize_seen(entry, open)))
1421                .collect();
1422            Value::MapRef(Arc::new(out))
1423        }
1424        other => other.clone(),
1425    }
1426}
1427
1428/// Reduce a parsed value to the S-expression form the shared fixtures
1429/// compare: every operator description becomes its source text, and a
1430/// term that was never filled is dropped.
1431///
1432/// This is the Rust spelling of the canonical `S` helper the TypeScript
1433/// suite uses and of the Go port's `Simplify`.
1434pub fn simplify(value: &Value) -> Value {
1435    let mut open: Vec<u64> = Vec::new();
1436    simplify_seen(value, &mut open)
1437}
1438
1439fn simplify_seen(value: &Value, open: &mut Vec<u64>) -> Value {
1440    match value {
1441        Value::ListRef(list) => {
1442            let Some(id) = node_id(value) else {
1443                return Value::array(
1444                    list.value
1445                        .iter()
1446                        .map(|entry| simplify_seen(entry, open))
1447                        .collect(),
1448                );
1449            };
1450            if open.contains(&id) {
1451                return Value::String("[CIRCLE]".into());
1452            }
1453            let Some((op, terms)) =
1454                with_node(value, |entry| (entry.op.clone(), entry.terms.clone()))
1455            else {
1456                released_handle(id)
1457            };
1458            open.push(id);
1459            let mut out = Vec::with_capacity(terms.len() + 1);
1460            if let Some(op) = &op {
1461                // A paren operator's `src` is its opening source, so one
1462                // field covers both, as it does in the canonical port.
1463                out.push(Value::String(op.src.clone()));
1464            }
1465            for term in &terms {
1466                // An unfilled slot is `undefined` in the canonical port,
1467                // and the canonical simplifier filters those out.
1468                if term.is_undefined() {
1469                    continue;
1470                }
1471                out.push(simplify_seen(term, open));
1472            }
1473            open.pop();
1474            Value::array(out)
1475        }
1476        // A REALIZED expression: the operator description is an object
1477        // carrying its source text, which is what the canonical
1478        // simplifier reads (`x[0].src`).
1479        Value::Array(entries) if realized_source(entries.first()).is_some() => {
1480            let mut out = Vec::with_capacity(entries.len());
1481            out.push(Value::String(
1482                realized_source(entries.first()).unwrap_or_default(),
1483            ));
1484            for entry in entries.iter().skip(1) {
1485                if entry.is_undefined() {
1486                    continue;
1487                }
1488                out.push(simplify_seen(entry, open));
1489            }
1490            Value::array(out)
1491        }
1492        Value::Array(entries) => Value::array(
1493            entries
1494                .iter()
1495                .map(|entry| simplify_seen(entry, open))
1496                .collect(),
1497        ),
1498        Value::Object(entries) => Value::object(
1499            entries
1500                .iter()
1501                .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1502                .collect(),
1503        ),
1504        Value::MapRef(map) => Value::object(
1505            map.value
1506                .iter()
1507                .map(|(key, entry)| (key.clone(), simplify_seen(entry, open)))
1508                .collect(),
1509        ),
1510        Value::Text(text) => Value::String(text.string.clone()),
1511        other => other.clone(),
1512    }
1513}
1514
1515/// The source text of a realized operator description, when a value is
1516/// one.
1517fn realized_source(value: Option<&Value>) -> Option<String> {
1518    match object_get(value?, "src") {
1519        Some(Value::String(src)) if !src.is_empty() => Some(src.clone()),
1520        _ => None,
1521    }
1522}
1523
1524// ---------------------------------------------------------------------------
1525// The Pratt core
1526// ---------------------------------------------------------------------------
1527
1528/// One occurrence of an operator: the shared description and the token
1529/// that introduced it. The canonical `makeOp` builds the same pair by
1530/// copying the description and attaching the token.
1531#[derive(Debug, Clone)]
1532pub struct OpRef {
1533    pub op: Arc<Op>,
1534    pub token: Option<Token>,
1535}
1536
1537impl OpRef {
1538    /// An occurrence with no token behind it, for direct use of
1539    /// [`prattify`].
1540    pub fn new(op: Op) -> Self {
1541        OpRef {
1542            op: Arc::new(opify(op)),
1543            token: None,
1544        }
1545    }
1546
1547    fn at(op: &Arc<Op>, token: Option<Token>) -> Self {
1548        OpRef {
1549            op: op.clone(),
1550            token,
1551        }
1552    }
1553
1554    /// A fresh expression node headed by this operator.
1555    pub fn node(&self, terms: Vec<Value>) -> Value {
1556        new_node(Some(self.op.clone()), self.token.clone(), terms)
1557    }
1558
1559    /// A fresh expression node built inside an existing expression.
1560    fn node_under(&self, terms: Vec<Value>, under: &Value) -> Value {
1561        new_node_under(
1562            Some(self.op.clone()),
1563            self.token.clone(),
1564            terms,
1565            Some(under),
1566        )
1567    }
1568}
1569
1570/// Normalize an operator built by hand, filling the derived term count
1571/// when it is unset, as the parser's own operator builder does. The Rust
1572/// spelling of the canonical `testing.opify`.
1573pub fn opify(mut op: Op) -> Op {
1574    if 0 == op.terms {
1575        op.terms = if op.ternary {
1576            3
1577        } else if op.infix {
1578            2
1579        } else {
1580            1
1581        };
1582    }
1583    op
1584}
1585
1586/// Embed a new operator into an expression tree, in place, according to
1587/// operator precedence.
1588///
1589/// The node keeps its identity, so every rule holding it observes the
1590/// rewrite: that is what preserves the referential integrity of the root
1591/// expression while it is still being assembled. The returned handle is
1592/// the sub-expression the new operator now heads, which is where its next
1593/// term belongs.
1594pub fn prattify(expr: &Value, op: &OpRef) -> Value {
1595    let mut out = expr.clone();
1596    let Some(expr_op) = op_of(expr) else {
1597        return out;
1598    };
1599    let new = &op.op;
1600
1601    if new.infix {
1602        if expr_op.suffix || new.left <= expr_op.right {
1603            // The new operator is looser: it takes the whole expression
1604            // built so far as its first term.
1605            let prior = dup_node(expr);
1606            update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1607        } else {
1608            // The new operator is tighter: it takes only the last term.
1609            let end = expr_op.terms;
1610            let last = term_at(expr, end);
1611            let drill = op_of(&last).is_some_and(|last_op| last_op.right < new.left);
1612            if drill {
1613                out = prattify(&last, op);
1614            } else {
1615                out = op.node_under(vec![last], expr);
1616                set_term(expr, end, out.clone());
1617            }
1618        }
1619    } else if new.prefix {
1620        out = op.node_under(Vec::new(), expr);
1621        set_term(expr, expr_op.terms, out.clone());
1622    } else if new.suffix {
1623        if !expr_op.suffix && expr_op.right <= new.left {
1624            let end = expr_op.terms;
1625            let last = term_at(expr, end);
1626            // NOTE: special case: a higher precedence suffix "drills"
1627            // into lower precedence prefixes, so `@@1!` is `@(@(1!))`
1628            // rather than `@((@1)!)`.
1629            let drill =
1630                op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left);
1631            if drill {
1632                prattify(&last, op);
1633            } else {
1634                set_term(expr, end, op.node_under(vec![last], expr));
1635            }
1636        } else {
1637            let prior = dup_node(expr);
1638            update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
1639        }
1640    }
1641
1642    out
1643}
1644
1645/// Convert a prior rule's node into the start of a new expression, the
1646/// port of the canonical `prior`.
1647fn prior_expr(rule: &mut Rule, prior: Option<&Rc<RuleSnapshot>>, op: &OpRef) -> Value {
1648    let prior_value = prior.map_or(Value::Undefined, |prior| prior.node.borrow().clone());
1649
1650    let node = if is_op(&prior_value) && !op.op.prefix {
1651        // Infix or suffix: the prior node is the genuine first term to
1652        // wrap (the `(1+2)` of `(1+2)+3`). Duplicate it so the in-place
1653        // rewrite below preserves referential integrity.
1654        let duplicate = dup_node(&prior_value);
1655        update_expr_node(
1656            &prior_value,
1657            Some(op.op.clone()),
1658            op.token.clone(),
1659            vec![duplicate],
1660        );
1661        prior_value
1662    } else {
1663        // A prefix operator never has a prior term, so any expression
1664        // sitting on the prior node here is a foreign parent-seed (a
1665        // ternary or paren wrapper the engine threaded down). Start
1666        // fresh rather than rewriting it.
1667        let terms = if op.op.prefix {
1668            Vec::new()
1669        } else {
1670            vec![prior_value]
1671        };
1672        let fresh = op.node(terms);
1673        if let Some(prior) = prior {
1674            // NOTE: nothing is written when there is no prior rule. The
1675            // canonical ports guard the same write, because a rule with
1676            // no parent would otherwise publish onto the no-rule
1677            // sentinel and leak the expression into every later parse.
1678            *prior.node.borrow_mut() = fresh.clone();
1679        }
1680        fresh
1681    };
1682
1683    // Ensure the first term's rule contains the final expression.
1684    if let Some(prior) = prior {
1685        rule.parent_rule = Some(prior.clone());
1686        rule.parent_node = Some(prior.node.clone());
1687    }
1688
1689    node
1690}
1691
1692// ---------------------------------------------------------------------------
1693// Evaluation
1694// ---------------------------------------------------------------------------
1695
1696/// Values an evaluator has already produced, by identity.
1697#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1698enum EvalKey {
1699    Node(u64),
1700    Shared(usize, usize),
1701}
1702
1703thread_local! {
1704    static EVALUATED: RefCell<Vec<EvalKey>> = const { RefCell::new(Vec::new()) };
1705}
1706
1707fn eval_key(value: &Value) -> Option<EvalKey> {
1708    if let Some(id) = node_id(value) {
1709        return Some(EvalKey::Node(id));
1710    }
1711    match value {
1712        Value::Array(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1713            Arc::as_ptr(entries) as usize,
1714            entries.len(),
1715        )),
1716        Value::Object(entries) if !entries.is_empty() => Some(EvalKey::Shared(
1717            Arc::as_ptr(entries) as usize,
1718            entries.len(),
1719        )),
1720        Value::ListRef(list) => Some(EvalKey::Shared(
1721            Arc::as_ptr(list) as usize,
1722            list.value.len(),
1723        )),
1724        Value::MapRef(map) => Some(EvalKey::Shared(Arc::as_ptr(map) as usize, map.value.len())),
1725        _ => None,
1726    }
1727}
1728
1729fn evaluated_seen(value: &Value) -> bool {
1730    eval_key(value).is_some_and(|key| EVALUATED.with(|set| set.borrow().contains(&key)))
1731}
1732
1733fn evaluated_mark(value: &Value) {
1734    if let Some(key) = eval_key(value) {
1735        EVALUATED.with(|set| {
1736            let mut set = set.borrow_mut();
1737            if !set.contains(&key) {
1738                set.push(key);
1739            }
1740        });
1741    }
1742}
1743
1744/// What [`evaluation_with`] reduces besides expressions and implicit lists.
1745#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1746pub struct EvaluationOptions {
1747    /// Reduce a map member by member into a NEW map of the same kind,
1748    /// which is what the eager `evaluate` option already does for an
1749    /// expression inside a map. Off by default: a map is then passed
1750    /// through as it is, as [`evaluation`] documents.
1751    pub objects: bool,
1752}
1753
1754/// Reduce an expression tree with an evaluator, innermost first.
1755///
1756/// An implicit list is reduced a member at a time as its members close and
1757/// again as a whole once it is complete, so a value the evaluator has
1758/// already produced is returned untouched rather than reduced twice. That
1759/// record is per-thread and is cleared with the expression arena.
1760///
1761/// A map is passed through unchanged; [`evaluation_with`] can reduce it
1762/// member by member instead.
1763pub fn evaluation(site: &mut EvalSite<'_>, value: &Value, evaluate: &Evaluate) -> Value {
1764    evaluation_with(site, value, evaluate, EvaluationOptions::default())
1765}
1766
1767/// [`evaluation`] with options: the port of the canonical
1768/// `evaluation(rule, ctx, expr, evaluate, { objects })`.
1769pub fn evaluation_with(
1770    site: &mut EvalSite<'_>,
1771    value: &Value,
1772    evaluate: &Evaluate,
1773    options: EvaluationOptions,
1774) -> Value {
1775    if value.is_undefined() || matches!(value, Value::Null) {
1776        return Value::Null;
1777    }
1778    if evaluated_seen(value) {
1779        return value.clone();
1780    }
1781
1782    let out = if is_op(value) {
1783        let Some((Some(op), token, terms)) = with_node(value, |entry| {
1784            (entry.op.clone(), entry.token.clone(), entry.terms.clone())
1785        }) else {
1786            return value.clone();
1787        };
1788        let reduced: Vec<Value> = terms
1789            .iter()
1790            .map(|term| evaluation_with(&mut site.reborrow(), term, evaluate, options))
1791            .collect();
1792        // The occurrence token travels on the site, not on the shared
1793        // description: `op` is one entry of the operator table and is the
1794        // same object for every occurrence. Restoring the previous token
1795        // keeps an outer reduction pointing at its own operator.
1796        let previous = std::mem::replace(&mut site.token, token);
1797        let reduction = evaluate(site, &op, &reduced);
1798        site.token = previous;
1799        reduction
1800    } else if let Value::Array(entries) = value {
1801        // An implicit list is a plain array, not an expression node, so
1802        // the branch above does not reach its members. Reduce them into a
1803        // NEW array: this is a documented entry point and the
1804        // parse-once, evaluate-many workflow needs a caller's tree to
1805        // survive a reduction intact.
1806        Value::array(
1807            entries
1808                .iter()
1809                .map(|entry| evaluation_with(&mut site.reborrow(), entry, evaluate, options))
1810                .collect(),
1811        )
1812    } else if options.objects && matches!(value, Value::Object(_) | Value::MapRef(_)) {
1813        // Into a NEW map of the same kind, members in their own order.
1814        let mut reduce = |entries: &IndexMap<String, Value>| -> IndexMap<String, Value> {
1815            entries
1816                .iter()
1817                .map(|(name, member)| {
1818                    let member = evaluation_with(&mut site.reborrow(), member, evaluate, options);
1819                    (name.clone(), member)
1820                })
1821                .collect()
1822        };
1823        match value {
1824            Value::MapRef(map) => {
1825                let mut out = (**map).clone();
1826                out.value = reduce(&map.value);
1827                Value::MapRef(Arc::new(out))
1828            }
1829            Value::Object(entries) => Value::object(reduce(entries)),
1830            _ => value.clone(),
1831        }
1832    } else {
1833        value.clone()
1834    };
1835
1836    // Only a value this reduction PRODUCED is marked. A node passed
1837    // through unchanged (a map, by default) is not, so a later reduction
1838    // with `objects` on still reaches the operators inside it.
1839    if eval_key(&out) != eval_key(value) {
1840        evaluated_mark(&out);
1841    }
1842    out
1843}
1844
1845// ---------------------------------------------------------------------------
1846// Grammar construction
1847// ---------------------------------------------------------------------------
1848
1849/// Which of the four token-led operator families a map is built for.
1850#[derive(Clone, Copy, PartialEq, Eq)]
1851enum Anyfix {
1852    Prefix,
1853    Suffix,
1854    Infix,
1855    Ternary,
1856}
1857
1858impl Anyfix {
1859    fn name(self) -> &'static str {
1860        match self {
1861            Anyfix::Prefix => "prefix",
1862            Anyfix::Suffix => "suffix",
1863            Anyfix::Infix => "infix",
1864            Anyfix::Ternary => "ternary",
1865        }
1866    }
1867
1868    fn selects(self, def: &OpDef) -> bool {
1869        match self {
1870            Anyfix::Prefix => def.prefix,
1871            Anyfix::Suffix => def.suffix,
1872            Anyfix::Infix => def.infix,
1873            Anyfix::Ternary => def.ternary,
1874        }
1875    }
1876
1877    fn terms(self) -> usize {
1878        match self {
1879            Anyfix::Ternary => 3,
1880            Anyfix::Infix => 2,
1881            _ => 1,
1882        }
1883    }
1884}
1885
1886/// Resolve the token identity for an operator source, preferring one this
1887/// INSTANCE already binds.
1888///
1889/// The canonical plugin looks a source up with `tabnas.fixed(src)`, an
1890/// instance lookup: a host grammar registers its punctuation as
1891/// instance-level fixed tokens, and binding an operator to a fresh
1892/// `#E<src>` identity instead would leave its alternate waiting on a token
1893/// the host lexer never emits.
1894fn operator_tin(parser: &mut Tabnas, src: &str) -> (Tin, String) {
1895    if let Some(tin) = parser.fixed(src) {
1896        let name = parser.token_name(tin);
1897        return (tin, name);
1898    }
1899    let name = format!("#E{src}");
1900    let tin = parser.token_with_source(name.clone(), src);
1901    (tin, name)
1902}
1903
1904/// An operator definition's binding power, or the fallback when it is
1905/// unset.
1906///
1907/// The canonical `makeOpMap` writes `opdef.left || Number.MIN_SAFE_INTEGER`
1908/// and `opdef.right || Number.MAX_SAFE_INTEGER`. JavaScript's `||` is
1909/// falsy-based, so a power of ZERO is not a power of zero there: it falls
1910/// through to the fallback exactly as an absent one does. Keeping the zero
1911/// changes the tree a zero-power operator builds against one with a
1912/// negative power, which `../test/spec/binding-power-zero.tsv` pins.
1913fn binding_power(power: Option<i64>, unset: i64) -> i64 {
1914    match power {
1915        Some(0) | None => unset,
1916        Some(power) => power,
1917    }
1918}
1919
1920/// Build one token-led operator map, the port of the canonical
1921/// `makeOpMap`.
1922fn make_op_map(
1923    parser: &mut Tabnas,
1924    ops: &IndexMap<String, Option<OpDef>>,
1925    anyfix: Anyfix,
1926) -> IndexMap<Tin, Arc<Op>> {
1927    let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
1928    for (name, def) in ops {
1929        let Some(def) = def else { continue };
1930        if !anyfix.selects(def) {
1931            continue;
1932        }
1933        let src = def.src.first().cloned().unwrap_or_default();
1934        let (tin, tkn) = operator_tin(parser, &src);
1935
1936        let suffix = format!("-{}", anyfix.name());
1937        let op = Op {
1938            src: src.clone(),
1939            left: binding_power(def.left, MIN_SAFE_INTEGER),
1940            right: binding_power(def.right, MAX_SAFE_INTEGER),
1941            name: if name.ends_with(&suffix) {
1942                name.clone()
1943            } else {
1944                format!("{name}{suffix}")
1945            },
1946            infix: Anyfix::Infix == anyfix,
1947            prefix: Anyfix::Prefix == anyfix,
1948            suffix: Anyfix::Suffix == anyfix,
1949            ternary: Anyfix::Ternary == anyfix,
1950            tkn,
1951            tin,
1952            terms: anyfix.terms(),
1953            use_data: def.use_data.clone(),
1954            separator: Anyfix::Infix == anyfix && def.separator,
1955            ..Default::default()
1956        };
1957
1958        if Anyfix::Ternary == anyfix {
1959            // A ternary has two source strings, and both resolve to the
1960            // same description apart from their token and their index.
1961            let second = def.src.get(1).cloned().unwrap_or_default();
1962            let (second_tin, second_tkn) = operator_tin(parser, &second);
1963
1964            let mut first = op.clone();
1965            first.ternary_index = Some(0);
1966            map.insert(tin, Arc::new(first));
1967
1968            let mut last = op;
1969            last.src = second;
1970            last.ternary_index = Some(1);
1971            last.tkn = second_tkn;
1972            last.tin = second_tin;
1973            map.insert(second_tin, Arc::new(last));
1974        } else {
1975            map.insert(tin, Arc::new(op));
1976        }
1977    }
1978    map
1979}
1980
1981/// Build the paren operator map, the port of the canonical
1982/// `makeParenMap`.
1983/// The paren operators, in the table's order. Several may share an
1984/// opener; the plugin picks, per opener, the group and the preval one.
1985fn make_paren_ops(parser: &mut Tabnas, ops: &IndexMap<String, Option<OpDef>>) -> Vec<Arc<Op>> {
1986    let mut list: Vec<Arc<Op>> = Vec::new();
1987    for (name, def) in ops {
1988        let Some(def) = def else { continue };
1989        if !def.paren {
1990            continue;
1991        }
1992        let (otin, otkn) = operator_tin(parser, &def.osrc);
1993        let (ctin, ctkn) = operator_tin(parser, &def.csrc);
1994        let op = Op {
1995            name: format!("{name}-paren"),
1996            osrc: def.osrc.clone(),
1997            csrc: def.csrc.clone(),
1998            otkn,
1999            otin,
2000            ctkn,
2001            ctin,
2002            preval: def.preval.clone().unwrap_or_default(),
2003            paren: true,
2004            src: def.osrc.clone(),
2005            terms: 1,
2006            use_data: def.use_data.clone(),
2007            // A binding power on a preval paren: compared like a suffix's
2008            // with the operator whose operand precedes it (see
2009            // `binds_here`). Unset, the paren binds to the value just
2010            // before it.
2011            left: binding_power(def.left, MIN_SAFE_INTEGER),
2012            content: def.content,
2013            ..Default::default()
2014        };
2015        list.push(Arc::new(op));
2016    }
2017    list
2018}
2019
2020/// The cast operators, by the opener of the group each is written with,
2021/// the port of the canonical `makeCastOps`.
2022fn make_cast_ops(
2023    parser: &mut Tabnas,
2024    ops: &IndexMap<String, Option<OpDef>>,
2025) -> IndexMap<Tin, Arc<Op>> {
2026    let mut map: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2027    for (name, def) in ops {
2028        let Some(def) = def else { continue };
2029        if !def.cast {
2030            continue;
2031        }
2032        let (otin, otkn) = operator_tin(parser, &def.osrc);
2033        let (ctin, ctkn) = operator_tin(parser, &def.csrc);
2034        let op = Op {
2035            name: if name.ends_with("-cast") {
2036                name.clone()
2037            } else {
2038                format!("{name}-cast")
2039            },
2040            src: def
2041                .src
2042                .first()
2043                .cloned()
2044                .unwrap_or_else(|| format!("{}{}", def.osrc, def.csrc)),
2045            left: MIN_SAFE_INTEGER,
2046            right: binding_power(def.right, MAX_SAFE_INTEGER),
2047            use_data: def.use_data.clone(),
2048            // A prefix, whose first term, the group's content, is fixed
2049            // when it opens: prattify reads it as one.
2050            prefix: true,
2051            terms: 2,
2052            osrc: def.osrc.clone(),
2053            csrc: def.csrc.clone(),
2054            otkn,
2055            otin,
2056            ctkn,
2057            ctin,
2058            cast: true,
2059            accept: def.accept.clone(),
2060            ..Default::default()
2061        };
2062        map.insert(otin, Arc::new(op));
2063    }
2064    map
2065}
2066
2067/// Everything the rule alternates read: the operator maps, the token
2068/// identities they match on, and the evaluator.
2069struct Grammar {
2070    prefix: IndexMap<Tin, Arc<Op>>,
2071    suffix: IndexMap<Tin, Arc<Op>>,
2072    infix: IndexMap<Tin, Arc<Op>>,
2073    ternary: IndexMap<Tin, Arc<Op>>,
2074    /// Every paren operator, in the table's order.
2075    parens: Vec<Arc<Op>>,
2076    /// Per opener, the operator a paren opens when no value precedes it.
2077    paren_plain: IndexMap<Tin, Arc<Op>>,
2078    /// Per opener, the operator a paren opens when a value precedes it.
2079    paren_preval: IndexMap<Tin, Arc<Op>>,
2080    tin_prefix: Vec<Tin>,
2081    tin_suffix: Vec<Tin>,
2082    tin_infix: Vec<Tin>,
2083    tin_tern0: Vec<Tin>,
2084    tin_tern1: Vec<Tin>,
2085    tin_open: Vec<Tin>,
2086    tin_close: Vec<Tin>,
2087    evaluate: Option<Evaluate>,
2088    /// Casts, by the opener of the group each is written with.
2089    cast: IndexMap<Tin, Arc<Op>>,
2090    /// The separators: jsonic's comma, and the token an infix operator on
2091    /// `,` uses, which a host lexer may emit in its place.
2092    tin_sep: Vec<Tin>,
2093    /// Some paren content is separated, or some infix operator on `,` is a
2094    /// separator, so some context separates on `,`.
2095    separating: bool,
2096    /// Some infix operator on `,` gives way to separators, so lists and
2097    /// maps separate on `,` too.
2098    has_separator: bool,
2099    /// Some paren operator's content is required.
2100    has_required: bool,
2101    /// Some preval paren has a binding power.
2102    has_bound: bool,
2103    /// Values side by side are refused (`juxtapose: false`).
2104    no_juxtapose: bool,
2105}
2106
2107/// The value tokens an expression term can start with, the canonical
2108/// `VAL = [TX, NR, ST, VL]`.
2109const VAL_TINS: [Tin; 4] = [TIN_TX, TIN_NR, TIN_ST, TIN_VL];
2110
2111impl Grammar {
2112    fn has_prefix(&self) -> bool {
2113        !self.tin_prefix.is_empty()
2114    }
2115
2116    fn has_infix(&self) -> bool {
2117        !self.tin_infix.is_empty()
2118    }
2119
2120    fn has_suffix(&self) -> bool {
2121        !self.tin_suffix.is_empty()
2122    }
2123
2124    fn has_ternary(&self) -> bool {
2125        !self.tin_tern0.is_empty() && !self.tin_tern1.is_empty()
2126    }
2127
2128    fn has_paren(&self) -> bool {
2129        !self.tin_open.is_empty() && !self.tin_close.is_empty()
2130    }
2131
2132    fn has_cast(&self) -> bool {
2133        !self.cast.is_empty()
2134    }
2135
2136    /// Whether a preval paren on this opener has a binding power, and so
2137    /// may be placed as a postfix of the expression before it.
2138    fn postfix_opener(&self, tin: Tin) -> bool {
2139        self.paren_preval.get(&tin).is_some_and(|op| bound(op))
2140    }
2141
2142    /// Whether a token starts a value, where the one before has ended.
2143    fn starts_value(&self, tin: Tin) -> bool {
2144        VAL_TINS.contains(&tin)
2145            || TIN_OB == tin
2146            || TIN_OS == tin
2147            || self.tin_open.contains(&tin)
2148            || self.tin_prefix.contains(&tin)
2149    }
2150
2151    /// The operator occurrence a matched token introduces, the port of the
2152    /// canonical `makeOp`.
2153    fn op_use(map: &IndexMap<Tin, Arc<Op>>, token: Option<&Token>) -> Option<OpRef> {
2154        let token = token?;
2155        map.get(&token.tin)
2156            .map(|op| OpRef::at(op, Some(token.clone())))
2157    }
2158}
2159
2160// ---------------------------------------------------------------------------
2161// Rule helpers
2162// ---------------------------------------------------------------------------
2163
2164/// A rule counter, absent reading as zero.
2165fn counter(rule: &Rule, name: &str) -> i32 {
2166    rule.n.get(name).copied().unwrap_or(0)
2167}
2168
2169/// A rule-local number, absent reading as zero.
2170fn local_number(rule: &Rule, name: &str) -> i64 {
2171    match rule.u.get(name) {
2172        Some(Value::Number(number)) => *number as i64,
2173        _ => 0,
2174    }
2175}
2176
2177fn set_local_number(rule: &mut Rule, name: &str, value: i64) {
2178    rule.u_mut()
2179        .insert(name.to_string(), Value::Number(value as f64));
2180}
2181
2182/// Assign a rule's node: the Rust spelling of the canonical `r.node = v`.
2183///
2184/// A pushed or replaced rule SHARES its parent's node cell, so writing
2185/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
2186/// Assigning installs a fresh cell instead.
2187fn set_node(rule: &mut Rule, value: Value) {
2188    rule.node = Rc::new(RefCell::new(value));
2189}
2190
2191fn node_of(rule: &Rule) -> Value {
2192    rule.node.borrow().clone()
2193}
2194
2195/// The `u` key an expr rule keeps its attachment point under, so that a
2196/// later rule reads the same node the canonical port would read off
2197/// `rule.node` even after the after-close has put the root back there.
2198const ATTACH: &str = "expr_attach";
2199
2200/// The `u` key of a prefix built inside the tree of the expression its
2201/// parent is building, whose after-close leaves the evaluation to that
2202/// expression: evaluation follows the tree, from the root, once.
2203const INNER: &str = "expr_inner";
2204
2205/// Publish an expression from an expr rule.
2206///
2207/// `rule.node` takes the ATTACHMENT POINT, where the operator's next term
2208/// belongs, exactly as the canonical port leaves it: the rules pushed from
2209/// here are seeded from it, and a chained prefix nests into it.
2210///
2211/// The ROOT goes to the rule's `u` bag, and the rule's after-close puts it
2212/// back on the node. The canonical port has no need for that, because it
2213/// reads the parse result off the FIRST rule of a replacement chain, which
2214/// the root reaches through `prior_expr`. This engine reads it off the
2215/// LAST, so a rule that kept only its attachment point would hand a
2216/// sub-expression back as the whole parse: `1+2*3` came back as
2217/// `["*",2,3]`.
2218fn publish_expr(rule: &mut Rule, attach: Value) {
2219    set_node(rule, attach.clone());
2220    rule.u_mut().insert(ATTACH.to_string(), attach);
2221}
2222
2223/// Write a value through a rule's shared node cell.
2224fn publish(rule: &mut Rule, value: Value) {
2225    *rule.node.borrow_mut() = value;
2226}
2227
2228/// The root of the expression this rule is building.
2229///
2230/// The rule the first term belongs to holds it: `prior_expr` writes the
2231/// new expression there, and the Pratt core rewrites that same node in
2232/// place however the tree grows, so its identity never moves. A rule with
2233/// no such prior holds the root itself.
2234fn expression_root(rule: &Rule) -> Value {
2235    root_node(&node_of(rule))
2236}
2237
2238/// A linked rule's node as the canonical port would read it.
2239///
2240/// An expr rule keeps its ATTACHMENT POINT on `rule.node` there, and this
2241/// port puts the root back on the node once the rule has closed, so an
2242/// expr rule is read through its attachment point instead: `0!-1!*2!`
2243/// needs the trailing suffix to bind to `2`, which it only does when the
2244/// Pratt core is handed the sub-expression the last operator attached to.
2245fn linked_node(link: Option<&Rc<RuleSnapshot>>) -> Value {
2246    let Some(link) = link else {
2247        return Value::Undefined;
2248    };
2249    if let Some(attach) = link.u.get(ATTACH) {
2250        if is_op(attach) {
2251            return attach.clone();
2252        }
2253    }
2254    link.node.borrow().clone()
2255}
2256
2257fn write_linked_node(link: Option<&Rc<RuleSnapshot>>, value: Value) {
2258    if let Some(link) = link {
2259        *link.node.borrow_mut() = value;
2260    }
2261}
2262
2263fn counters(pairs: &[(&str, i32)]) -> HashMap<String, i32> {
2264    pairs
2265        .iter()
2266        .map(|(name, value)| ((*name).to_string(), *value))
2267        .collect()
2268}
2269
2270fn locals(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
2271    pairs
2272        .iter()
2273        .map(|(name, value)| ((*name).to_string(), value.clone()))
2274        .collect()
2275}
2276
2277/// An alternate matching one token from the given set.
2278fn on(tins: &[Tin]) -> AltSpec {
2279    AltSpec {
2280        s: vec![tins.to_vec()],
2281        ..Default::default()
2282    }
2283}
2284
2285/// An alternate matching two tokens in sequence.
2286fn on2(first: &[Tin], second: &[Tin]) -> AltSpec {
2287    AltSpec {
2288        s: vec![first.to_vec(), second.to_vec()],
2289        ..Default::default()
2290    }
2291}
2292
2293/// An alternate with no token filter at all.
2294fn always() -> AltSpec {
2295    AltSpec::default()
2296}
2297
2298fn group_has(tags: &str, tag: &str) -> bool {
2299    tags.split(',').any(|entry| entry.trim() == tag)
2300}
2301
2302/// Add alternates the way the canonical `RuleSpec.open`/`close` do: the
2303/// whole list goes in FRONT of the alternates already there, keeping its
2304/// own order.
2305fn prepend_open_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2306    for alt in alts.into_iter().rev() {
2307        spec.prepend_open(alt);
2308    }
2309}
2310
2311fn prepend_close_all(spec: &mut RuleSpec, alts: Vec<AltSpec>) {
2312    for alt in alts.into_iter().rev() {
2313        spec.prepend_close(alt);
2314    }
2315}
2316
2317// ---------------------------------------------------------------------------
2318// The options of #105, every one off unless a table asks
2319// ---------------------------------------------------------------------------
2320
2321/// The `u` key of an expr rule whose close found a group a cast accepts:
2322/// the next expr rule opens the cast.
2323const CAST_NEXT: &str = "expr_cast_next";
2324
2325/// The `u` key of an expr rule whose close found a bound preval paren: the
2326/// next expr rule places it as a postfix.
2327const POSTFIX_NEXT: &str = "expr_postfix_next";
2328
2329/// The `u` key under which a postfix's expr rule keeps the node the paren
2330/// heads, `[op, target]`, which the paren's content extends.
2331const POSTFIX: &str = "expr_postfix";
2332
2333/// The `u` key of a paren rule opened with no value before it, a group,
2334/// which a cast may take as its token.
2335const PAREN_GROUP: &str = "expr_paren_group";
2336
2337/// The `u` keys of a separated paren content: the terms collected at the
2338/// separators, and the separator's pass, which goes on to the next term.
2339const PAREN_ITEMS: &str = "expr_items";
2340const PAREN_MORE: &str = "expr_paren_more";
2341
2342/// A preval paren with a binding power, `left`, binds like a suffix.
2343fn bound(op: &Op) -> bool {
2344    MIN_SAFE_INTEGER != op.left
2345}
2346
2347fn flag(u: &HashMap<String, Value>, name: &str) -> bool {
2348    matches!(u.get(name), Some(Value::Bool(true)))
2349}
2350
2351/// The operator whose operand a val is, when its parent is an expr rule
2352/// building one: the operator the expr's node, its attachment point,
2353/// heads.
2354fn enclosing(rule: &Rule) -> Option<Arc<Op>> {
2355    let parent = rule.parent_rule.as_ref()?;
2356    if "expr" != parent.name.as_ref() {
2357        return None;
2358    }
2359    let node = linked_node(Some(parent));
2360    if is_ternary_op(&node) || is_paren_op(&node) {
2361        return None;
2362    }
2363    op_of(&node)
2364}
2365
2366/// Whether a bound preval paren takes the value before it, compared as a
2367/// suffix is with the operator it would drill into (`a.b[1]` is
2368/// `(a.b)[1]` when `[` binds no tighter than `.`). A prefix built into an
2369/// enclosing tree (`expr_inner`) leaves the val holding that tree, not its
2370/// own value, so the enclosing expression places the paren instead.
2371fn binds_here(rule: &Rule, op: &Op) -> bool {
2372    if !bound(op) {
2373        return true;
2374    }
2375    if rule
2376        .child_rule
2377        .as_ref()
2378        .is_some_and(|child| flag(&child.u, INNER))
2379    {
2380        return false;
2381    }
2382    enclosing(rule).is_none_or(|encl| encl.right <= op.left)
2383}
2384
2385/// Whether the paren this expr rule pushed closed the token of a cast: a
2386/// group (no value before it) on a cast's opener and closer, holding a
2387/// content the cast's `accept` accepts.
2388fn cast_here(grammar: &Grammar, rule: &Rule) -> bool {
2389    let Some(child) = rule.child_rule.as_ref() else {
2390        return false;
2391    };
2392    if "paren" != child.name.as_ref() || !flag(&child.u, PAREN_GROUP) {
2393        return false;
2394    }
2395    let Some(Value::String(name)) = child.u.get(PAREN_OP) else {
2396        return false;
2397    };
2398    let Some(group) = grammar.parens.iter().find(|op| &op.name == name) else {
2399        return false;
2400    };
2401    let Some(cast) = grammar.cast.get(&group.otin) else {
2402        return false;
2403    };
2404    let Some(accept) = &cast.accept else {
2405        return false;
2406    };
2407    let node = rule.child_value();
2408    cast.ctin == group.ctin && is_op(&node) && 2 == node_length(&node) && {
2409        let content = term_at(&node, 1);
2410        accept.accepts(&content)
2411    }
2412}
2413
2414/// Whether this rule's context separates on `,`.
2415fn separated_here(rule: &Rule) -> bool {
2416    0 < counter(rule, "expr_sep")
2417}
2418
2419/// Whether the paren this rule opened has a separated content.
2420fn separated_paren(grammar: &Grammar, rule: &Rule) -> bool {
2421    opened_paren(grammar, rule).is_some_and(|op| op.content.separated)
2422}
2423
2424/// Collect a term of a separated paren content. The terms go into a node
2425/// of the arena of their own, pushed in place, which the rule's `u` names:
2426/// a list kept in `u` itself would be copied out and back at every
2427/// separator, since the rules pushed in between share `u`, and an argument
2428/// list would cost time quadratic in its length. The node is bookkeeping,
2429/// not part of the expression, so it counts against no expression's size.
2430fn collect_paren_item(rule: &mut Rule, term: Value) {
2431    let items = match rule.u.get(PAREN_ITEMS) {
2432        Some(items) if node_id(items).is_some() => items.clone(),
2433        _ => {
2434            let items = new_node(None, None, Vec::new());
2435            rule.u_mut().insert(PAREN_ITEMS.to_string(), items.clone());
2436            items
2437        }
2438    };
2439    with_node_mut(&items, |entry| entry.terms.push(term));
2440}
2441
2442/// The terms a separated paren content collected at its separators.
2443fn paren_items(rule: &Rule) -> Vec<Value> {
2444    rule.u
2445        .get(PAREN_ITEMS)
2446        .and_then(terms_of)
2447        .unwrap_or_default()
2448}
2449
2450/// The term a paren holds when it closes or meets a separator: its own
2451/// node, or the child's when it has none yet (see `close_paren`).
2452fn paren_term(rule: &Rule) -> Value {
2453    let node = node_of(rule);
2454    if node.is_undefined() {
2455        rule.child_node.clone()
2456    } else {
2457        node
2458    }
2459}
2460
2461/// Place a bound preval paren after an expression, as [`prattify`] places
2462/// a suffix: drilling into the last term while the operator heading it
2463/// binds no tighter than the paren, and wrapping the rest, in place.
2464/// Returns the node the paren heads, `[op, target]`, which the paren's
2465/// content then extends.
2466fn prattify_postfix(expr: &Value, op: &OpRef) -> Value {
2467    let Some(expr_op) = op_of(expr) else {
2468        return op.node(vec![expr.clone()]);
2469    };
2470    let new = &op.op;
2471    if !expr_op.suffix && expr_op.right <= new.left {
2472        let end = expr_op.terms;
2473        let last = term_at(expr, end);
2474        if op_of(&last).is_some_and(|last_op| last_op.prefix && last_op.right < new.left) {
2475            return prattify_postfix(&last, op);
2476        }
2477        let node = op.node_under(vec![last], expr);
2478        set_term(expr, end, node.clone());
2479        return node;
2480    }
2481    let prior = dup_node(expr);
2482    update_expr_node(expr, Some(new.clone()), op.token.clone(), vec![prior]);
2483    expr.clone()
2484}
2485
2486// ---------------------------------------------------------------------------
2487// The plugin
2488// ---------------------------------------------------------------------------
2489
2490/// Install the expression grammar on a parser that already carries the
2491/// jsonic base rules (`val`, `map`, `list`, `pair`, `elem`).
2492///
2493/// This is the plugin body; most callers want [`plugin`], [`apply`] or
2494/// [`make`].
2495pub fn expr(parser: &mut Tabnas, options: &ExprOptions) -> Result<(), PluginError> {
2496    let rules = parser.rule_names();
2497
2498    // A re-run on an instance that already carries the grammar must not
2499    // give it a second copy of every alternate. A derived instance starts
2500    // from an empty rule set and so installs normally.
2501    if rules.iter().any(|name| "expr" == name) {
2502        return Ok(());
2503    }
2504
2505    // The plugin hangs its operator alternates on the base grammar's
2506    // `val` rule. On a bare engine there is nothing to hang them on, and
2507    // the parse would fail later with a message about the document.
2508    if !rules.iter().any(|name| "val" == name) {
2509        return Err(PluginError(
2510            "tabnas-expr: the instance carries no `val` rule. This plugin layers on the \
2511             jsonic base grammar; install that first (tabnas_jsonic::jsonic, or \
2512             tabnas_expr::make)."
2513                .into(),
2514        ));
2515    }
2516
2517    let ops = resolve_options(options);
2518
2519    // A key operator registers no token: a fold recognises it by a map's
2520    // shape. The table is still checked here, as the canonical plugin
2521    // checks it when it installs, so two key operators on one member name
2522    // are refused when the grammar is built rather than at the first fold.
2523    if let Err(error) = make_key_map(&ops) {
2524        return Err(PluginError(format!(
2525            "tabnas-expr: {error} [{}]",
2526            error.code()
2527        )));
2528    }
2529
2530    let prefix = make_op_map(parser, &ops, Anyfix::Prefix);
2531    let suffix = make_op_map(parser, &ops, Anyfix::Suffix);
2532    let infix = make_op_map(parser, &ops, Anyfix::Infix);
2533    let ternary = make_op_map(parser, &ops, Anyfix::Ternary);
2534    // Several paren operators may share an opener: a group, whose preval
2535    // is inactive, and a call or a subscript, whose preval is active. A
2536    // value before the opener selects the preval one, and no value the
2537    // group, so `(e)` and `e()` are different operators. Each map gives,
2538    // for an opener, the operator of one of the two forms: the last
2539    // declared of its kind, and for the group, failing an operator whose
2540    // preval is inactive, the last whose preval is active and not
2541    // required, which serves both forms as a lone operator always has.
2542    let parens = make_paren_ops(parser, &ops);
2543    let mut paren_plain: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2544    let mut paren_preval: IndexMap<Tin, Arc<Op>> = IndexMap::new();
2545    for op in &parens {
2546        if op.preval.active {
2547            paren_preval.insert(op.otin, op.clone());
2548        }
2549        let group = paren_plain.get(&op.otin);
2550        if !op.preval.active
2551            || (!op.preval.required && group.is_none_or(|group| group.preval.active))
2552        {
2553            paren_plain.insert(op.otin, op.clone());
2554        }
2555    }
2556    let cast = make_cast_ops(parser, &ops);
2557    // Separators: a comma separates in a paren whose content is separated,
2558    // and, once an infix operator on `,` is declared a separator, in lists
2559    // and maps too.
2560    let mut tin_sep: Vec<Tin> = vec![TIN_CA];
2561    for op in infix.values() {
2562        if "," == op.src && !tin_sep.contains(&op.tin) {
2563            tin_sep.push(op.tin);
2564        }
2565    }
2566    let has_separator = infix.values().any(|op| op.separator);
2567    let separating = has_separator || parens.iter().any(|op| op.content.separated);
2568    let has_required = parens.iter().any(|op| op.content.required);
2569    let has_bound = paren_preval.values().any(|op| bound(op));
2570    let mut tin_open: Vec<Tin> = Vec::new();
2571    let mut tin_close: Vec<Tin> = Vec::new();
2572    for op in &parens {
2573        if !tin_open.contains(&op.otin) {
2574            tin_open.push(op.otin);
2575        }
2576        if !tin_close.contains(&op.ctin) {
2577            tin_close.push(op.ctin);
2578        }
2579    }
2580
2581    let grammar = Arc::new(Grammar {
2582        tin_prefix: prefix.keys().copied().collect(),
2583        tin_suffix: suffix.keys().copied().collect(),
2584        tin_infix: infix.keys().copied().collect(),
2585        tin_tern0: ternary
2586            .values()
2587            .filter(|op| Some(0) == op.ternary_index)
2588            .map(|op| op.tin)
2589            .collect(),
2590        tin_tern1: ternary
2591            .values()
2592            .filter(|op| Some(1) == op.ternary_index)
2593            .map(|op| op.tin)
2594            .collect(),
2595        tin_open,
2596        tin_close,
2597        prefix,
2598        suffix,
2599        infix,
2600        ternary,
2601        parens,
2602        paren_plain,
2603        paren_preval,
2604        evaluate: options.evaluate.clone(),
2605        cast,
2606        tin_sep,
2607        separating,
2608        has_separator,
2609        has_required,
2610        has_bound,
2611        no_juxtapose: Some(false) == options.juxtapose,
2612    });
2613
2614    comment_before_fixed(parser, &grammar);
2615
2616    // Release the previous parse's expression nodes when no parse this
2617    // crate drives is in flight. A caller driving the engine directly
2618    // therefore holds its result's nodes until the next parse on the
2619    // thread, which is when to call `realize`.
2620    parser.parse_prepare(|_context: &mut Context| release_arena());
2621
2622    bound_expression_size(parser);
2623
2624    install_val(parser, &grammar);
2625    install_list(parser, &grammar);
2626    install_map(parser, &grammar);
2627    install_elem(parser, &grammar);
2628    install_pair(parser, &grammar);
2629    install_expr(parser, &grammar);
2630    if grammar.has_paren() {
2631        install_paren(parser, &grammar);
2632    }
2633    if grammar.has_ternary() {
2634        install_ternary(parser, &grammar);
2635    }
2636
2637    Ok(())
2638}
2639
2640/// Keep a comment opening marker out of the fixed-token matcher's reach.
2641///
2642/// The canonical plugin moves the comment matcher in front of the fixed
2643/// one, because an operator such as `/` would otherwise cut `//` into two
2644/// operator tokens and a comment would never be recognised. This engine's
2645/// matcher families sit in fixed priority bands, so the same effect comes
2646/// from a `check` on the fixed family: where a comment starts, the fixed
2647/// matcher stands aside and the comment matcher takes the run.
2648///
2649/// It is installed whenever some operator source really is a prefix of a
2650/// comment marker, INCLUDING on a host that already configured
2651/// `options.fixed.check`. Omitting it there left the host's check in place
2652/// and the `/` operator ahead of `//` and `/*`, so a valid comment lexed
2653/// as operators and the document failed; the canonical runs a host check
2654/// and lexes comments correctly at the same time, because reordering the
2655/// matchers means the fixed family, its check included, is never reached
2656/// at a comment opener. Standing aside there is the same behaviour.
2657///
2658/// A host check is DISPLACED rather than chained. `LexCheck` holds its
2659/// callback privately and the engine offers no way to run one from
2660/// outside, so the check installed here cannot call through to the one it
2661/// replaces; everywhere but a contested comment opener it returns
2662/// `Continue`, which is what the fixed family does with no check at all. A
2663/// host that needs both installs its own check AFTER this plugin and skips
2664/// the comment openers itself.
2665fn comment_before_fixed(parser: &mut Tabnas, grammar: &Grammar) {
2666    let options = parser.config();
2667    let markers: Vec<String> = options
2668        .comment
2669        .definitions
2670        .values()
2671        .filter(|def| def.lex)
2672        .map(|def| def.start.clone())
2673        .filter(|start| !start.is_empty())
2674        .collect();
2675    if markers.is_empty() {
2676        return;
2677    }
2678
2679    let sources: Vec<String> = grammar
2680        .prefix
2681        .values()
2682        .chain(grammar.suffix.values())
2683        .chain(grammar.infix.values())
2684        .chain(grammar.ternary.values())
2685        .map(|op| op.src.clone())
2686        .chain(
2687            grammar
2688                .parens
2689                .iter()
2690                .flat_map(|op| [op.osrc.clone(), op.csrc.clone()]),
2691        )
2692        .filter(|src| !src.is_empty())
2693        .collect();
2694
2695    let contested: Vec<String> = markers
2696        .into_iter()
2697        .filter(|marker| {
2698            sources
2699                .iter()
2700                .any(|src| src.len() < marker.len() && marker.starts_with(src.as_str()))
2701        })
2702        .collect();
2703    if contested.is_empty() {
2704        return;
2705    }
2706
2707    parser.lex_check_ref(COMMENT_FIRST, move |remaining: &str| {
2708        if contested
2709            .iter()
2710            .any(|marker| remaining.starts_with(marker.as_str()))
2711        {
2712            tabnas::LexCheckResult::Skip
2713        } else {
2714            tabnas::LexCheckResult::Continue
2715        }
2716    });
2717    let _ = parser.grammar_json(COMMENT_FIRST_DOCUMENT);
2718}
2719
2720/// Refuse an expression that has outgrown [`NODE_LIMIT`].
2721///
2722/// The check rides on the engine's parse budget, and composes with a
2723/// budget already in force rather than replacing it: the jsonic base
2724/// grammar installs one to bound container nesting, and both limits exist
2725/// for the same reason (see [`NODE_LIMIT`]).
2726fn bound_expression_size(parser: &mut Tabnas) {
2727    let budget = parser.config().parse.budget.clone();
2728    let existing = budget.on_check.clone();
2729    let every = match budget.check_every_n {
2730        0 => 32,
2731        set => set.min(32),
2732    };
2733    parser.parse_budget(every, move |context: &Context| {
2734        if OVER_LIMIT.with(Cell::get) {
2735            return false;
2736        }
2737        if context.rule_stack.len() > RULE_LIMIT {
2738            return false;
2739        }
2740        existing.as_ref().is_none_or(|check| check(context))
2741    });
2742}
2743
2744const COMMENT_FIRST: &str = "@expr-comment-before-fixed";
2745const COMMENT_FIRST_DOCUMENT: &str =
2746    r#"{"options":{"fixed":{"check":"@expr-comment-before-fixed"}}}"#;
2747
2748// ---------------------------------------------------------------------------
2749// val
2750// ---------------------------------------------------------------------------
2751
2752fn install_val(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
2753    let grammar = grammar.clone();
2754    parser.define_rule("val", move |spec| {
2755        // Implicit pair not allowed inside a ternary: the `2:` of `1?2:3`
2756        // is the ternary's second operator, not a pair key.
2757        if grammar.has_ternary() && grammar.tin_tern1.contains(&TIN_CL) {
2758            for alt in spec.open.iter_mut().filter(|alt| group_has(&alt.g, "pair")) {
2759                let previous = alt.c_fn.clone();
2760                alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2761                    previous
2762                        .as_ref()
2763                        .is_none_or(|condition| condition(rule, context))
2764                        && 0 == counter(rule, "expr_ternary")
2765                }));
2766            }
2767        }
2768
2769        // With `juxtapose: false`, the base grammar's implicit list of
2770        // values side by side is refused inside a paren group, where the
2771        // paren rule allows implicits again, and after a value an
2772        // expression made (its val pushed an expr rule: `-a b`): no
2773        // alternate takes the second value, and the parse fails on it with
2774        // `unexpected`.
2775        if grammar.no_juxtapose {
2776            for alt in spec.close.iter_mut().filter(|alt| {
2777                group_has(&alt.g, "imp")
2778                    && group_has(&alt.g, "space")
2779                    && group_has(&alt.g, "jsonic")
2780            }) {
2781                let previous = alt.c_fn.clone();
2782                alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2783                    previous
2784                        .as_ref()
2785                        .is_none_or(|condition| condition(rule, context))
2786                        && 0 == counter(rule, "expr_paren")
2787                        && rule
2788                            .child_rule
2789                            .as_ref()
2790                            .is_none_or(|child| "expr" != child.name.as_ref())
2791                }));
2792            }
2793        }
2794
2795        let mut open: Vec<AltSpec> = Vec::new();
2796
2797        // The prefix operator of the first term of an expression.
2798        if grammar.has_prefix() {
2799            let mut alt = on(&grammar.tin_prefix);
2800            alt.b = 1;
2801            alt.n = counters(&[("expr_prefix", 1), ("expr_suffix", 0)]);
2802            alt.p = Some("expr".into());
2803            alt.g = "expr,expr-prefix".into();
2804            alt.add_action(detach_node);
2805            open.push(alt);
2806        }
2807
2808        // A value followed by an opening paren: `foo(1)`, `a[1]`.
2809        if grammar.has_paren() {
2810            let mut alt = on2(&VAL_TINS, &grammar.tin_open);
2811            alt.b = 1;
2812            alt.p = Some("expr".into());
2813            let condition = grammar.clone();
2814            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
2815                let Some(pdef) = rule
2816                    .o1()
2817                    .and_then(|token| condition.paren_preval.get(&token.tin))
2818                    .cloned()
2819                else {
2820                    return false;
2821                };
2822                if let Some(allow) = &pdef.preval.allow {
2823                    let preval = rule.resolve_open_value(0, context);
2824                    if !allow.contains(&value_string(Some(&preval))) {
2825                        return false;
2826                    }
2827                }
2828                binds_here(rule, &pdef)
2829            }));
2830            alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2831            alt.g = "expr,expr-paren,expr-paren-preval".into();
2832            alt.add_action(|rule: &mut Rule, context: &mut Context| {
2833                let preval = rule.resolve_open_value(0, context);
2834                set_node(rule, preval);
2835            });
2836            open.push(alt);
2837        }
2838
2839        // An opening parenthesis. NOTE: this can happen outside an
2840        // expression.
2841        if grammar.has_paren() {
2842            let mut alt = on(&grammar.tin_open);
2843            alt.b = 1;
2844            alt.p = Some("expr".into());
2845            let condition = grammar.clone();
2846            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2847                rule.o0()
2848                    .is_some_and(|token| condition.paren_plain.contains_key(&token.tin))
2849            }));
2850            alt.g = "expr,expr-paren".into();
2851            alt.add_action(detach_node);
2852            open.push(alt);
2853        }
2854
2855        prepend_open_all(spec, open);
2856
2857        let mut close: Vec<AltSpec> = Vec::new();
2858
2859        // A separator where the context separates (n.expr_sep): the value
2860        // ends, and the rule that collects the terms takes the comma.
2861        if grammar.separating {
2862            let mut alt = on(&grammar.tin_sep);
2863            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2864                separated_here(rule)
2865            }));
2866            alt.b = 1;
2867            alt.g = "expr,expr-sep".into();
2868            close.push(alt);
2869        }
2870
2871        // Comma-op suppression. When a parent rule (an embedding
2872        // grammar's wrapper rule, say) sets n.no_comma_op, bail at `,`
2873        // without treating it as the comma operator: the parent then
2874        // consumes the `,` itself as a separator. Match by `src` on the
2875        // next infix token, so this works whichever token the embedding
2876        // grammar uses for `,`.
2877        if grammar.has_infix() {
2878            let mut alt = on(&grammar.tin_infix);
2879            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2880                0 < counter(rule, "no_comma_op")
2881                    && rule.c0().is_some_and(|token| "," == token.src.as_str())
2882            }));
2883            alt.b = 1;
2884            alt.g = "expr,no-comma-op-bail".into();
2885            close.push(alt);
2886        }
2887
2888        if grammar.has_ternary() {
2889            let mut alt = on(&grammar.tin_tern0);
2890            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2891                0 == counter(rule, "expr")
2892            }));
2893            alt.b = 1;
2894            alt.r = Some("ternary".into());
2895            alt.g = "expr,expr-ternary".into();
2896            close.push(alt);
2897        }
2898
2899        // The infix operator following the first term of an expression.
2900        if grammar.has_infix() {
2901            let mut alt = on(&grammar.tin_infix);
2902            alt.b = 1;
2903            alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 0)]);
2904            alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2905                (0 == counter(rule, "expr")).then(|| "expr".to_string())
2906            }));
2907            alt.g = "expr,expr-infix".into();
2908            close.push(alt);
2909        }
2910
2911        // The suffix operator following the first term of an expression.
2912        if grammar.has_suffix() {
2913            let mut alt = on(&grammar.tin_suffix);
2914            alt.b = 1;
2915            alt.n = counters(&[("expr_prefix", 0), ("expr_suffix", 1)]);
2916            alt.r_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2917                (0 == counter(rule, "expr")).then(|| "expr".to_string())
2918            }));
2919            alt.g = "expr,expr-suffix".into();
2920            close.push(alt);
2921        }
2922
2923        // The closing parenthesis of an expression.
2924        if grammar.has_paren() {
2925            let mut alt = on(&grammar.tin_close);
2926            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
2927                0 != counter(rule, "expr_paren")
2928            }));
2929            alt.b = 1;
2930            alt.g = "expr,expr-paren".into();
2931            close.push(alt);
2932        }
2933
2934        // Chain for postfix paren forms. When a val has just produced a
2935        // value (`a[0]`, `f(0)`, or a parenthesised expression like
2936        // `(*p)`) and the next token is another preval-active paren-open,
2937        // push expr, which descends into paren, so the new paren-form
2938        // picks up this val's node as the preval. Pushing rather than
2939        // replacing keeps the current val rule alive, so the chained
2940        // result is still what the parse returns. `paren_preval` is set
2941        // so the paren close finds it on the grandparent and pushes this
2942        // node into the new paren expression. This complements the
2943        // open-time preval alternate above, which only fires on the first
2944        // preval-paren of an expression: chain-time detection is needed
2945        // for later parens, because by then the leading value is a
2946        // produced node rather than a token in the lex buffer.
2947        if grammar.has_paren() {
2948            let mut alt = on(&grammar.tin_open);
2949            alt.b = 1;
2950            let condition = grammar.clone();
2951            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2952                let Some(pdef) = rule
2953                    .c0()
2954                    .and_then(|token| condition.paren_preval.get(&token.tin))
2955                    .cloned()
2956                else {
2957                    return false;
2958                };
2959                let node = node_of(rule);
2960                if node.is_undefined() {
2961                    return false;
2962                }
2963                if let Some(allow) = &pdef.preval.allow {
2964                    if !allow.contains(&value_string(Some(&node))) {
2965                        return false;
2966                    }
2967                }
2968                binds_here(rule, &pdef)
2969            }));
2970            alt.p = Some("expr".into());
2971            alt.u = locals(&[("paren_preval", Value::Bool(true))]);
2972            alt.g = "expr,expr-paren,expr-paren-preval-chain".into();
2973            close.push(alt);
2974        }
2975
2976        // A bound preval paren that binds looser than the operator whose
2977        // operand this value is: the value ends, and the expression that
2978        // operator heads takes the paren as its postfix.
2979        if grammar.has_bound {
2980            let mut alt = on(&grammar.tin_open);
2981            alt.b = 1;
2982            let condition = grammar.clone();
2983            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
2984                let Some(pdef) = rule
2985                    .c0()
2986                    .and_then(|token| condition.paren_preval.get(&token.tin))
2987                    .cloned()
2988                else {
2989                    return false;
2990                };
2991                bound(&pdef) && !node_of(rule).is_undefined() && !binds_here(rule, &pdef)
2992            }));
2993            alt.g = "expr,expr-paren,expr-postfix".into();
2994            close.push(alt);
2995        }
2996
2997        if grammar.has_ternary() {
2998            let mut alt = on(&grammar.tin_tern1);
2999            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3000                0 != counter(rule, "expr_ternary")
3001            }));
3002            alt.b = 1;
3003            alt.g = "expr,expr-ternary".into();
3004            close.push(alt);
3005        }
3006
3007        // Do not create an implicit list inside an expression (comma
3008        // separator).
3009        let mut comma = on(&[TIN_CA]);
3010        comma.c_fn = Some(Arc::new(no_implicit_in_expr));
3011        comma.b = 1;
3012        comma.g = "expr,list,val,imp,comma,top".into();
3013        close.push(comma);
3014
3015        // Do not create an implicit list inside an expression (space
3016        // separator).
3017        let mut space = on(&VAL_TINS);
3018        space.c_fn = Some(Arc::new(no_implicit_in_expr));
3019        space.b = 1;
3020        space.g = "expr,list,val,imp,space,top".into();
3021        close.push(space);
3022
3023        prepend_close_all(spec, close);
3024    });
3025}
3026
3027/// Give this rule its own node cell, keeping the value it was seeded with.
3028///
3029/// A rule pushed by the engine shares its parent's cell, so a later write
3030/// to this rule's node would reach the parent too. The canonical engine
3031/// gives every rule its own `node` field and seeds it by VALUE, and the
3032/// base grammar's own val alternates reach the same state by resetting the
3033/// node outright. The alternates this plugin adds to `val` need the seeded
3034/// value, a partly built expression the operator alternates read back, so
3035/// they detach instead of resetting.
3036fn detach_node(rule: &mut Rule, _context: &mut Context) {
3037    let node = node_of(rule);
3038    set_node(rule, node);
3039}
3040
3041fn no_implicit_in_expr(rule: &mut Rule, _context: &mut Context) -> bool {
3042    (1 == rule.d && (1 <= counter(rule, "expr") || 1 <= counter(rule, "expr_ternary")))
3043        || (1 <= counter(rule, "expr_ternary") && 1 <= counter(rule, "expr_paren"))
3044}
3045
3046// ---------------------------------------------------------------------------
3047// list, map, elem, pair
3048// ---------------------------------------------------------------------------
3049
3050fn clear_expr_counters(rule: &mut Rule) {
3051    let counters = rule.n_mut();
3052    counters.insert("expr".into(), 0);
3053    counters.insert("expr_prefix".into(), 0);
3054    counters.insert("expr_suffix".into(), 0);
3055    counters.insert("expr_paren".into(), 0);
3056    counters.insert("expr_ternary".into(), 0);
3057}
3058
3059fn install_list(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3060    let grammar = grammar.clone();
3061    parser.define_rule("list", move |spec| {
3062        let flags = grammar.clone();
3063        spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
3064            // List elements are new expressions, unless this is an
3065            // implicit list.
3066            let implicit = rule
3067                .prev_rule
3068                .as_ref()
3069                .is_some_and(|prev| matches!(prev.u.get("implist"), Some(Value::Bool(true))));
3070            if !implicit {
3071                clear_expr_counters(rule);
3072                // A list separates on `,` once an infix operator on `,`
3073                // gives way to separators, and otherwise leaves the comma
3074                // to that operator.
3075                if flags.separating {
3076                    let sep = i32::from(flags.has_separator);
3077                    rule.n_mut().insert("expr_sep".into(), sep);
3078                }
3079            }
3080        });
3081
3082        let mut close: Vec<AltSpec> = Vec::new();
3083
3084        if grammar.has_paren() {
3085            let mut alt = on(&grammar.tin_close);
3086            // If this is the end of a normal list, consume `]`: it is not
3087            // a close paren.
3088            alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3089                let square = rule.c0().is_some_and(|token| TIN_CS == token.tin);
3090                if square && 0 == counter(rule, "expr_paren") {
3091                    0
3092                } else {
3093                    1
3094                }
3095            }));
3096            alt.g = "expr".into();
3097            close.push(alt);
3098        }
3099
3100        // An implicit list of values side by side ends at a separator of
3101        // the paren content it is a term of.
3102        if grammar.separating {
3103            let mut alt = on(&grammar.tin_sep);
3104            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3105                separated_here(rule)
3106                    && rule
3107                        .prev_rule
3108                        .as_ref()
3109                        .is_some_and(|prev| flag(&prev.u, "implist"))
3110            }));
3111            alt.b = 1;
3112            alt.g = "expr,expr-sep".into();
3113            close.push(alt);
3114        }
3115
3116        prepend_close_all(spec, close);
3117
3118        if grammar.has_paren() {
3119            spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3120                propagate_to_paren(rule);
3121            });
3122        }
3123    });
3124}
3125
3126fn install_map(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3127    let grammar = grammar.clone();
3128    parser.define_rule("map", move |spec| {
3129        // Map values are new expressions, and a map separates on `,` as a
3130        // list does.
3131        let flags = grammar.clone();
3132        spec.prepend_bo(move |rule: &mut Rule, _context: &mut Context| {
3133            clear_expr_counters(rule);
3134            if flags.separating {
3135                let sep = i32::from(flags.has_separator);
3136                rule.n_mut().insert("expr_sep".into(), sep);
3137            }
3138        });
3139
3140        if grammar.has_paren() {
3141            let mut alt = on(&grammar.tin_close);
3142            // If this is the end of a normal map, consume `}`: it is not
3143            // a close paren.
3144            alt.b_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3145                let brace = rule.c0().is_some_and(|token| TIN_CB == token.tin);
3146                if brace && 0 == counter(rule, "expr_paren") {
3147                    0
3148                } else {
3149                    1
3150                }
3151            }));
3152            alt.g = "expr".into();
3153            prepend_close_all(spec, vec![alt]);
3154        }
3155    });
3156}
3157
3158fn install_elem(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3159    let grammar = grammar.clone();
3160    parser.define_rule("elem", move |spec| {
3161        let mut close: Vec<AltSpec> = Vec::new();
3162
3163        // An implicit list of values side by side ends at a separator of
3164        // the paren content it is a term of: the list ends with it.
3165        if grammar.separating {
3166            let mut alt = on(&grammar.tin_sep);
3167            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3168                separated_here(rule)
3169                    && rule
3170                        .parent_rule
3171                        .as_ref()
3172                        .and_then(|parent| parent.prev_rule.clone())
3173                        .is_some_and(|prev| flag(&prev.u, "implist"))
3174            }));
3175            alt.b = 1;
3176            alt.g = "expr,expr-sep".into();
3177            close.push(alt);
3178        }
3179
3180        if !grammar.has_paren() {
3181            prepend_close_all(spec, close);
3182            return;
3183        }
3184
3185        // Close an implicit list within parens.
3186        let mut alt = on(&grammar.tin_close);
3187        alt.b = 1;
3188        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3189            0 != counter(rule, "expr_paren")
3190        }));
3191        alt.g = "expr,expr-paren,imp,close,list".into();
3192        close.push(alt);
3193
3194        // The following element is a paren expression.
3195        let mut alt = on(&grammar.tin_open);
3196        alt.b = 1;
3197        alt.r = Some("elem".into());
3198        alt.g = "expr,expr-paren,imp,open,list".into();
3199        close.push(alt);
3200
3201        prepend_close_all(spec, close);
3202
3203        // Propagate the collected list to the enclosing paren. A
3204        // container is copied on write here, so the paren cannot hold the
3205        // same array the `elem` rules are appending to; it takes the
3206        // finished one instead. The Go port does the same, for the same
3207        // reason.
3208        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3209            propagate_to_paren(rule);
3210        });
3211    });
3212}
3213
3214/// Write a rule's node onto the paren rule that encloses it.
3215fn propagate_to_paren(rule: &mut Rule) {
3216    if 0 == counter(rule, "expr_paren") {
3217        return;
3218    }
3219    let node = node_of(rule);
3220    let mut cursor = rule.parent_rule.clone();
3221    while let Some(current) = cursor {
3222        if "paren" == current.name.as_ref() {
3223            *current.node.borrow_mut() = node;
3224            return;
3225        }
3226        cursor = current.parent_rule.clone();
3227    }
3228}
3229
3230fn install_pair(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3231    let grammar = grammar.clone();
3232    parser.define_rule("pair", move |spec| {
3233        if !grammar.has_paren() {
3234            return;
3235        }
3236        // Close an implicit map within parens.
3237        let mut alt = on(&grammar.tin_close);
3238        alt.b = 1;
3239        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3240            0 != counter(rule, "expr_paren") || 0 < counter(rule, "pk")
3241        }));
3242        alt.g = "expr,expr-paren,imp,map".into();
3243        prepend_close_all(spec, vec![alt]);
3244    });
3245}
3246
3247// ---------------------------------------------------------------------------
3248// expr
3249// ---------------------------------------------------------------------------
3250
3251/// The completed expression a top-level implicit list should start with.
3252///
3253/// The rule that meets the separator is the last one the Pratt core built,
3254/// which for a right-leaning tree is a SUB-expression: `1+2*3` leaves it
3255/// holding `[*,2,3]` while the finished `[+,1,[*,2,3]]` sits on the val
3256/// this expression publishes to, and on the outermost expr in the
3257/// replacement chain. Seeding the list from the rule's own node therefore
3258/// dropped the `1+`, a wrong answer with nothing to signal it.
3259fn expr_root(rule: &Rule) -> Value {
3260    let parent = linked_node(rule.parent_rule.as_ref());
3261    if rule.parent_rule.is_some() && is_op(&parent) {
3262        return parent;
3263    }
3264
3265    // No usable parent. The outermost expr in the chain holds the root;
3266    // later entries are the sub-expressions built under it.
3267    let mut root: Option<Value> = None;
3268    if "expr" == rule.name.as_ref() {
3269        let node = node_of(rule);
3270        if is_op(&node) {
3271            root = Some(node);
3272        }
3273    }
3274    let mut cursor = rule.prev_rule.clone();
3275    while let Some(current) = cursor {
3276        if "expr" == current.name.as_ref() {
3277            let node = current.node.borrow().clone();
3278            if is_op(&node) {
3279                root = Some(node);
3280            }
3281        }
3282        cursor = current.prev_rule.clone();
3283    }
3284
3285    root.unwrap_or_else(|| node_of(rule))
3286}
3287
3288/// Start a top-level implicit list, publishing it to the rule's parent
3289/// unless there is none.
3290///
3291/// A rule seeds its node from its parent, so a list written to a missing
3292/// parent would be handed straight back out as the starting node of the
3293/// rules that follow. The rule's own node is what the parse returns at
3294/// this depth, so skipping the write costs nothing.
3295fn top_list(rule: &mut Rule) -> Value {
3296    let list = Value::array(vec![expr_root(rule)]);
3297
3298    if rule.parent_rule.is_some() {
3299        write_linked_node(rule.parent_rule.as_ref(), list.clone());
3300        return list;
3301    }
3302
3303    // No parent to publish to. The list is still built correctly by the
3304    // `elem` rules that follow, but nothing would ever read it: the
3305    // result would come back as the first member alone. Write it back
3306    // along the replacement chain instead, so whichever rule the parse
3307    // returns is holding this list.
3308    set_node(rule, list.clone());
3309    let mut cursor = rule.prev_rule.clone();
3310    while let Some(current) = cursor {
3311        *current.node.borrow_mut() = list.clone();
3312        cursor = current.prev_rule.clone();
3313    }
3314
3315    list
3316}
3317
3318/// Collect an expression into the implicit list its enclosing paren is
3319/// building, the port of the canonical `implicitList`.
3320fn implicit_list(mut matched: AltMatch, rule: &mut Rule, context: &mut Context) -> AltMatch {
3321    // Find the paren rule that contains this implicit list. A map or list
3322    // rule between the expression and the paren means the expression is
3323    // inside a contained value, not a direct paren child, so no implicit
3324    // list is created.
3325    let mut paren: Option<Rc<RuleSnapshot>> = None;
3326    let mut paren_index = 0usize;
3327    for index in (0..context.rule_stack.len()).rev() {
3328        let frame = &context.rule_stack[index];
3329        let name = frame.name.as_ref();
3330        if "paren" == name {
3331            paren = Some(frame.clone());
3332            paren_index = index;
3333            break;
3334        }
3335        if "map" == name || "list" == name {
3336            return matched;
3337        }
3338    }
3339
3340    let Some(paren) = paren else {
3341        return matched;
3342    };
3343
3344    // The node this expression contributes, captured before the write
3345    // below replaces it with the list. The ROOT, not the attachment
3346    // point: the canonical port takes it off the rule the paren pushed,
3347    // which is where `prior_expr` writes the whole expression, so a
3348    // right-leaning member such as `f(1+2*3, 4)` keeps its `1+`.
3349    let expr_node = node_of(rule);
3350    let expr_node = if is_op(&expr_node) {
3351        expression_root(rule)
3352    } else {
3353        expr_node
3354    };
3355
3356    // Create the list value for the paren rule, unless one is already
3357    // being collected, in which case the `elem` rules do the collecting.
3358    //
3359    // The canonical port reads and writes this through the paren's own
3360    // child rule, because a JavaScript array is shared by reference: the
3361    // rule collecting the list and the paren then hold the same array.
3362    // This engine copies a container on write, so the list is kept on the
3363    // paren itself and the `elem` after-close hook puts the finished one
3364    // back (as the Go port does, for the same reason).
3365    let paren_node = paren.node.borrow().clone();
3366    if matches!(&paren_node, Value::Array(members) if !members.is_empty()) {
3367        // An `elem` rule is already collecting the list, and this
3368        // expression is one of its members: leave the node alone so that
3369        // the member, and not the list, is what the collector reads.
3370        return matched;
3371    }
3372
3373    *paren.node.borrow_mut() = Value::array(vec![expr_node.clone()]);
3374    matched.r = Some("elem".into());
3375    matched.b = 0;
3376
3377    let list = paren.node.borrow().clone();
3378    set_node(rule, list.clone());
3379
3380    // The rule the first term belongs to holds the list too. The
3381    // canonical port gets that for nothing, because the rule it writes
3382    // the list through IS that rule; here the list is kept on the paren,
3383    // so this write is what the expression's own after-close reads when
3384    // it reduces the members with an evaluator.
3385    write_linked_node(rule.parent_rule.as_ref(), list.clone());
3386
3387    // The rule that sees the comma is not always the paren's own child. A
3388    // first argument that nests operators, a prefix whose operand is
3389    // itself a prefix, `f(- -1, 2)`, leaves further rules on the stack
3390    // between the paren and this rule, all holding the same expression
3391    // node. Each writes that node back over the paren's when it closes,
3392    // discarding every element collected after the first. Point them at
3393    // the implicit list so the close-back is a no-op instead of a
3394    // truncation.
3395    //
3396    // Only the frames that carry this expression: the `expr` rules
3397    // themselves, and the `val` rules they were pushed from, which hold
3398    // either nothing yet or the expression node. A rule a host plugin
3399    // stacked in between has a node of its own to close with, and
3400    // overwriting it would destroy a value this plugin knows nothing
3401    // about.
3402    for index in (paren_index + 1)..context.rule_stack.len() {
3403        let frame = context.rule_stack[index].clone();
3404        let name = frame.name.as_ref().to_string();
3405        let node = frame.node.borrow().clone();
3406        let carries = "expr" == name
3407            || ("val" == name
3408                && (node.is_undefined()
3409                    || matches!(node, Value::Null)
3410                    || same_node(&node, &expr_node)
3411                    || is_op(&node)));
3412        if carries {
3413            *frame.node.borrow_mut() = list.clone();
3414        }
3415    }
3416
3417    matched
3418}
3419
3420/// Node identity, the canonical `===` on two expression nodes.
3421fn same_node(left: &Value, right: &Value) -> bool {
3422    match (node_id(left), node_id(right)) {
3423        (Some(left), Some(right)) => left == right,
3424        _ => false,
3425    }
3426}
3427
3428fn install_expr(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3429    let grammar = grammar.clone();
3430    parser.define_rule("expr", move |spec| {
3431        let mut open: Vec<AltSpec> = Vec::new();
3432
3433        // A cast: the group just closed (the expr this one replaced holds
3434        // it, `[group, type]`) heads a prefix expression, `[cast, type]`,
3435        // whose operand follows. It takes no token: the group was the
3436        // token.
3437        if grammar.has_cast() {
3438            let mut alt = always();
3439            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3440                rule.prev_rule
3441                    .as_ref()
3442                    .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
3443            }));
3444            alt.n = counters(&[
3445                ("expr", 1),
3446                ("expr_prefix", 1),
3447                ("expr_suffix", 0),
3448                ("dlist", 1),
3449                ("dmap", 1),
3450            ]);
3451            alt.p = Some("val".into());
3452            alt.g = "expr,expr-cast".into();
3453            let ops = grammar.clone();
3454            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3455                let group = linked_node(rule.prev_rule.as_ref());
3456                let Some(cast) = op_of(&group).and_then(|gop| ops.cast.get(&gop.otin).cloned())
3457                else {
3458                    return;
3459                };
3460                let token = with_node(&group, |entry| entry.token.clone()).flatten();
3461                let op = OpRef::at(&cast, token);
3462                let prior = rule.parent_rule.clone();
3463                let node = prior_expr(rule, prior.as_ref(), &op);
3464                push_term(&node, term_at(&group, 1));
3465                publish_expr(rule, node.clone());
3466                // The val that pushed the group's expr reads its node from
3467                // that expr, its child, when it closes: that expr holds the
3468                // cast too.
3469                write_linked_node(rule.prev_rule.as_ref(), node);
3470            });
3471            open.push(alt);
3472        }
3473
3474        // A bound preval paren after an expression: a postfix operator
3475        // that takes the expression, or as much of it as it binds tighter
3476        // than, as its first term, placed as a suffix is
3477        // (`prattify_postfix`). The paren then parses the content into the
3478        // same node.
3479        if grammar.has_bound {
3480            let mut alt = on(&grammar.tin_open);
3481            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3482                rule.prev_rule
3483                    .as_ref()
3484                    .is_some_and(|prev| flag(&prev.u, POSTFIX_NEXT))
3485            }));
3486            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3487            alt.p = Some("paren".into());
3488            alt.b = 1;
3489            alt.g = "expr,expr-paren,expr-postfix".into();
3490            let ops = grammar.clone();
3491            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3492                let Some(op) = Grammar::op_use(&ops.paren_preval, rule.o0()) else {
3493                    return;
3494                };
3495                let previous = linked_node(rule.prev_rule.as_ref());
3496                let node = if is_op(&previous) {
3497                    prattify_postfix(&previous, &op)
3498                } else {
3499                    let prior = rule.prev_rule.clone();
3500                    prior_expr(rule, prior.as_ref(), &op)
3501                };
3502                publish_expr(rule, node.clone());
3503                rule.u_mut().insert(POSTFIX.to_string(), node);
3504            });
3505            open.push(alt);
3506        }
3507
3508        // An opening parenthesis of an expression.
3509        if grammar.has_paren() {
3510            let mut alt = on(&grammar.tin_open);
3511            alt.p = Some("paren".into());
3512            alt.b = 1;
3513            alt.g = "expr,expr-paren,expr-start".into();
3514            open.push(alt);
3515        }
3516
3517        if grammar.has_prefix() {
3518            let mut alt = on(&grammar.tin_prefix);
3519            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3520                0 != counter(rule, "expr_prefix")
3521            }));
3522            alt.n = counters(&[("expr", 1), ("dlist", 1), ("dmap", 1)]);
3523            alt.p = Some("val".into());
3524            alt.g = "expr,expr-prefix".into();
3525            let ops = grammar.clone();
3526            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3527                let Some(op) = Grammar::op_use(&ops.prefix, rule.o0()) else {
3528                    return;
3529                };
3530                let parent = linked_node(rule.parent_rule.as_ref());
3531                // Only fold into the parent's node when it is an
3532                // expression THIS prefix chain is building (the outer `-`
3533                // of `--1`). A ternary or paren node on the parent is a
3534                // foreign seed the engine threaded down, and folding into
3535                // it would corrupt the wrapper with a stray hole and a
3536                // duplicated operand. Start a fresh operand expression
3537                // for those, mirroring the infix guard.
3538                if is_op(&parent) && !is_ternary_op(&parent) && !is_paren_op(&parent) {
3539                    let attach = prattify(&parent, &op);
3540                    publish_expr(rule, attach);
3541                    // This prefix is a term of the expression the parent is
3542                    // building, inside that expression's own tree, so this
3543                    // rule does not evaluate it: the expression that holds
3544                    // the root evaluates the whole tree once it ends.
3545                    rule.u_mut().insert(INNER.to_string(), Value::Bool(true));
3546                } else {
3547                    let prior = rule.parent_rule.clone();
3548                    let node = prior_expr(rule, prior.as_ref(), &op);
3549                    publish_expr(rule, node);
3550                }
3551            });
3552            open.push(alt);
3553        }
3554
3555        if grammar.has_infix() {
3556            let mut alt = on(&grammar.tin_infix);
3557            alt.p = Some("val".into());
3558            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3559            alt.g = "expr,expr-infix".into();
3560            let ops = grammar.clone();
3561            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3562                let Some(op) = Grammar::op_use(&ops.infix, rule.o0()) else {
3563                    return;
3564                };
3565                let parent = linked_node(rule.parent_rule.as_ref());
3566                let previous = linked_node(rule.prev_rule.as_ref());
3567
3568                // Second and further operators.
3569                if is_op(&parent) && !is_ternary_op(&parent) {
3570                    let attach = prattify(&parent, &op);
3571                    publish_expr(rule, attach);
3572                }
3573                // The first term was a unary expression.
3574                else if is_op(&previous) {
3575                    let attach = prattify(&previous, &op);
3576                    if let Some(prev) = rule.prev_rule.clone() {
3577                        rule.parent_node = Some(prev.node.clone());
3578                        rule.parent_rule = Some(prev);
3579                    }
3580                    publish_expr(rule, attach);
3581                }
3582                // The first term was a plain value or a ternary part.
3583                else {
3584                    let prior = rule.prev_rule.clone();
3585                    let node = prior_expr(rule, prior.as_ref(), &op);
3586                    publish_expr(rule, node);
3587                }
3588            });
3589            open.push(alt);
3590        }
3591
3592        if grammar.has_suffix() {
3593            let mut alt = on(&grammar.tin_suffix);
3594            alt.n = counters(&[("expr", 1), ("expr_prefix", 0), ("dlist", 1), ("dmap", 1)]);
3595            alt.g = "expr,expr-suffix".into();
3596            let ops = grammar.clone();
3597            alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
3598                let Some(op) = Grammar::op_use(&ops.suffix, rule.o0()) else {
3599                    return;
3600                };
3601                let previous = linked_node(rule.prev_rule.as_ref());
3602                if is_op(&previous) {
3603                    let attach = prattify(&previous, &op);
3604                    // The suffix took over the val of the expression's
3605                    // first term, whose node holds the root (`-1!`, `(1)!`):
3606                    // the root is evaluated from there, as the infix after
3607                    // a unary expression does. A suffix that took over an
3608                    // expr rule already has the first term's val as its
3609                    // parent.
3610                    if let Some(prev) = rule.prev_rule.clone() {
3611                        if "val" == prev.name.as_ref() {
3612                            rule.parent_node = Some(prev.node.clone());
3613                            rule.parent_rule = Some(prev);
3614                        }
3615                    }
3616                    publish_expr(rule, attach);
3617                } else {
3618                    let prior = rule.prev_rule.clone();
3619                    let node = prior_expr(rule, prior.as_ref(), &op);
3620                    publish_expr(rule, node);
3621                }
3622            });
3623            open.push(alt);
3624        }
3625
3626        prepend_open_all(spec, open);
3627
3628        // Append the final term to the expression.
3629        spec.add_bc(|rule: &mut Rule, _context: &mut Context| {
3630            let node = node_of(rule);
3631            let Some(op) = op_of(&node) else {
3632                return;
3633            };
3634            let child = rule.child_node.clone();
3635            if term_count(&node) < op.terms && !same_node(&node, &child) {
3636                push_term(&node, child);
3637            }
3638        });
3639
3640        let mut close: Vec<AltSpec> = Vec::new();
3641
3642        // A group the table's cast accepts: the expression goes on as a
3643        // cast whose operand follows (the open alternate above), so this
3644        // close keeps n.expr and nothing evaluates the group yet. Inside a
3645        // list, a map or a paren, n.expr is zero by descent, and the
3646        // after-close would evaluate the group.
3647        if grammar.has_cast() {
3648            let mut alt = always();
3649            let condition = grammar.clone();
3650            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3651                cast_here(&condition, rule)
3652            }));
3653            alt.n = counters(&[("expr", 1)]);
3654            alt.r = Some("expr".into());
3655            alt.u = locals(&[(CAST_NEXT, Value::Bool(true))]);
3656            alt.g = "expr,expr-cast".into();
3657            close.push(alt);
3658        }
3659
3660        // A postfix paren's expression goes on after the paren, as a
3661        // suffix's does, so it takes the alternates below.
3662        let mut alt = always();
3663        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3664            rule.child_rule
3665                .as_ref()
3666                .is_some_and(|child| "paren" == child.name.as_ref())
3667                && !rule.u.contains_key(POSTFIX)
3668        }));
3669        alt.n = counters(&[("expr", 0)]);
3670        alt.g = "expr,expr-end,expr-paren-end".into();
3671        close.push(alt);
3672
3673        // Comma-op suppression. When n.no_comma_op is set by a parent
3674        // rule, terminate the expression at `,` without treating it as
3675        // the comma operator. Closing the expression frame lets the
3676        // parent rule regain control before any comma-op alternate below
3677        // fires.
3678        if grammar.has_infix() {
3679            let mut alt = on(&grammar.tin_infix);
3680            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3681                0 < counter(rule, "no_comma_op")
3682                    && rule.c0().is_some_and(|token| "," == token.src.as_str())
3683            }));
3684            alt.b = 1;
3685            alt.n = counters(&[("expr", 0)]);
3686            alt.g = "expr,no-comma-op-bail".into();
3687            close.push(alt);
3688        }
3689
3690        // A separator where the context separates: the expression ends,
3691        // and the rule that collects the terms takes the comma.
3692        if grammar.separating {
3693            let mut alt = on(&grammar.tin_sep);
3694            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3695                separated_here(rule)
3696            }));
3697            alt.b = 1;
3698            alt.n = counters(&[("expr", 0)]);
3699            alt.g = "expr,expr-sep".into();
3700            close.push(alt);
3701        }
3702
3703        if grammar.has_infix() {
3704            // Complete the prefix first.
3705            let mut alt = on(&grammar.tin_infix);
3706            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3707                0 == counter(rule, "expr_prefix")
3708            }));
3709            alt.b = 1;
3710            alt.r = Some("expr".into());
3711            alt.g = "expr,expr-infix,expr-prefix".into();
3712            close.push(alt);
3713
3714            let mut alt = on(&grammar.tin_infix);
3715            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3716                0 != counter(rule, "expr_prefix")
3717            }));
3718            alt.b = 1;
3719            alt.g = "expr,expr-infix".into();
3720            close.push(alt);
3721        }
3722
3723        if grammar.has_suffix() {
3724            let mut alt = on(&grammar.tin_suffix);
3725            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3726                0 == counter(rule, "expr_prefix")
3727            }));
3728            alt.b = 1;
3729            alt.r = Some("expr".into());
3730            alt.g = "expr,expr-suffix,expr-prefix".into();
3731            close.push(alt);
3732
3733            // A suffix after a prefix expression: complete the prefix
3734            // first, as the infix alternate above does, and leave the
3735            // suffix to the expression the prefix belongs to, which drills
3736            // it into the prefix (`-1!` is `-(1!)`). The expression goes
3737            // on, so this close keeps n.expr, and nothing evaluates it
3738            // here: the after-close below evaluates an expression only
3739            // once it has ended, and the expression the suffix extends
3740            // evaluates the whole tree.
3741            let mut alt = on(&grammar.tin_suffix);
3742            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3743                0 != counter(rule, "expr_prefix")
3744            }));
3745            alt.b = 1;
3746            alt.g = "expr,expr-suffix,expr-prefix".into();
3747            close.push(alt);
3748        }
3749
3750        // A bound preval paren after this expression: a postfix that the
3751        // next expr rule places, as the suffix alternate above does. After
3752        // a prefix expression the prefix completes first, as for a suffix,
3753        // and the paren is left to the expression the prefix belongs to.
3754        if grammar.has_bound {
3755            let mut alt = on(&grammar.tin_open);
3756            let condition = grammar.clone();
3757            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3758                rule.c0()
3759                    .is_some_and(|token| condition.postfix_opener(token.tin))
3760                    && 0 == counter(rule, "expr_prefix")
3761            }));
3762            alt.b = 1;
3763            alt.r = Some("expr".into());
3764            alt.u = locals(&[(POSTFIX_NEXT, Value::Bool(true))]);
3765            alt.g = "expr,expr-paren,expr-postfix".into();
3766            close.push(alt);
3767
3768            let mut alt = on(&grammar.tin_open);
3769            let condition = grammar.clone();
3770            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3771                rule.c0()
3772                    .is_some_and(|token| condition.postfix_opener(token.tin))
3773                    && 0 != counter(rule, "expr_prefix")
3774            }));
3775            alt.b = 1;
3776            alt.g = "expr,expr-paren,expr-postfix,expr-prefix".into();
3777            close.push(alt);
3778        }
3779
3780        if grammar.has_paren() {
3781            let mut alt = on(&grammar.tin_close);
3782            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3783                0 != counter(rule, "expr_paren")
3784            }));
3785            alt.b = 1;
3786            alt.g = "expr".into();
3787            close.push(alt);
3788        }
3789
3790        if grammar.has_ternary() {
3791            let mut alt = on(&grammar.tin_tern0);
3792            alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3793                0 == counter(rule, "expr_prefix")
3794            }));
3795            alt.b = 1;
3796            alt.r = Some("ternary".into());
3797            alt.g = "expr,expr-ternary".into();
3798            close.push(alt);
3799        }
3800
3801        // Implicit list at the top level, comma separated.
3802        let mut alt = on(&[TIN_CA]);
3803        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3804            0 == rule.d
3805        }));
3806        alt.n = counters(&[("expr", 0)]);
3807        alt.r = Some("elem".into());
3808        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3809            let list = top_list(rule);
3810            set_node(rule, list);
3811        });
3812        alt.g = "expr,comma,list,top".into();
3813        close.push(alt);
3814
3815        // Implicit list at the top level, space separated, unless values
3816        // side by side are refused.
3817        let mut alt = on(&VAL_TINS);
3818        let no_juxtapose = grammar.no_juxtapose;
3819        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3820            0 == rule.d && !no_juxtapose
3821        }));
3822        alt.n = counters(&[("expr", 0)]);
3823        alt.b = 1;
3824        alt.r = Some("elem".into());
3825        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
3826            let list = top_list(rule);
3827            set_node(rule, list);
3828        });
3829        alt.g = "expr,space,list,top".into();
3830        close.push(alt);
3831
3832        // Implicit list indicated by a comma.
3833        let mut alt = on(&[TIN_CA]);
3834        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
3835            rule.lte("pk", 0)
3836        }));
3837        alt.n = counters(&[("expr", 0)]);
3838        alt.b = 1;
3839        alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3840            implicit_list(matched, rule, context)
3841        }));
3842        alt.g = "expr,list,val,imp,comma".into();
3843        close.push(alt);
3844
3845        // Implicit list indicated by a space separated value.
3846        //
3847        // This alternate carries no token filter, so it also has to be
3848        // kept off a pending suffix operator. A suffix belongs to the
3849        // expression that just closed, not to a new element: `f(@x!)`
3850        // reaches here on the `!` of a completed prefix, opens `elem`,
3851        // and offers `!` as the start of a value, which nothing matches,
3852        // so a valid expression fails as unexpected. Leaving the token
3853        // alone lets the val-close suffix alternate take it, which is how
3854        // the same expression already parses at the top level.
3855        let mut alt = always();
3856        let condition = grammar.clone();
3857        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
3858            let next = context.t0().map(|token| token.tin);
3859            rule.lte("pk", 0)
3860                && rule.lte("expr_suffix", 0)
3861                && !next.is_some_and(|tin| condition.tin_suffix.contains(&tin))
3862                && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
3863        }));
3864        alt.n = counters(&[("expr", 0)]);
3865        alt.h_match = Some(Arc::new(|matched, rule, context, _next| {
3866            implicit_list(matched, rule, context)
3867        }));
3868        alt.g = "expr,list,val,imp,space".into();
3869        close.push(alt);
3870
3871        // The expression ends on a non-expression token.
3872        let mut alt = always();
3873        alt.n = counters(&[("expr", 0)]);
3874        alt.g = "expr,expr-end".into();
3875        close.push(alt);
3876
3877        prepend_close_all(spec, close);
3878
3879        // Put the ROOT of the expression back on the node, so the last
3880        // rule of a replacement chain hands the whole expression to the
3881        // rule that collects it, rather than the sub-expression the last
3882        // operator attached to. Only while the node still IS the
3883        // attachment point: a close alternate that produced an implicit
3884        // list has replaced it deliberately.
3885        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
3886            if is_op(&node_of(rule)) {
3887                let root = expression_root(rule);
3888                set_node(rule, root);
3889            }
3890        });
3891
3892        // Evaluate at the root of the expression, where n.expr is zero.
3893        if let Some(evaluate) = grammar.evaluate.clone() {
3894            spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
3895                if 0 != counter(rule, "expr") {
3896                    return;
3897                }
3898                // Evaluation follows the tree the S-expression shows, so an
3899                // expression is evaluated once, whole, from its root, once
3900                // it has ended. A prefix inside an operand of an enclosing
3901                // expression (`-2` in `1+-2`) was built into that
3902                // expression's tree: evaluating here evaluated the
3903                // enclosing tree too, before it was complete, and then
3904                // again when it was.
3905                if matches!(rule.u.get(INNER), Some(Value::Bool(true))) {
3906                    return;
3907                }
3908                let Some(parent) = rule.parent_rule.clone() else {
3909                    return;
3910                };
3911                let parent_node = parent.node.borrow().clone();
3912
3913                // The parent holds an implicit list (`f(1+2, 3)`,
3914                // `1+2, 3`) rather than this expression's own node. A
3915                // list is a plain array, not an expression node, so its
3916                // members would otherwise reach the caller as raw
3917                // S-expressions the evaluator was never called on.
3918                //
3919                // Reduce them in place, keeping the array: the list is
3920                // still being collected, and the paren rule and the expr
3921                // rules between it and here all hold a reference to this
3922                // exact array, so replacing it would strand the members
3923                // still to come. A member already reduced is returned
3924                // untouched rather than reduced again.
3925                if let Value::Array(members) = &parent_node {
3926                    let mut site = EvalSite::new(Some(parent.clone()), context);
3927                    let reduced: Vec<Value> = members
3928                        .iter()
3929                        .map(|member| evaluation(&mut site.reborrow(), member, &evaluate))
3930                        .collect();
3931                    let reduced = Value::array(reduced);
3932                    *parent.node.borrow_mut() = reduced.clone();
3933                    // Through the shared cell, not into a fresh one: the
3934                    // rule that collects the rest of the list was already
3935                    // seeded from this cell, and the canonical port keeps
3936                    // the one array for the same reason.
3937                    publish(rule, reduced);
3938                    return;
3939                }
3940
3941                // The parent node holds the root of the expression tree.
3942                let out = {
3943                    let mut site = EvalSite::new(Some(parent.clone()), context);
3944                    evaluation(&mut site, &parent_node, &evaluate)
3945                };
3946                *parent.node.borrow_mut() = out.clone();
3947
3948                // A cast took over its group's expr rule, which the val that
3949                // pushed it reads its node from when it closes.
3950                if rule
3951                    .prev_rule
3952                    .as_ref()
3953                    .is_some_and(|prev| flag(&prev.u, CAST_NEXT))
3954                {
3955                    write_linked_node(rule.prev_rule.as_ref(), out.clone());
3956                }
3957
3958                // Also write the evaluated result onto this rule's own
3959                // node. When the expr rule was PUSHED from a still-open
3960                // val (the prefix and paren forms, `+1`, `(a)`), that
3961                // val's close coalescing reads its child's node, which is
3962                // this rule, and would otherwise restore the raw
3963                // S-expression and discard the evaluated value.
3964                publish(rule, out);
3965            });
3966        }
3967    });
3968}
3969
3970// ---------------------------------------------------------------------------
3971// paren
3972// ---------------------------------------------------------------------------
3973
3974fn paren_depth(name: &str) -> String {
3975    format!("expr_paren_depth_{name}")
3976}
3977
3978fn install_paren(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
3979    let grammar = grammar.clone();
3980    parser.define_rule("paren", move |spec| {
3981        // Allow implicits inside parens.
3982        spec.add_bo(|rule: &mut Rule, _context: &mut Context| {
3983            let counters = rule.n_mut();
3984            counters.insert("dmap".into(), 0);
3985            counters.insert("dlist".into(), 0);
3986            counters.insert("pk".into(), 0);
3987        });
3988
3989        let mut open: Vec<AltSpec> = Vec::new();
3990
3991        // A paren whose content is required may not be empty: `()` is
3992        // refused at its closer, where a content was due.
3993        if grammar.has_required {
3994            let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
3995            let condition = grammar.clone();
3996            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
3997                let close = rule.o1().map(|token| token.tin);
3998                paren_op_for(&condition, rule)
3999                    .is_some_and(|op| Some(op.ctin) == close && op.content.required)
4000            }));
4001            alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4002                rule.o1().cloned()
4003            }));
4004            alt.g = "expr,expr-paren,empty,required".into();
4005            open.push(alt);
4006        }
4007
4008        // Empty parens: `()`.
4009        let mut alt = on2(&grammar.tin_open, &grammar.tin_close);
4010        alt.b = 1;
4011        alt.g = "expr,expr-paren,empty".into();
4012        let condition = grammar.clone();
4013        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4014            let close = rule.o1().map(|token| token.tin);
4015            paren_op_for(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
4016        }));
4017        let ops = grammar.clone();
4018        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4019            open_paren(&ops, rule);
4020        });
4021        open.push(alt);
4022
4023        // A normal paren open: consume the opener and push to val.
4024        let mut alt = on(&grammar.tin_open);
4025        alt.p = Some("val".into());
4026        alt.n = counters(&[
4027            ("expr_paren", 1),
4028            ("expr", 0),
4029            ("expr_prefix", 0),
4030            ("expr_suffix", 0),
4031        ]);
4032        alt.g = "expr,expr-paren,open".into();
4033        let ops = grammar.clone();
4034        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4035            open_paren(&ops, rule);
4036        });
4037        open.push(alt);
4038
4039        prepend_open_all(spec, open);
4040
4041        let mut close: Vec<AltSpec> = Vec::new();
4042
4043        // A separator in a separated content: the term before it is done,
4044        // and the next one follows. The loop is this rule's own close, so a
4045        // long argument list adds no rule depth. A term that is empty
4046        // (`f(,a)`, `f(a,,b)`) is refused at the separator after it.
4047        if grammar.separating {
4048            let mut alt = on(&grammar.tin_sep);
4049            let condition = grammar.clone();
4050            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4051                separated_paren(&condition, rule) && paren_term(rule).is_undefined()
4052            }));
4053            alt.e = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4054                rule.c0().cloned()
4055            }));
4056            alt.g = "expr,expr-paren,expr-sep,empty".into();
4057            close.push(alt);
4058
4059            let mut alt = on(&grammar.tin_sep);
4060            let condition = grammar.clone();
4061            alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4062                separated_paren(&condition, rule)
4063            }));
4064            alt.p = Some("val".into());
4065            alt.n = counters(&[("expr", 0), ("expr_prefix", 0), ("expr_suffix", 0)]);
4066            alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4067                let term = paren_term(rule);
4068                collect_paren_item(rule, term);
4069                rule.u_mut()
4070                    .insert(PAREN_MORE.to_string(), Value::Bool(true));
4071                // The next term starts empty, as the first did.
4072                set_node(rule, Value::Undefined);
4073            });
4074            alt.g = "expr,expr-paren,expr-sep".into();
4075            close.push(alt);
4076        }
4077
4078        let mut alt = on(&grammar.tin_close);
4079        let condition = grammar.clone();
4080        // The closer of the operator this paren opened.
4081        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4082            let close = rule.c0().map(|token| token.tin);
4083            opened_paren(&condition, rule).is_some_and(|op| Some(op.ctin) == close)
4084        }));
4085        let ops = grammar.clone();
4086        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4087            close_paren(&ops, rule);
4088        });
4089        alt.g = "expr,expr-paren,close".into();
4090        close.push(alt);
4091
4092        prepend_close_all(spec, close);
4093
4094        spec.add_ac(|rule: &mut Rule, _context: &mut Context| {
4095            // A separator's pass goes on to the next term: the paren is
4096            // not done.
4097            if flag(&rule.u, PAREN_MORE) {
4098                rule.u_mut()
4099                    .insert(PAREN_MORE.to_string(), Value::Bool(false));
4100                return;
4101            }
4102            // A postfix paren extended the node of the expression it
4103            // applies to, in place, and its expr rule holds that node
4104            // already: the rules above hold the expression's root, which
4105            // stays.
4106            if rule
4107                .parent_rule
4108                .as_ref()
4109                .is_some_and(|parent| parent.u.contains_key(POSTFIX))
4110            {
4111                return;
4112            }
4113            let node = node_of(rule);
4114            let parent = rule.parent_rule.clone();
4115            write_linked_node(parent.as_ref(), node.clone());
4116            let grandparent = parent.and_then(|parent| parent.parent_rule.clone());
4117            write_linked_node(grandparent.as_ref(), node);
4118        });
4119    });
4120}
4121
4122/// The paren operator a paren rule opens: the preval one when a value
4123/// precedes the opener, which the val that pushed this rule's expr records
4124/// as `u.paren_preval`, and the group otherwise.
4125fn paren_op_for(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
4126    let tin = rule.o0()?.tin;
4127    if paren_has_preval(rule) {
4128        grammar.paren_preval.get(&tin).cloned()
4129    } else {
4130        grammar.paren_plain.get(&tin).cloned()
4131    }
4132}
4133
4134/// Whether a value precedes this paren's opener: the val that pushed its
4135/// expr recorded `paren_preval`, or the paren is a postfix of the
4136/// expression its expr extends.
4137fn paren_has_preval(rule: &Rule) -> bool {
4138    let Some(parent) = rule.parent_rule.as_ref() else {
4139        return false;
4140    };
4141    parent.u.contains_key(POSTFIX)
4142        || parent
4143            .parent_rule
4144            .as_ref()
4145            .is_some_and(|grandparent| flag(&grandparent.u, "paren_preval"))
4146}
4147
4148/// The `u` key a paren rule records the operator it opened under, by name:
4149/// its close builds the node with it, since two operators may share a
4150/// closer.
4151const PAREN_OP: &str = "expr_paren_op";
4152
4153/// The operator this paren rule opened.
4154fn opened_paren(grammar: &Grammar, rule: &Rule) -> Option<Arc<Op>> {
4155    let Some(Value::String(name)) = rule.u.get(PAREN_OP) else {
4156        return None;
4157    };
4158    grammar.parens.iter().find(|op| &op.name == name).cloned()
4159}
4160
4161fn open_paren(grammar: &Grammar, rule: &mut Rule) {
4162    let Some(op) = paren_op_for(grammar, rule) else {
4163        return;
4164    };
4165    rule.u_mut()
4166        .insert(PAREN_OP.to_string(), Value::String(op.name.clone()));
4167    // A group, opened with no value before it, which a cast may take as
4168    // its token.
4169    let group = !paren_has_preval(rule);
4170    rule.u_mut()
4171        .insert(PAREN_GROUP.to_string(), Value::Bool(group));
4172    // The content separates on commas only in a paren whose content is
4173    // separated: a group inside a call takes the comma operator again.
4174    if grammar.separating {
4175        rule.n_mut()
4176            .insert("expr_sep".into(), i32::from(op.content.separated));
4177    }
4178    let depth = paren_depth(&op.name);
4179    rule.u_mut().insert(depth.clone(), Value::Number(1.0));
4180    rule.n_mut().insert(depth, 1);
4181    set_node(rule, Value::Undefined);
4182}
4183
4184fn close_paren(grammar: &Grammar, rule: &mut Rule) {
4185    let child = rule.child_node.clone();
4186    let mut node = node_of(rule);
4187    // The child's value, when this paren holds nothing of its own yet.
4188    //
4189    // The canonical port also takes the child whenever it is an operator,
4190    // and can, because it collects an implicit list IN the child's node
4191    // (`paren.child.node = [...]`): there the child IS the list. This
4192    // engine copies a container on write, so the list is collected on the
4193    // paren itself instead, while the child link stays on the rule the
4194    // paren PUSHED rather than on whichever rule of a replacement chain
4195    // popped last (tabnas/parser a801621, matching TS and Go). That rule
4196    // can still hold the list's first member, an operator. A node already
4197    // on the paren is the collected list, and the child must not overwrite
4198    // it: `(1?2:3 b)` would come back as `(1?2:3)`.
4199    if node.is_undefined() {
4200        node = child;
4201    }
4202
4203    let Some(op) = opened_paren(grammar, rule) else {
4204        set_node(rule, node);
4205        return;
4206    };
4207    let op = OpRef::at(&op, rule.c0().cloned());
4208    let depth = paren_depth(&op.op.name);
4209
4210    // Construct the completed paren expression.
4211    if local_number(rule, &depth) == i64::from(counter(rule, &depth)) {
4212        let mut terms: Vec<Value> = Vec::new();
4213
4214        let grandparent = rule
4215            .parent_rule
4216            .as_ref()
4217            .filter(|parent| !parent.u.contains_key(POSTFIX))
4218            .and_then(|parent| parent.parent_rule.clone());
4219        if let Some(grandparent) = &grandparent {
4220            let preval = grandparent.node.borrow().clone();
4221            if matches!(grandparent.u.get("paren_preval"), Some(Value::Bool(true)))
4222                && !preval.is_undefined()
4223            {
4224                terms.push(preval);
4225            }
4226        }
4227
4228        // The content's terms: the one term, or each term of a separated
4229        // content, the earlier ones collected at their separators.
4230        let mut content: Vec<Value> = paren_items(rule);
4231        if !node.is_undefined() {
4232            content.push(node);
4233        }
4234
4235        // A postfix paren extends the node its expr rule placed in the
4236        // tree, `[op, target]`, in place.
4237        let postfix = rule
4238            .parent_rule
4239            .as_ref()
4240            .and_then(|parent| parent.u.get(POSTFIX).cloned());
4241        if let Some(postfix) = postfix {
4242            with_node_mut(&postfix, |entry| {
4243                entry.op = Some(op.op.clone());
4244                entry.token = op.token.clone();
4245            });
4246            for term in content {
4247                push_term(&postfix, term);
4248            }
4249            set_node(rule, postfix);
4250            return;
4251        }
4252
4253        terms.extend(content);
4254        set_node(rule, op.node(terms));
4255    } else {
4256        set_node(rule, node);
4257    }
4258}
4259
4260// ---------------------------------------------------------------------------
4261// ternary
4262// ---------------------------------------------------------------------------
4263
4264fn install_ternary(parser: &mut Tabnas, grammar: &Arc<Grammar>) {
4265    let grammar = grammar.clone();
4266    parser.define_rule("ternary", move |spec| {
4267        let mut open: Vec<AltSpec> = Vec::new();
4268
4269        let mut alt = on(&grammar.tin_tern0);
4270        alt.p = Some("val".into());
4271        alt.n = counters(&[
4272            ("expr_ternary", 1),
4273            ("expr", 0),
4274            ("expr_prefix", 0),
4275            ("expr_suffix", 0),
4276        ]);
4277        alt.u = locals(&[("expr_ternary_step", Value::Number(1.0))]);
4278        alt.g = "expr,expr-ternary,open".into();
4279        let ops = grammar.clone();
4280        alt.add_action(move |rule: &mut Rule, _context: &mut Context| {
4281            let Some(op) = Grammar::op_use(&ops.ternary, rule.o0()) else {
4282                return;
4283            };
4284            rule.u_mut().insert(
4285                "expr_ternary_name".into(),
4286                Value::String(op.op.name.clone()),
4287            );
4288
4289            let previous = linked_node(rule.prev_rule.as_ref());
4290            let node = if is_op(&previous) {
4291                let duplicate = dup_node(&previous);
4292                update_expr_node(
4293                    &previous,
4294                    Some(op.op.clone()),
4295                    op.token.clone(),
4296                    vec![duplicate],
4297                );
4298                previous
4299            } else {
4300                let node = op.node(vec![previous]);
4301                write_linked_node(rule.prev_rule.as_ref(), node.clone());
4302                node
4303            };
4304            set_node(rule, node);
4305
4306            let paren = if 0 != counter(rule, "expr_paren") {
4307                i64::from(counter(rule, "expr_paren"))
4308            } else {
4309                rule.prev_rule
4310                    .as_ref()
4311                    .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"))
4312            };
4313            rule.u_mut()
4314                .insert("expr_ternary_paren".into(), Value::Number(paren as f64));
4315            rule.n_mut().insert("expr_paren".into(), 0);
4316        });
4317        open.push(alt);
4318
4319        let mut alt = always();
4320        alt.p = Some("val".into());
4321        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4322            rule.prev_rule
4323                .as_ref()
4324                .is_some_and(|prev| 2 == snapshot_number(prev, "expr_ternary_step"))
4325        }));
4326        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4327            let (step, paren) = rule.prev_rule.as_ref().map_or((0, 0), |prev| {
4328                (
4329                    snapshot_number(prev, "expr_ternary_step"),
4330                    snapshot_number(prev, "expr_ternary_paren"),
4331                )
4332            });
4333            set_local_number(rule, "expr_ternary_step", step);
4334            set_local_number(rule, "expr_ternary_paren", paren);
4335            rule.n_mut().insert("expr_paren".into(), paren as i32);
4336        });
4337        alt.g = "expr,expr-ternary,step".into();
4338        open.push(alt);
4339
4340        prepend_open_all(spec, open);
4341
4342        let mut close: Vec<AltSpec> = Vec::new();
4343
4344        let mut alt = on(&grammar.tin_tern1);
4345        let condition = grammar.clone();
4346        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, _context: &mut Context| {
4347            if 1 != local_number(rule, "expr_ternary_step") {
4348                return false;
4349            }
4350            let Some(op) = rule
4351                .c0()
4352                .and_then(|token| condition.ternary.get(&token.tin))
4353                .cloned()
4354            else {
4355                return false;
4356            };
4357            matches!(rule.u.get("expr_ternary_name"), Some(Value::String(name)) if name == &op.name)
4358        }));
4359        alt.r = Some("ternary".into());
4360        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4361            let step = local_number(rule, "expr_ternary_step");
4362            set_local_number(rule, "expr_ternary_step", step + 1);
4363            let node = node_of(rule);
4364            push_term(&node, rule.child_node.clone());
4365        });
4366        alt.g = "expr,expr-ternary,step".into();
4367        close.push(alt);
4368
4369        // End of ternary at the top level, implicit list indicated by a
4370        // comma. Handle a ternary as the first item of an implicit list
4371        // inside parens.
4372        let mut tins = vec![TIN_CA];
4373        tins.extend(grammar.tin_close.iter().copied());
4374        let mut alt = on(&tins);
4375        // Not at a separator of a separated content, which ends the
4376        // ternary as one of that content's terms.
4377        let condition = grammar.clone();
4378        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4379            let at_sep = rule
4380                .c0()
4381                .is_some_and(|token| condition.tin_sep.contains(&token.tin));
4382            implicit_ternary_cond(rule, context) && !(separated_here(rule) && at_sep)
4383        }));
4384        let closers = grammar.tin_close.clone();
4385        alt.b_fn = Some(Arc::new(move |_rule: &mut Rule, context: &mut Context| {
4386            usize::from(next_is_close(context, &closers))
4387        }));
4388        let closers = grammar.tin_close.clone();
4389        alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4390            let to_elem = !next_is_close(context, &closers)
4391                && (0 == rule.d
4392                    || (rule
4393                        .prev_rule
4394                        .as_ref()
4395                        .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren"))
4396                        && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))));
4397            to_elem.then(|| "elem".to_string())
4398        }));
4399        alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
4400            implicit_ternary_action(rule, matched);
4401            None
4402        });
4403        alt.g = "expr,expr-ternary,list,val,imp,comma".into();
4404        close.push(alt);
4405
4406        // End of ternary at the top level, implicit list indicated by a
4407        // space separated value.
4408        let mut alt = always();
4409        // Neither at a separator of a separated content, nor, with
4410        // `juxtapose: false`, at a value beside the ternary.
4411        let condition = grammar.clone();
4412        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4413            let next = context.t0().map(|token| token.tin);
4414            implicit_ternary_cond(rule, context)
4415                && !(separated_here(rule)
4416                    && next.is_some_and(|tin| condition.tin_sep.contains(&tin)))
4417                && !(condition.no_juxtapose && next.is_some_and(|tin| condition.starts_value(tin)))
4418        }));
4419        let closers = grammar.tin_close.clone();
4420        alt.r_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
4421            let ended = context.t0().is_some_and(|token| TIN_ZZ == token.tin);
4422            let to_elem = (0 == rule.d
4423                || !next_is_close(context, &closers)
4424                || rule
4425                    .prev_rule
4426                    .as_ref()
4427                    .is_some_and(|prev| 0 != snapshot_number(prev, "expr_ternary_paren")))
4428                && 0 == node_length(&linked_node(rule.parent_rule.as_ref()))
4429                && !ended;
4430            to_elem.then(|| "elem".to_string())
4431        }));
4432        alt.add_action_with_match(|rule: &mut Rule, _context: &mut Context, matched| {
4433            implicit_ternary_action(rule, matched);
4434            None
4435        });
4436        alt.g = "expr,expr-ternary,list,val,imp,space".into();
4437        close.push(alt);
4438
4439        // End of ternary.
4440        let mut alt = always();
4441        alt.c_fn = Some(Arc::new(|rule: &mut Rule, _context: &mut Context| {
4442            0 < rule.d && 2 == local_number(rule, "expr_ternary_step")
4443        }));
4444        alt.add_action(|rule: &mut Rule, _context: &mut Context| {
4445            let node = node_of(rule);
4446            push_term(&node, rule.child_node.clone());
4447        });
4448        alt.g = "expr,expr-ternary,close".into();
4449        close.push(alt);
4450
4451        prepend_close_all(spec, close);
4452
4453        // Ensure ternary results get evaluated. Without this, a ternary
4454        // that is not wrapped in an expr leaves its result as a raw
4455        // S-expression. Fire on every ternary instance's after-close, but
4456        // act only when the chain has reached its final step: the node
4457        // has accumulated all three operands and the next rule is not
4458        // another ternary. Write the evaluated value back along the
4459        // replacement chain so whichever node the parse returns reflects
4460        // the evaluated form.
4461        if let Some(evaluate) = grammar.evaluate.clone() {
4462            spec.add_ac(move |rule: &mut Rule, context: &mut Context| {
4463                if rule
4464                    .next_rule_name
4465                    .as_ref()
4466                    .is_some_and(|name| "ternary" == name.as_ref())
4467                {
4468                    return;
4469                }
4470                let node = node_of(rule);
4471                if !is_op(&node) {
4472                    return;
4473                }
4474                // The node is not fully populated until all three
4475                // operands sit under it; earlier steps carry fewer.
4476                if node_length(&node) < 4 {
4477                    return;
4478                }
4479                let out = {
4480                    // The canonical port hands the ternary rule itself to
4481                    // the evaluator here, where the expr rule hands its
4482                    // parent.
4483                    let site_rule = rule.snapshot();
4484                    let mut site = EvalSite::new(Some(site_rule), context);
4485                    evaluation(&mut site, &node, &evaluate)
4486                };
4487                publish(rule, out.clone());
4488                let mut cursor = rule.prev_rule.clone();
4489                while let Some(current) = cursor {
4490                    *current.node.borrow_mut() = out.clone();
4491                    cursor = current.prev_rule.clone();
4492                }
4493                write_linked_node(rule.parent_rule.as_ref(), out);
4494            });
4495        }
4496    });
4497}
4498
4499fn snapshot_number(snapshot: &RuleSnapshot, name: &str) -> i64 {
4500    match snapshot.u.get(name) {
4501        Some(Value::Number(number)) => *number as i64,
4502        _ => 0,
4503    }
4504}
4505
4506fn next_is_close(context: &mut Context, closers: &[Tin]) -> bool {
4507    context
4508        .t0()
4509        .is_some_and(|token| closers.contains(&token.tin))
4510}
4511
4512fn implicit_ternary_cond(rule: &mut Rule, _context: &mut Context) -> bool {
4513    (0 == rule.d || 1 <= counter(rule, "expr_paren"))
4514        && 0 == counter(rule, "pk")
4515        && 2 == local_number(rule, "expr_ternary_step")
4516}
4517
4518fn implicit_ternary_action(rule: &mut Rule, matched: &AltMatch) {
4519    let paren = rule
4520        .prev_rule
4521        .as_ref()
4522        .map_or(0, |prev| snapshot_number(prev, "expr_ternary_paren"));
4523    rule.n_mut().insert("expr_paren".into(), paren as i32);
4524
4525    let node = node_of(rule);
4526    push_term(&node, rule.child_node.clone());
4527
4528    if matched.r.as_deref() != Some("elem") {
4529        return;
4530    }
4531
4532    // The completed ternary becomes the first element of an implicit
4533    // list. The canonical port rewrites the node into that list in place,
4534    // so that every holder sees it; here the list is written through the
4535    // shared node cell instead, which is what the replacing `elem` rule
4536    // is seeded from, and onto the enclosing paren, because a container
4537    // is copied on write and the two cannot share one array.
4538    let list = Value::array(vec![node]);
4539    publish(rule, list.clone());
4540    if 1 <= counter(rule, "expr_paren") {
4541        let mut cursor = rule.parent_rule.clone();
4542        while let Some(current) = cursor {
4543            if "paren" == current.name.as_ref() {
4544                *current.node.borrow_mut() = list;
4545                break;
4546            }
4547            cursor = current.parent_rule.clone();
4548        }
4549    }
4550}
4551
4552// ---------------------------------------------------------------------------
4553// Public entry points
4554// ---------------------------------------------------------------------------
4555
4556/// The plugin, for [`Tabnas::use_plugin`], carrying the default operator
4557/// table as its declared defaults.
4558///
4559/// Call-site options are deep-merged over those defaults by the engine, so
4560/// an entry naming a default operator extends it and a `null` entry
4561/// deletes it, exactly as in the canonical TypeScript. An evaluator cannot
4562/// travel in a serialized option bag: pass one with [`plugin_with`].
4563///
4564/// ```
4565/// use tabnas::Value;
4566///
4567/// fn main() -> Result<(), Box<dyn std::error::Error>> {
4568///     let mut parser = tabnas_jsonic::make();
4569///     parser.use_plugin(tabnas_expr::plugin(), None)?;
4570///     let value = tabnas_expr::realize(&parser.parse("1+2")?);
4571///     assert_eq!(tabnas_expr::simplify(&value).to_string(), "[\"+\",1,2]");
4572///     Ok::<(), Box<dyn std::error::Error>>(())
4573/// }
4574/// ```
4575pub fn plugin() -> Plugin {
4576    Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
4577        expr(parser, &ExprOptions::from_value(options))
4578    })
4579    .with_defaults(defaults())
4580}
4581
4582/// The plugin with typed options, which is how an evaluator and any
4583/// operator data that no `Value` can carry reach the grammar.
4584///
4585/// The typed options resolve the defaults themselves, so the serialized
4586/// option bag is not consulted: an operator given here replaces the
4587/// default of the same name outright rather than extending it.
4588pub fn plugin_with(options: ExprOptions) -> Plugin {
4589    Plugin::new(PLUGIN_NAME, move |parser: &mut Tabnas, _options: &Value| {
4590        expr(parser, &options)
4591    })
4592}
4593
4594/// Install the expression grammar on a parser through
4595/// [`Tabnas::use_plugin`], so that a derived instance rebuilds it.
4596pub fn apply(parser: &mut Tabnas, options: ExprOptions) -> Result<(), PluginError> {
4597    parser.use_plugin(plugin_with(options), None).map(|_| ())
4598}
4599
4600/// Build a parser with the jsonic base grammar and the default operator
4601/// table.
4602///
4603/// ```
4604/// fn main() -> Result<(), Box<dyn std::error::Error>> {
4605///     let parser = tabnas_expr::make();
4606///     let value = tabnas_expr::parse_with(&parser, "(1+2)*3")?;
4607///     assert_eq!(tabnas_expr::simplify(&value).to_string(),
4608///                r#"["*",["(",["+",1,2]],3]"#);
4609///     Ok(())
4610/// }
4611/// ```
4612pub fn make() -> Tabnas {
4613    make_with(ExprOptions::new())
4614}
4615
4616/// Build a parser with the jsonic base grammar and the given options.
4617pub fn make_with(options: ExprOptions) -> Tabnas {
4618    make_on(tabnas_jsonic::make(), options)
4619}
4620
4621/// Install the expression grammar on `parser`, jsonic's base, and declare
4622/// this parser's own window setting: `lex.window` false, so that
4623/// [`Tabnas::parse_reader`] reads a reader whole (admin ADR-30). The
4624/// grammar's matchers are not yet verified at the window's edge, and a base
4625/// that declares the window must not carry it to them; the setting comes
4626/// last, after everything the base and the grammar set.
4627fn make_on(mut parser: Tabnas, options: ExprOptions) -> Tabnas {
4628    parser
4629        .use_plugin(plugin_with(options), None)
4630        .expect("the expression grammar installs on the jsonic base");
4631    parser
4632        .set_options(|options| options.lex.window = false)
4633        .expect("lex.window sets");
4634    parser
4635}
4636
4637#[cfg(test)]
4638mod window_tests {
4639    /// The parser's own setting wins over its base's: a base that declares
4640    /// `lex.window`, as jsonic's own constructor may, given the
4641    /// constructor's steps, comes out with the window off.
4642    #[test]
4643    fn a_windowed_base_comes_out_without_the_window() {
4644        let mut base = tabnas_jsonic::make();
4645        base.set_options(|options| options.lex.window = true)
4646            .expect("lex.window sets");
4647        assert!(base.options.lex.window);
4648        let parser = super::make_on(base, super::ExprOptions::new());
4649        assert!(!parser.options.lex.window);
4650        assert!(super::parse_with(&parser, "1+2*3").is_ok());
4651    }
4652}
4653
4654/// The lazily built instance the no-options [`parse`] reuses.
4655///
4656/// Building the grammar dominates a parse, so a fresh instance per call is
4657/// many times slower (see `tests/perf_test.rs`). Parsing builds a fresh
4658/// context per call and only reads instance state, so one shared instance
4659/// is safe to use from several threads.
4660static DEFAULT_PARSER: OnceLock<Tabnas> = OnceLock::new();
4661
4662/// Parse one document with the default operator table.
4663///
4664/// ```
4665/// fn main() -> Result<(), Box<dyn std::error::Error>> {
4666///     let value = tabnas_expr::parse("a:1+2")?;
4667///     assert_eq!(tabnas_expr::simplify(&value).to_string(),
4668///                r#"{"a":["+",1,2]}"#);
4669///     Ok(())
4670/// }
4671/// ```
4672pub fn parse(src: &str) -> Result<Value, TabnasError> {
4673    parse_with(DEFAULT_PARSER.get_or_init(make), src)
4674}
4675
4676/// Parse one document with a parser this crate configured, and realize the
4677/// expression nodes in the result.
4678///
4679/// A parser driven directly through [`Tabnas::parse`] returns a value whose
4680/// expression nodes are still handles into the per-parse arena; pass that
4681/// value to [`realize`] before the next parse on the same thread.
4682pub fn parse_with(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
4683    let _guard = ArenaGuard::enter();
4684    let value = parser.parse(src)?;
4685    Ok(realize(&value))
4686}
4687
4688/// Parse one document and hand the unrealized value to a closure, with
4689/// the expression arena held open for as long as it runs.
4690///
4691/// This is the parse-once, evaluate-many workflow: inside the closure the
4692/// expression nodes are live, so [`evaluation`] can reduce them, and
4693/// whatever the closure returns outlives them.
4694///
4695/// The arena is released when this returns, so the closure must not let an
4696/// expression HANDLE escape in what it returns. Return a reduced value, as
4697/// the example below does, or call [`realize`] on the tree and return
4698/// that; [`parse_with`] is the same parse with the realizing already done.
4699/// A handle that escapes names a node that no longer exists, and
4700/// [`realize`] and [`simplify`] then PANIC rather than report the lost
4701/// expression as an empty array. The closure return type is a type
4702/// parameter, so nothing in the signature can realize it for a caller, and
4703/// nothing in it can stop a handle from being returned.
4704///
4705/// ```
4706/// use tabnas::Value;
4707/// use tabnas_expr::{evaluation, EvalSite, Evaluate, Op};
4708///
4709/// fn main() -> Result<(), Box<dyn std::error::Error>> {
4710///     let parser = tabnas_expr::make();
4711///     let add: Evaluate = std::sync::Arc::new(
4712///         |_site: &mut EvalSite<'_>, _op: &Op, terms: &[Value]| match terms {
4713///             [Value::Number(left), Value::Number(right)] => Value::Number(left + right),
4714///             _ => Value::Null,
4715///         },
4716///     );
4717///     let total = tabnas_expr::parse_scope(&parser, "1+2", |value| {
4718///         evaluation(&mut EvalSite::detached(), &value, &add)
4719///     })?;
4720///     assert_eq!(total, Value::Number(3.0));
4721///     Ok(())
4722/// }
4723/// ```
4724pub fn parse_scope<R>(
4725    parser: &Tabnas,
4726    src: &str,
4727    use_value: impl FnOnce(Value) -> R,
4728) -> Result<R, TabnasError> {
4729    let _guard = ArenaGuard::enter();
4730    let value = parser.parse(src)?;
4731    Ok(use_value(value))
4732}
4733
4734/// Parse one document and reduce it to the S-expression form the shared
4735/// fixtures compare.
4736pub fn parse_simplified(parser: &Tabnas, src: &str) -> Result<Value, TabnasError> {
4737    let _guard = ArenaGuard::enter();
4738    let value = parser.parse(src)?;
4739    Ok(simplify(&value))
4740}
4741
4742// --- Translation parts (admin ADR-27) ---------------------------------
4743
4744/// One optional alchemy translation source and its explicit entry point.
4745#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4746pub struct TranslationPart {
4747    /// The definition a host calls after linking the source.
4748    pub entry: &'static str,
4749    /// The source text, or `None` for an entry supplied by alchemy.
4750    pub source: Option<&'static str>,
4751}
4752
4753/// The package-local structural translation interface.
4754#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4755pub struct TranslationParts {
4756    /// The complete `tabnas.plugin.json` text.
4757    pub manifest: &'static str,
4758    /// An optional lift from the grammar's events to its first read shape.
4759    pub lift: Option<TranslationPart>,
4760    /// An optional embedding of a plain tree in the format's schema, with its reverse.
4761    pub embed: Option<TranslationPart>,
4762    /// An optional render from the write shape to text.
4763    pub render: Option<TranslationPart>,
4764}
4765
4766const TRANSLATION: TranslationParts = TranslationParts {
4767    manifest: include_str!("../translate/manifest.json"),
4768    lift: None,
4769    embed: Some(TranslationPart {
4770        entry: "expr-embed",
4771        source: Some(include_str!("../translate/embed.alc")),
4772    }),
4773    render: Some(TranslationPart {
4774        entry: "expr-render",
4775        source: Some(include_str!("../translate/render.alc")),
4776    }),
4777};
4778
4779/// Return the expression format's immutable translation parts.
4780#[must_use]
4781pub const fn translate() -> Option<TranslationParts> {
4782    Some(TRANSLATION)
4783}
4784
4785/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
4786/// it. Its `translate` object is what a host that translates reads: the
4787/// shape an expression document is read as and written from (`tree`), the root the render
4788/// takes, the schema of the tree its events carry (`expr`), the files
4789/// that hold the embedding of a plain tree in that schema and the render,
4790/// and the sentences that say what a written document does not keep. The
4791/// crate embeds its own copy, `translate/manifest.json`, since a packaged
4792/// crate holds nothing outside `rs/`; `tests/translate_test.rs` holds the
4793/// copy to the file.
4794///
4795/// ```
4796/// assert!(tabnas_expr::manifest_text().contains("\"translate\""));
4797/// ```
4798pub fn manifest_text() -> &'static str {
4799    TRANSLATION.manifest
4800}
4801
4802/// The expression format's render, `alchemy/render.alc`, the file the manifest's
4803/// `translate.render` names: a library of alchemy definitions, with no
4804/// `export`, whose entry point `expr-render` writes a tree's events as one
4805/// document. A host links it with its own program. The crate embeds its
4806/// own copy, `translate/render.alc`, held to the file as the manifest's
4807/// is; the embedding, `translate/embed.alc`, is `translate().embed`.
4808///
4809/// ```
4810/// assert!(tabnas_expr::render_text().contains("def expr-render [input]"));
4811/// ```
4812pub fn render_text() -> &'static str {
4813    match TRANSLATION.render {
4814        Some(part) => part.source.unwrap_or_default(),
4815        None => "",
4816    }
4817}