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_CYCLE: &str = "fold_cycle";
44pub const FOLD_DEPTH: &str = "fold_depth";
47pub const FOLD_INHERIT: &str = "fold_inherit";
49pub const FOLD_KEY: &str = "fold_key";
52pub const FOLD_OPTION: &str = "fold_option";
56
57#[derive(Debug, Clone, PartialEq)]
72pub struct FoldError(Box<FoldErrorData>);
73
74#[derive(Debug, Clone, PartialEq)]
75struct FoldErrorData {
76 code: String,
77 message: String,
78 doc: Option<String>,
79 at: Option<String>,
80 target_doc: Option<String>,
81 target: Option<String>,
82 cause: Option<TabnasError>,
83}
84
85impl FoldError {
86 fn new(code: &str, message: impl fmt::Display) -> Self {
87 FoldError(Box::new(FoldErrorData {
88 code: code.to_string(),
89 message: format!("expr fold: {message}"),
90 doc: None,
91 at: None,
92 target_doc: None,
93 target: None,
94 cause: None,
95 }))
96 }
97
98 fn callback(cause: TabnasError) -> Self {
99 FoldError(Box::new(FoldErrorData {
100 code: cause.code.clone(),
101 message: cause.detail.clone(),
102 doc: None,
103 at: None,
104 target_doc: None,
105 target: None,
106 cause: Some(cause),
107 }))
108 }
109
110 fn located(mut self, doc: &str, at: Option<&str>) -> Self {
111 self.0.doc = Some(doc.to_string());
112 self.0.at = at.map(str::to_string);
113 self
114 }
115
116 fn targeted(mut self, target_doc: &str, target: &str) -> Self {
117 self.0.target_doc = Some(target_doc.to_string());
118 self.0.target = Some(target.to_string());
119 self
120 }
121
122 pub fn code(&self) -> &str {
124 &self.0.code
125 }
126
127 pub fn message(&self) -> &str {
130 &self.0.message
131 }
132
133 pub fn doc(&self) -> Option<&str> {
135 self.0.doc.as_deref()
136 }
137
138 pub fn at(&self) -> Option<&str> {
141 self.0.at.as_deref()
142 }
143
144 pub fn target_doc(&self) -> Option<&str> {
146 self.0.target_doc.as_deref()
147 }
148
149 pub fn target(&self) -> Option<&str> {
151 self.0.target.as_deref()
152 }
153
154 pub fn cause(&self) -> Option<&TabnasError> {
157 self.0.cause.as_ref()
158 }
159}
160
161impl fmt::Display for FoldError {
162 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163 formatter.write_str(&self.0.message)
164 }
165}
166
167impl std::error::Error for FoldError {
168 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
169 self.0
170 .cause
171 .as_ref()
172 .map(|cause| cause as &(dyn std::error::Error + 'static))
173 }
174}
175
176impl From<FoldError> for TabnasError {
177 fn from(error: FoldError) -> Self {
178 let data = *error.0;
179 if let Some(cause) = data.cause {
180 return cause;
181 }
182 let mut out = TabnasError::new(data.code, "", "", 0, 1, 1);
186 out.detail = data.message;
187 out.hint = String::new();
188 out
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq, Hash)]
203pub enum Seg {
204 Name(String),
206 Index(usize),
208}
209
210impl Seg {
211 fn text(&self) -> Cow<'_, str> {
212 match self {
213 Seg::Name(name) => Cow::Borrowed(name),
214 Seg::Index(index) => Cow::Owned(index.to_string()),
215 }
216 }
217}
218
219impl From<&str> for Seg {
220 fn from(name: &str) -> Self {
221 Seg::Name(name.to_string())
222 }
223}
224
225impl From<String> for Seg {
226 fn from(name: String) -> Self {
227 Seg::Name(name)
228 }
229}
230
231impl From<usize> for Seg {
232 fn from(index: usize) -> Self {
233 Seg::Index(index)
234 }
235}
236
237impl fmt::Display for Seg {
238 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
239 formatter.write_str(&self.text())
240 }
241}
242
243pub type Path = Vec<Seg>;
245
246#[derive(Debug, Clone, PartialEq)]
250pub struct FoldHit {
251 pub found: bool,
252 pub cycle: bool,
253 pub value: Option<Value>,
254}
255
256impl FoldHit {
257 fn missing() -> Self {
258 FoldHit {
259 found: false,
260 cycle: false,
261 value: None,
262 }
263 }
264
265 fn cycle() -> Self {
266 FoldHit {
267 found: true,
268 cycle: true,
269 value: None,
270 }
271 }
272
273 fn found(value: Value) -> Self {
274 FoldHit {
275 found: true,
276 cycle: false,
277 value: Some(value),
278 }
279 }
280}
281
282#[derive(Debug, Clone, Default, PartialEq, Eq)]
285pub struct FoldEntry {
286 pub doc: String,
287 pub at: String,
288 pub target_doc: String,
289 pub target: String,
290}
291
292#[derive(Debug, Clone, Default, PartialEq, Eq)]
294pub struct FoldDynamic {
295 pub doc: String,
296 pub at: String,
297 pub src: String,
298}
299
300#[derive(Debug, Clone, Default, PartialEq, Eq)]
302pub struct FoldReport {
303 pub cycles: Vec<FoldEntry>,
304 pub unresolved: Vec<FoldEntry>,
305 pub dynamic: Vec<FoldDynamic>,
306}
307
308pub type FoldEvaluate<'a> =
317 Box<dyn Fn(&Site<'_>, &Op, &[Value]) -> Result<Value, TabnasError> + 'a>;
318
319pub type Inherit<'a> = Box<dyn Fn(&Site<'_>, &Value, &Value) -> Result<Value, TabnasError> + 'a>;
325
326pub type Recognise<'a> = Box<dyn Fn(&Site<'_>, &Op) -> Result<bool, TabnasError> + 'a>;
330
331pub type Load<'a> = Box<dyn Fn(&str, &Site<'_>) -> Result<Option<Value>, TabnasError> + 'a>;
334
335pub type Positions<'a> = Box<dyn Fn(&Value) -> Option<Token> + 'a>;
338
339#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
341pub enum FoldCycle {
342 #[default]
344 Verbatim,
345 Error,
347}
348
349pub struct FoldOptions<'a> {
356 pub op: IndexMap<String, Option<OpDef>>,
359 pub evaluate: FoldEvaluate<'a>,
360 pub inherit: Option<Inherit<'a>>,
361 pub recognise: Option<Recognise<'a>>,
362 pub k: Value,
364 pub doc: String,
366 pub load: Option<Load<'a>>,
367 pub cycle: FoldCycle,
368 pub tokens: bool,
373 pub positions: Option<Positions<'a>>,
374 pub max_depth: usize,
377 pub max_stack: usize,
386 pub report: Option<Box<dyn Fn(FoldReport) + 'a>>,
388}
389
390impl<'a> FoldOptions<'a> {
391 pub fn new(
393 evaluate: impl Fn(&Site<'_>, &Op, &[Value]) -> Result<Value, TabnasError> + 'a,
394 ) -> Self {
395 FoldOptions {
396 op: IndexMap::new(),
397 evaluate: Box::new(evaluate),
398 inherit: None,
399 recognise: None,
400 k: Value::object(IndexMap::new()),
401 doc: String::new(),
402 load: None,
403 cycle: FoldCycle::Verbatim,
404 tokens: true,
405 positions: None,
406 max_depth: 1000,
407 max_stack: FOLD_MAX_STACK,
408 report: None,
409 }
410 }
411
412 pub fn with_op(mut self, name: impl Into<String>, def: OpDef) -> Self {
414 self.op.insert(name.into(), Some(def));
415 self
416 }
417
418 pub fn with_ops(mut self, op: IndexMap<String, Option<OpDef>>) -> Self {
421 self.op = op;
422 self
423 }
424
425 pub fn with_inherit(
426 mut self,
427 inherit: impl Fn(&Site<'_>, &Value, &Value) -> Result<Value, TabnasError> + 'a,
428 ) -> Self {
429 self.inherit = Some(Box::new(inherit));
430 self
431 }
432
433 pub fn with_recognise(
434 mut self,
435 recognise: impl Fn(&Site<'_>, &Op) -> Result<bool, TabnasError> + 'a,
436 ) -> Self {
437 self.recognise = Some(Box::new(recognise));
438 self
439 }
440
441 pub fn with_k(mut self, k: Value) -> Self {
442 self.k = k;
443 self
444 }
445
446 pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
447 self.doc = doc.into();
448 self
449 }
450
451 pub fn with_load(
452 mut self,
453 load: impl Fn(&str, &Site<'_>) -> Result<Option<Value>, TabnasError> + 'a,
454 ) -> Self {
455 self.load = Some(Box::new(load));
456 self
457 }
458
459 pub fn with_cycle(mut self, cycle: FoldCycle) -> Self {
460 self.cycle = cycle;
461 self
462 }
463
464 pub fn with_tokens(mut self, tokens: bool) -> Self {
465 self.tokens = tokens;
466 self
467 }
468
469 pub fn with_positions(mut self, positions: impl Fn(&Value) -> Option<Token> + 'a) -> Self {
470 self.positions = Some(Box::new(positions));
471 self
472 }
473
474 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
475 self.max_depth = max_depth;
476 self
477 }
478
479 pub fn with_max_stack(mut self, max_stack: usize) -> Self {
480 self.max_stack = max_stack;
481 self
482 }
483
484 pub fn with_report(mut self, report: impl Fn(FoldReport) + 'a) -> Self {
485 self.report = Some(Box::new(report));
486 self
487 }
488}
489
490impl fmt::Debug for FoldOptions<'_> {
491 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
492 let function = |present: bool| if present { "<function>" } else { "none" };
493 formatter
494 .debug_struct("FoldOptions")
495 .field("op", &self.op)
496 .field("evaluate", &"<function>")
497 .field("inherit", &function(self.inherit.is_some()))
498 .field("recognise", &function(self.recognise.is_some()))
499 .field("k", &self.k)
500 .field("doc", &self.doc)
501 .field("load", &function(self.load.is_some()))
502 .field("cycle", &self.cycle)
503 .field("tokens", &self.tokens)
504 .field("positions", &function(self.positions.is_some()))
505 .field("max_depth", &self.max_depth)
506 .field("max_stack", &self.max_stack)
507 .field("report", &function(self.report.is_some()))
508 .finish()
509 }
510}
511
512#[derive(Debug, Clone, Default)]
521pub struct KeyMap {
522 ops: Vec<Arc<Op>>,
523}
524
525impl KeyMap {
526 pub fn iter(&self) -> std::slice::Iter<'_, Arc<Op>> {
528 self.ops.iter()
529 }
530
531 pub fn get(&self, src: &str) -> Option<&Arc<Op>> {
533 self.ops.iter().find(|op| op.src == src)
534 }
535
536 pub fn len(&self) -> usize {
537 self.ops.len()
538 }
539
540 pub fn is_empty(&self) -> bool {
541 self.ops.is_empty()
542 }
543}
544
545pub fn make_key_map(ops: &IndexMap<String, Option<OpDef>>) -> Result<KeyMap, FoldError> {
551 let mut found: Vec<Op> = Vec::new();
552 let mut owner: HashMap<&str, &str> = HashMap::new();
553 for (name, def) in ops {
554 let Some(def) = def else { continue };
555 if !def.key {
556 continue;
557 }
558 let src = def.src.first().map(String::as_str).unwrap_or_default();
559 if src.is_empty() {
560 return Err(FoldError::new(
561 FOLD_KEY,
562 format_args!("key operator {} names no member", shown(name)),
563 ));
564 }
565 if let Some(prior) = owner.get(src) {
566 return Err(FoldError::new(
567 FOLD_KEY,
568 format_args!(
569 "key operators {} and {} both name the member {}",
570 shown(prior),
571 shown(name),
572 shown(src)
573 ),
574 ));
575 }
576 owner.insert(src, name);
577 found.push(Op {
578 name: if name.ends_with("-key") {
579 name.clone()
580 } else {
581 format!("{name}-key")
582 },
583 src: src.to_string(),
584 left: MIN_SAFE_INTEGER,
585 right: MAX_SAFE_INTEGER,
586 use_data: def.use_data.clone(),
587 terms: 2,
588 key: true,
589 dynamic: def.dynamic,
590 ..Default::default()
591 });
592 }
593 found.sort_by(|a, b| a.dynamic.cmp(&b.dynamic).then_with(|| a.src.cmp(&b.src)));
596 Ok(KeyMap {
597 ops: found.into_iter().map(Arc::new).collect(),
598 })
599}
600
601pub fn key_op_of(keys: &KeyMap, node: &Value) -> Option<Arc<Op>> {
605 let members = map_entries(node)?;
606 keys.ops
607 .iter()
608 .find(|op| members.contains_key(op.src.as_str()))
609 .cloned()
610}
611
612pub struct Site<'f> {
621 fold: &'f Folder<'f>,
622 pn: usize,
623 parent_k: Option<Value>,
624 doc: Rc<str>,
625 root: Value,
626 node: Value,
627 path: OnceCell<Path>,
628}
629
630impl Site<'_> {
631 pub fn root(&self) -> &Value {
633 &self.root
634 }
635
636 pub fn doc(&self) -> &str {
638 &self.doc
639 }
640
641 pub fn path(&self) -> &[Seg] {
643 self.path.get_or_init(|| self.fold.path_of(self.pn))
644 }
645
646 pub fn node(&self) -> &Value {
648 &self.node
649 }
650
651 pub fn k(&self) -> Result<Value, FoldError> {
657 match &self.parent_k {
658 Some(k) => Ok(k.clone()),
659 None => self.fold.k_of(self.pn),
660 }
661 }
662
663 pub fn token(&self) -> Option<Token> {
669 if node_id(&self.node).is_some() {
670 return with_node(&self.node, |entry| entry.token.clone()).flatten();
671 }
672 self.fold
673 .options
674 .positions
675 .as_ref()
676 .and_then(|lookup| lookup(&self.node))
677 }
678
679 pub fn at(&self, path: &[Seg], doc: Option<&str>) -> Result<FoldHit, FoldError> {
685 self.fold.at(self.pn, path, doc)
686 }
687
688 pub fn locate(&self, path: &[Seg], doc: Option<&str>) -> Result<Option<Value>, FoldError> {
690 self.fold.locate(self.pn, path, doc)
691 }
692
693 pub fn plain(&self) -> Result<Value, FoldError> {
696 self.fold.plain_of(self.pn)
697 }
698}
699
700impl fmt::Debug for Site<'_> {
701 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
702 formatter
703 .debug_struct("Site")
704 .field("doc", &self.doc)
705 .field("path", &self.path())
706 .field("node", &self.node)
707 .finish()
708 }
709}
710
711pub fn fold(root: &Value, options: &FoldOptions<'_>) -> Result<Value, FoldError> {
743 let keys = make_key_map(&options.op)?;
744 let base = StackBase::enter();
745 let folder = Folder {
746 options,
747 keys,
748 stack_base: base.at,
749 main: Rc::from(options.doc.as_str()),
750 state: RefCell::new(State::default()),
751 };
752 let doc = folder.make_doc(&options.doc, root.clone());
753 let top = folder.state.borrow().docs[doc].top;
754 let out = folder.walk(top, FROM_PARENT)?;
755 if let Some(report) = &options.report {
756 let rows = std::mem::take(&mut folder.state.borrow_mut().report);
757 report(rows);
758 }
759 Ok(out)
760}
761
762const FREE: u8 = 0;
765const ACTIVE: u8 = 1;
766const DONE: u8 = 2;
767
768const FROM_PARENT: u8 = 0;
771const FROM_REFERENCE: u8 = 1;
772
773const CYCLES: u8 = 0;
775const UNRESOLVED: u8 = 1;
776const DYNAMIC: u8 = 2;
777
778pub const FOLD_MAX_STACK: usize = 1 << 20;
782
783struct Folder<'f> {
787 options: &'f FoldOptions<'f>,
788 keys: KeyMap,
789 stack_base: usize,
790 main: Rc<str>,
791 state: RefCell<State>,
792}
793
794#[derive(Default)]
795struct State {
796 nodes: Vec<PNode>,
798 docs: Vec<Doc>,
799 doc_keys: HashMap<String, Option<usize>>,
802 stack: Vec<usize>,
804 report: FoldReport,
805 noted: HashSet<(u8, String, String, String, String)>,
806 failure: Option<FoldError>,
809}
810
811struct Doc {
812 key: Rc<str>,
813 root: Value,
814 top: usize,
815}
816
817struct PNode {
819 doc: usize,
820 parent: Option<usize>,
821 seg: Seg,
822 raw: Value,
823 kids: Option<Box<Kids>>,
824 state: u8,
825 via: u8,
826 value: Value,
827 k: Option<Value>,
828 k_busy: bool,
829 cut: bool,
831 looped: bool,
834 site: Option<Option<Arc<Op>>>,
837 parts: Option<Box<Parts>>,
838 plain: Option<Value>,
839 ptr: Option<Rc<str>>,
840}
841
842impl PNode {
843 fn new(doc: usize, parent: Option<usize>, seg: Seg, raw: Value) -> Self {
844 PNode {
845 doc,
846 parent,
847 seg,
848 raw,
849 kids: None,
850 state: FREE,
851 via: FROM_PARENT,
852 value: Value::Undefined,
853 k: None,
854 k_busy: false,
855 cut: false,
856 looped: false,
857 site: None,
858 parts: None,
859 plain: None,
860 ptr: None,
861 }
862 }
863}
864
865enum Kids {
867 Names(HashMap<String, usize>),
868 Indices(HashMap<usize, usize>),
869}
870
871struct Parts {
873 src: String,
874 value: Value,
875 siblings: Value,
876}
877
878struct StackBase {
880 at: usize,
881 outermost: bool,
882}
883
884thread_local! {
885 static STACK_BASE: Cell<Option<usize>> = const { Cell::new(None) };
886}
887
888impl StackBase {
889 fn enter() -> Self {
890 let here = stack_here();
891 STACK_BASE.with(|base| match base.get() {
892 Some(at) => StackBase {
893 at,
894 outermost: false,
895 },
896 None => {
897 base.set(Some(here));
898 StackBase {
899 at: here,
900 outermost: true,
901 }
902 }
903 })
904 }
905}
906
907impl Drop for StackBase {
908 fn drop(&mut self) {
909 if self.outermost {
910 STACK_BASE.with(|base| base.set(None));
911 }
912 }
913}
914
915#[inline(never)]
917fn stack_here() -> usize {
918 let marker = 0u8;
919 std::hint::black_box(&marker) as *const u8 as usize
920}
921
922struct Frame {
925 pn: usize,
926 raw: Value,
927 next: usize,
928 kind: Kind,
929}
930
931enum Kind {
932 List { out: Vec<Value> },
934 Node {
939 op: Option<Arc<Op>>,
940 terms: Vec<Value>,
941 out: Vec<Value>,
942 },
943 Plain { out: IndexMap<String, Value> },
945 Site {
947 op: Arc<Op>,
948 value: Value,
949 siblings: IndexMap<String, Value>,
950 },
951}
952
953enum Member {
956 Index(usize),
957 Name(usize),
958}
959
960enum Found {
962 Hit(FoldHit),
964 Through(usize, usize),
967 End(usize),
969}
970
971impl Frame {
972 fn take(&mut self) -> Option<(Member, Value)> {
973 let at = self.next;
974 let taken = match &self.kind {
975 Kind::List { .. } => list_items(&self.raw)
976 .get(at)
977 .map(|item| (Member::Index(at), item.clone())),
978 Kind::Node { op, terms, .. } => terms
979 .get(at)
980 .map(|term| (Member::Index(at + usize::from(op.is_some())), term.clone())),
981 Kind::Plain { .. } | Kind::Site { .. } => map_entries(&self.raw)
982 .and_then(|members| members.get_index(at))
983 .map(|(_, member)| (Member::Name(at), member.clone())),
984 };
985 if taken.is_some() {
986 self.next += 1;
987 }
988 taken
989 }
990
991 fn accept(&mut self, value: Value) {
992 let at = self.next - 1;
993 let Frame { raw, kind, .. } = self;
994 match kind {
995 Kind::List { out } | Kind::Node { out, .. } => out.push(value),
996 Kind::Plain { out } => {
997 out.insert(member_name(raw, at).to_string(), value);
998 }
999 Kind::Site {
1000 op,
1001 value: slot,
1002 siblings,
1003 } => {
1004 let name = member_name(raw, at);
1005 if name == op.src {
1006 *slot = value;
1007 } else {
1008 siblings.insert(name.to_string(), value);
1009 }
1010 }
1011 }
1012 }
1013}
1014
1015impl Folder<'_> {
1016 fn site(&self, pn: usize, parent_k: Option<Value>) -> Site<'_> {
1017 let state = self.state.borrow();
1018 let node = &state.nodes[pn];
1019 let doc = &state.docs[node.doc];
1020 Site {
1021 fold: self,
1022 pn,
1023 parent_k,
1024 doc: doc.key.clone(),
1025 root: doc.root.clone(),
1026 node: node.raw.clone(),
1027 path: OnceCell::new(),
1028 }
1029 }
1030
1031 fn make_doc(&self, key: &str, raw: Value) -> usize {
1032 let mut state = self.state.borrow_mut();
1033 let doc = state.docs.len();
1034 let top = state.nodes.len();
1035 state
1036 .nodes
1037 .push(PNode::new(doc, None, Seg::Name(String::new()), raw.clone()));
1038 state.docs.push(Doc {
1039 key: Rc::from(key),
1040 root: raw,
1041 top,
1042 });
1043 state.doc_keys.insert(key.to_string(), Some(doc));
1044 doc
1045 }
1046
1047 fn doc_key(&self, pn: usize) -> Rc<str> {
1048 let state = self.state.borrow();
1049 state.docs[state.nodes[pn].doc].key.clone()
1050 }
1051
1052 fn doc_of(&self, from: usize, key: Option<&str>) -> Result<Option<usize>, FoldError> {
1054 let own = self.state.borrow().nodes[from].doc;
1055 let Some(key) = key else {
1056 return Ok(Some(own));
1057 };
1058 if *self.doc_key(from) == *key {
1059 return Ok(Some(own));
1060 }
1061 let known = self.state.borrow().doc_keys.get(key).copied();
1062 if let Some(known) = known {
1063 return Ok(known);
1064 }
1065 let raw = match &self.options.load {
1066 Some(load) => {
1067 self.guard()?;
1068 load(key, &self.site(from, None)).map_err(|error| self.callback_error(&error))?
1069 }
1070 None => None,
1071 };
1072 let doc = match raw {
1073 Some(raw) if !raw.is_undefined() => Some(self.make_doc(key, raw)),
1074 _ => None,
1075 };
1076 self.state
1077 .borrow_mut()
1078 .doc_keys
1079 .insert(key.to_string(), doc);
1080 Ok(doc)
1081 }
1082
1083 fn kid_named(&self, pn: usize, name: &str, raw: Value) -> usize {
1084 let mut state = self.state.borrow_mut();
1085 let found = match state.nodes[pn].kids.as_deref() {
1086 Some(Kids::Names(names)) => names.get(name).copied(),
1087 _ => None,
1088 };
1089 if let Some(found) = found {
1090 return found;
1091 }
1092 let id = state.nodes.len();
1093 let doc = state.nodes[pn].doc;
1094 state
1095 .nodes
1096 .push(PNode::new(doc, Some(pn), Seg::Name(name.to_string()), raw));
1097 let kids = state.nodes[pn]
1098 .kids
1099 .get_or_insert_with(|| Box::new(Kids::Names(HashMap::new())));
1100 if let Kids::Names(names) = &mut **kids {
1101 names.insert(name.to_string(), id);
1102 }
1103 id
1104 }
1105
1106 fn kid_indexed(&self, pn: usize, index: usize, raw: Value) -> usize {
1107 let mut state = self.state.borrow_mut();
1108 let found = match state.nodes[pn].kids.as_deref() {
1109 Some(Kids::Indices(indices)) => indices.get(&index).copied(),
1110 _ => None,
1111 };
1112 if let Some(found) = found {
1113 return found;
1114 }
1115 let id = state.nodes.len();
1116 let doc = state.nodes[pn].doc;
1117 state
1118 .nodes
1119 .push(PNode::new(doc, Some(pn), Seg::Index(index), raw));
1120 let kids = state.nodes[pn]
1121 .kids
1122 .get_or_insert_with(|| Box::new(Kids::Indices(HashMap::new())));
1123 if let Kids::Indices(indices) = &mut **kids {
1124 indices.insert(index, id);
1125 }
1126 id
1127 }
1128
1129 fn kid_of(&self, pn: usize, raw: &Value, member: Member, child: Value) -> usize {
1130 match member {
1131 Member::Index(index) => self.kid_indexed(pn, index, child),
1132 Member::Name(at) => self.kid_named(pn, member_name(raw, at), child),
1133 }
1134 }
1135
1136 fn ptr_of(&self, pn: usize) -> Rc<str> {
1139 let mut state = self.state.borrow_mut();
1140 let state = &mut *state;
1141 if let Some(done) = &state.nodes[pn].ptr {
1142 return done.clone();
1143 }
1144 let mut chain = Vec::new();
1145 let mut cursor = Some(pn);
1146 while let Some(at) = cursor {
1147 if state.nodes[at].ptr.is_some() {
1148 break;
1149 }
1150 chain.push(at);
1151 cursor = state.nodes[at].parent;
1152 }
1153 let mut text = cursor
1154 .and_then(|at| state.nodes[at].ptr.as_deref().map(str::to_string))
1155 .unwrap_or_default();
1156 for &at in chain.iter().rev() {
1157 let node = &mut state.nodes[at];
1158 if node.parent.is_none() {
1159 text.clear();
1160 } else {
1161 text.push('/');
1162 escape_segment(&mut text, &node.seg.text());
1163 }
1164 node.ptr = Some(Rc::from(text.as_str()));
1165 }
1166 state.nodes[pn].ptr.clone().unwrap_or_else(|| Rc::from(""))
1167 }
1168
1169 fn path_of(&self, pn: usize) -> Path {
1170 let state = self.state.borrow();
1171 let mut path = Vec::new();
1172 let mut cursor = Some(pn);
1173 while let Some(at) = cursor {
1174 let node = &state.nodes[at];
1175 if node.parent.is_none() {
1176 break;
1177 }
1178 path.push(node.seg.clone());
1179 cursor = node.parent;
1180 }
1181 path.reverse();
1182 path
1183 }
1184
1185 fn note(&self, list: u8, row: FoldEntry) {
1186 let mut state = self.state.borrow_mut();
1187 let key = (
1188 list,
1189 row.doc.clone(),
1190 row.at.clone(),
1191 row.target_doc.clone(),
1192 row.target.clone(),
1193 );
1194 if state.noted.insert(key) {
1195 if CYCLES == list {
1196 state.report.cycles.push(row);
1197 } else {
1198 state.report.unresolved.push(row);
1199 }
1200 }
1201 }
1202
1203 fn note_dynamic(&self, pn: usize, src: &str) {
1204 let row = FoldDynamic {
1205 doc: self.doc_key(pn).to_string(),
1206 at: self.ptr_of(pn).to_string(),
1207 src: src.to_string(),
1208 };
1209 let mut state = self.state.borrow_mut();
1210 let key = (
1211 DYNAMIC,
1212 row.doc.clone(),
1213 row.at.clone(),
1214 row.src.clone(),
1215 String::new(),
1216 );
1217 if state.noted.insert(key) {
1218 state.report.dynamic.push(row);
1219 }
1220 }
1221
1222 fn raise(&self, error: FoldError) -> FoldError {
1224 self.state.borrow_mut().failure = Some(error.clone());
1225 error
1226 }
1227
1228 fn callback_error(&self, error: &TabnasError) -> FoldError {
1232 let own = self.state.borrow().failure.clone();
1233 match own {
1234 Some(own) if own.code() == error.code && own.message() == error.detail => own,
1235 _ => FoldError::callback(error.clone()),
1236 }
1237 }
1238
1239 fn guard(&self) -> Result<(), FoldError> {
1242 if stack_here().abs_diff(self.stack_base) <= self.options.max_stack {
1243 return Ok(());
1244 }
1245 let error = FoldError::new(
1246 FOLD_DEPTH,
1247 format_args!(
1248 "the stack ran out before max_depth ({}) was reached; lower max_depth",
1249 self.options.max_depth
1250 ),
1251 )
1252 .located(&self.main, None);
1253 Err(self.raise(error))
1254 }
1255
1256 fn k_of(&self, pn: usize) -> Result<Value, FoldError> {
1260 let Some(inherit) = &self.options.inherit else {
1261 return Ok(self.options.k.clone());
1262 };
1263 self.guard()?;
1264 let (chain, mut bag) = {
1265 let state = self.state.borrow();
1266 if let Some(bag) = &state.nodes[pn].k {
1267 return Ok(bag.clone());
1268 }
1269 let mut chain = Vec::new();
1270 let mut cursor = Some(pn);
1271 let mut busy = None;
1272 while let Some(at) = cursor {
1273 let node = &state.nodes[at];
1274 if node.k.is_some() {
1275 break;
1276 }
1277 if node.k_busy {
1278 busy = Some(at);
1279 break;
1280 }
1281 chain.push(at);
1282 cursor = node.parent;
1283 }
1284 match busy {
1285 Some(at) => (Err(at), Value::Undefined),
1286 None => (
1287 Ok(chain),
1288 cursor
1289 .and_then(|at| state.nodes[at].k.clone())
1290 .unwrap_or_else(|| self.options.k.clone()),
1291 ),
1292 }
1293 };
1294 let chain = match chain {
1295 Ok(chain) => chain,
1296 Err(at) => return Err(self.inherit_error("inherit folded its own subtree at", at)),
1297 };
1298 for &at in chain.iter().rev() {
1299 let raw = self.state.borrow().nodes[at].raw.clone();
1300 if is_record(&raw) {
1301 self.state.borrow_mut().nodes[at].k_busy = true;
1302 let next = inherit(&self.site(at, Some(bag.clone())), &raw, &bag);
1303 self.state.borrow_mut().nodes[at].k_busy = false;
1304 let next = next.map_err(|error| self.callback_error(&error))?;
1305 if !is_container(&next) {
1308 return Err(self.inherit_error("inherit returned no bag at", at));
1309 }
1310 bag = next;
1311 }
1312 self.state.borrow_mut().nodes[at].k = Some(bag.clone());
1313 }
1314 Ok(bag)
1315 }
1316
1317 fn inherit_error(&self, what: &str, at: usize) -> FoldError {
1318 let pointer = self.ptr_of(at);
1319 let doc = self.doc_key(at);
1320 let error = FoldError::new(FOLD_INHERIT, format_args!("{what} {}", shown(&pointer)))
1321 .located(&doc, Some(&pointer));
1322 self.raise(error)
1323 }
1324
1325 fn site_op_of(&self, pn: usize) -> Result<Option<Arc<Op>>, FoldError> {
1328 let raw = {
1329 let state = self.state.borrow();
1330 let node = &state.nodes[pn];
1331 if let Some(decided) = &node.site {
1332 return Ok(decided.clone());
1333 }
1334 node.raw.clone()
1335 };
1336 let op = key_op_of(&self.keys, &raw);
1337 self.state.borrow_mut().nodes[pn].site = Some(op.clone());
1338 if let (Some(found), Some(recognise)) = (&op, &self.options.recognise) {
1339 let yes = recognise(&self.site(pn, None), found)
1340 .map_err(|error| self.callback_error(&error))?;
1341 if !yes {
1342 self.state.borrow_mut().nodes[pn].site = Some(None);
1343 return Ok(None);
1344 }
1345 }
1346 Ok(op)
1347 }
1348
1349 fn miss(&self, from: usize, key: Option<&str>, target: &[Seg]) -> FoldHit {
1350 let doc = self.doc_key(from);
1351 let row = FoldEntry {
1352 doc: doc.to_string(),
1353 at: self.ptr_of(from).to_string(),
1354 target_doc: key.unwrap_or(&doc).to_string(),
1355 target: pointer(target),
1356 };
1357 self.note(UNRESOLVED, row);
1358 FoldHit::missing()
1359 }
1360
1361 fn cycle_to(&self, from: usize, target: usize) -> Result<FoldHit, FoldError> {
1369 let row = FoldEntry {
1370 doc: self.doc_key(from).to_string(),
1371 at: self.ptr_of(from).to_string(),
1372 target_doc: self.doc_key(target).to_string(),
1373 target: self.ptr_of(target).to_string(),
1374 };
1375 if FoldCycle::Error == self.options.cycle {
1376 let error = FoldError::new(
1377 FOLD_CYCLE,
1378 format_args!("cycle at {} to {}", shown(&row.at), shown(&row.target)),
1379 )
1380 .located(&row.doc, Some(&row.at))
1381 .targeted(&row.target_doc, &row.target);
1382 return Err(self.raise(error));
1383 }
1384 self.note(CYCLES, row);
1385 let mut state = self.state.borrow_mut();
1386 let state = &mut *state;
1387 state.nodes[from].cut = true;
1388 if ACTIVE == state.nodes[target].state {
1389 if let Some(start) = state.stack.iter().rposition(|&entry| entry == target) {
1390 let refs = state.stack[start + 1..]
1391 .iter()
1392 .all(|&entry| FROM_REFERENCE == state.nodes[entry].via);
1393 if refs {
1394 for &entry in &state.stack[start..] {
1395 state.nodes[entry].looped = true;
1396 }
1397 state.nodes[from].looped = true;
1398 }
1399 }
1400 } else if state.nodes[target].looped {
1401 state.nodes[from].looped = true;
1402 }
1403 Ok(FoldHit::cycle())
1404 }
1405
1406 fn state_of(&self, pn: usize) -> (u8, bool, bool) {
1407 let state = self.state.borrow();
1408 let node = &state.nodes[pn];
1409 (node.state, node.looped, node.cut)
1410 }
1411
1412 fn at(&self, from: usize, target: &[Seg], key: Option<&str>) -> Result<FoldHit, FoldError> {
1423 self.guard()?;
1424 match self.find(from, target, key)? {
1425 Found::Hit(hit) => Ok(hit),
1426 Found::Through(pn, next) => self.through(from, pn, target, next, key),
1427 Found::End(pn) => self.reach(from, pn),
1428 }
1429 }
1430
1431 fn through(
1434 &self,
1435 from: usize,
1436 pn: usize,
1437 target: &[Seg],
1438 next: usize,
1439 key: Option<&str>,
1440 ) -> Result<FoldHit, FoldError> {
1441 let (state, looped, _) = self.state_of(pn);
1442 if ACTIVE == state || looped {
1443 return self.cycle_to(from, pn);
1444 }
1445 match self.walk(pn, FROM_REFERENCE) {
1446 Ok(folded) => self.read_on(from, pn, folded, target, next, key),
1447 Err(error) => Err(error),
1448 }
1449 }
1450
1451 fn read_on(
1454 &self,
1455 from: usize,
1456 pn: usize,
1457 folded: Value,
1458 target: &[Seg],
1459 next: usize,
1460 key: Option<&str>,
1461 ) -> Result<FoldHit, FoldError> {
1462 let (_, looped, cut) = self.state_of(pn);
1463 if looped || cut {
1464 return self.cycle_to(from, pn);
1465 }
1466 Ok(match read_raw(folded, &target[next..]) {
1467 Some(value) => FoldHit::found(value),
1468 None => self.miss(from, key, target),
1469 })
1470 }
1471
1472 fn reach(&self, from: usize, pn: usize) -> Result<FoldHit, FoldError> {
1474 let (state, _, _) = self.state_of(pn);
1475 if ACTIVE == state {
1476 return self.cycle_to(from, pn);
1477 }
1478 match self.walk(pn, FROM_REFERENCE) {
1479 Ok(value) => self.reached(from, pn, value),
1480 Err(error) => Err(error),
1481 }
1482 }
1483
1484 fn reached(&self, from: usize, pn: usize, value: Value) -> Result<FoldHit, FoldError> {
1487 let (_, looped, _) = self.state_of(pn);
1488 if looped {
1489 return self.cycle_to(from, pn);
1490 }
1491 Ok(FoldHit::found(value))
1492 }
1493
1494 fn find(&self, from: usize, target: &[Seg], key: Option<&str>) -> Result<Found, FoldError> {
1498 let Some(doc) = self.doc_of(from, key)? else {
1499 return Ok(Found::Hit(self.miss(from, key, target)));
1500 };
1501 let (mut pn, mut node) = {
1502 let state = self.state.borrow();
1503 let doc = &state.docs[doc];
1504 (doc.top, doc.root.clone())
1505 };
1506 for (i, seg) in target.iter().enumerate() {
1507 let last = i + 1 == target.len();
1508 let Some(stepped) = step(&node, seg) else {
1509 return Ok(Found::Hit(self.miss(from, key, target)));
1510 };
1511 let (index, value) = match stepped {
1512 Step::Head(head) => {
1516 return Ok(Found::Hit(match read_raw(head, &target[i + 1..]) {
1517 Some(value) => FoldHit::found(value),
1518 None => self.miss(from, key, target),
1519 }));
1520 }
1521 Step::Member(value) => (None, value),
1522 Step::Item(index, value) => (Some(index), value),
1523 };
1524 if last && !is_container(&value) {
1525 return Ok(Found::Hit(FoldHit::found(value)));
1526 }
1527 pn = match index {
1528 Some(index) => self.kid_indexed(pn, index, value.clone()),
1529 None => self.kid_named(pn, &seg.text(), value.clone()),
1530 };
1531 node = value;
1532 if !last && is_record(&node) {
1536 if let Some(op) = self.site_op_of(pn)? {
1537 if !op.dynamic {
1538 return Ok(Found::Through(pn, i + 1));
1539 }
1540 }
1541 }
1542 }
1543 Ok(Found::End(pn))
1544 }
1545
1546 fn locate(
1547 &self,
1548 from: usize,
1549 target: &[Seg],
1550 key: Option<&str>,
1551 ) -> Result<Option<Value>, FoldError> {
1552 self.guard()?;
1553 let Some(doc) = self.doc_of(from, key)? else {
1554 return Ok(None);
1555 };
1556 let root = self.state.borrow().docs[doc].root.clone();
1557 Ok(read_raw(root, target))
1558 }
1559
1560 fn member(&self, pn: usize, name: &str, child: &Value) -> Result<Value, FoldError> {
1563 if is_container(child) {
1564 let kid = self.kid_named(pn, name, child.clone());
1565 self.walk(kid, FROM_PARENT)
1566 } else {
1567 Ok(child.clone())
1568 }
1569 }
1570
1571 fn plain_of(&self, pn: usize) -> Result<Value, FoldError> {
1573 self.guard()?;
1574 let (raw, parts) = {
1575 let state = self.state.borrow();
1576 let node = &state.nodes[pn];
1577 if let Some(plain) = &node.plain {
1578 return Ok(plain.clone());
1579 }
1580 let parts = node.parts.as_deref().map(|parts| {
1581 (
1582 parts.src.clone(),
1583 parts.value.clone(),
1584 parts.siblings.clone(),
1585 )
1586 });
1587 (node.raw.clone(), parts)
1588 };
1589 let Some(members) = map_entries(&raw) else {
1590 return self.walk(pn, FROM_PARENT);
1591 };
1592 let mut out = IndexMap::with_capacity(members.len());
1593 for (name, member) in members {
1594 let value = match &parts {
1595 None => self.member(pn, name, member)?,
1596 Some((src, value, _)) if src == name => value.clone(),
1597 Some((_, _, siblings)) => map_entries(siblings)
1598 .and_then(|siblings| siblings.get(name))
1599 .cloned()
1600 .unwrap_or(Value::Undefined),
1601 };
1602 out.insert(name.clone(), value);
1603 }
1604 let out = rebuild_map(&raw, out);
1605 self.state.borrow_mut().nodes[pn].plain = Some(out.clone());
1606 Ok(out)
1607 }
1608
1609 fn depth_error(&self, pn: usize) -> FoldError {
1610 let pointer = self.ptr_of(pn);
1611 let doc = self.doc_key(pn);
1612 let error = FoldError::new(
1613 FOLD_DEPTH,
1614 format_args!(
1615 "nesting and references deeper than {} at {}",
1616 self.options.max_depth,
1617 shown(&pointer)
1618 ),
1619 )
1620 .located(&doc, Some(&pointer));
1621 self.raise(error)
1622 }
1623
1624 fn walk(&self, pn: usize, via: u8) -> Result<Value, FoldError> {
1631 self.guard()?;
1632 let mut frames = Vec::new();
1633 if let Some(value) = self.enter(pn, via, &mut frames)? {
1634 return Ok(value);
1635 }
1636 loop {
1637 if let Err(error) = self.descend(&mut frames) {
1638 self.unwind(&frames);
1639 return Err(error);
1640 }
1641 let finished = match frames.last_mut() {
1642 Some(top) => self.finish(top),
1643 None => return Ok(Value::Undefined),
1644 };
1645 frames.truncate(frames.len() - 1);
1647 match finished {
1648 Ok(value) => match frames.last_mut() {
1649 Some(parent) => parent.accept(value),
1650 None => return Ok(value),
1651 },
1652 Err(error) => {
1653 self.unwind(&frames);
1654 return Err(error);
1655 }
1656 }
1657 }
1658 }
1659
1660 fn descend(&self, frames: &mut Vec<Frame>) -> Result<(), FoldError> {
1665 loop {
1666 let Some(top) = frames.last_mut() else {
1667 return Ok(());
1668 };
1669 let Some((member, child)) = top.take() else {
1670 return Ok(());
1671 };
1672 if !is_container(&child) {
1673 top.accept(child);
1674 continue;
1675 }
1676 let kid = self.kid_of(top.pn, &top.raw, member, child);
1677 if let Some(value) = self.enter(kid, FROM_PARENT, frames)? {
1678 if let Some(top) = frames.last_mut() {
1679 top.accept(value);
1680 }
1681 }
1682 }
1683 }
1684
1685 fn enter(
1689 &self,
1690 pn: usize,
1691 via: u8,
1692 frames: &mut Vec<Frame>,
1693 ) -> Result<Option<Value>, FoldError> {
1694 let raw = {
1695 let state = self.state.borrow();
1696 let node = &state.nodes[pn];
1697 if DONE == node.state {
1698 return Ok(Some(node.value.clone()));
1699 }
1700 if ACTIVE == node.state || !is_container(&node.raw) {
1701 return Ok(Some(node.raw.clone()));
1702 }
1703 node.raw.clone()
1704 };
1705 {
1706 let mut state = self.state.borrow_mut();
1707 if self.options.max_depth <= state.stack.len() {
1708 drop(state);
1709 return Err(self.depth_error(pn));
1710 }
1711 state.nodes[pn].state = ACTIVE;
1712 state.nodes[pn].via = via;
1713 state.stack.push(pn);
1714 }
1715 let kind = if is_record(&raw) {
1716 let op = match self.site_op_of(pn) {
1717 Ok(op) => op,
1718 Err(error) => {
1719 self.leave(pn, None);
1720 return Err(error);
1721 }
1722 };
1723 match op {
1724 Some(op) if !op.dynamic => Kind::Site {
1725 op,
1726 value: Value::Undefined,
1727 siblings: IndexMap::new(),
1728 },
1729 op => {
1730 if let Some(op) = op {
1731 self.note_dynamic(pn, &op.src);
1732 }
1733 let plain = self.state.borrow().nodes[pn].plain.clone();
1734 if let Some(plain) = plain {
1735 self.leave(pn, Some(plain.clone()));
1736 return Ok(Some(plain));
1737 }
1738 Kind::Plain {
1739 out: IndexMap::with_capacity(map_entries(&raw).map_or(0, IndexMap::len)),
1740 }
1741 }
1742 }
1743 } else if let Some(id) = node_id(&raw) {
1744 let (op, terms) = with_node(&raw, |entry| (entry.op.clone(), entry.terms.clone()))
1745 .unwrap_or_else(|| released_handle(id));
1746 Kind::Node {
1747 op,
1748 out: Vec::with_capacity(terms.len()),
1749 terms,
1750 }
1751 } else {
1752 Kind::List {
1753 out: Vec::with_capacity(list_items(&raw).len()),
1754 }
1755 };
1756 frames.push(Frame {
1757 pn,
1758 raw,
1759 next: 0,
1760 kind,
1761 });
1762 Ok(None)
1763 }
1764
1765 fn finish(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1773 let pn = frame.pn;
1774 let out = match frame.kind {
1775 Kind::Node { op: Some(_), .. } => self.reduce_node(frame),
1776 Kind::Site { .. } => self.reduce_site(frame),
1777 _ => Ok(self.rebuild(frame)),
1778 };
1779 self.leave(pn, out.as_ref().ok().cloned());
1780 out
1781 }
1782
1783 fn rebuild(&self, frame: &mut Frame) -> Value {
1786 let Frame { pn, raw, kind, .. } = frame;
1787 match kind {
1788 Kind::List { out } => rebuild_list(raw, std::mem::take(out)),
1789 Kind::Node { out, .. } => Value::array(std::mem::take(out)),
1790 Kind::Plain { out } => {
1791 let out = rebuild_map(raw, std::mem::take(out));
1792 self.state.borrow_mut().nodes[*pn].plain = Some(out.clone());
1793 out
1794 }
1795 Kind::Site { .. } => Value::Undefined,
1796 }
1797 }
1798
1799 fn reduce_node(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1803 let Frame { pn, raw, kind, .. } = frame;
1804 let Kind::Node {
1805 op: Some(op), out, ..
1806 } = kind
1807 else {
1808 return Ok(Value::Undefined);
1809 };
1810 let op = op.clone();
1811 let terms = std::mem::take(out);
1812 if self.options.tokens {
1813 self.call_evaluate(*pn, &op, &terms)
1814 } else {
1815 Ok(operator_node(raw, op, terms))
1816 }
1817 }
1818
1819 fn reduce_site(&self, frame: &mut Frame) -> Result<Value, FoldError> {
1822 let Frame { pn, raw, kind, .. } = frame;
1823 let Kind::Site {
1824 op,
1825 value,
1826 siblings,
1827 } = kind
1828 else {
1829 return Ok(Value::Undefined);
1830 };
1831 let op = op.clone();
1832 let terms = [
1833 std::mem::replace(value, Value::Undefined),
1834 rebuild_map(raw, std::mem::take(siblings)),
1835 ];
1836 self.keep_parts(*pn, &op, &terms);
1837 self.call_evaluate(*pn, &op, &terms)
1838 }
1839
1840 fn keep_parts(&self, pn: usize, op: &Op, terms: &[Value; 2]) {
1841 self.state.borrow_mut().nodes[pn].parts = Some(Box::new(Parts {
1842 src: op.src.clone(),
1843 value: terms[0].clone(),
1844 siblings: terms[1].clone(),
1845 }));
1846 }
1847
1848 fn call_evaluate(&self, pn: usize, op: &Op, terms: &[Value]) -> Result<Value, FoldError> {
1851 let site = self.site(pn, None);
1852 let result = (self.options.evaluate)(&site, op, terms);
1853 match &result {
1856 Ok(value) => Ok(value.clone()),
1857 Err(error) => Err(self.callback_error(error)),
1858 }
1859 }
1860
1861 fn leave(&self, pn: usize, out: Option<Value>) {
1864 let mut state = self.state.borrow_mut();
1865 let top = state.stack.pop();
1866 debug_assert_eq!(Some(pn), top, "the active stack unwinds in order");
1867 let node = &mut state.nodes[pn];
1868 match out {
1869 Some(value) => {
1870 node.state = DONE;
1871 node.value = value;
1872 }
1873 None => node.state = FREE,
1874 }
1875 }
1876
1877 fn unwind(&self, frames: &[Frame]) {
1879 for frame in frames.iter().rev() {
1880 self.leave(frame.pn, None);
1881 }
1882 }
1883}
1884
1885fn is_record(value: &Value) -> bool {
1891 matches!(value, Value::Object(_) | Value::MapRef(_))
1892}
1893
1894fn is_container(value: &Value) -> bool {
1897 matches!(
1898 value,
1899 Value::Object(_) | Value::MapRef(_) | Value::Array(_) | Value::ListRef(_)
1900 )
1901}
1902
1903fn map_entries(value: &Value) -> Option<&IndexMap<String, Value>> {
1904 match value {
1905 Value::Object(members) => Some(members),
1906 Value::MapRef(map) => Some(&map.value),
1907 _ => None,
1908 }
1909}
1910
1911fn list_items(value: &Value) -> &[Value] {
1912 match value {
1913 Value::Array(items) => items,
1914 Value::ListRef(list) => &list.value,
1915 _ => &[],
1916 }
1917}
1918
1919fn member_name(raw: &Value, at: usize) -> &str {
1920 map_entries(raw)
1921 .and_then(|members| members.get_index(at))
1922 .map_or("", |(name, _)| name.as_str())
1923}
1924
1925fn rebuild_map(like: &Value, members: IndexMap<String, Value>) -> Value {
1928 match like {
1929 Value::MapRef(map) => {
1930 let mut out = (**map).clone();
1931 out.value = members;
1932 Value::MapRef(Arc::new(out))
1933 }
1934 _ => Value::object(members),
1935 }
1936}
1937
1938fn rebuild_list(like: &Value, items: Vec<Value>) -> Value {
1940 match like {
1941 Value::ListRef(list) => {
1942 let mut out = (**list).clone();
1943 out.value = items;
1944 Value::ListRef(Arc::new(out))
1945 }
1946 _ => Value::array(items),
1947 }
1948}
1949
1950fn operator_node(raw: &Value, op: Arc<Op>, terms: Vec<Value>) -> Value {
1953 let token = with_node(raw, |entry| entry.token.clone()).flatten();
1954 new_node(Some(op), token, terms)
1955}
1956
1957enum Step {
1959 Member(Value),
1961 Item(usize, Value),
1963 Head(Value),
1965}
1966
1967fn step(node: &Value, seg: &Seg) -> Option<Step> {
1970 match node {
1971 Value::Object(members) => members.get(seg.text().as_ref()).cloned().map(Step::Member),
1972 Value::MapRef(map) => map
1973 .value
1974 .get(seg.text().as_ref())
1975 .cloned()
1976 .map(Step::Member),
1977 Value::Array(items) => {
1978 array_index(seg, items.len()).map(|index| Step::Item(index, items[index].clone()))
1979 }
1980 Value::ListRef(list) => match node_id(node) {
1981 None => array_index(seg, list.value.len())
1982 .map(|index| Step::Item(index, list.value[index].clone())),
1983 Some(id) => with_node(node, |entry| {
1986 let head = usize::from(entry.op.is_some());
1987 let index = array_index(seg, entry.terms.len() + head)?;
1988 match (index, &entry.op) {
1989 (0, Some(op)) => Some(Step::Head(op.to_value(entry.token.as_ref()))),
1990 _ => Some(Step::Item(index, entry.terms[index - head].clone())),
1991 }
1992 })
1993 .unwrap_or_else(|| released_handle(id)),
1994 },
1995 _ => None,
1996 }
1997}
1998
1999fn read_raw(mut node: Value, path: &[Seg]) -> Option<Value> {
2001 for seg in path {
2002 node = match step(&node, seg)? {
2003 Step::Member(value) | Step::Item(_, value) | Step::Head(value) => value,
2004 };
2005 }
2006 Some(node)
2007}
2008
2009fn array_index(seg: &Seg, length: usize) -> Option<usize> {
2013 let index = match seg {
2014 Seg::Index(index) => *index,
2015 Seg::Name(text) => {
2016 let canonical = "0" == text
2017 || (!text.is_empty()
2018 && !text.starts_with('0')
2019 && text.bytes().all(|byte| byte.is_ascii_digit()));
2020 if !canonical {
2021 return None;
2022 }
2023 text.parse::<usize>().ok()?
2024 }
2025 };
2026 (index < length).then_some(index)
2027}
2028
2029fn pointer(path: &[Seg]) -> String {
2031 let mut out = String::new();
2032 for seg in path {
2033 out.push('/');
2034 escape_segment(&mut out, &seg.text());
2035 }
2036 out
2037}
2038
2039fn escape_segment(out: &mut String, text: &str) {
2040 for c in text.chars() {
2041 match c {
2042 '~' => out.push_str("~0"),
2043 '/' => out.push_str("~1"),
2044 c => out.push(c),
2045 }
2046 }
2047}
2048
2049fn shown(text: &str) -> String {
2054 let mut quoted = String::with_capacity(text.len() + 2);
2055 quoted.push('"');
2056 for c in text.chars() {
2057 match c {
2058 '"' => quoted.push_str("\\\""),
2059 '\\' => quoted.push_str("\\\\"),
2060 '\n' => quoted.push_str("\\n"),
2061 '\r' => quoted.push_str("\\r"),
2062 '\t' => quoted.push_str("\\t"),
2063 '\u{8}' => quoted.push_str("\\b"),
2064 '\u{c}' => quoted.push_str("\\f"),
2065 c if (c as u32) < 0x20 => quoted.push_str(&format!("\\u{:04x}", c as u32)),
2066 c => quoted.push(c),
2067 }
2068 }
2069 quoted.push('"');
2070 if quoted.encode_utf16().count() <= 80 {
2071 return quoted;
2072 }
2073 let mut out = String::new();
2074 let mut units = 0;
2075 for c in quoted.chars() {
2076 units += c.len_utf16();
2077 if 76 < units {
2078 break;
2079 }
2080 out.push(c);
2081 }
2082 out.push_str("...\"");
2083 out
2084}