Skip to main content

tabnas_expr/
lib.rs

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