1#![allow(clippy::result_large_err)]
61
62use std::collections::BTreeMap;
63use std::fmt;
64use std::sync::{Arc, Mutex};
65use std::time::{SystemTime, UNIX_EPOCH};
66
67use indexmap::IndexMap;
68use serde_json::json;
69
70use tabnas::{
71 ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, Tabnas,
72 TabnasError, Token, Value,
73};
74use tabnas_directive::{set_node, DirectiveOptions, RuleMod, RulesOption};
75
76mod preload;
77mod processor;
78mod resolver;
79mod vfs;
80
81pub use preload::{preload_files, preload_files_with, PreloadOptions};
82pub use processor::{default_processor, jsonic_processor, parse_nested, Processor, ProcessorInput};
83pub use resolver::{FileResolver, MapResolver, PkgResolver};
84pub use vfs::{os_fs, DirEntry, MapFs, OsFs, SharedFs, SourceFs};
85
86pub const VERSION: &str = "0.6.0";
92
93pub const NONE: &str = "";
95
96pub const TOP: &str = "\0TOP";
103
104pub const PLUGIN_NAME: &str = "MultiSource";
106
107pub const RULE_NAME: &str = "multisource";
109
110pub const DEFAULT_MARKCHAR: &str = "@";
112
113pub const DEFAULT_MAX_DEPTH: usize = 64;
121
122#[derive(Clone, Debug, Default, PartialEq, Eq)]
128pub struct PathSpec {
129 pub kind: String,
131 pub path: Option<String>,
133 pub full: Option<String>,
135 pub base: String,
137 pub abs: bool,
139}
140
141#[derive(Clone, Debug)]
143pub struct Resolution {
144 pub spec: PathSpec,
147 pub src: Option<String>,
149 pub val: Value,
151 pub found: bool,
153 pub search: Vec<String>,
155 pub err: Option<Box<TabnasError>>,
160}
161
162impl Default for Resolution {
163 fn default() -> Self {
164 Resolution::not_found(PathSpec::default())
165 }
166}
167
168impl Resolution {
169 pub fn not_found(spec: PathSpec) -> Self {
171 Resolution {
172 spec,
173 src: None,
174 val: Value::Undefined,
175 found: false,
176 search: Vec::new(),
177 err: None,
178 }
179 }
180
181 pub fn found(mut spec: PathSpec, full: impl Into<String>, src: impl Into<String>) -> Self {
183 let full = full.into();
184 spec.kind = ext_kind(Some(&full));
185 spec.full = Some(full);
186 Resolution {
187 spec,
188 src: Some(src.into()),
189 val: Value::Undefined,
190 found: true,
191 search: Vec::new(),
192 err: None,
193 }
194 }
195
196 pub fn with_search(mut self, search: Vec<String>) -> Self {
198 self.search = search;
199 self
200 }
201
202 pub fn full_path(&self) -> String {
206 self.spec
207 .full
208 .clone()
209 .or_else(|| self.spec.path.clone())
210 .unwrap_or_else(|| "no-path".to_string())
211 }
212}
213
214#[derive(Clone, Copy)]
221pub struct ResolverInput<'a> {
222 pub options: &'a MultiSourceOptions,
224 pub meta: &'a Value,
227}
228
229impl fmt::Debug for ResolverInput<'_> {
230 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231 formatter
232 .debug_struct("ResolverInput")
233 .field("meta", self.meta)
234 .finish_non_exhaustive()
235 }
236}
237
238impl ResolverInput<'_> {
239 pub fn source_path(&self) -> Option<String> {
242 meta_multisource_string(self.meta, "path")
243 }
244}
245
246pub trait Resolver: Send + Sync {
253 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution;
257}
258
259impl<F> Resolver for F
260where
261 F: Fn(Option<&str>, &ResolverInput<'_>) -> Resolution + Send + Sync,
262{
263 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
264 self(reference, input)
265 }
266}
267
268pub type SharedResolver = Arc<dyn Resolver>;
270
271#[derive(Clone, Debug, PartialEq, Eq)]
277pub struct Dependency {
278 pub tar: String,
280 pub src: String,
282 pub wen: u64,
284}
285
286pub type DependencyMap = BTreeMap<String, BTreeMap<String, Dependency>>;
294
295#[derive(Clone)]
301pub enum ProcessorEntry {
302 Call(Arc<dyn Processor>),
304 Alias(String),
308}
309
310impl fmt::Debug for ProcessorEntry {
311 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312 match self {
313 Self::Call(_) => formatter.write_str("ProcessorEntry::Call(<function>)"),
314 Self::Alias(kind) => write!(formatter, "ProcessorEntry::Alias({kind:?})"),
315 }
316 }
317}
318
319#[derive(Clone)]
321pub struct MultiSourceOptions {
322 pub resolver: SharedResolver,
324 pub path: String,
326 pub markchar: String,
328 pub processor: IndexMap<String, ProcessorEntry>,
330 pub implicit_ext: Vec<String>,
332 pub preload: Option<PreloadOptions>,
336 pub fs: Option<SharedFs>,
342 pub deps: Option<Arc<Mutex<DependencyMap>>>,
345 pub max_depth: usize,
347}
348
349impl fmt::Debug for MultiSourceOptions {
350 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
351 formatter
352 .debug_struct("MultiSourceOptions")
353 .field("path", &self.path)
354 .field("markchar", &self.markchar)
355 .field("processor", &self.processor)
356 .field("implicit_ext", &self.implicit_ext)
357 .field("preload", &self.preload)
358 .field("fs", &self.fs.as_ref().map(|_| "<SourceFs>"))
359 .field("deps", &self.deps.as_ref().map(|_| "<DependencyMap>"))
360 .field("max_depth", &self.max_depth)
361 .finish_non_exhaustive()
362 }
363}
364
365impl Default for MultiSourceOptions {
366 fn default() -> Self {
367 Self::new(MapResolver::new())
368 }
369}
370
371impl MultiSourceOptions {
372 pub fn new(resolver: impl Resolver + 'static) -> Self {
374 MultiSourceOptions {
375 resolver: Arc::new(resolver),
376 path: String::new(),
377 markchar: DEFAULT_MARKCHAR.to_string(),
378 processor: default_processors(),
379 implicit_ext: default_implicit_ext(),
380 preload: None,
381 fs: None,
382 deps: None,
383 max_depth: DEFAULT_MAX_DEPTH,
384 }
385 }
386
387 pub fn with_resolver(mut self, resolver: SharedResolver) -> Self {
389 self.resolver = resolver;
390 self
391 }
392
393 pub fn with_path(mut self, path: impl Into<String>) -> Self {
395 self.path = path.into();
396 self
397 }
398
399 pub fn with_markchar(mut self, markchar: impl Into<String>) -> Self {
401 self.markchar = markchar.into();
402 self
403 }
404
405 pub fn with_processor(
407 mut self,
408 kind: impl Into<String>,
409 processor: impl Processor + 'static,
410 ) -> Self {
411 self.processor
412 .insert(kind.into(), ProcessorEntry::Call(Arc::new(processor)));
413 self
414 }
415
416 pub fn with_processor_alias(
418 mut self,
419 kind: impl Into<String>,
420 target: impl Into<String>,
421 ) -> Self {
422 self.processor
423 .insert(kind.into(), ProcessorEntry::Alias(target.into()));
424 self
425 }
426
427 pub fn with_processors(mut self, processors: IndexMap<String, ProcessorEntry>) -> Self {
429 self.processor = processors;
430 self
431 }
432
433 pub fn with_implicit_ext<I, S>(mut self, extensions: I) -> Self
436 where
437 I: IntoIterator<Item = S>,
438 S: AsRef<str>,
439 {
440 self.implicit_ext = extensions
441 .into_iter()
442 .map(|ext| dotted(ext.as_ref()))
443 .collect();
444 self
445 }
446
447 pub fn with_preload(mut self, preload: PreloadOptions) -> Self {
449 self.preload = Some(preload);
450 self
451 }
452
453 pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
455 self.fs = Some(Arc::new(filesystem));
456 self
457 }
458
459 pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
461 self.fs = Some(filesystem);
462 self
463 }
464
465 pub fn with_deps(mut self, deps: Arc<Mutex<DependencyMap>>) -> Self {
467 self.deps = Some(deps);
468 self
469 }
470
471 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
473 self.max_depth = max_depth;
474 self
475 }
476
477 pub fn processor_for(&self, kind: &str) -> Option<Arc<dyn Processor>> {
480 let fallback = match self.processor.get(NONE) {
481 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
482 _ => None,
483 };
484 match self.processor.get(kind) {
485 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
486 Some(ProcessorEntry::Alias(target)) => match self.processor.get(target.as_str()) {
487 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
488 _ => fallback,
492 },
493 None => fallback,
494 }
495 }
496}
497
498pub fn default_processors() -> IndexMap<String, ProcessorEntry> {
506 let mut processors = IndexMap::new();
507 processors.insert(
508 NONE.to_string(),
509 ProcessorEntry::Call(Arc::new(default_processor)),
510 );
511 processors.insert(
512 "jsonic".to_string(),
513 ProcessorEntry::Call(Arc::new(jsonic_processor)),
514 );
515 processors.insert(
516 "jsc".to_string(),
517 ProcessorEntry::Alias("jsonic".to_string()),
518 );
519 processors
520}
521
522pub fn default_implicit_ext() -> Vec<String> {
533 vec![
534 ".jsonic".to_string(),
535 ".jsc".to_string(),
536 ".json".to_string(),
537 ]
538}
539
540fn dotted(ext: &str) -> String {
541 if ext.starts_with('.') {
542 ext.to_string()
543 } else {
544 format!(".{ext}")
545 }
546}
547
548pub fn ext_kind(full: Option<&str>) -> String {
560 let Some(full) = full else {
561 return NONE.to_string();
562 };
563 let segment = match full.rfind(['/', '\\']) {
564 Some(index) => &full[index + 1..],
565 None => full,
566 };
567 match segment.rfind('.') {
568 Some(index) => segment[index + 1..].to_string(),
569 None => NONE.to_string(),
570 }
571}
572
573pub fn resolve_path_spec(reference: Option<&str>, base: &str) -> PathSpec {
578 let path = reference.map(str::to_string);
579 let abs = path
580 .as_deref()
581 .map(|path| path.starts_with('/') || path.starts_with('\\'))
582 .unwrap_or(false);
583 let full = match path.as_deref() {
584 Some(path) if abs => Some(path.to_string()),
585 Some(path) if !path.is_empty() => Some(if base.is_empty() {
586 path.to_string()
587 } else {
588 format!("{base}/{path}")
589 }),
590 _ => None,
591 };
592 PathSpec {
593 kind: ext_kind(full.as_deref()),
594 path,
595 full,
596 base: base.to_string(),
597 abs,
598 }
599}
600
601pub fn build_potentials(full: &str, implicit_ext: &[String]) -> Vec<String> {
608 if full.is_empty() {
609 return Vec::new();
610 }
611 let mut potentials = vec![full.to_string()];
612 let segment = match full.rfind(['/', '\\']) {
613 Some(index) => &full[index + 1..],
614 None => full,
615 };
616 if segment.contains('.') {
617 return potentials;
618 }
619 for ext in implicit_ext {
620 potentials.push(format!("{full}{ext}"));
621 }
622 for ext in implicit_ext {
623 potentials.push(format!("{full}/index{ext}"));
624 }
625 if !segment.is_empty() && segment != "." {
626 for ext in implicit_ext {
627 potentials.push(format!("{full}/index.{segment}{ext}"));
628 }
629 }
630 potentials
631}
632
633pub fn source_dir(path: &str) -> String {
640 let trimmed = path.trim_end_matches(['/', '\\']);
641 match trimmed.rfind(['/', '\\']) {
642 None => String::new(),
643 Some(0) => trimmed[..1].to_string(),
644 Some(index) => trimmed[..index].to_string(),
645 }
646}
647
648fn meta_object(meta: &Value) -> Option<&IndexMap<String, Value>> {
653 match meta {
654 Value::Object(map) => Some(map),
655 Value::MapRef(map) => Some(&map.value),
656 _ => None,
657 }
658}
659
660fn meta_get<'a>(meta: &'a Value, key: &str) -> Option<&'a Value> {
661 meta_object(meta).and_then(|map| map.get(key))
662}
663
664fn meta_multisource_string(meta: &Value, key: &str) -> Option<String> {
665 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, key)) {
666 Some(Value::String(text)) => Some(text.clone()),
667 Some(Value::Text(text)) => Some(text.string.clone()),
668 _ => None,
669 }
670}
671
672fn is_nested_meta(meta: &Value) -> bool {
675 matches!(
676 meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, NESTED_MARK)),
677 Some(Value::Bool(true))
678 )
679}
680
681fn meta_parents(meta: &Value) -> Vec<String> {
682 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, "parents")) {
683 Some(Value::Array(items)) => items
684 .iter()
685 .filter_map(|item| match item {
686 Value::String(text) => Some(text.clone()),
687 Value::Text(text) => Some(text.string.clone()),
688 _ => None,
689 })
690 .collect(),
691 _ => Vec::new(),
692 }
693}
694
695const NESTED_MARK: &str = "nested";
702
703fn child_meta(
708 parent: &Value,
709 resolution: &Resolution,
710 parents: &[String],
711 dive: Option<&Value>,
712 ticket: &str,
713) -> Value {
714 let mut child = meta_object(parent).cloned().unwrap_or_default();
715
716 let previous = meta_get(parent, RULE_NAME)
717 .and_then(meta_object)
718 .cloned()
719 .unwrap_or_default();
720 let mut entry = previous;
721 entry.insert(
722 "parents".to_string(),
723 Value::array(parents.iter().cloned().map(Value::String).collect()),
724 );
725 entry.insert(
726 "path".to_string(),
727 match &resolution.spec.full {
728 Some(full) => Value::String(full.clone()),
729 None => Value::Undefined,
730 },
731 );
732 entry.insert(NESTED_MARK.to_string(), Value::Bool(true));
733 entry.insert(REPORT_TICKET.to_string(), Value::String(ticket.to_string()));
736 child.insert(RULE_NAME.to_string(), Value::object(entry));
737
738 if let Some(path) = &resolution.spec.path {
739 child.insert("fileName".to_string(), Value::String(path.clone()));
740 }
741
742 if let Some(Value::Array(segments)) = dive {
746 let mut path = IndexMap::new();
747 path.insert("base".to_string(), Value::array(segments.as_ref().clone()));
748 child.insert("path".to_string(), Value::object(path));
749 }
750
751 Value::object(child)
752}
753
754#[derive(Default)]
769struct NestedParser {
770 current: Mutex<Option<Arc<Tabnas>>>,
771}
772
773impl NestedParser {
774 fn publish(&self, parser: &Tabnas) {
775 if let Ok(mut slot) = self.current.lock() {
776 *slot = Some(Arc::new(parser.clone()));
777 }
778 }
779
780 fn get(&self) -> Option<Arc<Tabnas>> {
781 self.current.lock().ok().and_then(|slot| slot.clone())
782 }
783}
784
785type Report = (String, Vec<(String, Value)>);
788
789#[derive(Default)]
812struct LastReport {
813 slots: Mutex<BTreeMap<String, Report>>,
814 next: std::sync::atomic::AtomicU64,
815}
816
817impl LastReport {
818 fn ticket(&self) -> String {
820 let count = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
821 format!("{count}")
822 }
823
824 fn record(&self, ticket: &str, code: &str, details: &[(String, Value)]) {
825 if let Ok(mut slots) = self.slots.lock() {
826 slots.insert(ticket.to_string(), (code.to_string(), details.to_vec()));
827 }
828 }
829
830 fn take(&self, ticket: &str, code: &str) -> Option<Vec<(String, Value)>> {
833 let mut slots = self.slots.lock().ok()?;
834 match slots.remove(ticket) {
835 Some((recorded, details)) if recorded == code => Some(details),
836 _ => None,
837 }
838 }
839
840 fn discard(&self, ticket: &str) {
843 if let Ok(mut slots) = self.slots.lock() {
844 slots.remove(ticket);
845 }
846 }
847}
848
849const REPORT_TICKET: &str = "report";
853
854pub fn plugin_with(options: MultiSourceOptions) -> Plugin {
866 let options = Arc::new(normalize(options));
867 Plugin::new(PLUGIN_NAME, move |parser, _plugin_options| {
868 install(parser, Arc::clone(&options)).map_err(PluginError::from)
869 })
870}
871
872pub fn plugin() -> Plugin {
875 plugin_with(MultiSourceOptions::default())
876}
877
878pub fn multisource(
885 parser: &mut Tabnas,
886 options: MultiSourceOptions,
887) -> Result<(), MultiSourceError> {
888 parser
889 .use_plugin(plugin_with(options), None)
890 .map(|_| ())
891 .map_err(MultiSourceError::from)
892}
893
894#[derive(Clone, Debug, PartialEq, Eq)]
898pub struct MultiSourceError(pub String);
899
900impl fmt::Display for MultiSourceError {
901 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
902 formatter.write_str(&self.0)
903 }
904}
905
906impl std::error::Error for MultiSourceError {}
907
908impl From<PluginError> for MultiSourceError {
909 fn from(error: PluginError) -> Self {
910 Self(error.0)
911 }
912}
913
914impl From<MultiSourceError> for PluginError {
915 fn from(error: MultiSourceError) -> Self {
916 Self(error.0)
917 }
918}
919
920fn normalize(mut options: MultiSourceOptions) -> MultiSourceOptions {
922 if options.markchar.is_empty() {
923 options.markchar = DEFAULT_MARKCHAR.to_string();
924 }
925 for ext in &mut options.implicit_ext {
926 if !ext.starts_with('.') {
927 *ext = format!(".{ext}");
928 }
929 }
930 if options.max_depth == 0 {
931 options.max_depth = DEFAULT_MAX_DEPTH;
932 }
933 options
934}
935
936fn install(parser: &mut Tabnas, options: Arc<MultiSourceOptions>) -> Result<(), MultiSourceError> {
937 let rules = parser.rule_names();
941 for required in ["val", "map", "pair"] {
942 if !rules.iter().any(|name| name == required) {
943 return Err(MultiSourceError(format!(
944 "MultiSource needs a host grammar supplying the {required:?} rule: \
945 install one that defines val, map and pair (tabnas-jsonic, for \
946 example) before this plugin"
947 )));
948 }
949 }
950
951 let nested = Arc::new(NestedParser::default());
954 let reports = Arc::new(LastReport::default());
955
956 parser
957 .set_options(|engine| {
958 engine.error.insert(
959 "multisource_not_found".to_string(),
960 "source not found: {path}".to_string(),
961 );
962 engine.error.insert(
963 "multisource_cycle".to_string(),
964 "source includes itself: {path}".to_string(),
965 );
966 engine.error.insert(
967 "multisource_depth".to_string(),
968 "source nesting is too deep: {path}".to_string(),
969 );
970 engine.hint.insert(
971 "multisource_not_found".to_string(),
972 "The source path {path} was not found.\n\nSearch paths:\n{searchstr}".to_string(),
973 );
974 engine.hint.insert(
975 "multisource_cycle".to_string(),
976 "Including {path} here would loop forever:\n\n{loop}\n\n\
977 A source may be included from more than one place, but it cannot \
978 be an ancestor of itself."
979 .to_string(),
980 );
981 engine.hint.insert(
982 "multisource_depth".to_string(),
983 "Loading {path} would nest sources more than {max} deep.\n\n\
984 Each source is loaded inside the parse that referenced it, so an \
985 unbounded chain would exhaust the stack. Raise max_depth if the \
986 chain is genuine."
987 .to_string(),
988 );
989 })
990 .map_err(|error| MultiSourceError(error.to_string()))?;
991
992 {
996 let options = Arc::clone(&options);
997 let nested = Arc::clone(&nested);
998 parser.parse_prepare_with_instance(move |instance, context, _meta| {
999 if !context.source.contains(options.markchar.as_str()) {
1000 return;
1001 }
1002 if is_nested_meta(&context.meta) {
1003 return;
1004 }
1005 nested.publish(instance);
1006 });
1007 }
1008
1009 let name = RULE_NAME.to_string();
1010 let markchar = options.markchar.clone();
1011 let action_options = Arc::clone(&options);
1012 let action_nested = Arc::clone(&nested);
1013 let action_reports = Arc::clone(&reports);
1014
1015 let directive = DirectiveOptions::new(name.clone(), markchar)
1016 .with_rules(
1017 RulesOption::new()
1018 .open_rule("val", RuleMod::new())
1019 .open_rule("pair", RuleMod::when(|rule, _context| rule.lte("pk", 0))),
1023 )
1024 .with_token_action(move |rule, context| {
1025 directive_action(
1026 &action_options,
1027 &action_nested,
1028 &action_reports,
1029 rule,
1030 context,
1031 )
1032 })
1033 .with_custom(move |parser, config| {
1034 if let Err(error) = install_grammar(parser, &config.name) {
1035 panic!("MultiSource grammar: {error}");
1039 }
1040 });
1041
1042 tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
1043}
1044
1045fn install_grammar(parser: &mut Tabnas, name: &str) -> Result<(), MultiSourceError> {
1048 let open_token = format!("#OD_{name}");
1049 let top_counter = format!("{name}_top");
1050
1051 parser.alt_condition("@ms-pk-val", |rule, _context| {
1057 rule.gt("pk", 0)
1058 && rule
1059 .parent_rule
1060 .as_ref()
1061 .map(|parent| parent.name.as_ref() != "pair")
1062 .unwrap_or(true)
1063 });
1064 parser.alt_condition("@ms-pk", |rule, _context| rule.gt("pk", 0));
1065 parser.alt_condition("@ms-top", |rule, _context| rule.d == 0);
1066 let counter = top_counter.clone();
1067 parser.alt_condition("@ms-top-map", move |rule, _context| {
1068 rule.d == 1 && rule.eq(&counter, 1)
1069 });
1070
1071 let document = json!({
1072 "rule": {
1073 "val": {
1074 "open": [
1075 { "s": open_token, "c": "@ms-pk-val", "b": 1 },
1076 {
1077 "s": open_token,
1078 "c": "@ms-top",
1079 "p": "map",
1080 "b": 1,
1081 "n": { top_counter.clone(): 1 },
1082 },
1083 ],
1084 },
1085 "map": {
1086 "open": [{
1087 "s": open_token,
1088 "c": "@ms-top-map",
1089 "p": "pair",
1090 "b": 1,
1091 "a": "@object$",
1097 "k": { "object$": { "implicit": true } },
1098 }],
1099 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1100 },
1101 "pair": {
1102 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1103 },
1104 },
1105 });
1106
1107 let spec =
1108 GrammarSpec::from_value(document).map_err(|error| MultiSourceError(error.to_string()))?;
1109 parser
1110 .grammar_with_setting(&spec, &GrammarSetting::groups(name))
1111 .map(|_| ())
1112 .map_err(|error| MultiSourceError(error.to_string()))
1113}
1114
1115fn reference_of(value: &Value) -> Option<String> {
1129 match value {
1130 Value::Object(_) | Value::MapRef(_) => coerce_reference(meta_get(value, "path").as_ref()?),
1131 other => coerce_reference(other),
1132 }
1133}
1134
1135fn coerce_reference(value: &Value) -> Option<String> {
1137 match value {
1138 Value::String(text) => Some(text.clone()),
1139 Value::Text(text) => Some(text.string.clone()),
1140 Value::Number(number) => Some(format_number(*number)),
1141 Value::Bool(flag) => Some(flag.to_string()),
1142 _ => None,
1143 }
1144}
1145
1146fn format_number(number: f64) -> String {
1160 if number.is_nan() {
1161 return "NaN".to_string();
1162 }
1163 if number == 0.0 {
1165 return "0".to_string();
1166 }
1167 if number < 0.0 {
1168 return format!("-{}", format_number(-number));
1169 }
1170 if number.is_infinite() {
1171 return "Infinity".to_string();
1172 }
1173
1174 let shortest = format!("{number:e}");
1179 let shortest_k = shortest
1180 .split_once('e')
1181 .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
1182 .expect("a finite f64 always formats with an exponent");
1183
1184 let exponential = format!("{:.*e}", shortest_k - 1, number);
1190 let (mantissa, exponent) = exponential
1191 .split_once('e')
1192 .expect("a finite f64 always formats with an exponent");
1193 let digits = mantissa
1196 .chars()
1197 .filter(|digit| *digit != '.')
1198 .collect::<String>();
1199 let digits = digits.trim_end_matches('0');
1200 let digits = if digits.is_empty() { "0" } else { digits };
1201 let k = digits.len() as i32;
1202 let n = exponent
1203 .parse::<i32>()
1204 .expect("a formatted exponent is an integer")
1205 + 1;
1206
1207 if (k..=21).contains(&n) {
1210 let mut text = digits.to_string();
1212 text.push_str(&"0".repeat((n - k) as usize));
1213 text
1214 } else if (1..=21).contains(&n) {
1215 let point = n as usize;
1216 format!("{}.{}", &digits[..point], &digits[point..])
1217 } else if (-5..=0).contains(&n) {
1218 format!("0.{}{}", "0".repeat(-n as usize), digits)
1219 } else {
1220 let sign = if n - 1 < 0 { '-' } else { '+' };
1223 let power = (n - 1).abs();
1224 if k == 1 {
1225 format!("{digits}e{sign}{power}")
1226 } else {
1227 format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
1228 }
1229 }
1230}
1231
1232fn error_token(rule: &Rule, context: &Context) -> Option<Token> {
1236 rule.parent_rule
1237 .as_ref()
1238 .and_then(|parent| parent.o.first())
1239 .or_else(|| rule.o.first())
1240 .cloned()
1241 .or_else(|| context.t0().cloned())
1242}
1243
1244fn fail(
1245 reports: &LastReport,
1246 rule: &Rule,
1247 context: &Context,
1248 code: &str,
1249 details: Vec<(String, Value)>,
1250) -> Result<Option<Token>, ActionError> {
1251 if let Some(ticket) = meta_multisource_string(&context.meta, REPORT_TICKET) {
1254 reports.record(&ticket, code, &details);
1255 }
1256 match error_token(rule, context) {
1257 Some(mut token) => {
1258 token.bad_with_details(code, details);
1259 Ok(Some(token))
1260 }
1261 None => Err(ActionError::new(code, format!("[{code}]"))),
1264 }
1265}
1266
1267fn directive_action(
1268 options: &Arc<MultiSourceOptions>,
1269 nested: &Arc<NestedParser>,
1270 reports: &Arc<LastReport>,
1271 rule: &mut Rule,
1272 context: &mut Context,
1273) -> Result<Option<Token>, ActionError> {
1274 let from = rule
1275 .parent_rule
1276 .as_ref()
1277 .map(|parent| parent.name.to_string())
1278 .unwrap_or_default();
1279
1280 let reference = reference_of(&rule.child_node);
1281
1282 let mut resolution = {
1283 let input = ResolverInput {
1284 options,
1285 meta: &context.meta,
1286 };
1287 options.resolver.resolve(reference.as_deref(), &input)
1288 };
1289
1290 if !resolution.found {
1291 let mut search = resolution.search.clone();
1292 if search.is_empty() {
1293 if let Some(full) = &resolution.spec.full {
1294 search.push(full.clone());
1295 }
1296 }
1297 let named = resolution
1298 .spec
1299 .path
1300 .clone()
1301 .or_else(|| reference.clone())
1302 .unwrap_or_default();
1303 return fail(
1304 reports,
1305 rule,
1306 context,
1307 "multisource_not_found",
1308 vec![
1309 ("path".to_string(), Value::String(named)),
1310 (
1311 "full".to_string(),
1312 Value::String(resolution.spec.full.clone().unwrap_or_default()),
1313 ),
1314 ("searchstr".to_string(), Value::String(search.join("\n"))),
1315 ],
1316 );
1317 }
1318
1319 let fullpath = resolution.full_path();
1320
1321 if resolution.spec.kind.is_empty() {
1322 resolution.spec.kind = NONE.to_string();
1323 }
1324
1325 let mut parents = meta_parents(&context.meta);
1330 if let Some(path) = meta_multisource_string(&context.meta, "path") {
1331 parents.push(path);
1332 }
1333
1334 if let Some(index) = parents.iter().position(|parent| parent == &fullpath) {
1339 let mut loop_path: Vec<String> = parents[index..].to_vec();
1340 loop_path.push(fullpath.clone());
1341 return fail(
1342 reports,
1343 rule,
1344 context,
1345 "multisource_cycle",
1346 vec![
1347 ("path".to_string(), Value::String(fullpath)),
1348 ("loop".to_string(), Value::String(loop_path.join(" -> "))),
1349 ],
1350 );
1351 }
1352
1353 if parents.len() >= options.max_depth {
1356 return fail(
1357 reports,
1358 rule,
1359 context,
1360 "multisource_depth",
1361 vec![
1362 ("path".to_string(), Value::String(fullpath)),
1363 ("max".to_string(), Value::Number(options.max_depth as f64)),
1364 ],
1365 );
1366 }
1367
1368 if let Some(deps) = &options.deps {
1369 let target = parents.last().cloned().unwrap_or_else(|| TOP.to_string());
1370 if let Ok(mut deps) = deps.lock() {
1371 deps.entry(target.clone()).or_default().insert(
1372 fullpath.clone(),
1373 Dependency {
1374 tar: target,
1375 src: fullpath.clone(),
1376 wen: now_millis(),
1377 },
1378 );
1379 }
1380 }
1381
1382 let dive = rule.k.get("path").cloned();
1383 let ticket = reports.ticket();
1384 let meta = child_meta(&context.meta, &resolution, &parents, dive.as_ref(), &ticket);
1385
1386 let Some(parser) = nested.get() else {
1387 return Err(ActionError::new(
1392 "internal",
1393 "MultiSource: no parser was published for the nested parse",
1394 ));
1395 };
1396
1397 if let Some(processor) = options.processor_for(&resolution.spec.kind) {
1398 let input = ProcessorInput {
1399 options,
1400 meta: &meta,
1401 parser: &parser,
1402 depth: parents.len(),
1403 };
1404 processor.process(&mut resolution, &input);
1405 }
1406
1407 if let Some(error) = resolution.err.take() {
1408 let code = if error.code.is_empty() {
1412 "unexpected".to_string()
1413 } else {
1414 error.code.clone()
1415 };
1416 let details = reports.take(&ticket, &code).unwrap_or_else(|| {
1422 vec![
1423 ("path".to_string(), Value::String(fullpath)),
1424 ("searchstr".to_string(), Value::String(error.detail.clone())),
1425 ]
1426 });
1427 return fail(reports, rule, context, &code, details);
1428 }
1429
1430 reports.discard(&ticket);
1432
1433 let value = std::mem::replace(&mut resolution.val, Value::Undefined);
1434
1435 if from == "pair" {
1436 splice_into_parent(rule, context, value);
1437 } else {
1438 set_node(rule, value);
1439 }
1440
1441 Ok(None)
1442}
1443
1444fn now_millis() -> u64 {
1445 SystemTime::now()
1446 .duration_since(UNIX_EPOCH)
1447 .map(|since| since.as_millis() as u64)
1448 .unwrap_or(0)
1449}
1450
1451fn splice_into_parent(rule: &mut Rule, context: &mut Context, value: Value) {
1461 let Some(target) = rule
1462 .parent_rule
1463 .as_ref()
1464 .and_then(|parent| parent.parent_rule.as_ref())
1465 .map(|grandparent| grandparent.node.clone())
1466 else {
1467 return;
1468 };
1469
1470 let merge = context.options.map.merge.clone();
1471 let extend = context.options.map.extend;
1472
1473 if let Some(merge) = merge {
1474 let base = target.borrow().clone();
1475 let merged = merge(base, value, rule, context);
1476 *target.borrow_mut() = merged;
1477 return;
1478 }
1479
1480 if extend {
1481 let base = target.borrow().clone();
1482 let merged = deep_merge(base, value);
1483 *target.borrow_mut() = merged;
1484 return;
1485 }
1486
1487 let Some(entries) = object_entries(&value) else {
1489 return;
1490 };
1491 let mut node = target.borrow_mut();
1492 match &mut *node {
1493 Value::Object(map) => {
1494 let map = Arc::make_mut(map);
1495 for (key, item) in entries {
1496 map.insert(key, item);
1497 }
1498 }
1499 Value::MapRef(map) => {
1500 let map = Arc::make_mut(map);
1501 for (key, item) in entries {
1502 map.value.insert(key, item);
1503 }
1504 }
1505 _ => {}
1506 }
1507}
1508
1509fn object_entries(value: &Value) -> Option<Vec<(String, Value)>> {
1510 match value {
1511 Value::Object(map) => Some(
1512 map.iter()
1513 .map(|(key, item)| (key.clone(), item.clone()))
1514 .collect(),
1515 ),
1516 Value::MapRef(map) => Some(
1517 map.value
1518 .iter()
1519 .map(|(key, item)| (key.clone(), item.clone()))
1520 .collect(),
1521 ),
1522 _ => None,
1523 }
1524}
1525
1526fn deep_merge(base: Value, overlay: Value) -> Value {
1541 const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
1542
1543 fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
1544 for (key, value) in overlay {
1545 if DANGEROUS.contains(&key.as_str()) {
1546 continue;
1547 }
1548 let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
1549 base.insert(key, deep_merge(previous, value));
1550 }
1551 }
1552
1553 fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
1554 for (index, value) in overlay.into_iter().enumerate() {
1555 if index < base.len() {
1556 let previous = std::mem::replace(&mut base[index], Value::Undefined);
1557 base[index] = deep_merge(previous, value);
1558 } else {
1559 base.push(value);
1560 }
1561 }
1562 }
1563
1564 match (base, overlay) {
1565 (base, Value::Undefined) => base,
1566 (Value::Object(base), Value::Object(overlay)) => {
1567 let mut base = unwrap_arc(base);
1568 merge_entries(&mut base, unwrap_arc(overlay));
1569 Value::object(base)
1570 }
1571 (Value::Object(base), Value::MapRef(overlay)) => {
1572 let mut base = unwrap_arc(base);
1573 merge_entries(&mut base, unwrap_arc(overlay).value);
1574 Value::object(base)
1575 }
1576 (Value::MapRef(base), Value::Object(overlay)) => {
1577 let mut base = unwrap_arc(base);
1578 merge_entries(&mut base.value, unwrap_arc(overlay));
1579 Value::MapRef(Arc::new(base))
1580 }
1581 (Value::MapRef(base), Value::MapRef(overlay)) => {
1582 let mut base = unwrap_arc(base);
1583 merge_entries(&mut base.value, unwrap_arc(overlay).value);
1584 Value::MapRef(Arc::new(base))
1585 }
1586 (Value::Array(base), Value::Array(overlay)) => {
1587 let mut base = unwrap_arc(base);
1588 merge_items(&mut base, unwrap_arc(overlay));
1589 Value::array(base)
1590 }
1591 (Value::Array(base), Value::ListRef(overlay)) => {
1592 let mut base = unwrap_arc(base);
1593 merge_items(&mut base, unwrap_arc(overlay).value);
1594 Value::array(base)
1595 }
1596 (Value::ListRef(base), Value::Array(overlay)) => {
1597 let mut base = unwrap_arc(base);
1598 merge_items(&mut base.value, unwrap_arc(overlay));
1599 Value::ListRef(Arc::new(base))
1600 }
1601 (Value::ListRef(base), Value::ListRef(overlay)) => {
1602 let mut base = unwrap_arc(base);
1603 merge_items(&mut base.value, unwrap_arc(overlay).value);
1604 Value::ListRef(Arc::new(base))
1605 }
1606 (_, overlay) => overlay,
1607 }
1608}
1609
1610fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
1613 Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618 use super::*;
1619
1620 fn object(entries: &[(&str, Value)]) -> Value {
1621 Value::object(
1622 entries
1623 .iter()
1624 .map(|(key, value)| (key.to_string(), value.clone()))
1625 .collect(),
1626 )
1627 }
1628
1629 fn number(value: f64) -> Value {
1630 Value::Number(value)
1631 }
1632
1633 #[test]
1636 fn deep_merge_agrees_with_the_jsonic_merge_it_replaces() {
1637 let cases: Vec<(Value, Value)> = vec![
1638 (
1639 object(&[("a", number(1.0)), ("n", object(&[("x", number(1.0))]))]),
1640 object(&[("b", number(2.0)), ("n", object(&[("y", number(2.0))]))]),
1641 ),
1642 (
1643 Value::array(vec![number(1.0), object(&[("a", number(1.0))])]),
1644 Value::array(vec![
1645 number(9.0),
1646 object(&[("b", number(2.0))]),
1647 number(3.0),
1648 ]),
1649 ),
1650 (
1651 object(&[("a", number(1.0))]),
1652 Value::array(vec![number(1.0)]),
1653 ),
1654 (object(&[("a", number(1.0))]), Value::Undefined),
1655 (Value::Null, object(&[("a", number(1.0))])),
1656 (number(1.0), Value::String("s".to_string())),
1657 (
1658 object(&[("a", number(1.0))]),
1659 object(&[
1660 ("__proto__", object(&[("polluted", Value::Bool(true))])),
1661 ("constructor", number(1.0)),
1662 ("prototype", number(2.0)),
1663 ("ok", number(3.0)),
1664 ]),
1665 ),
1666 ];
1667 for (base, overlay) in cases {
1668 let ours = deep_merge(base.clone(), overlay.clone());
1669 let theirs = tabnas_jsonic::deep_merge(base.clone(), overlay.clone());
1670 assert_eq!(ours, theirs, "deep_merge({base}, {overlay})");
1671 }
1672 }
1673
1674 #[test]
1677 fn deep_merge_keeps_the_base_container_and_its_metadata() {
1678 let mut meta = IndexMap::new();
1679 meta.insert("tag".to_string(), Value::String("kept".to_string()));
1680 let mut entries = IndexMap::new();
1681 entries.insert("a".to_string(), number(1.0));
1682 let base = Value::MapRef(Arc::new(tabnas::MapRef {
1683 value: entries,
1684 implicit: true,
1685 meta,
1686 }));
1687
1688 match deep_merge(base, object(&[("b", number(2.0))])) {
1689 Value::MapRef(map) => {
1690 assert!(map.implicit);
1691 assert_eq!(map.meta.get("tag"), Some(&Value::String("kept".into())));
1692 assert_eq!(map.value.get("a"), Some(&number(1.0)));
1693 assert_eq!(map.value.get("b"), Some(&number(2.0)));
1694 }
1695 other => panic!("the base container kind is kept, got {other:?}"),
1696 }
1697 }
1698}
1699
1700#[cfg(doctest)]
1701#[doc = include_str!("../README.md")]
1702mod readme_examples {}