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