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