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.4";
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 {
579 let path = reference.map(str::to_string);
580 let abs = path
581 .as_deref()
582 .map(|path| path.starts_with('/') || path.starts_with('\\') || is_drive_absolute(path))
583 .unwrap_or(false);
584 let full = match path.as_deref() {
585 Some(path) if abs => Some(path.to_string()),
586 Some(path) if !path.is_empty() => Some(if base.is_empty() {
587 path.to_string()
588 } else {
589 format!("{base}/{path}")
590 }),
591 _ => None,
592 };
593 PathSpec {
594 kind: ext_kind(full.as_deref()),
595 path,
596 full,
597 base: base.to_string(),
598 abs,
599 }
600}
601
602fn is_drive_absolute(path: &str) -> bool {
606 matches!(path.as_bytes(), [drive, b':', b'/' | b'\\', ..] if drive.is_ascii_alphabetic())
607}
608
609pub fn build_potentials(full: &str, implicit_ext: &[String]) -> Vec<String> {
616 if full.is_empty() {
617 return Vec::new();
618 }
619 let mut potentials = vec![full.to_string()];
620 let segment = match full.rfind(['/', '\\']) {
621 Some(index) => &full[index + 1..],
622 None => full,
623 };
624 if segment.contains('.') {
625 return potentials;
626 }
627 for ext in implicit_ext {
628 potentials.push(format!("{full}{ext}"));
629 }
630 for ext in implicit_ext {
631 potentials.push(format!("{full}/index{ext}"));
632 }
633 if !segment.is_empty() && segment != "." {
634 for ext in implicit_ext {
635 potentials.push(format!("{full}/index.{segment}{ext}"));
636 }
637 }
638 potentials
639}
640
641pub fn source_dir(path: &str) -> String {
648 let trimmed = path.trim_end_matches(['/', '\\']);
649 match trimmed.rfind(['/', '\\']) {
650 None => String::new(),
651 Some(0) => trimmed[..1].to_string(),
652 Some(index) => trimmed[..index].to_string(),
653 }
654}
655
656fn meta_object(meta: &Value) -> Option<&IndexMap<String, Value>> {
661 match meta {
662 Value::Object(map) => Some(map),
663 Value::MapRef(map) => Some(&map.value),
664 _ => None,
665 }
666}
667
668fn meta_get<'a>(meta: &'a Value, key: &str) -> Option<&'a Value> {
669 meta_object(meta).and_then(|map| map.get(key))
670}
671
672fn meta_multisource_string(meta: &Value, key: &str) -> Option<String> {
673 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, key)) {
674 Some(Value::String(text)) => Some(text.clone()),
675 Some(Value::Text(text)) => Some(text.string.clone()),
676 _ => None,
677 }
678}
679
680fn is_nested_meta(meta: &Value) -> bool {
683 matches!(
684 meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, NESTED_MARK)),
685 Some(Value::Bool(true))
686 )
687}
688
689fn meta_parents(meta: &Value) -> Vec<String> {
690 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, "parents")) {
691 Some(Value::Array(items)) => items
692 .iter()
693 .filter_map(|item| match item {
694 Value::String(text) => Some(text.clone()),
695 Value::Text(text) => Some(text.string.clone()),
696 _ => None,
697 })
698 .collect(),
699 _ => Vec::new(),
700 }
701}
702
703const NESTED_MARK: &str = "nested";
710
711fn child_meta(
716 parent: &Value,
717 resolution: &Resolution,
718 parents: &[String],
719 dive: Option<&Value>,
720 ticket: &str,
721) -> Value {
722 let mut child = meta_object(parent).cloned().unwrap_or_default();
723
724 let previous = meta_get(parent, RULE_NAME)
725 .and_then(meta_object)
726 .cloned()
727 .unwrap_or_default();
728 let mut entry = previous;
729 entry.insert(
730 "parents".to_string(),
731 Value::array(parents.iter().cloned().map(Value::String).collect()),
732 );
733 entry.insert(
734 "path".to_string(),
735 match &resolution.spec.full {
736 Some(full) => Value::String(full.clone()),
737 None => Value::Undefined,
738 },
739 );
740 entry.insert(NESTED_MARK.to_string(), Value::Bool(true));
741 entry.insert(REPORT_TICKET.to_string(), Value::String(ticket.to_string()));
744 child.insert(RULE_NAME.to_string(), Value::object(entry));
745
746 if let Some(path) = &resolution.spec.path {
747 child.insert("fileName".to_string(), Value::String(path.clone()));
748 }
749
750 if let Some(Value::Array(segments)) = dive {
754 let mut path = IndexMap::new();
755 path.insert("base".to_string(), Value::array(segments.as_ref().clone()));
756 child.insert("path".to_string(), Value::object(path));
757 }
758
759 Value::object(child)
760}
761
762#[derive(Default)]
777struct NestedParser {
778 current: Mutex<Option<Arc<Tabnas>>>,
779}
780
781impl NestedParser {
782 fn publish(&self, parser: &Tabnas) {
783 if let Ok(mut slot) = self.current.lock() {
784 *slot = Some(Arc::new(parser.clone()));
785 }
786 }
787
788 fn get(&self) -> Option<Arc<Tabnas>> {
789 self.current.lock().ok().and_then(|slot| slot.clone())
790 }
791}
792
793type Report = (String, Vec<(String, Value)>);
796
797#[derive(Default)]
820struct LastReport {
821 slots: Mutex<BTreeMap<String, Report>>,
822 next: std::sync::atomic::AtomicU64,
823}
824
825impl LastReport {
826 fn ticket(&self) -> String {
828 let count = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
829 format!("{count}")
830 }
831
832 fn record(&self, ticket: &str, code: &str, details: &[(String, Value)]) {
833 if let Ok(mut slots) = self.slots.lock() {
834 slots.insert(ticket.to_string(), (code.to_string(), details.to_vec()));
835 }
836 }
837
838 fn take(&self, ticket: &str, code: &str) -> Option<Vec<(String, Value)>> {
841 let mut slots = self.slots.lock().ok()?;
842 match slots.remove(ticket) {
843 Some((recorded, details)) if recorded == code => Some(details),
844 _ => None,
845 }
846 }
847
848 fn discard(&self, ticket: &str) {
851 if let Ok(mut slots) = self.slots.lock() {
852 slots.remove(ticket);
853 }
854 }
855}
856
857const REPORT_TICKET: &str = "report";
861
862pub fn plugin_with(options: MultiSourceOptions) -> Plugin {
874 let options = Arc::new(normalize(options));
875 Plugin::new(PLUGIN_NAME, move |parser, _plugin_options| {
876 install(parser, Arc::clone(&options)).map_err(PluginError::from)
877 })
878}
879
880pub fn plugin() -> Plugin {
883 plugin_with(MultiSourceOptions::default())
884}
885
886pub fn multisource(
893 parser: &mut Tabnas,
894 options: MultiSourceOptions,
895) -> Result<(), MultiSourceError> {
896 parser
897 .use_plugin(plugin_with(options), None)
898 .map(|_| ())
899 .map_err(MultiSourceError::from)
900}
901
902#[derive(Clone, Debug, PartialEq, Eq)]
906pub struct MultiSourceError(pub String);
907
908impl fmt::Display for MultiSourceError {
909 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
910 formatter.write_str(&self.0)
911 }
912}
913
914impl std::error::Error for MultiSourceError {}
915
916impl From<PluginError> for MultiSourceError {
917 fn from(error: PluginError) -> Self {
918 Self(error.0)
919 }
920}
921
922impl From<MultiSourceError> for PluginError {
923 fn from(error: MultiSourceError) -> Self {
924 Self(error.0)
925 }
926}
927
928fn normalize(mut options: MultiSourceOptions) -> MultiSourceOptions {
930 if options.markchar.is_empty() {
931 options.markchar = DEFAULT_MARKCHAR.to_string();
932 }
933 for ext in &mut options.implicit_ext {
934 if !ext.starts_with('.') {
935 *ext = format!(".{ext}");
936 }
937 }
938 if options.max_depth == 0 {
939 options.max_depth = DEFAULT_MAX_DEPTH;
940 }
941 options
942}
943
944fn install(parser: &mut Tabnas, options: Arc<MultiSourceOptions>) -> Result<(), MultiSourceError> {
945 let rules = parser.rule_names();
949 for required in ["val", "map", "pair"] {
950 if !rules.iter().any(|name| name == required) {
951 return Err(MultiSourceError(format!(
952 "MultiSource needs a host grammar supplying the {required:?} rule: \
953 install one that defines val, map and pair (tabnas-jsonic, for \
954 example) before this plugin"
955 )));
956 }
957 }
958
959 let nested = Arc::new(NestedParser::default());
962 let reports = Arc::new(LastReport::default());
963
964 parser
965 .set_options(|engine| {
966 engine.error.insert(
967 "multisource_not_found".to_string(),
968 "source not found: {path}".to_string(),
969 );
970 engine.error.insert(
971 "multisource_cycle".to_string(),
972 "source includes itself: {path}".to_string(),
973 );
974 engine.error.insert(
975 "multisource_depth".to_string(),
976 "source nesting is too deep: {path}".to_string(),
977 );
978 engine.hint.insert(
979 "multisource_not_found".to_string(),
980 "The source path {path} was not found.\n\nSearch paths:\n{searchstr}".to_string(),
981 );
982 engine.hint.insert(
983 "multisource_cycle".to_string(),
984 "Including {path} here would loop forever:\n\n{loop}\n\n\
985 A source may be included from more than one place, but it cannot \
986 be an ancestor of itself."
987 .to_string(),
988 );
989 engine.hint.insert(
990 "multisource_depth".to_string(),
991 "Loading {path} would nest sources more than {max} deep.\n\n\
992 Each source is loaded inside the parse that referenced it, so an \
993 unbounded chain would exhaust the stack. Raise max_depth if the \
994 chain is genuine."
995 .to_string(),
996 );
997 })
998 .map_err(|error| MultiSourceError(error.to_string()))?;
999
1000 {
1004 let options = Arc::clone(&options);
1005 let nested = Arc::clone(&nested);
1006 parser.parse_prepare_with_instance(move |instance, context, _meta| {
1007 if !context.source.contains(options.markchar.as_str()) {
1008 return;
1009 }
1010 if is_nested_meta(&context.meta) {
1011 return;
1012 }
1013 nested.publish(instance);
1014 });
1015 }
1016
1017 let name = RULE_NAME.to_string();
1018 let markchar = options.markchar.clone();
1019 let action_options = Arc::clone(&options);
1020 let action_nested = Arc::clone(&nested);
1021 let action_reports = Arc::clone(&reports);
1022
1023 let directive = DirectiveOptions::new(name.clone(), markchar)
1024 .with_rules(
1025 RulesOption::new()
1026 .open_rule("val", RuleMod::new())
1027 .open_rule("pair", RuleMod::when(|rule, _context| rule.lte("pk", 0))),
1031 )
1032 .with_token_action(move |rule, context| {
1033 directive_action(
1034 &action_options,
1035 &action_nested,
1036 &action_reports,
1037 rule,
1038 context,
1039 )
1040 })
1041 .with_custom(move |parser, config| {
1042 if let Err(error) = install_grammar(parser, &config.name) {
1043 panic!("MultiSource grammar: {error}");
1047 }
1048 });
1049
1050 tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
1051}
1052
1053fn install_grammar(parser: &mut Tabnas, name: &str) -> Result<(), MultiSourceError> {
1056 let open_token = format!("#OD_{name}");
1057 let top_counter = format!("{name}_top");
1058
1059 parser.alt_condition("@ms-pk-val", |rule, _context| {
1065 rule.gt("pk", 0)
1066 && rule
1067 .parent_rule
1068 .as_ref()
1069 .map(|parent| parent.name.as_ref() != "pair")
1070 .unwrap_or(true)
1071 });
1072 parser.alt_condition("@ms-pk", |rule, _context| rule.gt("pk", 0));
1073 parser.alt_condition("@ms-top", |rule, _context| rule.d == 0);
1074 let counter = top_counter.clone();
1075 parser.alt_condition("@ms-top-map", move |rule, _context| {
1076 rule.d == 1 && rule.eq(&counter, 1)
1077 });
1078
1079 let document = json!({
1080 "rule": {
1081 "val": {
1082 "open": [
1083 { "s": open_token, "c": "@ms-pk-val", "b": 1 },
1084 {
1085 "s": open_token,
1086 "c": "@ms-top",
1087 "p": "map",
1088 "b": 1,
1089 "n": { top_counter.clone(): 1 },
1090 },
1091 ],
1092 },
1093 "map": {
1094 "open": [{
1095 "s": open_token,
1096 "c": "@ms-top-map",
1097 "p": "pair",
1098 "b": 1,
1099 "a": "@object$",
1105 "k": { "object$": { "implicit": true } },
1106 }],
1107 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1108 },
1109 "pair": {
1110 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1111 },
1112 },
1113 });
1114
1115 let spec =
1116 GrammarSpec::from_value(document).map_err(|error| MultiSourceError(error.to_string()))?;
1117 parser
1118 .grammar_with_setting(&spec, &GrammarSetting::groups(name))
1119 .map(|_| ())
1120 .map_err(|error| MultiSourceError(error.to_string()))
1121}
1122
1123fn reference_of(value: &Value) -> Option<String> {
1137 match value {
1138 Value::Object(_) | Value::MapRef(_) => coerce_reference(meta_get(value, "path").as_ref()?),
1139 other => coerce_reference(other),
1140 }
1141}
1142
1143fn coerce_reference(value: &Value) -> Option<String> {
1145 match value {
1146 Value::String(text) => Some(text.clone()),
1147 Value::Text(text) => Some(text.string.clone()),
1148 Value::Number(number) => Some(format_number(*number)),
1149 Value::Bool(flag) => Some(flag.to_string()),
1150 _ => None,
1151 }
1152}
1153
1154fn format_number(number: f64) -> String {
1168 if number.is_nan() {
1169 return "NaN".to_string();
1170 }
1171 if number == 0.0 {
1173 return "0".to_string();
1174 }
1175 if number < 0.0 {
1176 return format!("-{}", format_number(-number));
1177 }
1178 if number.is_infinite() {
1179 return "Infinity".to_string();
1180 }
1181
1182 let shortest = format!("{number:e}");
1187 let shortest_k = shortest
1188 .split_once('e')
1189 .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
1190 .expect("a finite f64 always formats with an exponent");
1191
1192 let exponential = format!("{:.*e}", shortest_k - 1, number);
1198 let (mantissa, exponent) = exponential
1199 .split_once('e')
1200 .expect("a finite f64 always formats with an exponent");
1201 let digits = mantissa
1204 .chars()
1205 .filter(|digit| *digit != '.')
1206 .collect::<String>();
1207 let digits = digits.trim_end_matches('0');
1208 let digits = if digits.is_empty() { "0" } else { digits };
1209 let k = digits.len() as i32;
1210 let n = exponent
1211 .parse::<i32>()
1212 .expect("a formatted exponent is an integer")
1213 + 1;
1214
1215 if (k..=21).contains(&n) {
1218 let mut text = digits.to_string();
1220 text.push_str(&"0".repeat((n - k) as usize));
1221 text
1222 } else if (1..=21).contains(&n) {
1223 let point = n as usize;
1224 format!("{}.{}", &digits[..point], &digits[point..])
1225 } else if (-5..=0).contains(&n) {
1226 format!("0.{}{}", "0".repeat(-n as usize), digits)
1227 } else {
1228 let sign = if n - 1 < 0 { '-' } else { '+' };
1231 let power = (n - 1).abs();
1232 if k == 1 {
1233 format!("{digits}e{sign}{power}")
1234 } else {
1235 format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
1236 }
1237 }
1238}
1239
1240fn error_token(rule: &Rule, context: &Context) -> Option<Token> {
1244 rule.parent_rule
1245 .as_ref()
1246 .and_then(|parent| parent.o.first())
1247 .or_else(|| rule.o.first())
1248 .cloned()
1249 .or_else(|| context.t0().cloned())
1250}
1251
1252fn fail(
1253 reports: &LastReport,
1254 rule: &Rule,
1255 context: &Context,
1256 code: &str,
1257 details: Vec<(String, Value)>,
1258) -> Result<Option<Token>, ActionError> {
1259 if let Some(ticket) = meta_multisource_string(&context.meta, REPORT_TICKET) {
1262 reports.record(&ticket, code, &details);
1263 }
1264 match error_token(rule, context) {
1265 Some(mut token) => {
1266 token.bad_with_details(code, details);
1267 Ok(Some(token))
1268 }
1269 None => Err(ActionError::new(code, format!("[{code}]"))),
1272 }
1273}
1274
1275fn directive_action(
1276 options: &Arc<MultiSourceOptions>,
1277 nested: &Arc<NestedParser>,
1278 reports: &Arc<LastReport>,
1279 rule: &mut Rule,
1280 context: &mut Context,
1281) -> Result<Option<Token>, ActionError> {
1282 let from = rule
1283 .parent_rule
1284 .as_ref()
1285 .map(|parent| parent.name.to_string())
1286 .unwrap_or_default();
1287
1288 let reference = reference_of(&rule.child_node);
1289
1290 let mut resolution = {
1291 let input = ResolverInput {
1292 options,
1293 meta: &context.meta,
1294 };
1295 options.resolver.resolve(reference.as_deref(), &input)
1296 };
1297
1298 if !resolution.found {
1299 let mut search = resolution.search.clone();
1300 if search.is_empty() {
1301 if let Some(full) = &resolution.spec.full {
1302 search.push(full.clone());
1303 }
1304 }
1305 let named = resolution
1306 .spec
1307 .path
1308 .clone()
1309 .or_else(|| reference.clone())
1310 .unwrap_or_default();
1311 return fail(
1312 reports,
1313 rule,
1314 context,
1315 "multisource_not_found",
1316 vec![
1317 ("path".to_string(), Value::String(named)),
1318 (
1319 "full".to_string(),
1320 Value::String(resolution.spec.full.clone().unwrap_or_default()),
1321 ),
1322 ("searchstr".to_string(), Value::String(search.join("\n"))),
1323 ],
1324 );
1325 }
1326
1327 let fullpath = resolution.full_path();
1328
1329 if resolution.spec.kind.is_empty() {
1330 resolution.spec.kind = NONE.to_string();
1331 }
1332
1333 let mut parents = meta_parents(&context.meta);
1338 if let Some(path) = meta_multisource_string(&context.meta, "path") {
1339 parents.push(path);
1340 }
1341
1342 if let Some(index) = parents.iter().position(|parent| parent == &fullpath) {
1347 let mut loop_path: Vec<String> = parents[index..].to_vec();
1348 loop_path.push(fullpath.clone());
1349 return fail(
1350 reports,
1351 rule,
1352 context,
1353 "multisource_cycle",
1354 vec![
1355 ("path".to_string(), Value::String(fullpath)),
1356 ("loop".to_string(), Value::String(loop_path.join(" -> "))),
1357 ],
1358 );
1359 }
1360
1361 if parents.len() >= options.max_depth {
1364 return fail(
1365 reports,
1366 rule,
1367 context,
1368 "multisource_depth",
1369 vec![
1370 ("path".to_string(), Value::String(fullpath)),
1371 ("max".to_string(), Value::Number(options.max_depth as f64)),
1372 ],
1373 );
1374 }
1375
1376 if let Some(deps) = &options.deps {
1377 let target = parents.last().cloned().unwrap_or_else(|| TOP.to_string());
1378 if let Ok(mut deps) = deps.lock() {
1379 deps.entry(target.clone()).or_default().insert(
1380 fullpath.clone(),
1381 Dependency {
1382 tar: target,
1383 src: fullpath.clone(),
1384 wen: now_millis(),
1385 },
1386 );
1387 }
1388 }
1389
1390 let dive = rule.k.get("path").cloned();
1391 let ticket = reports.ticket();
1392 let meta = child_meta(&context.meta, &resolution, &parents, dive.as_ref(), &ticket);
1393
1394 let Some(parser) = nested.get() else {
1395 return Err(ActionError::new(
1400 "internal",
1401 "MultiSource: no parser was published for the nested parse",
1402 ));
1403 };
1404
1405 if let Some(processor) = options.processor_for(&resolution.spec.kind) {
1406 let input = ProcessorInput {
1407 options,
1408 meta: &meta,
1409 parser: &parser,
1410 depth: parents.len(),
1411 };
1412 processor.process(&mut resolution, &input);
1413 }
1414
1415 if let Some(error) = resolution.err.take() {
1416 let code = if error.code.is_empty() {
1420 "unexpected".to_string()
1421 } else {
1422 error.code.clone()
1423 };
1424 let details = reports.take(&ticket, &code).unwrap_or_else(|| {
1430 vec![
1431 ("path".to_string(), Value::String(fullpath)),
1432 ("searchstr".to_string(), Value::String(error.detail.clone())),
1433 ]
1434 });
1435 return fail(reports, rule, context, &code, details);
1436 }
1437
1438 reports.discard(&ticket);
1440
1441 let value = std::mem::replace(&mut resolution.val, Value::Undefined);
1442
1443 if from == "pair" {
1444 splice_into_parent(rule, context, value);
1445 } else {
1446 set_node(rule, value);
1447 }
1448
1449 Ok(None)
1450}
1451
1452fn now_millis() -> u64 {
1453 SystemTime::now()
1454 .duration_since(UNIX_EPOCH)
1455 .map(|since| since.as_millis() as u64)
1456 .unwrap_or(0)
1457}
1458
1459fn splice_into_parent(rule: &mut Rule, context: &mut Context, value: Value) {
1469 let Some(target) = rule
1470 .parent_rule
1471 .as_ref()
1472 .and_then(|parent| parent.parent_rule.as_ref())
1473 .map(|grandparent| grandparent.node.clone())
1474 else {
1475 return;
1476 };
1477
1478 let merge = context.options.map.merge.clone();
1479 let extend = context.options.map.extend;
1480
1481 if let Some(merge) = merge {
1482 let base = target.borrow().clone();
1483 let merged = merge(base, value, rule, context);
1484 *target.borrow_mut() = merged;
1485 return;
1486 }
1487
1488 if extend {
1489 let base = target.borrow().clone();
1490 let merged = deep_merge(base, value);
1491 *target.borrow_mut() = merged;
1492 return;
1493 }
1494
1495 let Some(entries) = object_entries(&value) else {
1497 return;
1498 };
1499 let mut node = target.borrow_mut();
1500 match &mut *node {
1501 Value::Object(map) => {
1502 let map = Arc::make_mut(map);
1503 for (key, item) in entries {
1504 map.insert(key, item);
1505 }
1506 }
1507 Value::MapRef(map) => {
1508 let map = Arc::make_mut(map);
1509 for (key, item) in entries {
1510 map.value.insert(key, item);
1511 }
1512 }
1513 _ => {}
1514 }
1515}
1516
1517fn object_entries(value: &Value) -> Option<Vec<(String, Value)>> {
1518 match value {
1519 Value::Object(map) => Some(
1520 map.iter()
1521 .map(|(key, item)| (key.clone(), item.clone()))
1522 .collect(),
1523 ),
1524 Value::MapRef(map) => Some(
1525 map.value
1526 .iter()
1527 .map(|(key, item)| (key.clone(), item.clone()))
1528 .collect(),
1529 ),
1530 _ => None,
1531 }
1532}
1533
1534fn deep_merge(base: Value, overlay: Value) -> Value {
1549 const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
1550
1551 fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
1552 for (key, value) in overlay {
1553 if DANGEROUS.contains(&key.as_str()) {
1554 continue;
1555 }
1556 let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
1557 base.insert(key, deep_merge(previous, value));
1558 }
1559 }
1560
1561 fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
1562 for (index, value) in overlay.into_iter().enumerate() {
1563 if index < base.len() {
1564 let previous = std::mem::replace(&mut base[index], Value::Undefined);
1565 base[index] = deep_merge(previous, value);
1566 } else {
1567 base.push(value);
1568 }
1569 }
1570 }
1571
1572 match (base, overlay) {
1573 (base, Value::Undefined) => base,
1574 (Value::Object(base), Value::Object(overlay)) => {
1575 let mut base = unwrap_arc(base);
1576 merge_entries(&mut base, unwrap_arc(overlay));
1577 Value::object(base)
1578 }
1579 (Value::Object(base), Value::MapRef(overlay)) => {
1580 let mut base = unwrap_arc(base);
1581 merge_entries(&mut base, unwrap_arc(overlay).value);
1582 Value::object(base)
1583 }
1584 (Value::MapRef(base), Value::Object(overlay)) => {
1585 let mut base = unwrap_arc(base);
1586 merge_entries(&mut base.value, unwrap_arc(overlay));
1587 Value::MapRef(Arc::new(base))
1588 }
1589 (Value::MapRef(base), Value::MapRef(overlay)) => {
1590 let mut base = unwrap_arc(base);
1591 merge_entries(&mut base.value, unwrap_arc(overlay).value);
1592 Value::MapRef(Arc::new(base))
1593 }
1594 (Value::Array(base), Value::Array(overlay)) => {
1595 let mut base = unwrap_arc(base);
1596 merge_items(&mut base, unwrap_arc(overlay));
1597 Value::array(base)
1598 }
1599 (Value::Array(base), Value::ListRef(overlay)) => {
1600 let mut base = unwrap_arc(base);
1601 merge_items(&mut base, unwrap_arc(overlay).value);
1602 Value::array(base)
1603 }
1604 (Value::ListRef(base), Value::Array(overlay)) => {
1605 let mut base = unwrap_arc(base);
1606 merge_items(&mut base.value, unwrap_arc(overlay));
1607 Value::ListRef(Arc::new(base))
1608 }
1609 (Value::ListRef(base), Value::ListRef(overlay)) => {
1610 let mut base = unwrap_arc(base);
1611 merge_items(&mut base.value, unwrap_arc(overlay).value);
1612 Value::ListRef(Arc::new(base))
1613 }
1614 (_, overlay) => overlay,
1615 }
1616}
1617
1618fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
1621 Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626 use super::*;
1627
1628 fn object(entries: &[(&str, Value)]) -> Value {
1629 Value::object(
1630 entries
1631 .iter()
1632 .map(|(key, value)| (key.to_string(), value.clone()))
1633 .collect(),
1634 )
1635 }
1636
1637 fn number(value: f64) -> Value {
1638 Value::Number(value)
1639 }
1640
1641 #[test]
1644 fn deep_merge_agrees_with_the_jsonic_merge_it_replaces() {
1645 let cases: Vec<(Value, Value)> = vec![
1646 (
1647 object(&[("a", number(1.0)), ("n", object(&[("x", number(1.0))]))]),
1648 object(&[("b", number(2.0)), ("n", object(&[("y", number(2.0))]))]),
1649 ),
1650 (
1651 Value::array(vec![number(1.0), object(&[("a", number(1.0))])]),
1652 Value::array(vec![
1653 number(9.0),
1654 object(&[("b", number(2.0))]),
1655 number(3.0),
1656 ]),
1657 ),
1658 (
1659 object(&[("a", number(1.0))]),
1660 Value::array(vec![number(1.0)]),
1661 ),
1662 (object(&[("a", number(1.0))]), Value::Undefined),
1663 (Value::Null, object(&[("a", number(1.0))])),
1664 (number(1.0), Value::String("s".to_string())),
1665 (
1666 object(&[("a", number(1.0))]),
1667 object(&[
1668 ("__proto__", object(&[("polluted", Value::Bool(true))])),
1669 ("constructor", number(1.0)),
1670 ("prototype", number(2.0)),
1671 ("ok", number(3.0)),
1672 ]),
1673 ),
1674 ];
1675 for (base, overlay) in cases {
1676 let ours = deep_merge(base.clone(), overlay.clone());
1677 let theirs = tabnas_jsonic::deep_merge(base.clone(), overlay.clone());
1678 assert_eq!(ours, theirs, "deep_merge({base}, {overlay})");
1679 }
1680 }
1681
1682 #[test]
1685 fn deep_merge_keeps_the_base_container_and_its_metadata() {
1686 let mut meta = IndexMap::new();
1687 meta.insert("tag".to_string(), Value::String("kept".to_string()));
1688 let mut entries = IndexMap::new();
1689 entries.insert("a".to_string(), number(1.0));
1690 let base = Value::MapRef(Arc::new(tabnas::MapRef {
1691 value: entries,
1692 implicit: true,
1693 meta,
1694 }));
1695
1696 match deep_merge(base, object(&[("b", number(2.0))])) {
1697 Value::MapRef(map) => {
1698 assert!(map.implicit);
1699 assert_eq!(map.meta.get("tag"), Some(&Value::String("kept".into())));
1700 assert_eq!(map.value.get("a"), Some(&number(1.0)));
1701 assert_eq!(map.value.get("b"), Some(&number(2.0)));
1702 }
1703 other => panic!("the base container kind is kept, got {other:?}"),
1704 }
1705 }
1706}
1707
1708#[cfg(doctest)]
1709#[doc = include_str!("../README.md")]
1710mod readme_examples {}