1use 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
38pub const FOLD_BUDGET: &str = "fold_budget";
44pub const FOLD_CANCEL: &str = "fold_cancel";
46pub const FOLD_CYCLE: &str = "fold_cycle";
48pub const FOLD_DEPTH: &str = "fold_depth";
51pub const FOLD_INHERIT: &str = "fold_inherit";
53pub const FOLD_KEY: &str = "fold_key";
56pub const FOLD_OPTION: &str = "fold_option";
60
61#[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 pub fn code(&self) -> &str {
129 &self.0.code
130 }
131
132 pub fn message(&self) -> &str {
135 &self.0.message
136 }
137
138 pub fn doc(&self) -> Option<&str> {
140 self.0.doc.as_deref()
141 }
142
143 pub fn at(&self) -> Option<&str> {
146 self.0.at.as_deref()
147 }
148
149 pub fn target_doc(&self) -> Option<&str> {
151 self.0.target_doc.as_deref()
152 }
153
154 pub fn target(&self) -> Option<&str> {
156 self.0.target.as_deref()
157 }
158
159 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 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
208pub enum Seg {
209 Name(String),
211 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
248pub type Path = Vec<Seg>;
250
251#[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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
299pub struct FoldDynamic {
300 pub doc: String,
301 pub at: String,
302 pub src: String,
303}
304
305#[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
313pub type FoldEvaluate<'a> =
322 Box<dyn Fn(&Site<'_>, &Op, &[Value]) -> Result<Value, TabnasError> + 'a>;
323
324pub type Inherit<'a> = Box<dyn Fn(&Site<'_>, &Value, &Value) -> Result<Value, TabnasError> + 'a>;
330
331pub type Recognise<'a> = Box<dyn Fn(&Site<'_>, &Op) -> Result<bool, TabnasError> + 'a>;
335
336pub type Load<'a> = Box<dyn Fn(&str, &Site<'_>) -> Result<Option<Value>, TabnasError> + 'a>;
339
340pub type Positions<'a> = Box<dyn Fn(&Value) -> Option<Token> + 'a>;
343
344#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
346pub enum FoldCycle {
347 #[default]
349 Verbatim,
350 Error,
352}
353
354#[derive(Default)]
370pub struct FoldBudget<'a> {
371 pub steps: usize,
373 pub check_every_n: usize,
375 pub on_check: Option<Box<dyn Fn(usize) -> bool + 'a>>,
377}
378
379impl<'a> FoldBudget<'a> {
380 pub fn new(steps: usize) -> Self {
382 FoldBudget {
383 steps,
384 ..FoldBudget::default()
385 }
386 }
387
388 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
418pub struct FoldOptions<'a> {
425 pub op: IndexMap<String, Option<OpDef>>,
428 pub evaluate: FoldEvaluate<'a>,
429 pub inherit: Option<Inherit<'a>>,
430 pub recognise: Option<Recognise<'a>>,
431 pub k: Value,
433 pub doc: String,
435 pub load: Option<Load<'a>>,
436 pub cycle: FoldCycle,
437 pub tokens: bool,
442 pub positions: Option<Positions<'a>>,
443 pub max_depth: usize,
446 pub max_stack: usize,
455 pub budget: Option<FoldBudget<'a>>,
458 pub report: Option<Box<dyn Fn(FoldReport) + 'a>>,
460}
461
462impl<'a> FoldOptions<'a> {
463 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 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 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#[derive(Debug, Clone, Default)]
600pub struct KeyMap {
601 ops: Vec<Arc<Op>>,
602}
603
604impl KeyMap {
605 pub fn iter(&self) -> std::slice::Iter<'_, Arc<Op>> {
607 self.ops.iter()
608 }
609
610 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
624pub 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 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
680pub 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
691pub 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 pub fn root(&self) -> &Value {
712 &self.root
713 }
714
715 pub fn doc(&self) -> &str {
717 &self.doc
718 }
719
720 pub fn path(&self) -> &[Seg] {
722 self.path.get_or_init(|| self.fold.path_of(self.pn))
723 }
724
725 pub fn node(&self) -> &Value {
727 &self.node
728 }
729
730 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 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 pub fn at(&self, path: &[Seg], doc: Option<&str>) -> Result<FoldHit, FoldError> {
764 self.fold.at(self.pn, path, doc)
765 }
766
767 pub fn written(&self, path: &[Seg], doc: Option<&str>) -> Result<FoldHit, FoldError> {
774 self.fold.written(self.pn, path, doc)
775 }
776
777 pub fn locate(&self, path: &[Seg], doc: Option<&str>) -> Result<Option<Value>, FoldError> {
779 self.fold.locate(self.pn, path, doc)
780 }
781
782 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
800pub 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
852const FREE: u8 = 0;
855const ACTIVE: u8 = 1;
856const DONE: u8 = 2;
857
858const FROM_PARENT: u8 = 0;
861const FROM_REFERENCE: u8 = 1;
862
863const CYCLES: u8 = 0;
865const UNRESOLVED: u8 = 1;
866const DYNAMIC: u8 = 2;
867
868pub const FOLD_MAX_STACK: usize = 1 << 20;
872
873struct Folder<'f> {
877 options: &'f FoldOptions<'f>,
878 keys: KeyMap,
879 stack_base: usize,
880 main: Rc<str>,
881 steps: Cell<usize>,
883 state: RefCell<State>,
884}
885
886#[derive(Default)]
887struct State {
888 nodes: Vec<PNode>,
890 docs: Vec<Doc>,
891 doc_keys: HashMap<String, Option<usize>>,
894 stack: Vec<usize>,
896 report: FoldReport,
897 noted: HashSet<(u8, String, String, String, String)>,
898 failure: Option<FoldError>,
901}
902
903impl State {
904 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
926struct 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 under: u32,
939 value: Value,
940 k: Option<Value>,
941 k_busy: bool,
942 cut: bool,
944 looped: bool,
947 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
979enum Kids {
981 Names(HashMap<String, usize>),
982 Indices(HashMap<usize, usize>),
983}
984
985struct Parts {
987 src: String,
988 value: Value,
989 siblings: Value,
990}
991
992struct 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#[inline(never)]
1031fn stack_here() -> usize {
1032 let marker = 0u8;
1033 std::hint::black_box(&marker) as *const u8 as usize
1034}
1035
1036struct Frame {
1039 pn: usize,
1040 ahead: bool,
1043 raw: Value,
1044 next: usize,
1045 kind: Kind,
1046}
1047
1048enum Kind {
1049 List { out: Vec<Value> },
1051 Node {
1056 op: Option<Arc<Op>>,
1057 terms: Vec<Value>,
1058 out: Vec<Value>,
1059 },
1060 Plain { out: IndexMap<String, Value> },
1062 Site {
1064 op: Arc<Op>,
1065 value: Value,
1066 siblings: IndexMap<String, Value>,
1067 },
1068}
1069
1070enum Member {
1073 Index(usize),
1074 Name(usize),
1075}
1076
1077enum Found {
1079 Hit(FoldHit),
1081 Through(usize, usize),
1084 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 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 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 fn raise(&self, error: FoldError) -> FoldError {
1341 self.state.borrow_mut().failure = Some(error.clone());
1342 error
1343 }
1344
1345 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 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 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 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 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 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 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 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 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 Found::Through(pn, next) => self.through(from, pn, target, next, key),
1599 Found::End(pn) => self.reach(from, pn),
1600 }
1601 }
1602
1603 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 match &result {
2061 Ok(value) => Ok(value.clone()),
2062 Err(error) => Err(self.callback_error(error)),
2063 }
2064 }
2065
2066 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 fn unwind(&self, frames: &[Frame]) {
2088 for frame in frames.iter().rev() {
2089 self.leave(frame.pn, frame.ahead, None);
2090 }
2091 }
2092}
2093
2094fn is_record(value: &Value) -> bool {
2100 matches!(value, Value::Object(_) | Value::MapRef(_))
2101}
2102
2103fn 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
2134fn 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
2147fn 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
2159fn 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
2166enum Step {
2168 Member(Value),
2170 Item(usize, Value),
2172 Head(Value),
2174}
2175
2176fn 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 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
2208fn 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
2218fn 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
2238fn 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
2258fn 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}