Skip to main content

tabnas_expr/
tree.rs

1/* Copyright (c) 2026 Richard Rodger and other contributors, MIT License */
2
3// The tree layer: key operators and `fold`, the port of the canonical
4// layer in `ts/src/expr.ts` (`makeKeyMap`, `keyOpOf`, `FoldError`, `fold`
5// and `foldTree`). The contract is the one the repository's `AGENTS.md`
6// states under "The tree layer"; what is particular to this port is said
7// where it is done, and summed up in `rs/AGENTS.md`.
8//
9// Three things shape it that the canonical does not have to think about.
10//
11// 1. The memory is a trie of locations held in one `Vec`, addressed by
12//    index, never by a `Value`'s identity: an engine value is copied on
13//    write, so identity says nothing about location.
14// 2. Every callback can re-enter the fold (`site.at`, `site.plain`,
15//    `site.k`, `site.locate`) while the fold is still inside an outer
16//    callback. All state sits in one `RefCell`, and no borrow of it is
17//    ever held across a callback.
18// 3. A stack overflow is an abort here, not an exception. The walk over
19//    nested containers is iterative, so nesting costs heap, not stack;
20//    the recursion that remains is the re-entry through callbacks, one
21//    level per reference hop, and `guard` turns a stack running low into
22//    `fold_depth` before it can abort the process.
23
24use std::borrow::Cow;
25use std::cell::{Cell, OnceCell, RefCell};
26use std::collections::{HashMap, HashSet};
27use std::fmt;
28use std::rc::Rc;
29use std::sync::Arc;
30
31use indexmap::IndexMap;
32use tabnas::{TabnasError, Token, Value};
33
34use crate::{
35    new_node, node_id, released_handle, with_node, Op, OpDef, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER,
36};
37
38// ---------------------------------------------------------------------------
39// Errors
40// ---------------------------------------------------------------------------
41
42/// A cycle met while [`FoldOptions::cycle`] is [`FoldCycle::Error`].
43pub const FOLD_CYCLE: &str = "fold_cycle";
44/// Nesting and reference hops past [`FoldOptions::max_depth`], or the
45/// thread's stack running low before that.
46pub const FOLD_DEPTH: &str = "fold_depth";
47/// An `inherit` that returned no bag, or folded its own subtree.
48pub const FOLD_INHERIT: &str = "fold_inherit";
49/// An operator table with two key operators on one member name, or one
50/// on none.
51pub const FOLD_KEY: &str = "fold_key";
52/// TypeScript's refusal of `positions: true` outside its deferred mode.
53/// The Rust options cannot say that, so a Rust fold never raises it; the
54/// code is declared so every runtime names the same set.
55pub const FOLD_OPTION: &str = "fold_option";
56
57/// The error [`fold`] returns: one of the layer's own failures, with its
58/// code and location, or the error a callback returned, unchanged.
59///
60/// `code` is what a fixture pins: [`FOLD_CYCLE`], [`FOLD_DEPTH`],
61/// [`FOLD_INHERIT`] or [`FOLD_KEY`] for the layer's own failures, and the
62/// callback's own code for a callback's. The document key and the
63/// pointers are fields; the message quotes them JSON-escaped and cut
64/// short, since member names are document content.
65///
66/// `TabnasError::from` gives the callback's error back as it was, and
67/// for the layer's own failures a new error carrying the code and the
68/// message, so `?` works inside a callback, which returns a
69/// `TabnasError`: the fold recognises its own failure coming back out of
70/// a callback and returns it with its location.
71#[derive(Debug, Clone, PartialEq)]
72pub struct FoldError(Box<FoldErrorData>);
73
74#[derive(Debug, Clone, PartialEq)]
75struct FoldErrorData {
76    code: String,
77    message: String,
78    doc: Option<String>,
79    at: Option<String>,
80    target_doc: Option<String>,
81    target: Option<String>,
82    cause: Option<TabnasError>,
83}
84
85impl FoldError {
86    fn new(code: &str, message: impl fmt::Display) -> Self {
87        FoldError(Box::new(FoldErrorData {
88            code: code.to_string(),
89            message: format!("expr fold: {message}"),
90            doc: None,
91            at: None,
92            target_doc: None,
93            target: None,
94            cause: None,
95        }))
96    }
97
98    fn callback(cause: TabnasError) -> Self {
99        FoldError(Box::new(FoldErrorData {
100            code: cause.code.clone(),
101            message: cause.detail.clone(),
102            doc: None,
103            at: None,
104            target_doc: None,
105            target: None,
106            cause: Some(cause),
107        }))
108    }
109
110    fn located(mut self, doc: &str, at: Option<&str>) -> Self {
111        self.0.doc = Some(doc.to_string());
112        self.0.at = at.map(str::to_string);
113        self
114    }
115
116    fn targeted(mut self, target_doc: &str, target: &str) -> Self {
117        self.0.target_doc = Some(target_doc.to_string());
118        self.0.target = Some(target.to_string());
119        self
120    }
121
122    /// The code: one of the layer's own, or the failing callback's.
123    pub fn code(&self) -> &str {
124        &self.0.code
125    }
126
127    /// The message, which for the layer's own failures starts
128    /// `expr fold: `.
129    pub fn message(&self) -> &str {
130        &self.0.message
131    }
132
133    /// The key of the document the failure happened in.
134    pub fn doc(&self) -> Option<&str> {
135        self.0.doc.as_deref()
136    }
137
138    /// The location of the failure in that document, as an RFC 6901
139    /// pointer.
140    pub fn at(&self) -> Option<&str> {
141        self.0.at.as_deref()
142    }
143
144    /// For a cycle, the document of the location the site named.
145    pub fn target_doc(&self) -> Option<&str> {
146        self.0.target_doc.as_deref()
147    }
148
149    /// For a cycle, the location the site named, as an RFC 6901 pointer.
150    pub fn target(&self) -> Option<&str> {
151        self.0.target.as_deref()
152    }
153
154    /// The error a callback (`evaluate`, `inherit`, `recognise` or
155    /// `load`) returned, when the failure was the callback's.
156    pub fn cause(&self) -> Option<&TabnasError> {
157        self.0.cause.as_ref()
158    }
159}
160
161impl fmt::Display for FoldError {
162    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163        formatter.write_str(&self.0.message)
164    }
165}
166
167impl std::error::Error for FoldError {
168    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
169        self.0
170            .cause
171            .as_ref()
172            .map(|cause| cause as &(dyn std::error::Error + 'static))
173    }
174}
175
176impl From<FoldError> for TabnasError {
177    fn from(error: FoldError) -> Self {
178        let data = *error.0;
179        if let Some(cause) = data.cause {
180            return cause;
181        }
182        // As the engine converts its own `ActionError`: no source position,
183        // since a fold runs on a finished tree. The hint is cleared rather
184        // than left as the engine's "unknown error code" text.
185        let mut out = TabnasError::new(data.code, "", "", 0, 1, 1);
186        out.detail = data.message;
187        out.hint = String::new();
188        out
189    }
190}
191
192// ---------------------------------------------------------------------------
193// Paths, hits and the report
194// ---------------------------------------------------------------------------
195
196/// One step of a [`Path`]: a member name, or an array index.
197///
198/// An index into a list is RFC 6901's: [`Seg::Index`], or a name that is
199/// `0` or digits with no leading zero. A name that is anything else, `-`,
200/// `01` or `1.0` among them, names nothing in a list. A number steps into
201/// a map as the member of that name, as in TypeScript.
202#[derive(Debug, Clone, PartialEq, Eq, Hash)]
203pub enum Seg {
204    /// A member name, or an index written as a name.
205    Name(String),
206    /// An array index.
207    Index(usize),
208}
209
210impl Seg {
211    fn text(&self) -> Cow<'_, str> {
212        match self {
213            Seg::Name(name) => Cow::Borrowed(name),
214            Seg::Index(index) => Cow::Owned(index.to_string()),
215        }
216    }
217}
218
219impl From<&str> for Seg {
220    fn from(name: &str) -> Self {
221        Seg::Name(name.to_string())
222    }
223}
224
225impl From<String> for Seg {
226    fn from(name: String) -> Self {
227        Seg::Name(name)
228    }
229}
230
231impl From<usize> for Seg {
232    fn from(index: usize) -> Self {
233        Seg::Index(index)
234    }
235}
236
237impl fmt::Display for Seg {
238    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
239        formatter.write_str(&self.text())
240    }
241}
242
243/// A location, as steps from a document's root.
244pub type Path = Vec<Seg>;
245
246/// What [`Site::at`] gives back: whether the location names anything,
247/// whether reaching it closed a cycle, and, only when it was found and is
248/// not a cycle, its folded value.
249#[derive(Debug, Clone, PartialEq)]
250pub struct FoldHit {
251    pub found: bool,
252    pub cycle: bool,
253    pub value: Option<Value>,
254}
255
256impl FoldHit {
257    fn missing() -> Self {
258        FoldHit {
259            found: false,
260            cycle: false,
261            value: None,
262        }
263    }
264
265    fn cycle() -> Self {
266        FoldHit {
267            found: true,
268            cycle: true,
269            value: None,
270        }
271    }
272
273    fn found(value: Value) -> Self {
274        FoldHit {
275            found: true,
276            cycle: false,
277            value: Some(value),
278        }
279    }
280}
281
282/// One report row: the site (`doc`, `at`) and the location it named
283/// (`target_doc`, `target`), as document keys and RFC 6901 pointers.
284#[derive(Debug, Clone, Default, PartialEq, Eq)]
285pub struct FoldEntry {
286    pub doc: String,
287    pub at: String,
288    pub target_doc: String,
289    pub target: String,
290}
291
292/// A dynamic key operator's site: recognised, reported, never evaluated.
293#[derive(Debug, Clone, Default, PartialEq, Eq)]
294pub struct FoldDynamic {
295    pub doc: String,
296    pub at: String,
297    pub src: String,
298}
299
300/// What a fold met that it could not resolve, each row once.
301#[derive(Debug, Clone, Default, PartialEq, Eq)]
302pub struct FoldReport {
303    pub cycles: Vec<FoldEntry>,
304    pub unresolved: Vec<FoldEntry>,
305    pub dynamic: Vec<FoldDynamic>,
306}
307
308// ---------------------------------------------------------------------------
309// Options
310// ---------------------------------------------------------------------------
311
312/// Reduce one site: a key operator with `[value, siblings]`, both already
313/// folded, or, when [`FoldOptions::tokens`] is on, a token operator met in
314/// the walk with its folded terms. What it returns is placed at the site as
315/// it is.
316pub type FoldEvaluate<'a> =
317    Box<dyn Fn(&Site<'_>, &Op, &[Value]) -> Result<Value, TabnasError> + 'a>;
318
319/// The bag a map's subtree inherits, from the bag its parent's subtree
320/// sees: called with the site, the map, and the parent's bag, once per map
321/// on a path the fold needs, from the root down. It returns a map, or at
322/// least a container, as the canonical's `typeof === 'object'` admits;
323/// anything else fails the fold with [`FOLD_INHERIT`].
324pub type Inherit<'a> = Box<dyn Fn(&Site<'_>, &Value, &Value) -> Result<Value, TabnasError> + 'a>;
325
326/// Whether a map that owns a key operator's member is an occurrence of it
327/// here. A map for which this is false folds as a plain map, with no
328/// `evaluate` call and no report row.
329pub type Recognise<'a> = Box<dyn Fn(&Site<'_>, &Op) -> Result<bool, TabnasError> + 'a>;
330
331/// Another document's raw root, by key: called once per key, `None` when
332/// it cannot be had.
333pub type Load<'a> = Box<dyn Fn(&str, &Site<'_>) -> Result<Option<Value>, TabnasError> + 'a>;
334
335/// The opening token of a container, when the host can say: see
336/// [`Site::token`].
337pub type Positions<'a> = Box<dyn Fn(&Value) -> Option<Token> + 'a>;
338
339/// What a fold does on meeting a cycle.
340#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
341pub enum FoldCycle {
342    /// Tell the resolver: [`Site::at`] answers with `cycle: true`.
343    #[default]
344    Verbatim,
345    /// Fail the fold with [`FOLD_CYCLE`].
346    Error,
347}
348
349/// The options of one [`fold`]. Only `evaluate` is required; build with
350/// [`FoldOptions::new`] and the `with_` methods.
351///
352/// The callbacks are plain closures that may borrow from the caller's
353/// scope, for the life `'a` of the options: a fold runs to completion
354/// inside the call.
355pub struct FoldOptions<'a> {
356    /// The operator table; only its key operators matter to a fold. The
357    /// same table the plugin was given can be passed as it is.
358    pub op: IndexMap<String, Option<OpDef>>,
359    pub evaluate: FoldEvaluate<'a>,
360    pub inherit: Option<Inherit<'a>>,
361    pub recognise: Option<Recognise<'a>>,
362    /// The starting bag of every document's root. An empty map by default.
363    pub k: Value,
364    /// The key of the document being folded. Empty by default.
365    pub doc: String,
366    pub load: Option<Load<'a>>,
367    pub cycle: FoldCycle,
368    /// Reduce token operator nodes met in the walk through `evaluate`
369    /// too, so one fold handles `+` and `$ref`. On by default. A token
370    /// operator is recognised only on a LIVE expression node, inside
371    /// [`crate::parse_scope`]: see [`fold`].
372    pub tokens: bool,
373    pub positions: Option<Positions<'a>>,
374    /// How deep the walk may go, nesting and reference hops counted
375    /// together. 1000 by default.
376    pub max_depth: usize,
377    /// How much stack, in bytes, the fold may use, measured from the
378    /// outermost fold running on the thread: [`FOLD_MAX_STACK`], a
379    /// megabyte, by default. Past it the fold fails with [`FOLD_DEPTH`]
380    /// rather than overflow the stack, which would end the process. A
381    /// level of nesting costs no stack, since the walk over containers is
382    /// iterative; each reference hop does, since it re-enters the fold
383    /// through the resolver. Raise it only on a thread known to have more
384    /// than twice as much stack.
385    pub max_stack: usize,
386    /// Called once with the report when the fold succeeds.
387    pub report: Option<Box<dyn Fn(FoldReport) + 'a>>,
388}
389
390impl<'a> FoldOptions<'a> {
391    /// Options with the given resolver and every default.
392    pub fn new(
393        evaluate: impl Fn(&Site<'_>, &Op, &[Value]) -> Result<Value, TabnasError> + 'a,
394    ) -> Self {
395        FoldOptions {
396            op: IndexMap::new(),
397            evaluate: Box::new(evaluate),
398            inherit: None,
399            recognise: None,
400            k: Value::object(IndexMap::new()),
401            doc: String::new(),
402            load: None,
403            cycle: FoldCycle::Verbatim,
404            tokens: true,
405            positions: None,
406            max_depth: 1000,
407            max_stack: FOLD_MAX_STACK,
408            report: None,
409        }
410    }
411
412    /// Add or replace one operator definition.
413    pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
414        self.op.insert(name.into(), Some(def));
415        self
416    }
417
418    /// Use a whole operator table, such as the one an `ExprOptions`
419    /// carries.
420    pub fn with_ops(mut self, op: IndexMap<String, Option<OpDef>>) -> Self {
421        self.op = op;
422        self
423    }
424
425    pub fn with_inherit(
426        mut self,
427        inherit: impl Fn(&Site<'_>, &Value, &Value) -> Result<Value, TabnasError> + 'a,
428    ) -> Self {
429        self.inherit = Some(Box::new(inherit));
430        self
431    }
432
433    pub fn with_recognise(
434        mut self,
435        recognise: impl Fn(&Site<'_>, &Op) -> Result<bool, TabnasError> + 'a,
436    ) -> Self {
437        self.recognise = Some(Box::new(recognise));
438        self
439    }
440
441    pub fn with_k(mut self, k: Value) -> Self {
442        self.k = k;
443        self
444    }
445
446    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
447        self.doc = doc.into();
448        self
449    }
450
451    pub fn with_load(
452        mut self,
453        load: impl Fn(&str, &Site<'_>) -> Result<Option<Value>, TabnasError> + 'a,
454    ) -> Self {
455        self.load = Some(Box::new(load));
456        self
457    }
458
459    pub fn with_cycle(mut self, cycle: FoldCycle) -> Self {
460        self.cycle = cycle;
461        self
462    }
463
464    pub fn with_tokens(mut self, tokens: bool) -> Self {
465        self.tokens = tokens;
466        self
467    }
468
469    pub fn with_positions(mut self, positions: impl Fn(&Value) -> Option<Token> + 'a) -> Self {
470        self.positions = Some(Box::new(positions));
471        self
472    }
473
474    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
475        self.max_depth = max_depth;
476        self
477    }
478
479    pub fn with_max_stack(mut self, max_stack: usize) -> Self {
480        self.max_stack = max_stack;
481        self
482    }
483
484    pub fn with_report(mut self, report: impl Fn(FoldReport) + 'a) -> Self {
485        self.report = Some(Box::new(report));
486        self
487    }
488}
489
490impl fmt::Debug for FoldOptions<'_> {
491    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
492        let function = |present: bool| if present { "<function>" } else { "none" };
493        formatter
494            .debug_struct("FoldOptions")
495            .field("op", &self.op)
496            .field("evaluate", &"<function>")
497            .field("inherit", &function(self.inherit.is_some()))
498            .field("recognise", &function(self.recognise.is_some()))
499            .field("k", &self.k)
500            .field("doc", &self.doc)
501            .field("load", &function(self.load.is_some()))
502            .field("cycle", &self.cycle)
503            .field("tokens", &self.tokens)
504            .field("positions", &function(self.positions.is_some()))
505            .field("max_depth", &self.max_depth)
506            .field("max_stack", &self.max_stack)
507            .field("report", &function(self.report.is_some()))
508            .finish()
509    }
510}
511
512// ---------------------------------------------------------------------------
513// Key operators
514// ---------------------------------------------------------------------------
515
516/// The key operators of a table, in the order a map that owns two of their
517/// members is resolved by: static operators before dynamic ones, then
518/// member names in code-point order. Neither declaration order nor member
519/// order is used, so every runtime resolves such a map alike.
520#[derive(Debug, Clone, Default)]
521pub struct KeyMap {
522    ops: Vec<Arc<Op>>,
523}
524
525impl KeyMap {
526    /// The operators, in resolution order.
527    pub fn iter(&self) -> std::slice::Iter<'_, Arc<Op>> {
528        self.ops.iter()
529    }
530
531    /// The operator a member name marks.
532    pub fn get(&self, src: &str) -> Option<&Arc<Op>> {
533        self.ops.iter().find(|op| op.src == src)
534    }
535
536    pub fn len(&self) -> usize {
537        self.ops.len()
538    }
539
540    pub fn is_empty(&self) -> bool {
541        self.ops.is_empty()
542    }
543}
544
545/// The key operators of an operator table, the port of the canonical
546/// `makeKeyMap`. A key operator carries no token, no tin and no binding
547/// power; its `terms` is 2, the member's value and the sibling map. Two
548/// key operators on one member name, or one naming no member, are refused
549/// with [`FOLD_KEY`].
550pub fn make_key_map(ops: &IndexMap<String, Option<OpDef>>) -> Result<KeyMap, FoldError> {
551    let mut found: Vec<Op> = Vec::new();
552    let mut owner: HashMap<&str, &str> = HashMap::new();
553    for (name, def) in ops {
554        let Some(def) = def else { continue };
555        if !def.key {
556            continue;
557        }
558        let src = def.src.first().map(String::as_str).unwrap_or_default();
559        if src.is_empty() {
560            return Err(FoldError::new(
561                FOLD_KEY,
562                format_args!("key operator {} names no member", shown(name)),
563            ));
564        }
565        if let Some(prior) = owner.get(src) {
566            return Err(FoldError::new(
567                FOLD_KEY,
568                format_args!(
569                    "key operators {} and {} both name the member {}",
570                    shown(prior),
571                    shown(name),
572                    shown(src)
573                ),
574            ));
575        }
576        owner.insert(src, name);
577        found.push(Op {
578            name: if name.ends_with("-key") {
579                name.clone()
580            } else {
581                format!("{name}-key")
582            },
583            src: src.to_string(),
584            left: MIN_SAFE_INTEGER,
585            right: MAX_SAFE_INTEGER,
586            use_data: def.use_data.clone(),
587            terms: 2,
588            key: true,
589            dynamic: def.dynamic,
590            ..Default::default()
591        });
592    }
593    // `false` sorts before `true`, so static operators come first; `str`
594    // compares by byte, which for UTF-8 is code-point order.
595    found.sort_by(|a, b| a.dynamic.cmp(&b.dynamic).then_with(|| a.src.cmp(&b.src)));
596    Ok(KeyMap {
597        ops: found.into_iter().map(Arc::new).collect(),
598    })
599}
600
601/// The key operator a map is an occurrence of, by shape: the first, in the
602/// table's order, whose member the map owns. `None` for anything else,
603/// lists and scalars included.
604pub fn key_op_of(keys: &KeyMap, node: &Value) -> Option<Arc<Op>> {
605    let members = map_entries(node)?;
606    keys.ops
607        .iter()
608        .find(|op| members.contains_key(op.src.as_str()))
609        .cloned()
610}
611
612// ---------------------------------------------------------------------------
613// The site
614// ---------------------------------------------------------------------------
615
616/// What [`fold`] hands its callbacks for one map, or one token operator
617/// node: where it is, what it is, and the ways to reach the rest of the
618/// tree. `at`, `plain`, `locate` and `k` re-enter the fold, which is
619/// what a resolver does to fold the target of a reference.
620pub struct Site<'f> {
621    fold: &'f Folder<'f>,
622    pn: usize,
623    parent_k: Option<Value>,
624    doc: Rc<str>,
625    root: Value,
626    node: Value,
627    path: OnceCell<Path>,
628}
629
630impl Site<'_> {
631    /// The verbatim root of the site's document.
632    pub fn root(&self) -> &Value {
633        &self.root
634    }
635
636    /// The key of the site's document.
637    pub fn doc(&self) -> &str {
638        &self.doc
639    }
640
641    /// The path from the document's root to the site.
642    pub fn path(&self) -> &[Seg] {
643        self.path.get_or_init(|| self.fold.path_of(self.pn))
644    }
645
646    /// The verbatim node at the site: the map, or the operator node.
647    pub fn node(&self) -> &Value {
648        &self.node
649    }
650
651    /// The bag inherited along the path: [`FoldOptions::inherit`] applied
652    /// at every map from the root down to and including this one, each
653    /// map's bag kept, so a site reached early through a reference gets
654    /// its own ancestors' bag, never the referrer's. Inside an `inherit`
655    /// call it is the parent's bag.
656    pub fn k(&self) -> Result<Value, FoldError> {
657        match &self.parent_k {
658            Some(k) => Ok(k.clone()),
659            None => self.fold.k_of(self.pn),
660        }
661    }
662
663    /// A position for the site. At a token operator site, the token the
664    /// operator OCCURRENCE was matched from, as [`crate::EvalSite::token`]
665    /// gives it. At a map, what [`FoldOptions::positions`] says, if it is
666    /// set: this crate records no opening tokens of its own, so without a
667    /// host's lookup it is `None`.
668    pub fn token(&self) -> Option<Token> {
669        if node_id(&self.node).is_some() {
670            return with_node(&self.node, |entry| entry.token.clone()).flatten();
671        }
672        self.fold
673            .options
674            .positions
675            .as_ref()
676            .and_then(|lookup| lookup(&self.node))
677    }
678
679    /// The folded value at `path` in this document, or in the document
680    /// `doc`, through any key operator site on the way: a pointer may pass
681    /// through a `$ref` to reach a member of its target. A target still
682    /// being folded closes a cycle, and so does a path through a site that
683    /// was cut. A hit never carries a value when `cycle` is set.
684    pub fn at(&self, path: &[Seg], doc: Option<&str>) -> Result<FoldHit, FoldError> {
685        self.fold.at(self.pn, path, doc)
686    }
687
688    /// The raw value at `path`, following nothing.
689    pub fn locate(&self, path: &[Seg], doc: Option<&str>) -> Result<Option<Value>, FoldError> {
690        self.fold.locate(self.pn, path, doc)
691    }
692
693    /// This map folded as a plain map, members in their own order, which is
694    /// what a resolver returns where the operator does not apply.
695    pub fn plain(&self) -> Result<Value, FoldError> {
696        self.fold.plain_of(self.pn)
697    }
698}
699
700impl fmt::Debug for Site<'_> {
701    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
702        formatter
703            .debug_struct("Site")
704            .field("doc", &self.doc)
705            .field("path", &self.path())
706            .field("node", &self.node)
707            .finish()
708    }
709}
710
711// ---------------------------------------------------------------------------
712// The fold
713// ---------------------------------------------------------------------------
714
715/// Fold a finished tree: walk it, reduce every key operator site bottom-up
716/// through `options.evaluate`, and return a NEW tree; the input is never
717/// changed, though what a resolver returns, `site.node()` among it, is
718/// placed in the output as it is.
719///
720/// Values flow up through `evaluate`; context flows down through
721/// `inherit`, worked out per path from each map's own ancestors and kept.
722/// One result per location, so every site naming one target shares one
723/// folded value. Every container being folded is on an active stack, and a
724/// site whose target is on it closes a cycle, which the resolver is told
725/// about (or which fails the fold, under [`FoldCycle::Error`]). Dynamic key
726/// operators are reported and folded as plain maps.
727///
728/// A TOKEN operator is recognised only on a live expression node, so a
729/// fold that should reduce `+` as well as `$ref` runs inside
730/// [`crate::parse_scope`], on the value the parse hands the closure. A
731/// realized array, the operator description followed by its terms, is
732/// plain data here and is never read as an operator: a document can spell
733/// exactly that array, and reading it would let untrusted input forge one.
734///
735/// `max_depth` bounds nesting and reference hops together. The walk over
736/// nested containers is iterative, so nesting costs no stack. Each
737/// reference hop re-enters the fold through the resolver, and the fold
738/// also fails with [`FOLD_DEPTH`] once the hops have used
739/// [`FoldOptions::max_stack`] bytes of stack, a megabyte by default, rather
740/// than let a thread with the default 2 MiB overflow, which would end the
741/// process.
742pub fn fold(root: &Value, options: &FoldOptions<'_>) -> Result<Value, FoldError> {
743    let keys = make_key_map(&options.op)?;
744    let base = StackBase::enter();
745    let folder = Folder {
746        options,
747        keys,
748        stack_base: base.at,
749        main: Rc::from(options.doc.as_str()),
750        state: RefCell::new(State::default()),
751    };
752    let doc = folder.make_doc(&options.doc, root.clone());
753    let top = folder.state.borrow().docs[doc].top;
754    let out = folder.walk(top, FROM_PARENT)?;
755    if let Some(report) = &options.report {
756        let rows = std::mem::take(&mut folder.state.borrow_mut().report);
757        report(rows);
758    }
759    Ok(out)
760}
761
762// How a location stands: not folded yet, being folded (on the active
763// stack), or folded and kept.
764const FREE: u8 = 0;
765const ACTIVE: u8 = 1;
766const DONE: u8 = 2;
767
768// How the walk entered a container: from its parent, or through a
769// reference.
770const FROM_PARENT: u8 = 0;
771const FROM_REFERENCE: u8 = 1;
772
773// The report lists, for the de-duplication key.
774const CYCLES: u8 = 0;
775const UNRESOLVED: u8 = 1;
776const DYNAMIC: u8 = 2;
777
778/// The default of [`FoldOptions::max_stack`]: a megabyte, which leaves the
779/// other half of a default 2 MiB thread for the fold's caller and for the
780/// frames of the callback that runs past the last check.
781pub const FOLD_MAX_STACK: usize = 1 << 20;
782
783/// The engine of one fold. Every method takes `&self`, so a callback can
784/// re-enter it through its [`Site`]; the state is behind one `RefCell`,
785/// and no borrow of it is held across a callback.
786struct Folder<'f> {
787    options: &'f FoldOptions<'f>,
788    keys: KeyMap,
789    stack_base: usize,
790    main: Rc<str>,
791    state: RefCell<State>,
792}
793
794#[derive(Default)]
795struct State {
796    /// The trie of locations, every document's, by index.
797    nodes: Vec<PNode>,
798    docs: Vec<Doc>,
799    /// Every document key asked for, and its document when it could be
800    /// had.
801    doc_keys: HashMap<String, Option<usize>>,
802    /// The active stack: every container being folded, outermost first.
803    stack: Vec<usize>,
804    report: FoldReport,
805    noted: HashSet<(u8, String, String, String, String)>,
806    /// The last of the layer's own failures, so it can be recognised when
807    /// it comes back out of a callback as a `TabnasError`.
808    failure: Option<FoldError>,
809}
810
811struct Doc {
812    key: Rc<str>,
813    root: Value,
814    top: usize,
815}
816
817/// One location the fold has reached: a node of the trie.
818struct PNode {
819    doc: usize,
820    parent: Option<usize>,
821    seg: Seg,
822    raw: Value,
823    kids: Option<Box<Kids>>,
824    state: u8,
825    via: u8,
826    value: Value,
827    k: Option<Value>,
828    k_busy: bool,
829    /// Its resolution met a cycle, so the resolver was told `cycle: true`.
830    cut: bool,
831    /// A member of a loop of references with no container in it, or a
832    /// reference into one: there is nothing to resolve it to.
833    looped: bool,
834    /// The key operator this map is an occurrence of, decided once: shape,
835    /// then the host's `recognise`.
836    site: Option<Option<Arc<Op>>>,
837    parts: Option<Box<Parts>>,
838    plain: Option<Value>,
839    ptr: Option<Rc<str>>,
840}
841
842impl PNode {
843    fn new(doc: usize, parent: Option<usize>, seg: Seg, raw: Value) -> Self {
844        PNode {
845            doc,
846            parent,
847            seg,
848            raw,
849            kids: None,
850            state: FREE,
851            via: FROM_PARENT,
852            value: Value::Undefined,
853            k: None,
854            k_busy: false,
855            cut: false,
856            looped: false,
857            site: None,
858            parts: None,
859            plain: None,
860            ptr: None,
861        }
862    }
863}
864
865/// A node's children by step: a map's by member name, a list's by index.
866enum Kids {
867    Names(HashMap<String, usize>),
868    Indices(HashMap<usize, usize>),
869}
870
871/// A site's terms, kept for `site.plain()`.
872struct Parts {
873    src: String,
874    value: Value,
875    siblings: Value,
876}
877
878/// The stack address the outermost fold on this thread started from.
879struct StackBase {
880    at: usize,
881    outermost: bool,
882}
883
884thread_local! {
885    static STACK_BASE: Cell<Option<usize>> = const { Cell::new(None) };
886}
887
888impl StackBase {
889    fn enter() -> Self {
890        let here = stack_here();
891        STACK_BASE.with(|base| match base.get() {
892            Some(at) => StackBase {
893                at,
894                outermost: false,
895            },
896            None => {
897                base.set(Some(here));
898                StackBase {
899                    at: here,
900                    outermost: true,
901                }
902            }
903        })
904    }
905}
906
907impl Drop for StackBase {
908    fn drop(&mut self) {
909        if self.outermost {
910            STACK_BASE.with(|base| base.set(None));
911        }
912    }
913}
914
915/// The address of a local in a frame of its own: where the stack is now.
916#[inline(never)]
917fn stack_here() -> usize {
918    let marker = 0u8;
919    std::hint::black_box(&marker) as *const u8 as usize
920}
921
922/// A container in the middle of being walked: its members are taken one at
923/// a time, and the folded ones collected.
924struct Frame {
925    pn: usize,
926    raw: Value,
927    next: usize,
928    kind: Kind,
929}
930
931enum Kind {
932    /// A list.
933    List { out: Vec<Value> },
934    /// A live expression node: its operator and occurrence token, and its
935    /// terms, at path indices from 1 when it has an operator, the head
936    /// taking index 0. A node with no operator is a ternary the grammar
937    /// rewrote into a plain list of its terms, in place.
938    Node {
939        op: Option<Arc<Op>>,
940        terms: Vec<Value>,
941        out: Vec<Value>,
942    },
943    /// A map that is not a static site.
944    Plain { out: IndexMap<String, Value> },
945    /// A key operator site.
946    Site {
947        op: Arc<Op>,
948        value: Value,
949        siblings: IndexMap<String, Value>,
950    },
951}
952
953/// A member taken from a frame: its index, or the place of its name in the
954/// map.
955enum Member {
956    Index(usize),
957    Name(usize),
958}
959
960/// How far a path reaches before the fold has to walk.
961enum Found {
962    /// An answer, with nothing to walk.
963    Hit(FoldHit),
964    /// A static site part way along: walk it, then read the rest of the
965    /// path, from this step on, in its folded value.
966    Through(usize, usize),
967    /// The location at the end of the path: walk it.
968    End(usize),
969}
970
971impl Frame {
972    fn take(&mut self) -> Option<(Member, Value)> {
973        let at = self.next;
974        let taken = match &self.kind {
975            Kind::List { .. } => list_items(&self.raw)
976                .get(at)
977                .map(|item| (Member::Index(at), item.clone())),
978            Kind::Node { op, terms, .. } => terms
979                .get(at)
980                .map(|term| (Member::Index(at + usize::from(op.is_some())), term.clone())),
981            Kind::Plain { .. } | Kind::Site { .. } => map_entries(&self.raw)
982                .and_then(|members| members.get_index(at))
983                .map(|(_, member)| (Member::Name(at), member.clone())),
984        };
985        if taken.is_some() {
986            self.next += 1;
987        }
988        taken
989    }
990
991    fn accept(&mut self, value: Value) {
992        let at = self.next - 1;
993        let Frame { raw, kind, .. } = self;
994        match kind {
995            Kind::List { out } | Kind::Node { out, .. } => out.push(value),
996            Kind::Plain { out } => {
997                out.insert(member_name(raw, at).to_string(), value);
998            }
999            Kind::Site {
1000                op,
1001                value: slot,
1002                siblings,
1003            } => {
1004                let name = member_name(raw, at);
1005                if name == op.src {
1006                    *slot = value;
1007                } else {
1008                    siblings.insert(name.to_string(), value);
1009                }
1010            }
1011        }
1012    }
1013}
1014
1015impl Folder<'_> {
1016    fn site(&self, pn: usize, parent_k: Option<Value>) -> Site<'_> {
1017        let state = self.state.borrow();
1018        let node = &state.nodes[pn];
1019        let doc = &state.docs[node.doc];
1020        Site {
1021            fold: self,
1022            pn,
1023            parent_k,
1024            doc: doc.key.clone(),
1025            root: doc.root.clone(),
1026            node: node.raw.clone(),
1027            path: OnceCell::new(),
1028        }
1029    }
1030
1031    fn make_doc(&self, key: &str, raw: Value) -> usize {
1032        let mut state = self.state.borrow_mut();
1033        let doc = state.docs.len();
1034        let top = state.nodes.len();
1035        state
1036            .nodes
1037            .push(PNode::new(doc, None, Seg::Name(String::new()), raw.clone()));
1038        state.docs.push(Doc {
1039            key: Rc::from(key),
1040            root: raw,
1041            top,
1042        });
1043        state.doc_keys.insert(key.to_string(), Some(doc));
1044        doc
1045    }
1046
1047    fn doc_key(&self, pn: usize) -> Rc<str> {
1048        let state = self.state.borrow();
1049        state.docs[state.nodes[pn].doc].key.clone()
1050    }
1051
1052    /// Another document, by key, loaded once; `None` when it cannot be had.
1053    fn doc_of(&self, from: usize, key: Option<&str>) -> Result<Option<usize>, FoldError> {
1054        let own = self.state.borrow().nodes[from].doc;
1055        let Some(key) = key else {
1056            return Ok(Some(own));
1057        };
1058        if *self.doc_key(from) == *key {
1059            return Ok(Some(own));
1060        }
1061        let known = self.state.borrow().doc_keys.get(key).copied();
1062        if let Some(known) = known {
1063            return Ok(known);
1064        }
1065        let raw = match &self.options.load {
1066            Some(load) => {
1067                self.guard()?;
1068                load(key, &self.site(from, None)).map_err(|error| self.callback_error(&error))?
1069            }
1070            None => None,
1071        };
1072        let doc = match raw {
1073            Some(raw) if !raw.is_undefined() => Some(self.make_doc(key, raw)),
1074            _ => None,
1075        };
1076        self.state
1077            .borrow_mut()
1078            .doc_keys
1079            .insert(key.to_string(), doc);
1080        Ok(doc)
1081    }
1082
1083    fn kid_named(&self, pn: usize, name: &str, raw: Value) -> usize {
1084        let mut state = self.state.borrow_mut();
1085        let found = match state.nodes[pn].kids.as_deref() {
1086            Some(Kids::Names(names)) => names.get(name).copied(),
1087            _ => None,
1088        };
1089        if let Some(found) = found {
1090            return found;
1091        }
1092        let id = state.nodes.len();
1093        let doc = state.nodes[pn].doc;
1094        state
1095            .nodes
1096            .push(PNode::new(doc, Some(pn), Seg::Name(name.to_string()), raw));
1097        let kids = state.nodes[pn]
1098            .kids
1099            .get_or_insert_with(|| Box::new(Kids::Names(HashMap::new())));
1100        if let Kids::Names(names) = &mut **kids {
1101            names.insert(name.to_string(), id);
1102        }
1103        id
1104    }
1105
1106    fn kid_indexed(&self, pn: usize, index: usize, raw: Value) -> usize {
1107        let mut state = self.state.borrow_mut();
1108        let found = match state.nodes[pn].kids.as_deref() {
1109            Some(Kids::Indices(indices)) => indices.get(&index).copied(),
1110            _ => None,
1111        };
1112        if let Some(found) = found {
1113            return found;
1114        }
1115        let id = state.nodes.len();
1116        let doc = state.nodes[pn].doc;
1117        state
1118            .nodes
1119            .push(PNode::new(doc, Some(pn), Seg::Index(index), raw));
1120        let kids = state.nodes[pn]
1121            .kids
1122            .get_or_insert_with(|| Box::new(Kids::Indices(HashMap::new())));
1123        if let Kids::Indices(indices) = &mut **kids {
1124            indices.insert(index, id);
1125        }
1126        id
1127    }
1128
1129    fn kid_of(&self, pn: usize, raw: &Value, member: Member, child: Value) -> usize {
1130        match member {
1131            Member::Index(index) => self.kid_indexed(pn, index, child),
1132            Member::Name(at) => self.kid_named(pn, member_name(raw, at), child),
1133        }
1134    }
1135
1136    /// A location's RFC 6901 pointer, made only for report rows and errors
1137    /// and kept once made.
1138    fn ptr_of(&self, pn: usize) -> Rc<str> {
1139        let mut state = self.state.borrow_mut();
1140        let state = &mut *state;
1141        if let Some(done) = &state.nodes[pn].ptr {
1142            return done.clone();
1143        }
1144        let mut chain = Vec::new();
1145        let mut cursor = Some(pn);
1146        while let Some(at) = cursor {
1147            if state.nodes[at].ptr.is_some() {
1148                break;
1149            }
1150            chain.push(at);
1151            cursor = state.nodes[at].parent;
1152        }
1153        let mut text = cursor
1154            .and_then(|at| state.nodes[at].ptr.as_deref().map(str::to_string))
1155            .unwrap_or_default();
1156        for &at in chain.iter().rev() {
1157            let node = &mut state.nodes[at];
1158            if node.parent.is_none() {
1159                text.clear();
1160            } else {
1161                text.push('/');
1162                escape_segment(&mut text, &node.seg.text());
1163            }
1164            node.ptr = Some(Rc::from(text.as_str()));
1165        }
1166        state.nodes[pn].ptr.clone().unwrap_or_else(|| Rc::from(""))
1167    }
1168
1169    fn path_of(&self, pn: usize) -> Path {
1170        let state = self.state.borrow();
1171        let mut path = Vec::new();
1172        let mut cursor = Some(pn);
1173        while let Some(at) = cursor {
1174            let node = &state.nodes[at];
1175            if node.parent.is_none() {
1176                break;
1177            }
1178            path.push(node.seg.clone());
1179            cursor = node.parent;
1180        }
1181        path.reverse();
1182        path
1183    }
1184
1185    fn note(&self, list: u8, row: FoldEntry) {
1186        let mut state = self.state.borrow_mut();
1187        let key = (
1188            list,
1189            row.doc.clone(),
1190            row.at.clone(),
1191            row.target_doc.clone(),
1192            row.target.clone(),
1193        );
1194        if state.noted.insert(key) {
1195            if CYCLES == list {
1196                state.report.cycles.push(row);
1197            } else {
1198                state.report.unresolved.push(row);
1199            }
1200        }
1201    }
1202
1203    fn note_dynamic(&self, pn: usize, src: &str) {
1204        let row = FoldDynamic {
1205            doc: self.doc_key(pn).to_string(),
1206            at: self.ptr_of(pn).to_string(),
1207            src: src.to_string(),
1208        };
1209        let mut state = self.state.borrow_mut();
1210        let key = (
1211            DYNAMIC,
1212            row.doc.clone(),
1213            row.at.clone(),
1214            row.src.clone(),
1215            String::new(),
1216        );
1217        if state.noted.insert(key) {
1218            state.report.dynamic.push(row);
1219        }
1220    }
1221
1222    /// Record one of the layer's own failures, and return it.
1223    fn raise(&self, error: FoldError) -> FoldError {
1224        self.state.borrow_mut().failure = Some(error.clone());
1225        error
1226    }
1227
1228    /// A callback's error as the fold's: the layer's own failure, with its
1229    /// location, when that is what came back out of the callback, and the
1230    /// callback's error, unchanged, otherwise.
1231    fn callback_error(&self, error: &TabnasError) -> FoldError {
1232        let own = self.state.borrow().failure.clone();
1233        match own {
1234            Some(own) if own.code() == error.code && own.message() == error.detail => own,
1235            _ => FoldError::callback(error.clone()),
1236        }
1237    }
1238
1239    /// Fail with `fold_depth` before the re-entry through callbacks can
1240    /// run the thread's stack out.
1241    fn guard(&self) -> Result<(), FoldError> {
1242        if stack_here().abs_diff(self.stack_base) <= self.options.max_stack {
1243            return Ok(());
1244        }
1245        let error = FoldError::new(
1246            FOLD_DEPTH,
1247            format_args!(
1248                "the stack ran out before max_depth ({}) was reached; lower max_depth",
1249                self.options.max_depth
1250            ),
1251        )
1252        .located(&self.main, None);
1253        Err(self.raise(error))
1254    }
1255
1256    /// The bag at a map: the `inherit` calls of its ancestors and of the
1257    /// map itself, from the root down, each kept, worked out without
1258    /// recursion.
1259    fn k_of(&self, pn: usize) -> Result<Value, FoldError> {
1260        let Some(inherit) = &self.options.inherit else {
1261            return Ok(self.options.k.clone());
1262        };
1263        self.guard()?;
1264        let (chain, mut bag) = {
1265            let state = self.state.borrow();
1266            if let Some(bag) = &state.nodes[pn].k {
1267                return Ok(bag.clone());
1268            }
1269            let mut chain = Vec::new();
1270            let mut cursor = Some(pn);
1271            let mut busy = None;
1272            while let Some(at) = cursor {
1273                let node = &state.nodes[at];
1274                if node.k.is_some() {
1275                    break;
1276                }
1277                if node.k_busy {
1278                    busy = Some(at);
1279                    break;
1280                }
1281                chain.push(at);
1282                cursor = node.parent;
1283            }
1284            match busy {
1285                Some(at) => (Err(at), Value::Undefined),
1286                None => (
1287                    Ok(chain),
1288                    cursor
1289                        .and_then(|at| state.nodes[at].k.clone())
1290                        .unwrap_or_else(|| self.options.k.clone()),
1291                ),
1292            }
1293        };
1294        let chain = match chain {
1295            Ok(chain) => chain,
1296            Err(at) => return Err(self.inherit_error("inherit folded its own subtree at", at)),
1297        };
1298        for &at in chain.iter().rev() {
1299            let raw = self.state.borrow().nodes[at].raw.clone();
1300            if is_record(&raw) {
1301                self.state.borrow_mut().nodes[at].k_busy = true;
1302                let next = inherit(&self.site(at, Some(bag.clone())), &raw, &bag);
1303                self.state.borrow_mut().nodes[at].k_busy = false;
1304                let next = next.map_err(|error| self.callback_error(&error))?;
1305                // A container, as the canonical's `typeof next === 'object'`
1306                // admits; anything else is no bag.
1307                if !is_container(&next) {
1308                    return Err(self.inherit_error("inherit returned no bag at", at));
1309                }
1310                bag = next;
1311            }
1312            self.state.borrow_mut().nodes[at].k = Some(bag.clone());
1313        }
1314        Ok(bag)
1315    }
1316
1317    fn inherit_error(&self, what: &str, at: usize) -> FoldError {
1318        let pointer = self.ptr_of(at);
1319        let doc = self.doc_key(at);
1320        let error = FoldError::new(FOLD_INHERIT, format_args!("{what} {}", shown(&pointer)))
1321            .located(&doc, Some(&pointer));
1322        self.raise(error)
1323    }
1324
1325    /// The key operator a map is an occurrence of here, if any: its shape,
1326    /// then the host's `recognise`, decided once per location.
1327    fn site_op_of(&self, pn: usize) -> Result<Option<Arc<Op>>, FoldError> {
1328        let raw = {
1329            let state = self.state.borrow();
1330            let node = &state.nodes[pn];
1331            if let Some(decided) = &node.site {
1332                return Ok(decided.clone());
1333            }
1334            node.raw.clone()
1335        };
1336        let op = key_op_of(&self.keys, &raw);
1337        self.state.borrow_mut().nodes[pn].site = Some(op.clone());
1338        if let (Some(found), Some(recognise)) = (&op, &self.options.recognise) {
1339            let yes = recognise(&self.site(pn, None), found)
1340                .map_err(|error| self.callback_error(&error))?;
1341            if !yes {
1342                self.state.borrow_mut().nodes[pn].site = Some(None);
1343                return Ok(None);
1344            }
1345        }
1346        Ok(op)
1347    }
1348
1349    fn miss(&self, from: usize, key: Option<&str>, target: &[Seg]) -> FoldHit {
1350        let doc = self.doc_key(from);
1351        let row = FoldEntry {
1352            doc: doc.to_string(),
1353            at: self.ptr_of(from).to_string(),
1354            target_doc: key.unwrap_or(&doc).to_string(),
1355            target: pointer(target),
1356        };
1357        self.note(UNRESOLVED, row);
1358        FoldHit::missing()
1359    }
1360
1361    /// A cycle: `from` named `target` while `target` was still being folded
1362    /// (a back edge), or `target` is in a loop of references. Every member
1363    /// of a loop made only of references is a cycle, and so is every
1364    /// reference into one, since none of them has anything to resolve to.
1365    /// A cycle that passes through a container is cut once, at the site
1366    /// whose target was being folded; a later reference to that site gets
1367    /// its folded value.
1368    fn cycle_to(&self, from: usize, target: usize) -> Result<FoldHit, FoldError> {
1369        let row = FoldEntry {
1370            doc: self.doc_key(from).to_string(),
1371            at: self.ptr_of(from).to_string(),
1372            target_doc: self.doc_key(target).to_string(),
1373            target: self.ptr_of(target).to_string(),
1374        };
1375        if FoldCycle::Error == self.options.cycle {
1376            let error = FoldError::new(
1377                FOLD_CYCLE,
1378                format_args!("cycle at {} to {}", shown(&row.at), shown(&row.target)),
1379            )
1380            .located(&row.doc, Some(&row.at))
1381            .targeted(&row.target_doc, &row.target);
1382            return Err(self.raise(error));
1383        }
1384        self.note(CYCLES, row);
1385        let mut state = self.state.borrow_mut();
1386        let state = &mut *state;
1387        state.nodes[from].cut = true;
1388        if ACTIVE == state.nodes[target].state {
1389            if let Some(start) = state.stack.iter().rposition(|&entry| entry == target) {
1390                let refs = state.stack[start + 1..]
1391                    .iter()
1392                    .all(|&entry| FROM_REFERENCE == state.nodes[entry].via);
1393                if refs {
1394                    for &entry in &state.stack[start..] {
1395                        state.nodes[entry].looped = true;
1396                    }
1397                    state.nodes[from].looped = true;
1398                }
1399            }
1400        } else if state.nodes[target].looped {
1401            state.nodes[from].looped = true;
1402        }
1403        Ok(FoldHit::cycle())
1404    }
1405
1406    fn state_of(&self, pn: usize) -> (u8, bool, bool) {
1407        let state = self.state.borrow();
1408        let node = &state.nodes[pn];
1409        (node.state, node.looped, node.cut)
1410    }
1411
1412    /// The folded value at `target` in a document, for the site at `from`.
1413    /// Raw members are followed from the root; a key operator site met on
1414    /// the way is folded (through the memory) and the remaining steps read
1415    /// its folded value, so a reference to a reference resolves. A target
1416    /// still being folded is a cycle, and so is a path that must pass
1417    /// through a site that was cut.
1418    ///
1419    /// The steps are taken in `find`, whose frame is gone before the walk
1420    /// this recurses into starts: this frame is on the stack once per
1421    /// reference hop, so it holds as little as it can.
1422    fn at(&self, from: usize, target: &[Seg], key: Option<&str>) -> Result<FoldHit, FoldError> {
1423        self.guard()?;
1424        match self.find(from, target, key)? {
1425            Found::Hit(hit) => Ok(hit),
1426            Found::Through(pn, next) => self.through(from, pn, target, next, key),
1427            Found::End(pn) => self.reach(from, pn),
1428        }
1429    }
1430
1431    /// Fold the static site `pn` part way along `target`, then read the
1432    /// rest of the path, from step `next`, in its folded value.
1433    fn through(
1434        &self,
1435        from: usize,
1436        pn: usize,
1437        target: &[Seg],
1438        next: usize,
1439        key: Option<&str>,
1440    ) -> Result<FoldHit, FoldError> {
1441        let (state, looped, _) = self.state_of(pn);
1442        if ACTIVE == state || looped {
1443            return self.cycle_to(from, pn);
1444        }
1445        match self.walk(pn, FROM_REFERENCE) {
1446            Ok(folded) => self.read_on(from, pn, folded, target, next, key),
1447            Err(error) => Err(error),
1448        }
1449    }
1450
1451    /// The rest of a path through a static site, read in the site's
1452    /// folded value: a cycle when the site was cut or is in a loop.
1453    fn read_on(
1454        &self,
1455        from: usize,
1456        pn: usize,
1457        folded: Value,
1458        target: &[Seg],
1459        next: usize,
1460        key: Option<&str>,
1461    ) -> Result<FoldHit, FoldError> {
1462        let (_, looped, cut) = self.state_of(pn);
1463        if looped || cut {
1464            return self.cycle_to(from, pn);
1465        }
1466        Ok(match read_raw(folded, &target[next..]) {
1467            Some(value) => FoldHit::found(value),
1468            None => self.miss(from, key, target),
1469        })
1470    }
1471
1472    /// Fold the location at the end of a path.
1473    fn reach(&self, from: usize, pn: usize) -> Result<FoldHit, FoldError> {
1474        let (state, _, _) = self.state_of(pn);
1475        if ACTIVE == state {
1476            return self.cycle_to(from, pn);
1477        }
1478        match self.walk(pn, FROM_REFERENCE) {
1479            Ok(value) => self.reached(from, pn, value),
1480            Err(error) => Err(error),
1481        }
1482    }
1483
1484    /// A location folded at the end of a path: a cycle when it is in a
1485    /// loop of references.
1486    fn reached(&self, from: usize, pn: usize, value: Value) -> Result<FoldHit, FoldError> {
1487        let (_, looped, _) = self.state_of(pn);
1488        if looped {
1489            return self.cycle_to(from, pn);
1490        }
1491        Ok(FoldHit::found(value))
1492    }
1493
1494    /// Follow `target` raw from the document's root, as far as the fold has
1495    /// to go: to its end, to a static key operator site met on the way,
1496    /// or to an answer.
1497    fn find(&self, from: usize, target: &[Seg], key: Option<&str>) -> Result<Found, FoldError> {
1498        let Some(doc) = self.doc_of(from, key)? else {
1499            return Ok(Found::Hit(self.miss(from, key, target)));
1500        };
1501        let (mut pn, mut node) = {
1502            let state = self.state.borrow();
1503            let doc = &state.docs[doc];
1504            (doc.top, doc.root.clone())
1505        };
1506        for (i, seg) in target.iter().enumerate() {
1507            let last = i + 1 == target.len();
1508            let Some(stepped) = step(&node, seg) else {
1509                return Ok(Found::Hit(self.miss(from, key, target)));
1510            };
1511            let (index, value) = match stepped {
1512                // The head of an operator node, its description: a leaf to
1513                // the fold, as the canonical treats its operator object, so
1514                // the rest of the path reads it raw.
1515                Step::Head(head) => {
1516                    return Ok(Found::Hit(match read_raw(head, &target[i + 1..]) {
1517                        Some(value) => FoldHit::found(value),
1518                        None => self.miss(from, key, target),
1519                    }));
1520                }
1521                Step::Member(value) => (None, value),
1522                Step::Item(index, value) => (Some(index), value),
1523            };
1524            if last && !is_container(&value) {
1525                return Ok(Found::Hit(FoldHit::found(value)));
1526            }
1527            pn = match index {
1528                Some(index) => self.kid_indexed(pn, index, value.clone()),
1529                None => self.kid_named(pn, &seg.text(), value.clone()),
1530            };
1531            node = value;
1532            // Only a static site changes what lies below it; any other map,
1533            // a dynamic one or one `recognise` refused, folds member by
1534            // member, so the raw path below it names the same location.
1535            if !last && is_record(&node) {
1536                if let Some(op) = self.site_op_of(pn)? {
1537                    if !op.dynamic {
1538                        return Ok(Found::Through(pn, i + 1));
1539                    }
1540                }
1541            }
1542        }
1543        Ok(Found::End(pn))
1544    }
1545
1546    fn locate(
1547        &self,
1548        from: usize,
1549        target: &[Seg],
1550        key: Option<&str>,
1551    ) -> Result<Option<Value>, FoldError> {
1552        self.guard()?;
1553        let Some(doc) = self.doc_of(from, key)? else {
1554            return Ok(None);
1555        };
1556        let root = self.state.borrow().docs[doc].root.clone();
1557        Ok(read_raw(root, target))
1558    }
1559
1560    /// A member's folded value: a container through the memory, anything
1561    /// else as it is.
1562    fn member(&self, pn: usize, name: &str, child: &Value) -> Result<Value, FoldError> {
1563        if is_container(child) {
1564            let kid = self.kid_named(pn, name, child.clone());
1565            self.walk(kid, FROM_PARENT)
1566        } else {
1567            Ok(child.clone())
1568        }
1569    }
1570
1571    /// A map folded as a plain map, members in its own order.
1572    fn plain_of(&self, pn: usize) -> Result<Value, FoldError> {
1573        self.guard()?;
1574        let (raw, parts) = {
1575            let state = self.state.borrow();
1576            let node = &state.nodes[pn];
1577            if let Some(plain) = &node.plain {
1578                return Ok(plain.clone());
1579            }
1580            let parts = node.parts.as_deref().map(|parts| {
1581                (
1582                    parts.src.clone(),
1583                    parts.value.clone(),
1584                    parts.siblings.clone(),
1585                )
1586            });
1587            (node.raw.clone(), parts)
1588        };
1589        let Some(members) = map_entries(&raw) else {
1590            return self.walk(pn, FROM_PARENT);
1591        };
1592        let mut out = IndexMap::with_capacity(members.len());
1593        for (name, member) in members {
1594            let value = match &parts {
1595                None => self.member(pn, name, member)?,
1596                Some((src, value, _)) if src == name => value.clone(),
1597                Some((_, _, siblings)) => map_entries(siblings)
1598                    .and_then(|siblings| siblings.get(name))
1599                    .cloned()
1600                    .unwrap_or(Value::Undefined),
1601            };
1602            out.insert(name.clone(), value);
1603        }
1604        let out = rebuild_map(&raw, out);
1605        self.state.borrow_mut().nodes[pn].plain = Some(out.clone());
1606        Ok(out)
1607    }
1608
1609    fn depth_error(&self, pn: usize) -> FoldError {
1610        let pointer = self.ptr_of(pn);
1611        let doc = self.doc_key(pn);
1612        let error = FoldError::new(
1613            FOLD_DEPTH,
1614            format_args!(
1615                "nesting and references deeper than {} at {}",
1616                self.options.max_depth,
1617                shown(&pointer)
1618            ),
1619        )
1620        .located(&doc, Some(&pointer));
1621        self.raise(error)
1622    }
1623
1624    /// Fold one location, and everything below it that is not folded yet.
1625    ///
1626    /// Iterative: the containers being walked are frames on a heap stack,
1627    /// so a level of nesting costs no stack. A callback this calls can
1628    /// re-enter the fold, and that nested walk is a new call with its own
1629    /// frames, which is where the stack grows: one call per reference hop.
1630    fn walk(&self, pn: usize, via: u8) -> Result<Value, FoldError> {
1631        self.guard()?;
1632        let mut frames = Vec::new();
1633        if let Some(value) = self.enter(pn, via, &mut frames)? {
1634            return Ok(value);
1635        }
1636        loop {
1637            if let Err(error) = self.descend(&mut frames) {
1638                self.unwind(&frames);
1639                return Err(error);
1640            }
1641            let finished = match frames.last_mut() {
1642                Some(top) => self.finish(top),
1643                None => return Ok(Value::Undefined),
1644            };
1645            // Dropped in place: `pop` would hand the frame back by value.
1646            frames.truncate(frames.len() - 1);
1647            match finished {
1648                Ok(value) => match frames.last_mut() {
1649                    Some(parent) => parent.accept(value),
1650                    None => return Ok(value),
1651                },
1652                Err(error) => {
1653                    self.unwind(&frames);
1654                    return Err(error);
1655                }
1656            }
1657        }
1658    }
1659
1660    /// Take the top frame's members until it has none left: a leaf, or a
1661    /// container already folded or being folded, is accepted as it is, and
1662    /// any other container gets a frame of its own on top, which is then
1663    /// the one read. Returns once the top frame is complete.
1664    fn descend(&self, frames: &mut Vec<Frame>) -> Result<(), FoldError> {
1665        loop {
1666            let Some(top) = frames.last_mut() else {
1667                return Ok(());
1668            };
1669            let Some((member, child)) = top.take() else {
1670                return Ok(());
1671            };
1672            if !is_container(&child) {
1673                top.accept(child);
1674                continue;
1675            }
1676            let kid = self.kid_of(top.pn, &top.raw, member, child);
1677            if let Some(value) = self.enter(kid, FROM_PARENT, frames)? {
1678                if let Some(top) = frames.last_mut() {
1679                    top.accept(value);
1680                }
1681            }
1682        }
1683    }
1684
1685    /// Start folding a location: its memorised value, the node itself when
1686    /// it is a leaf or already being folded, or `None` with a frame for its
1687    /// members pushed on `frames`.
1688    fn enter(
1689        &self,
1690        pn: usize,
1691        via: u8,
1692        frames: &mut Vec<Frame>,
1693    ) -> Result<Option<Value>, FoldError> {
1694        let raw = {
1695            let state = self.state.borrow();
1696            let node = &state.nodes[pn];
1697            if DONE == node.state {
1698                return Ok(Some(node.value.clone()));
1699            }
1700            if ACTIVE == node.state || !is_container(&node.raw) {
1701                return Ok(Some(node.raw.clone()));
1702            }
1703            node.raw.clone()
1704        };
1705        {
1706            let mut state = self.state.borrow_mut();
1707            if self.options.max_depth <= state.stack.len() {
1708                drop(state);
1709                return Err(self.depth_error(pn));
1710            }
1711            state.nodes[pn].state = ACTIVE;
1712            state.nodes[pn].via = via;
1713            state.stack.push(pn);
1714        }
1715        let kind = if is_record(&raw) {
1716            let op = match self.site_op_of(pn) {
1717                Ok(op) => op,
1718                Err(error) => {
1719                    self.leave(pn, None);
1720                    return Err(error);
1721                }
1722            };
1723            match op {
1724                Some(op) if !op.dynamic => Kind::Site {
1725                    op,
1726                    value: Value::Undefined,
1727                    siblings: IndexMap::new(),
1728                },
1729                op => {
1730                    if let Some(op) = op {
1731                        self.note_dynamic(pn, &op.src);
1732                    }
1733                    let plain = self.state.borrow().nodes[pn].plain.clone();
1734                    if let Some(plain) = plain {
1735                        self.leave(pn, Some(plain.clone()));
1736                        return Ok(Some(plain));
1737                    }
1738                    Kind::Plain {
1739                        out: IndexMap::with_capacity(map_entries(&raw).map_or(0, IndexMap::len)),
1740                    }
1741                }
1742            }
1743        } else if let Some(id) = node_id(&raw) {
1744            let (op, terms) = with_node(&raw, |entry| (entry.op.clone(), entry.terms.clone()))
1745                .unwrap_or_else(|| released_handle(id));
1746            Kind::Node {
1747                op,
1748                out: Vec::with_capacity(terms.len()),
1749                terms,
1750            }
1751        } else {
1752            Kind::List {
1753                out: Vec::with_capacity(list_items(&raw).len()),
1754            }
1755        };
1756        frames.push(Frame {
1757            pn,
1758            raw,
1759            next: 0,
1760            kind,
1761        });
1762        Ok(None)
1763    }
1764
1765    /// Close a location once its members are folded: reduce it, keep the
1766    /// result, and take it off the active stack.
1767    ///
1768    /// This and the functions it calls through to the callback are on the
1769    /// stack once per reference hop, so each holds only what it needs: the
1770    /// frame is read in place, not moved, and the work that calls nothing
1771    /// back is done in frames that are gone before a callback runs.
1772    fn finish(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1773        let pn = frame.pn;
1774        let out = match frame.kind {
1775            Kind::Node { op: Some(_), .. } => self.reduce_node(frame),
1776            Kind::Site { .. } => self.reduce_site(frame),
1777            _ => Ok(self.rebuild(frame)),
1778        };
1779        self.leave(pn, out.as_ref().ok().cloned());
1780        out
1781    }
1782
1783    /// A list, an expression node with no operator, or a plain map: the
1784    /// folded members, in a new container of the same kind.
1785    fn rebuild(&self, frame: &mut Frame) -> Value {
1786        let Frame { pn, raw, kind, .. } = frame;
1787        match kind {
1788            Kind::List { out } => rebuild_list(raw, std::mem::take(out)),
1789            Kind::Node { out, .. } => Value::array(std::mem::take(out)),
1790            Kind::Plain { out } => {
1791                let out = rebuild_map(raw, std::mem::take(out));
1792                self.state.borrow_mut().nodes[*pn].plain = Some(out.clone());
1793                out
1794            }
1795            Kind::Site { .. } => Value::Undefined,
1796        }
1797    }
1798
1799    /// A token operator node: through `evaluate` when `tokens` is on, and
1800    /// otherwise rebuilt around its own operator, so it stays an operator
1801    /// node, a new live node in the same arena.
1802    fn reduce_node(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1803        let Frame { pn, raw, kind, .. } = frame;
1804        let Kind::Node {
1805            op: Some(op), out, ..
1806        } = kind
1807        else {
1808            return Ok(Value::Undefined);
1809        };
1810        let op = op.clone();
1811        let terms = std::mem::take(out);
1812        if self.options.tokens {
1813            self.call_evaluate(*pn, &op, &terms)
1814        } else {
1815            Ok(operator_node(raw, op, terms))
1816        }
1817    }
1818
1819    /// A key operator site: its terms kept for `site.plain()`, then
1820    /// `evaluate` with `[value, siblings]`.
1821    fn reduce_site(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1822        let Frame { pn, raw, kind, .. } = frame;
1823        let Kind::Site {
1824            op,
1825            value,
1826            siblings,
1827        } = kind
1828        else {
1829            return Ok(Value::Undefined);
1830        };
1831        let op = op.clone();
1832        let terms = [
1833            std::mem::replace(value, Value::Undefined),
1834            rebuild_map(raw, std::mem::take(siblings)),
1835        ];
1836        self.keep_parts(*pn, &op, &terms);
1837        self.call_evaluate(*pn, &op, &terms)
1838    }
1839
1840    fn keep_parts(&self, pn: usize, op: &Op, terms: &[Value; 2]) {
1841        self.state.borrow_mut().nodes[pn].parts = Some(Box::new(Parts {
1842            src: op.src.clone(),
1843            value: terms[0].clone(),
1844            siblings: terms[1].clone(),
1845        }));
1846    }
1847
1848    /// The resolver, at a site. Its result is a `TabnasError` result, which
1849    /// is large, so it is converted after the call, in a frame of its own.
1850    fn call_evaluate(&self, pn: usize, op: &Op, terms: &[Value]) -> Result<Value, FoldError> {
1851        let site = self.site(pn, None);
1852        let result = (self.options.evaluate)(&site, op, terms);
1853        // Read in place: moving the result into a conversion would copy it
1854        // into this frame again.
1855        match &result {
1856            Ok(value) => Ok(value.clone()),
1857            Err(error) => Err(self.callback_error(error)),
1858        }
1859    }
1860
1861    /// Take a location off the active stack: kept when it has a value,
1862    /// free again when its fold failed.
1863    fn leave(&self, pn: usize, out: Option<Value>) {
1864        let mut state = self.state.borrow_mut();
1865        let top = state.stack.pop();
1866        debug_assert_eq!(Some(pn), top, "the active stack unwinds in order");
1867        let node = &mut state.nodes[pn];
1868        match out {
1869            Some(value) => {
1870                node.state = DONE;
1871                node.value = value;
1872            }
1873            None => node.state = FREE,
1874        }
1875    }
1876
1877    /// A walk failed: every location it still had open is free again.
1878    fn unwind(&self, frames: &[Frame]) {
1879        for frame in frames.iter().rev() {
1880            self.leave(frame.pn, None);
1881        }
1882    }
1883}
1884
1885// ---------------------------------------------------------------------------
1886// Values
1887// ---------------------------------------------------------------------------
1888
1889/// A map: what a key operator can be recognised on.
1890fn is_record(value: &Value) -> bool {
1891    matches!(value, Value::Object(_) | Value::MapRef(_))
1892}
1893
1894/// A map or a list: what the fold walks into. An expression node is a
1895/// list.
1896fn is_container(value: &Value) -> bool {
1897    matches!(
1898        value,
1899        Value::Object(_) | Value::MapRef(_) | Value::Array(_) | Value::ListRef(_)
1900    )
1901}
1902
1903fn map_entries(value: &Value) -> Option<&IndexMap<String, Value>> {
1904    match value {
1905        Value::Object(members) => Some(members),
1906        Value::MapRef(map) => Some(&map.value),
1907        _ => None,
1908    }
1909}
1910
1911fn list_items(value: &Value) -> &[Value] {
1912    match value {
1913        Value::Array(items) => items,
1914        Value::ListRef(list) => &list.value,
1915        _ => &[],
1916    }
1917}
1918
1919fn member_name(raw: &Value, at: usize) -> &str {
1920    map_entries(raw)
1921        .and_then(|members| members.get_index(at))
1922        .map_or("", |(name, _)| name.as_str())
1923}
1924
1925/// A new map of the same kind as `like`: an `Object` for an `Object`, and
1926/// a `MapRef` keeping its flags and metadata for a `MapRef`.
1927fn rebuild_map(like: &Value, members: IndexMap<String, Value>) -> Value {
1928    match like {
1929        Value::MapRef(map) => {
1930            let mut out = (**map).clone();
1931            out.value = members;
1932            Value::MapRef(Arc::new(out))
1933        }
1934        _ => Value::object(members),
1935    }
1936}
1937
1938/// A new list of the same kind as `like`.
1939fn rebuild_list(like: &Value, items: Vec<Value>) -> Value {
1940    match like {
1941        Value::ListRef(list) => {
1942            let mut out = (**list).clone();
1943            out.value = items;
1944            Value::ListRef(Arc::new(out))
1945        }
1946        _ => Value::array(items),
1947    }
1948}
1949
1950/// An operator node rebuilt around its own operator and occurrence token,
1951/// with folded terms: a new live node in the arena `raw` is in.
1952fn operator_node(raw: &Value, op: Arc<Op>, terms: Vec<Value>) -> Value {
1953    let token = with_node(raw, |entry| entry.token.clone()).flatten();
1954    new_node(Some(op), token, terms)
1955}
1956
1957/// One step of a path.
1958enum Step {
1959    /// A map's member.
1960    Member(Value),
1961    /// A list's item, by its index.
1962    Item(usize, Value),
1963    /// The head of a live operator node: its realized description.
1964    Head(Value),
1965}
1966
1967/// One step of a path: an index into a list, or an own member of a map.
1968/// `None` when the step names nothing.
1969fn step(node: &Value, seg: &Seg) -> Option<Step> {
1970    match node {
1971        Value::Object(members) => members.get(seg.text().as_ref()).cloned().map(Step::Member),
1972        Value::MapRef(map) => map
1973            .value
1974            .get(seg.text().as_ref())
1975            .cloned()
1976            .map(Step::Member),
1977        Value::Array(items) => {
1978            array_index(seg, items.len()).map(|index| Step::Item(index, items[index].clone()))
1979        }
1980        Value::ListRef(list) => match node_id(node) {
1981            None => array_index(seg, list.value.len())
1982                .map(|index| Step::Item(index, list.value[index].clone())),
1983            // A live expression node reads as the canonical array does: the
1984            // operator first, then the terms.
1985            Some(id) => with_node(node, |entry| {
1986                let head = usize::from(entry.op.is_some());
1987                let index = array_index(seg, entry.terms.len() + head)?;
1988                match (index, &entry.op) {
1989                    (0, Some(op)) => Some(Step::Head(op.to_value(entry.token.as_ref()))),
1990                    _ => Some(Step::Item(index, entry.terms[index - head].clone())),
1991                }
1992            })
1993            .unwrap_or_else(|| released_handle(id)),
1994        },
1995        _ => None,
1996    }
1997}
1998
1999/// Read raw from `node` along `path`, following nothing.
2000fn read_raw(mut node: Value, path: &[Seg]) -> Option<Value> {
2001    for seg in path {
2002        node = match step(&node, seg)? {
2003            Step::Member(value) | Step::Item(_, value) | Step::Head(value) => value,
2004        };
2005    }
2006    Some(node)
2007}
2008
2009/// An RFC 6901 array index: `0`, or digits with no leading zero, given as
2010/// a name, or an index; `None` for anything else, `-` and out-of-range
2011/// indices included.
2012fn array_index(seg: &Seg, length: usize) -> Option<usize> {
2013    let index = match seg {
2014        Seg::Index(index) => *index,
2015        Seg::Name(text) => {
2016            let canonical = "0" == text
2017                || (!text.is_empty()
2018                    && !text.starts_with('0')
2019                    && text.bytes().all(|byte| byte.is_ascii_digit()));
2020            if !canonical {
2021                return None;
2022            }
2023            text.parse::<usize>().ok()?
2024        }
2025    };
2026    (index < length).then_some(index)
2027}
2028
2029/// RFC 6901: a pointer from path steps.
2030fn pointer(path: &[Seg]) -> String {
2031    let mut out = String::new();
2032    for seg in path {
2033        out.push('/');
2034        escape_segment(&mut out, &seg.text());
2035    }
2036    out
2037}
2038
2039fn escape_segment(out: &mut String, text: &str) {
2040    for c in text.chars() {
2041        match c {
2042            '~' => out.push_str("~0"),
2043            '/' => out.push_str("~1"),
2044            c => out.push(c),
2045        }
2046    }
2047}
2048
2049/// A key or pointer for a message: JSON-escaped, as `JSON.stringify`
2050/// writes a string, so a newline or an escape sequence in a member name
2051/// stays visible, and at most about 80 characters long, counted as
2052/// JavaScript counts them, in UTF-16 units.
2053fn shown(text: &str) -> String {
2054    let mut quoted = String::with_capacity(text.len() + 2);
2055    quoted.push('"');
2056    for c in text.chars() {
2057        match c {
2058            '"' => quoted.push_str("\\\""),
2059            '\\' => quoted.push_str("\\\\"),
2060            '\n' => quoted.push_str("\\n"),
2061            '\r' => quoted.push_str("\\r"),
2062            '\t' => quoted.push_str("\\t"),
2063            '\u{8}' => quoted.push_str("\\b"),
2064            '\u{c}' => quoted.push_str("\\f"),
2065            c if (c as u32) < 0x20 => quoted.push_str(&format!("\\u{:04x}", c as u32)),
2066            c => quoted.push(c),
2067        }
2068    }
2069    quoted.push('"');
2070    if quoted.encode_utf16().count() <= 80 {
2071        return quoted;
2072    }
2073    let mut out = String::new();
2074    let mut units = 0;
2075    for c in quoted.chars() {
2076        units += c.len_utf16();
2077        if 76 < units {
2078            break;
2079        }
2080        out.push(c);
2081    }
2082    out.push_str("...\"");
2083    out
2084}