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