tabnas_multisource/lib.rs
1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Load partial values from multiple external sources into one parse
4//! result, as a plugin for the [tabnas](https://github.com/tabnas/parser)
5//! parsing engine over the
6//! [jsonic](https://github.com/tabnas/jsonic) relaxed-JSON grammar.
7//!
8//! A directive character (`@` by default) marks a reference in the
9//! input. The plugin **resolves** the reference to a source, **processes**
10//! that source into a value, and splices the value into the output,
11//! recursively, so a loaded source can reference more sources.
12//!
13//! ```
14//! use tabnas_multisource::{make_with, MapResolver, MultiSourceOptions};
15//!
16//! fn main() -> Result<(), Box<dyn std::error::Error>> {
17//! let sources = MapResolver::from([("a.jsonic", "a:1")]);
18//! let parser = make_with(MultiSourceOptions::new(sources));
19//! assert_eq!(parser.parse(r#"@"a.jsonic" b:2"#)?.to_string(), r#"{"a":1,"b":2}"#);
20//! Ok(())
21//! }
22//! ```
23//!
24//! TypeScript is canonical: `ts/src/multisource.ts` defines behaviour,
25//! option names and defaults. The shared fixtures in `test/spec/*.tsv`
26//! are the parity contract across TypeScript, Go and Rust. Differences
27//! are recorded in `DIVERGENCE.md` at the repository root.
28//!
29//! # Untrusted input
30//!
31//! Following `@` references is this plugin's whole job, which is exactly
32//! why the boundary matters. A reference reaches only what the configured
33//! [`Resolver`] can see, so the resolver is the sandbox:
34//!
35//! - [`MapResolver`] and a [`FileResolver`] over a [`MapFs`] touch no
36//! disk at all.
37//! - [`FileResolver::with_root`] confines every candidate path to one
38//! directory, so `@"../../etc/passwd"` resolves to nothing rather than
39//! to a file. The root and the candidate are both resolved through the
40//! filesystem before they are compared, so a symbolic link inside the
41//! root is judged by where it points; a link created between that
42//! check and the read is beyond what a resolver can see.
43//! - A cycle between sources raises `multisource_cycle`, and a chain
44//! longer than [`MultiSourceOptions::max_depth`] raises
45//! `multisource_depth`, so neither hangs nor overflows the stack.
46//!
47//! A loaded value is still data, never instructions, and splicing is not
48//! sanitising: escaping for SQL, HTML or a shell remains the caller's job.
49
50#![allow(clippy::result_large_err)]
51
52use std::collections::BTreeMap;
53use std::fmt;
54use std::sync::{Arc, Mutex};
55use std::time::{SystemTime, UNIX_EPOCH};
56
57use indexmap::IndexMap;
58use serde_json::json;
59
60use tabnas::{
61 ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, Tabnas,
62 TabnasError, Token, Value,
63};
64use tabnas_directive::{set_node, DirectiveOptions, RuleMod, RulesOption};
65
66mod preload;
67mod processor;
68mod resolver;
69mod vfs;
70
71pub use preload::{preload_files, preload_files_with, PreloadOptions};
72pub use processor::{
73 default_processor, json_processor, jsonic_processor, parse_nested, Processor, ProcessorInput,
74};
75pub use resolver::{FileResolver, MapResolver, PkgResolver};
76pub use vfs::{os_fs, DirEntry, MapFs, OsFs, SharedFs, SourceFs};
77
78/// VERSION is this crate's version. It MUST equal `ts/package.json`
79/// "version" and the `version` field in `rs/Cargo.toml`: the release
80/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
81/// the build if they drift. Mirrors `VERSION` in `ts/src/multisource.ts`
82/// and `const VERSION` in `go/multisource.go`.
83pub const VERSION: &str = "0.5.9";
84
85/// An unknown or missing source-reference extension.
86pub const NONE: &str = "";
87
88/// The top of the dependency tree: the [`DependencyMap`] target key used
89/// for sources referenced directly by the top-level parse.
90///
91/// The TypeScript export is a `Symbol`, which Rust has no counterpart
92/// for, so this mirrors the Go port's sentinel. The leading NUL byte
93/// guarantees it cannot collide with a real source path.
94pub const TOP: &str = "\0TOP";
95
96/// The plugin name, as the engine records it.
97pub const PLUGIN_NAME: &str = "MultiSource";
98
99/// The rule and directive this plugin installs.
100pub const RULE_NAME: &str = "multisource";
101
102/// The default directive character.
103pub const DEFAULT_MARKCHAR: &str = "@";
104
105/// How deep a chain of sources may nest before the parse is failed.
106///
107/// Each nested source is parsed inside the parse that referenced it, so
108/// the chain runs on the call stack. Without a cap a chain of a few
109/// thousand sources with no cycle in it overflows that stack and aborts
110/// the process, which is why this is a cap rather than a note. See
111/// `DIVERGENCE.md`.
112pub const DEFAULT_MAX_DEPTH: usize = 64;
113
114// ---------------------------------------------------------------------
115// Path specs and resolutions
116// ---------------------------------------------------------------------
117
118/// The path to a source, including the base prefix when there is one.
119#[derive(Clone, Debug, Default, PartialEq, Eq)]
120pub struct PathSpec {
121 /// The source kind, normally the extension of the last path segment.
122 pub kind: String,
123 /// The reference exactly as written, which may be relative.
124 pub path: Option<String>,
125 /// The normalized full path.
126 pub full: Option<String>,
127 /// The base the reference resolved against.
128 pub base: String,
129 /// Whether the reference was absolute.
130 pub abs: bool,
131}
132
133/// A source and where it was found.
134#[derive(Clone, Debug)]
135pub struct Resolution {
136 /// The normalized path, rewritten by the resolver when an implicit
137 /// extension or an index file matched.
138 pub spec: PathSpec,
139 /// The source text. `None` when nothing was found.
140 pub src: Option<String>,
141 /// The processed value, filled by a [`Processor`].
142 pub val: Value,
143 /// Whether a source was found.
144 pub found: bool,
145 /// Every path that was tried, for the not-found report.
146 pub search: Vec<String>,
147 /// A failure while PROCESSING found source, for example a nested
148 /// reference inside it that could not be resolved. The plugin
149 /// propagates it so the parse fails, matching TypeScript, which lets
150 /// a nested parse error escape rather than substituting raw text.
151 pub err: Option<Box<TabnasError>>,
152}
153
154impl Default for Resolution {
155 fn default() -> Self {
156 Resolution::not_found(PathSpec::default())
157 }
158}
159
160impl Resolution {
161 /// A resolution that found nothing, for the spec it was built from.
162 pub fn not_found(spec: PathSpec) -> Self {
163 Resolution {
164 spec,
165 src: None,
166 val: Value::Undefined,
167 found: false,
168 search: Vec::new(),
169 err: None,
170 }
171 }
172
173 /// A resolution that found `src` at `full`.
174 pub fn found(mut spec: PathSpec, full: impl Into<String>, src: impl Into<String>) -> Self {
175 let full = full.into();
176 spec.kind = ext_kind(Some(&full));
177 spec.full = Some(full);
178 Resolution {
179 spec,
180 src: Some(src.into()),
181 val: Value::Undefined,
182 found: true,
183 search: Vec::new(),
184 err: None,
185 }
186 }
187
188 /// Record the paths that were searched.
189 pub fn with_search(mut self, search: Vec<String>) -> Self {
190 self.search = search;
191 self
192 }
193
194 /// The path this resolution is known by: the normalized full path,
195 /// else the reference as written, else `no-path`. Mirrors the
196 /// TypeScript `fullpath` fallback chain.
197 pub fn full_path(&self) -> String {
198 self.spec
199 .full
200 .clone()
201 .or_else(|| self.spec.path.clone())
202 .unwrap_or_else(|| "no-path".to_string())
203 }
204}
205
206/// What a [`Resolver`] is given: the plugin options and the parse
207/// metadata for the enclosing source.
208///
209/// The canonical TypeScript hands a resolver the whole parse `Context`,
210/// of which resolvers read only `ctx.meta`. Narrowing it to the metadata
211/// keeps a resolver callable, and therefore testable, outside a parse.
212#[derive(Clone, Copy)]
213pub struct ResolverInput<'a> {
214 /// The plugin options in force for this parse.
215 pub options: &'a MultiSourceOptions,
216 /// The parse metadata. `multisource.path` names the source that
217 /// contains this reference, when there is one.
218 pub meta: &'a Value,
219}
220
221impl fmt::Debug for ResolverInput<'_> {
222 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223 formatter
224 .debug_struct("ResolverInput")
225 .field("meta", self.meta)
226 .finish_non_exhaustive()
227 }
228}
229
230impl ResolverInput<'_> {
231 /// The full path of the source that contains this reference, when
232 /// the reference was found inside another source.
233 pub fn source_path(&self) -> Option<String> {
234 meta_multisource_string(self.meta, "path")
235 }
236}
237
238/// Find the source content a reference names.
239///
240/// Implementations must be `Send + Sync`: a `Tabnas` instance parses
241/// through `&self`, so the plugin, its options and every callback they
242/// hold are shared across threads. Nothing is held in global state, so
243/// two parsers configured differently never see each other's sources.
244pub trait Resolver: Send + Sync {
245 /// Resolve `reference` to a [`Resolution`]. A reference that names
246 /// nothing returns [`Resolution::not_found`]; raising the error is
247 /// the plugin's job, not the resolver's.
248 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution;
249}
250
251impl<F> Resolver for F
252where
253 F: Fn(Option<&str>, &ResolverInput<'_>) -> Resolution + Send + Sync,
254{
255 fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
256 self(reference, input)
257 }
258}
259
260/// A shared resolver handle.
261pub type SharedResolver = Arc<dyn Resolver>;
262
263// ---------------------------------------------------------------------
264// Dependencies
265// ---------------------------------------------------------------------
266
267/// One record that target `tar` pulled in source `src` during a parse.
268#[derive(Clone, Debug, PartialEq, Eq)]
269pub struct Dependency {
270 /// The target that depends on the source; [`TOP`] at the top level.
271 pub tar: String,
272 /// The source the target depends on.
273 pub src: String,
274 /// When the source resolved, in Unix milliseconds.
275 pub wen: u64,
276}
277
278/// A flattened dependency tree, keyed by target full path and then by
279/// source full path.
280///
281/// The TypeScript plugin fills an object the caller passes in the parse
282/// metadata. A Rust parse metadata value cannot be written back to, so
283/// the sink is a typed option instead:
284/// [`MultiSourceOptions::with_deps`].
285pub type DependencyMap = BTreeMap<String, BTreeMap<String, Dependency>>;
286
287// ---------------------------------------------------------------------
288// Options
289// ---------------------------------------------------------------------
290
291/// How one source kind becomes a value.
292#[derive(Clone)]
293pub enum ProcessorEntry {
294 /// A processor callback.
295 Call(Arc<dyn Processor>),
296 /// Another kind's processor, by name. One level of aliasing, as in
297 /// the canonical TypeScript, where a processor entry may be a string
298 /// naming another kind.
299 Alias(String),
300}
301
302impl fmt::Debug for ProcessorEntry {
303 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304 match self {
305 Self::Call(_) => formatter.write_str("ProcessorEntry::Call(<function>)"),
306 Self::Alias(kind) => write!(formatter, "ProcessorEntry::Alias({kind:?})"),
307 }
308 }
309}
310
311/// Configuration for the plugin.
312#[derive(Clone)]
313pub struct MultiSourceOptions {
314 /// Resolves a reference to a source.
315 pub resolver: SharedResolver,
316 /// The base path references resolve against at the top level.
317 pub path: String,
318 /// The character that starts a reference.
319 pub markchar: String,
320 /// Per-kind processors. The empty kind is the fallback.
321 pub processor: IndexMap<String, ProcessorEntry>,
322 /// Extensions tried for a reference with none, in order.
323 pub implicit_ext: Vec<String>,
324 /// A declarative record of a folder preload. As in TypeScript and
325 /// Go, the plugin does not consume it: call [`preload_files`] and
326 /// hand the result to [`FileResolver::with_preload`].
327 pub preload: Option<PreloadOptions>,
328 /// The filesystem the `file` and `pkg` resolvers read, when they
329 /// carry none of their own. `None` is the real filesystem.
330 ///
331 /// This is the Rust spelling of the TypeScript `ctx.meta.fs`
332 /// injection point and of Go's `MultiSourceOptions.FS`.
333 pub fs: Option<SharedFs>,
334 /// Where to record the `tar` to `src` dependency tree, when the
335 /// caller wants one.
336 pub deps: Option<Arc<Mutex<DependencyMap>>>,
337 /// How deep a chain of sources may nest. See [`DEFAULT_MAX_DEPTH`].
338 pub max_depth: usize,
339}
340
341impl fmt::Debug for MultiSourceOptions {
342 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
343 formatter
344 .debug_struct("MultiSourceOptions")
345 .field("path", &self.path)
346 .field("markchar", &self.markchar)
347 .field("processor", &self.processor)
348 .field("implicit_ext", &self.implicit_ext)
349 .field("preload", &self.preload)
350 .field("fs", &self.fs.as_ref().map(|_| "<SourceFs>"))
351 .field("deps", &self.deps.as_ref().map(|_| "<DependencyMap>"))
352 .field("max_depth", &self.max_depth)
353 .finish_non_exhaustive()
354 }
355}
356
357impl Default for MultiSourceOptions {
358 fn default() -> Self {
359 Self::new(MapResolver::new())
360 }
361}
362
363impl MultiSourceOptions {
364 /// Options resolving through `resolver`, everything else default.
365 pub fn new(resolver: impl Resolver + 'static) -> Self {
366 MultiSourceOptions {
367 resolver: Arc::new(resolver),
368 path: String::new(),
369 markchar: DEFAULT_MARKCHAR.to_string(),
370 processor: default_processors(),
371 implicit_ext: default_implicit_ext(),
372 preload: None,
373 fs: None,
374 deps: None,
375 max_depth: DEFAULT_MAX_DEPTH,
376 }
377 }
378
379 /// Options resolving through an already shared resolver.
380 pub fn with_resolver(mut self, resolver: SharedResolver) -> Self {
381 self.resolver = resolver;
382 self
383 }
384
385 /// Set the base path references resolve against.
386 pub fn with_path(mut self, path: impl Into<String>) -> Self {
387 self.path = path.into();
388 self
389 }
390
391 /// Set the directive character.
392 pub fn with_markchar(mut self, markchar: impl Into<String>) -> Self {
393 self.markchar = markchar.into();
394 self
395 }
396
397 /// Register a processor for one kind, replacing any entry for it.
398 pub fn with_processor(
399 mut self,
400 kind: impl Into<String>,
401 processor: impl Processor + 'static,
402 ) -> Self {
403 self.processor
404 .insert(kind.into(), ProcessorEntry::Call(Arc::new(processor)));
405 self
406 }
407
408 /// Point one kind at another kind's processor.
409 pub fn with_processor_alias(
410 mut self,
411 kind: impl Into<String>,
412 target: impl Into<String>,
413 ) -> Self {
414 self.processor
415 .insert(kind.into(), ProcessorEntry::Alias(target.into()));
416 self
417 }
418
419 /// Replace the whole processor table.
420 pub fn with_processors(mut self, processors: IndexMap<String, ProcessorEntry>) -> Self {
421 self.processor = processors;
422 self
423 }
424
425 /// Replace the implicit extension list. A missing leading dot is
426 /// added, as the TypeScript plugin does when it installs.
427 pub fn with_implicit_ext<I, S>(mut self, extensions: I) -> Self
428 where
429 I: IntoIterator<Item = S>,
430 S: AsRef<str>,
431 {
432 self.implicit_ext = extensions
433 .into_iter()
434 .map(|ext| dotted(ext.as_ref()))
435 .collect();
436 self
437 }
438
439 /// Record a preload configuration. The plugin does not act on it.
440 pub fn with_preload(mut self, preload: PreloadOptions) -> Self {
441 self.preload = Some(preload);
442 self
443 }
444
445 /// Set the filesystem the file and pkg resolvers read.
446 pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
447 self.fs = Some(Arc::new(filesystem));
448 self
449 }
450
451 /// Set the filesystem from an already shared handle.
452 pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
453 self.fs = Some(filesystem);
454 self
455 }
456
457 /// Collect the dependency tree into `deps` as the parse runs.
458 pub fn with_deps(mut self, deps: Arc<Mutex<DependencyMap>>) -> Self {
459 self.deps = Some(deps);
460 self
461 }
462
463 /// Set how deep a chain of sources may nest.
464 pub fn with_max_depth(mut self, max_depth: usize) -> Self {
465 self.max_depth = max_depth;
466 self
467 }
468
469 /// The processor for `kind`, resolving one level of aliasing and
470 /// falling back to the [`NONE`] entry, as `getProcessor` does.
471 pub fn processor_for(&self, kind: &str) -> Option<Arc<dyn Processor>> {
472 let fallback = match self.processor.get(NONE) {
473 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
474 _ => None,
475 };
476 match self.processor.get(kind) {
477 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
478 Some(ProcessorEntry::Alias(target)) => match self.processor.get(target.as_str()) {
479 Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
480 // An alias to an alias is one level too many, exactly as
481 // in TypeScript, where the second lookup yields a string
482 // and nothing callable comes back.
483 _ => fallback,
484 },
485 None => fallback,
486 }
487 }
488}
489
490/// The default processor table: raw text for an unknown kind, the strict
491/// JSON reader for `json`, and a re-parse with the live engine for
492/// `jsonic` and `jsc`.
493pub fn default_processors() -> IndexMap<String, ProcessorEntry> {
494 let mut processors = IndexMap::new();
495 processors.insert(
496 NONE.to_string(),
497 ProcessorEntry::Call(Arc::new(default_processor)),
498 );
499 processors.insert(
500 "jsonic".to_string(),
501 ProcessorEntry::Call(Arc::new(jsonic_processor)),
502 );
503 processors.insert(
504 "jsc".to_string(),
505 ProcessorEntry::Alias("jsonic".to_string()),
506 );
507 processors.insert(
508 "json".to_string(),
509 ProcessorEntry::Call(Arc::new(json_processor)),
510 );
511 processors
512}
513
514/// The default implicit extensions.
515///
516/// `.js` is deliberately absent: the TypeScript `js` kind `require`s,
517/// which is to say executes, the module, and Rust has no JavaScript
518/// runtime to do that in. The Go port leaves it out for the same reason.
519/// See `DIVERGENCE.md`.
520pub fn default_implicit_ext() -> Vec<String> {
521 vec![
522 ".jsonic".to_string(),
523 ".jsc".to_string(),
524 ".json".to_string(),
525 ]
526}
527
528fn dotted(ext: &str) -> String {
529 if ext.starts_with('.') {
530 ext.to_string()
531 } else {
532 format!(".{ext}")
533 }
534}
535
536// ---------------------------------------------------------------------
537// Path helpers
538// ---------------------------------------------------------------------
539
540/// The source kind: the extension of the LAST path segment, without the
541/// dot, or [`NONE`] when that segment has no dot.
542///
543/// It must be segment-scoped. Matching the whole path makes a dot in a
544/// parent folder (`a.d/foo`) produce a kind that is not [`NONE`], so the
545/// implicit-extension search is skipped and an extensionless reference
546/// under a dotted folder is wrongly reported as missing.
547pub fn ext_kind(full: Option<&str>) -> String {
548 let Some(full) = full else {
549 return NONE.to_string();
550 };
551 let segment = match full.rfind(['/', '\\']) {
552 Some(index) => &full[index + 1..],
553 None => full,
554 };
555 match segment.rfind('.') {
556 Some(index) => segment[index + 1..].to_string(),
557 None => NONE.to_string(),
558 }
559}
560
561/// Normalize a reference into a [`PathSpec`] against `base`.
562///
563/// The counterpart of the TypeScript `resolvePathSpec` and Go's
564/// `ResolvePathSpec`. An absolute reference ignores the base.
565pub fn resolve_path_spec(reference: Option<&str>, base: &str) -> PathSpec {
566 let path = reference.map(str::to_string);
567 let abs = path
568 .as_deref()
569 .map(|path| path.starts_with('/') || path.starts_with('\\'))
570 .unwrap_or(false);
571 let full = match path.as_deref() {
572 Some(path) if abs => Some(path.to_string()),
573 Some(path) if !path.is_empty() => Some(if base.is_empty() {
574 path.to_string()
575 } else {
576 format!("{base}/{path}")
577 }),
578 _ => None,
579 };
580 PathSpec {
581 kind: ext_kind(full.as_deref()),
582 path,
583 full,
584 base: base.to_string(),
585 abs,
586 }
587}
588
589/// Every path a reference could name: the path itself, then the implicit
590/// extensions, then a folder index file, then a folder index file that
591/// repeats the folder name.
592///
593/// Whether a reference already has an extension is a property of its LAST
594/// segment, not of the whole path, for the reason [`ext_kind`] gives.
595pub fn build_potentials(full: &str, implicit_ext: &[String]) -> Vec<String> {
596 if full.is_empty() {
597 return Vec::new();
598 }
599 let mut potentials = vec![full.to_string()];
600 let segment = match full.rfind(['/', '\\']) {
601 Some(index) => &full[index + 1..],
602 None => full,
603 };
604 if segment.contains('.') {
605 return potentials;
606 }
607 for ext in implicit_ext {
608 potentials.push(format!("{full}{ext}"));
609 }
610 for ext in implicit_ext {
611 potentials.push(format!("{full}/index{ext}"));
612 }
613 if !segment.is_empty() && segment != "." {
614 for ext in implicit_ext {
615 potentials.push(format!("{full}/index.{segment}{ext}"));
616 }
617 }
618 potentials
619}
620
621/// The directory a relative reference inside `path` resolves against.
622///
623/// A path with no separator (an in-memory key such as `a.jsonic`) yields
624/// the empty string, so a bare nested reference resolves plainly; a
625/// separator at index zero yields the root separator. Mirrors Go's
626/// `sourceDir` and the TypeScript mem resolver's `resolvefolder`.
627pub fn source_dir(path: &str) -> String {
628 let trimmed = path.trim_end_matches(['/', '\\']);
629 match trimmed.rfind(['/', '\\']) {
630 None => String::new(),
631 Some(0) => trimmed[..1].to_string(),
632 Some(index) => trimmed[..index].to_string(),
633 }
634}
635
636// ---------------------------------------------------------------------
637// Parse metadata
638// ---------------------------------------------------------------------
639
640fn meta_object(meta: &Value) -> Option<&IndexMap<String, Value>> {
641 match meta {
642 Value::Object(map) => Some(map),
643 Value::MapRef(map) => Some(&map.value),
644 _ => None,
645 }
646}
647
648fn meta_get<'a>(meta: &'a Value, key: &str) -> Option<&'a Value> {
649 meta_object(meta).and_then(|map| map.get(key))
650}
651
652fn meta_multisource_string(meta: &Value, key: &str) -> Option<String> {
653 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, key)) {
654 Some(Value::String(text)) => Some(text.clone()),
655 Some(Value::Text(text)) => Some(text.string.clone()),
656 _ => None,
657 }
658}
659
660/// Was this metadata built by [`child_meta`], rather than handed in by
661/// a caller?
662fn is_nested_meta(meta: &Value) -> bool {
663 matches!(
664 meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, NESTED_MARK)),
665 Some(Value::Bool(true))
666 )
667}
668
669fn meta_parents(meta: &Value) -> Vec<String> {
670 match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, "parents")) {
671 Some(Value::Array(items)) => items
672 .iter()
673 .filter_map(|item| match item {
674 Value::String(text) => Some(text.clone()),
675 Value::Text(text) => Some(text.string.clone()),
676 _ => None,
677 })
678 .collect(),
679 _ => Vec::new(),
680 }
681}
682
683/// The key marking metadata this plugin built for a nested parse.
684///
685/// The prepare hook needs to tell a nested parse from a top-level one,
686/// and `multisource.path` cannot do it: a caller may legitimately set
687/// that at the top level to choose the base a relative reference
688/// resolves against, exactly as the canonical TypeScript tests do.
689const NESTED_MARK: &str = "nested";
690
691/// The metadata a nested parse gets: the parent's metadata with the
692/// multisource entry updated to name this source and its ancestors.
693/// Mirrors the TypeScript action's `meta` construction and Go's
694/// `childMeta`; the parent metadata is never mutated.
695fn child_meta(
696 parent: &Value,
697 resolution: &Resolution,
698 parents: &[String],
699 dive: Option<&Value>,
700 ticket: &str,
701) -> Value {
702 let mut child = meta_object(parent).cloned().unwrap_or_default();
703
704 let previous = meta_get(parent, RULE_NAME)
705 .and_then(meta_object)
706 .cloned()
707 .unwrap_or_default();
708 let mut entry = previous;
709 entry.insert(
710 "parents".to_string(),
711 Value::array(parents.iter().cloned().map(Value::String).collect()),
712 );
713 entry.insert(
714 "path".to_string(),
715 match &resolution.spec.full {
716 Some(full) => Value::String(full.clone()),
717 None => Value::Undefined,
718 },
719 );
720 entry.insert(NESTED_MARK.to_string(), Value::Bool(true));
721 // The slot this nested parse records a diagnostic under, so the
722 // load below reads back its own report and no other parse's.
723 entry.insert(REPORT_TICKET.to_string(), Value::String(ticket.to_string()));
724 child.insert(RULE_NAME.to_string(), Value::object(entry));
725
726 if let Some(path) = &resolution.spec.path {
727 child.insert("fileName".to_string(), Value::String(path.clone()));
728 }
729
730 // The path-diving plugin reads `meta.path.base` to seed the path of
731 // the root value. Carrying the current dive down means a reference
732 // that lands at a dived key keeps its place in the tree.
733 if let Some(Value::Array(segments)) = dive {
734 let mut path = IndexMap::new();
735 path.insert("base".to_string(), Value::array(segments.as_ref().clone()));
736 child.insert("path".to_string(), Value::object(path));
737 }
738
739 Value::object(child)
740}
741
742// ---------------------------------------------------------------------
743// The nested-parser slot
744// ---------------------------------------------------------------------
745
746/// The live parser, published for the duration of a top-level parse so
747/// that a processor which re-parses its source uses the instance the
748/// document is being parsed by, plugins installed after this one
749/// included.
750///
751/// The canonical TypeScript closes over the instance, and a JavaScript
752/// closure sees every later change to it. A Rust callback cannot hold a
753/// borrow across a parse, so the instance is cloned once per top-level
754/// parse that could contain a reference at all, and nested parses reuse
755/// what the top-level parse published.
756#[derive(Default)]
757struct NestedParser {
758 current: Mutex<Option<Arc<Tabnas>>>,
759}
760
761impl NestedParser {
762 fn publish(&self, parser: &Tabnas) {
763 if let Ok(mut slot) = self.current.lock() {
764 *slot = Some(Arc::new(parser.clone()));
765 }
766 }
767
768 fn get(&self) -> Option<Arc<Tabnas>> {
769 self.current.lock().ok().and_then(|slot| slot.clone())
770 }
771}
772
773/// A raised diagnostic: its code and the detail bag its message and
774/// hint are rendered from.
775type Report = (String, Vec<(String, Value)>);
776
777/// The diagnostics this plugin has raised inside nested parses, so that
778/// an outer load can re-raise one unchanged.
779///
780/// In the canonical TypeScript a nested parse throws and the exception
781/// travels out untouched, so the caller reads the innermost report: the
782/// loop of a cycle, the search paths of a missing source. Here a nested
783/// parse RETURNS its error, whose rendered text an outer level can read
784/// but whose detail bag it cannot, so the bag is recorded as it is
785/// raised and taken again when the same code comes back.
786///
787/// Each nested load gets its OWN slot, keyed by a ticket the loading
788/// action mints and threads to the nested parse through its metadata.
789/// One slot per instance was not enough: this type is shared by every
790/// parse of an instance, and an instance is explicitly shareable
791/// between threads, so two parses failing at the same time overwrote
792/// each other and an error could come back naming the other document's
793/// path, search list or loop. The ticket also survives the segment
794/// thread `processor::parse_nested` runs a level on, which a
795/// thread-local slot would not.
796///
797/// A slot is TAKEN, not read, so a report is used once, and the loading
798/// action drops its ticket whether or not the load failed.
799#[derive(Default)]
800struct LastReport {
801 slots: Mutex<BTreeMap<String, Report>>,
802 next: std::sync::atomic::AtomicU64,
803}
804
805impl LastReport {
806 /// A ticket for one nested load, unique within this instance.
807 fn ticket(&self) -> String {
808 let count = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
809 format!("{count}")
810 }
811
812 fn record(&self, ticket: &str, code: &str, details: &[(String, Value)]) {
813 if let Ok(mut slots) = self.slots.lock() {
814 slots.insert(ticket.to_string(), (code.to_string(), details.to_vec()));
815 }
816 }
817
818 /// The report a nested parse left under `ticket`, if it carries the
819 /// code that came back. The slot is freed either way.
820 fn take(&self, ticket: &str, code: &str) -> Option<Vec<(String, Value)>> {
821 let mut slots = self.slots.lock().ok()?;
822 match slots.remove(ticket) {
823 Some((recorded, details)) if recorded == code => Some(details),
824 _ => None,
825 }
826 }
827
828 /// Drop a ticket whose load did not fail, so a slot cannot outlive
829 /// the parse that minted it.
830 fn discard(&self, ticket: &str) {
831 if let Ok(mut slots) = self.slots.lock() {
832 slots.remove(ticket);
833 }
834 }
835}
836
837/// The metadata key carrying the ticket a nested parse records its
838/// report under. The loading action mints it; the nested parse only
839/// reads it back.
840const REPORT_TICKET: &str = "report";
841
842// ---------------------------------------------------------------------
843// The plugin
844// ---------------------------------------------------------------------
845
846/// Build the plugin for `options`.
847///
848/// The returned [`Plugin`] installs through [`Tabnas::use_plugin`], so a
849/// derived instance rebuilds it. Typed option data lives in the returned
850/// closure rather than in the engine's serialized plugin-option bag,
851/// because a resolver and a processor are Rust callbacks and no
852/// [`Value`] can carry one.
853pub fn plugin_with(options: MultiSourceOptions) -> Plugin {
854 let options = Arc::new(normalize(options));
855 Plugin::new(PLUGIN_NAME, move |parser, _plugin_options| {
856 install(parser, Arc::clone(&options)).map_err(PluginError::from)
857 })
858}
859
860/// Build the plugin with default options: no sources, so every reference
861/// raises `multisource_not_found`.
862pub fn plugin() -> Plugin {
863 plugin_with(MultiSourceOptions::default())
864}
865
866/// Install the plugin on `parser`.
867///
868/// The convenience constructor mirroring `tn.use(MultiSource, options)`.
869/// The host grammar must already supply `val`, `map` and `pair`: install
870/// [`tabnas_jsonic`] first, or use [`make_with`].
871pub fn multisource(
872 parser: &mut Tabnas,
873 options: MultiSourceOptions,
874) -> Result<(), MultiSourceError> {
875 parser
876 .use_plugin(plugin_with(options), None)
877 .map(|_| ())
878 .map_err(MultiSourceError::from)
879}
880
881/// A registration failure: a host grammar without the rules the plugin
882/// modifies, a directive character already taken, or a grammar the
883/// engine refused.
884#[derive(Clone, Debug, PartialEq, Eq)]
885pub struct MultiSourceError(pub String);
886
887impl fmt::Display for MultiSourceError {
888 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
889 formatter.write_str(&self.0)
890 }
891}
892
893impl std::error::Error for MultiSourceError {}
894
895impl From<PluginError> for MultiSourceError {
896 fn from(error: PluginError) -> Self {
897 Self(error.0)
898 }
899}
900
901impl From<MultiSourceError> for PluginError {
902 fn from(error: MultiSourceError) -> Self {
903 Self(error.0)
904 }
905}
906
907/// Fill in what the plugin would otherwise have to guess at parse time.
908fn normalize(mut options: MultiSourceOptions) -> MultiSourceOptions {
909 if options.markchar.is_empty() {
910 options.markchar = DEFAULT_MARKCHAR.to_string();
911 }
912 for ext in &mut options.implicit_ext {
913 if !ext.starts_with('.') {
914 *ext = format!(".{ext}");
915 }
916 }
917 if options.max_depth == 0 {
918 options.max_depth = DEFAULT_MAX_DEPTH;
919 }
920 options
921}
922
923fn install(parser: &mut Tabnas, options: Arc<MultiSourceOptions>) -> Result<(), MultiSourceError> {
924 // The plugin modifies `val`, `map` and `pair`: it defines no value
925 // grammar of its own. Installing it on a bare engine would register
926 // a directive that can never match, so say so instead.
927 let rules = parser.rule_names();
928 for required in ["val", "map", "pair"] {
929 if !rules.iter().any(|name| name == required) {
930 return Err(MultiSourceError(format!(
931 "MultiSource needs a host grammar supplying the {required:?} rule: \
932 install tabnas_jsonic first, or use make_with"
933 )));
934 }
935 }
936
937 // One slot per install, so two instances never share a published
938 // parser, and a derived instance gets its own.
939 let nested = Arc::new(NestedParser::default());
940 let reports = Arc::new(LastReport::default());
941
942 parser
943 .set_options(|engine| {
944 engine.error.insert(
945 "multisource_not_found".to_string(),
946 "source not found: {path}".to_string(),
947 );
948 engine.error.insert(
949 "multisource_cycle".to_string(),
950 "source includes itself: {path}".to_string(),
951 );
952 engine.error.insert(
953 "multisource_depth".to_string(),
954 "source nesting is too deep: {path}".to_string(),
955 );
956 engine.hint.insert(
957 "multisource_not_found".to_string(),
958 "The source path {path} was not found.\n\nSearch paths:\n{searchstr}".to_string(),
959 );
960 engine.hint.insert(
961 "multisource_cycle".to_string(),
962 "Including {path} here would loop forever:\n\n{loop}\n\n\
963 A source may be included from more than one place, but it cannot \
964 be an ancestor of itself."
965 .to_string(),
966 );
967 engine.hint.insert(
968 "multisource_depth".to_string(),
969 "Loading {path} would nest sources more than {max} deep.\n\n\
970 Each source is loaded inside the parse that referenced it, so an \
971 unbounded chain would exhaust the stack. Raise max_depth if the \
972 chain is genuine."
973 .to_string(),
974 );
975 })
976 .map_err(|error| MultiSourceError(error.to_string()))?;
977
978 // Publish the live instance for nested parses, once per top-level
979 // parse of a document that could hold a reference at all. A nested
980 // parse carries `multisource.path` in its metadata and skips.
981 {
982 let options = Arc::clone(&options);
983 let nested = Arc::clone(&nested);
984 parser.parse_prepare_with_instance(move |instance, context, _meta| {
985 if !context.source.contains(options.markchar.as_str()) {
986 return;
987 }
988 if is_nested_meta(&context.meta) {
989 return;
990 }
991 nested.publish(instance);
992 });
993 }
994
995 let name = RULE_NAME.to_string();
996 let markchar = options.markchar.clone();
997 let action_options = Arc::clone(&options);
998 let action_nested = Arc::clone(&nested);
999 let action_reports = Arc::clone(&reports);
1000
1001 let directive = DirectiveOptions::new(name.clone(), markchar)
1002 .with_rules(
1003 RulesOption::new()
1004 .open_rule("val", RuleMod::new())
1005 // A `@` in key position only opens a directive while the
1006 // rule is not already diving into a key, which is what
1007 // `pk` counts.
1008 .open_rule("pair", RuleMod::when(|rule, _context| rule.lte("pk", 0))),
1009 )
1010 .with_token_action(move |rule, context| {
1011 directive_action(
1012 &action_options,
1013 &action_nested,
1014 &action_reports,
1015 rule,
1016 context,
1017 )
1018 })
1019 .with_custom(move |parser, config| {
1020 if let Err(error) = install_grammar(parser, &config.name) {
1021 // The custom hook cannot return, so a refusal here is a
1022 // programming error in this crate rather than a caller
1023 // mistake: the document below is a constant.
1024 panic!("MultiSource grammar: {error}");
1025 }
1026 });
1027
1028 tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
1029}
1030
1031/// The grammar that lets a reference stand where a value, a bare
1032/// top-level key, or a pair value can.
1033fn install_grammar(parser: &mut Tabnas, name: &str) -> Result<(), MultiSourceError> {
1034 let open_token = format!("#OD_{name}");
1035 let top_counter = format!("{name}_top");
1036
1037 // Back-track the mark up a path dive only when the rule is inside a
1038 // dive AND the mark is not already a pair's value. In a colon chain
1039 // (`a: b: @"f"`) the value-position `val` has `pk > 0` but its
1040 // parent IS the pair for that key, so this stays false and the load
1041 // lands under the key instead of unwinding to depth zero.
1042 parser.alt_condition("@ms-pk-val", |rule, _context| {
1043 rule.gt("pk", 0)
1044 && rule
1045 .parent_rule
1046 .as_ref()
1047 .map(|parent| parent.name.as_ref() != "pair")
1048 .unwrap_or(true)
1049 });
1050 parser.alt_condition("@ms-pk", |rule, _context| rule.gt("pk", 0));
1051 parser.alt_condition("@ms-top", |rule, _context| rule.d == 0);
1052 let counter = top_counter.clone();
1053 parser.alt_condition("@ms-top-map", move |rule, _context| {
1054 rule.d == 1 && rule.eq(&counter, 1)
1055 });
1056
1057 let document = json!({
1058 "rule": {
1059 "val": {
1060 "open": [
1061 { "s": open_token, "c": "@ms-pk-val", "b": 1 },
1062 {
1063 "s": open_token,
1064 "c": "@ms-top",
1065 "p": "map",
1066 "b": 1,
1067 "n": { top_counter.clone(): 1 },
1068 },
1069 ],
1070 },
1071 "map": {
1072 "open": [{
1073 "s": open_token,
1074 "c": "@ms-top-map",
1075 "p": "pair",
1076 "b": 1,
1077 // Allocate the implicit top-level map here. The core
1078 // only auto-allocates for `{`, so without this the
1079 // pushed `pair` is seeded with an undefined node and
1080 // a pair following a leading `@` has nowhere to go.
1081 // The action's merge writes into this same node.
1082 "a": "@object$",
1083 "k": { "object$": { "implicit": true } },
1084 }],
1085 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1086 },
1087 "pair": {
1088 "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1089 },
1090 },
1091 });
1092
1093 let spec =
1094 GrammarSpec::from_value(document).map_err(|error| MultiSourceError(error.to_string()))?;
1095 parser
1096 .grammar_with_setting(&spec, &GrammarSetting::groups(name))
1097 .map(|_| ())
1098 .map_err(|error| MultiSourceError(error.to_string()))
1099}
1100
1101// ---------------------------------------------------------------------
1102// The directive action
1103// ---------------------------------------------------------------------
1104
1105/// The reference a directive body names: a bare string, or an object
1106/// with a `path` key (`@{path:"a.jsonic"}`).
1107///
1108/// Neither the canonical nor this port requires the value to be a
1109/// string, so the coercion decides which source is named and has to be
1110/// the canonical one: `'' + spec.path`, whose rules are JavaScript's.
1111/// A number goes through [`format_number`]; a boolean is `true` or
1112/// `false`; a null is an absent path, which is what the canonical's
1113/// `null != spec.path` guard makes of it.
1114fn reference_of(value: &Value) -> Option<String> {
1115 match value {
1116 Value::Object(_) | Value::MapRef(_) => coerce_reference(meta_get(value, "path").as_ref()?),
1117 other => coerce_reference(other),
1118 }
1119}
1120
1121/// `'' + value` for the one value a directive body can carry.
1122fn coerce_reference(value: &Value) -> Option<String> {
1123 match value {
1124 Value::String(text) => Some(text.clone()),
1125 Value::Text(text) => Some(text.string.clone()),
1126 Value::Number(number) => Some(format_number(*number)),
1127 Value::Bool(flag) => Some(flag.to_string()),
1128 _ => None,
1129 }
1130}
1131
1132/// JavaScript's `Number::toString` (ECMA-262 6.1.6.1.20), which is what
1133/// the canonical `'' + spec.path` spells for a numeric reference, and so
1134/// what such a reference names.
1135///
1136/// Rust's own `f64` formatting differs from it in ways that reach a map
1137/// key. `number as i64` SATURATES, so every integral value above
1138/// `i64::MAX` became `9223372036854775807` and named the wrong source.
1139/// Plain `{}` keeps the sign of negative zero (`-0`, where JavaScript
1140/// says `0`) and never switches to exponent form, where JavaScript does
1141/// so at `1e21` and at `1e-7`.
1142///
1143/// The same implementation, for the same reason, is in `tabnas-csv` and
1144/// `tabnas-xml`; keep the three in step.
1145fn format_number(number: f64) -> String {
1146 if number.is_nan() {
1147 return "NaN".to_string();
1148 }
1149 // Catches -0.0 as well: JavaScript spells both zeros "0".
1150 if number == 0.0 {
1151 return "0".to_string();
1152 }
1153 if number < 0.0 {
1154 return format!("-{}", format_number(-number));
1155 }
1156 if number.is_infinite() {
1157 return "Infinity".to_string();
1158 }
1159
1160 // The specification wants the shortest digit string `s` that
1161 // round-trips (length `k`), and `n`, the position of the decimal
1162 // point relative to it. Rust's `{:e}` yields digits of exactly that
1163 // shortest length.
1164 let shortest = format!("{number:e}");
1165 let shortest_k = shortest
1166 .split_once('e')
1167 .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
1168 .expect("a finite f64 always formats with an exponent");
1169
1170 // Re-render to that same length to settle a tie. Where two digit
1171 // strings of length `k` are equally close to `number`, the
1172 // specification takes the one ending in an even digit; Rust's
1173 // shortest form does not, but its exactly-rounded fixed-precision
1174 // form does.
1175 let exponential = format!("{:.*e}", shortest_k - 1, number);
1176 let (mantissa, exponent) = exponential
1177 .split_once('e')
1178 .expect("a finite f64 always formats with an exponent");
1179 // Rounding can leave trailing zeros (and, on a carry, one digit too
1180 // many); dropping them keeps `s` shortest, which is what `k` means.
1181 let digits = mantissa
1182 .chars()
1183 .filter(|digit| *digit != '.')
1184 .collect::<String>();
1185 let digits = digits.trim_end_matches('0');
1186 let digits = if digits.is_empty() { "0" } else { digits };
1187 let k = digits.len() as i32;
1188 let n = exponent
1189 .parse::<i32>()
1190 .expect("a formatted exponent is an integer")
1191 + 1;
1192
1193 // The four cases of the specification, in its order. The range
1194 // bounds are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
1195 if (k..=21).contains(&n) {
1196 // Integral, with n - k trailing zeros to restore.
1197 let mut text = digits.to_string();
1198 text.push_str(&"0".repeat((n - k) as usize));
1199 text
1200 } else if (1..=21).contains(&n) {
1201 let point = n as usize;
1202 format!("{}.{}", &digits[..point], &digits[point..])
1203 } else if (-5..=0).contains(&n) {
1204 format!("0.{}{}", "0".repeat(-n as usize), digits)
1205 } else {
1206 // Exponent form. `n - 1` is never 0 here, so the sign is never
1207 // "+0".
1208 let sign = if n - 1 < 0 { '-' } else { '+' };
1209 let power = (n - 1).abs();
1210 if k == 1 {
1211 format!("{digits}e{sign}{power}")
1212 } else {
1213 format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
1214 }
1215 }
1216}
1217
1218/// The token a diagnostic is reported against: the enclosing rule's
1219/// opening token, as `rule.parent?.o0` names in TypeScript, then this
1220/// rule's own, then whatever the lexer is looking at.
1221fn error_token(rule: &Rule, context: &Context) -> Option<Token> {
1222 rule.parent_rule
1223 .as_ref()
1224 .and_then(|parent| parent.o.first())
1225 .or_else(|| rule.o.first())
1226 .cloned()
1227 .or_else(|| context.t0().cloned())
1228}
1229
1230fn fail(
1231 reports: &LastReport,
1232 rule: &Rule,
1233 context: &Context,
1234 code: &str,
1235 details: Vec<(String, Value)>,
1236) -> Result<Option<Token>, ActionError> {
1237 // Only a NESTED parse has a ticket, and only a nested report is
1238 // ever taken: a top-level failure is raised to the caller whole.
1239 if let Some(ticket) = meta_multisource_string(&context.meta, REPORT_TICKET) {
1240 reports.record(&ticket, code, &details);
1241 }
1242 match error_token(rule, context) {
1243 Some(mut token) => {
1244 token.bad_with_details(code, details);
1245 Ok(Some(token))
1246 }
1247 // No token to hang the report on, which the engine's own error
1248 // path still has to be told about.
1249 None => Err(ActionError::new(code, format!("[{code}]"))),
1250 }
1251}
1252
1253fn directive_action(
1254 options: &Arc<MultiSourceOptions>,
1255 nested: &Arc<NestedParser>,
1256 reports: &Arc<LastReport>,
1257 rule: &mut Rule,
1258 context: &mut Context,
1259) -> Result<Option<Token>, ActionError> {
1260 let from = rule
1261 .parent_rule
1262 .as_ref()
1263 .map(|parent| parent.name.to_string())
1264 .unwrap_or_default();
1265
1266 let reference = reference_of(&rule.child_node);
1267
1268 let mut resolution = {
1269 let input = ResolverInput {
1270 options,
1271 meta: &context.meta,
1272 };
1273 options.resolver.resolve(reference.as_deref(), &input)
1274 };
1275
1276 if !resolution.found {
1277 let mut search = resolution.search.clone();
1278 if search.is_empty() {
1279 if let Some(full) = &resolution.spec.full {
1280 search.push(full.clone());
1281 }
1282 }
1283 let named = resolution
1284 .spec
1285 .path
1286 .clone()
1287 .or_else(|| reference.clone())
1288 .unwrap_or_default();
1289 return fail(
1290 reports,
1291 rule,
1292 context,
1293 "multisource_not_found",
1294 vec![
1295 ("path".to_string(), Value::String(named)),
1296 (
1297 "full".to_string(),
1298 Value::String(resolution.spec.full.clone().unwrap_or_default()),
1299 ),
1300 ("searchstr".to_string(), Value::String(search.join("\n"))),
1301 ],
1302 );
1303 }
1304
1305 let fullpath = resolution.full_path();
1306
1307 if resolution.spec.kind.is_empty() {
1308 resolution.spec.kind = NONE.to_string();
1309 }
1310
1311 // Copy rather than extend in place: the inherited chain is shared
1312 // with every sibling include at this level, so mutating it would
1313 // make `parents` an accumulating visit log rather than the ancestor
1314 // chain, and the cycle check below would then fire on a diamond.
1315 let mut parents = meta_parents(&context.meta);
1316 if let Some(path) = meta_multisource_string(&context.meta, "path") {
1317 parents.push(path);
1318 }
1319
1320 // Cycle check. Without it, a -> b -> a recurses until the stack
1321 // overflows, with no source position and no indication of which
1322 // sources are at fault. Compared against the ancestor chain, so a
1323 // source included from two branches is reuse, not a cycle.
1324 if let Some(index) = parents.iter().position(|parent| parent == &fullpath) {
1325 let mut loop_path: Vec<String> = parents[index..].to_vec();
1326 loop_path.push(fullpath.clone());
1327 return fail(
1328 reports,
1329 rule,
1330 context,
1331 "multisource_cycle",
1332 vec![
1333 ("path".to_string(), Value::String(fullpath)),
1334 ("loop".to_string(), Value::String(loop_path.join(" -> "))),
1335 ],
1336 );
1337 }
1338
1339 // An acyclic chain can still be arbitrarily long, and each link runs
1340 // inside the parse that referenced it.
1341 if parents.len() >= options.max_depth {
1342 return fail(
1343 reports,
1344 rule,
1345 context,
1346 "multisource_depth",
1347 vec![
1348 ("path".to_string(), Value::String(fullpath)),
1349 ("max".to_string(), Value::Number(options.max_depth as f64)),
1350 ],
1351 );
1352 }
1353
1354 if let Some(deps) = &options.deps {
1355 let target = parents.last().cloned().unwrap_or_else(|| TOP.to_string());
1356 if let Ok(mut deps) = deps.lock() {
1357 deps.entry(target.clone()).or_default().insert(
1358 fullpath.clone(),
1359 Dependency {
1360 tar: target,
1361 src: fullpath.clone(),
1362 wen: now_millis(),
1363 },
1364 );
1365 }
1366 }
1367
1368 let dive = rule.k.get("path").cloned();
1369 let ticket = reports.ticket();
1370 let meta = child_meta(&context.meta, &resolution, &parents, dive.as_ref(), &ticket);
1371
1372 let Some(parser) = nested.get() else {
1373 // The prepare hook publishes the instance for every parse whose
1374 // source holds the mark character, and a directive cannot fire
1375 // on a source that does not, so this is unreachable rather than
1376 // a condition a document can provoke.
1377 return Err(ActionError::new(
1378 "internal",
1379 "MultiSource: no parser was published for the nested parse",
1380 ));
1381 };
1382
1383 if let Some(processor) = options.processor_for(&resolution.spec.kind) {
1384 let input = ProcessorInput {
1385 options,
1386 meta: &meta,
1387 parser: &parser,
1388 depth: parents.len(),
1389 };
1390 processor.process(&mut resolution, &input);
1391 }
1392
1393 if let Some(error) = resolution.err.take() {
1394 // A source resolved but failed to process, typically a nested
1395 // reference inside it. Re-raise the nested code rather than
1396 // silently substituting the raw source text.
1397 let code = if error.code.is_empty() {
1398 "unexpected".to_string()
1399 } else {
1400 error.code.clone()
1401 };
1402 // Re-raise the nested report as it was raised, so the caller
1403 // reads the loop of a cycle or the search paths of a missing
1404 // source rather than a summary of them, exactly as the
1405 // canonical TypeScript exception carries them out. The ticket
1406 // is what makes it THIS load's report and no other parse's.
1407 let details = reports.take(&ticket, &code).unwrap_or_else(|| {
1408 vec![
1409 ("path".to_string(), Value::String(fullpath)),
1410 ("searchstr".to_string(), Value::String(error.detail.clone())),
1411 ]
1412 });
1413 return fail(reports, rule, context, &code, details);
1414 }
1415
1416 // The load succeeded, so nothing will ever ask for its slot.
1417 reports.discard(&ticket);
1418
1419 let value = std::mem::replace(&mut resolution.val, Value::Undefined);
1420
1421 if from == "pair" {
1422 splice_into_parent(rule, context, value);
1423 } else {
1424 set_node(rule, value);
1425 }
1426
1427 Ok(None)
1428}
1429
1430fn now_millis() -> u64 {
1431 SystemTime::now()
1432 .duration_since(UNIX_EPOCH)
1433 .map(|since| since.as_millis() as u64)
1434 .unwrap_or(0)
1435}
1436
1437/// Merge a loaded map into the enclosing map, for the `{@foo}` form.
1438///
1439/// TypeScript assigns the merged object back to `rule.parent.parent.node`
1440/// and its `deep` mutates the base in place, so the enclosing map keeps
1441/// its identity and a pair that follows the directive writes into the
1442/// same node. A Rust rule reaches its grandparent only through a
1443/// snapshot, which cannot be assigned to, so the merge is written
1444/// through the shared node cell instead. The cell is the same one, so
1445/// the identity the following pair depends on is preserved.
1446fn splice_into_parent(rule: &mut Rule, context: &mut Context, value: Value) {
1447 let Some(target) = rule
1448 .parent_rule
1449 .as_ref()
1450 .and_then(|parent| parent.parent_rule.as_ref())
1451 .map(|grandparent| grandparent.node.clone())
1452 else {
1453 return;
1454 };
1455
1456 let merge = context.options.map.merge.clone();
1457 let extend = context.options.map.extend;
1458
1459 if let Some(merge) = merge {
1460 let base = target.borrow().clone();
1461 let merged = merge(base, value, rule, context);
1462 *target.borrow_mut() = merged;
1463 return;
1464 }
1465
1466 if extend {
1467 let base = target.borrow().clone();
1468 let merged = tabnas_jsonic::deep_merge(base, value);
1469 *target.borrow_mut() = merged;
1470 return;
1471 }
1472
1473 // `Object.assign`: a shallow per-key overwrite.
1474 let Some(entries) = object_entries(&value) else {
1475 return;
1476 };
1477 let mut node = target.borrow_mut();
1478 match &mut *node {
1479 Value::Object(map) => {
1480 let map = Arc::make_mut(map);
1481 for (key, item) in entries {
1482 map.insert(key, item);
1483 }
1484 }
1485 Value::MapRef(map) => {
1486 let map = Arc::make_mut(map);
1487 for (key, item) in entries {
1488 map.value.insert(key, item);
1489 }
1490 }
1491 _ => {}
1492 }
1493}
1494
1495fn object_entries(value: &Value) -> Option<Vec<(String, Value)>> {
1496 match value {
1497 Value::Object(map) => Some(
1498 map.iter()
1499 .map(|(key, item)| (key.clone(), item.clone()))
1500 .collect(),
1501 ),
1502 Value::MapRef(map) => Some(
1503 map.value
1504 .iter()
1505 .map(|(key, item)| (key.clone(), item.clone()))
1506 .collect(),
1507 ),
1508 _ => None,
1509 }
1510}
1511
1512// ---------------------------------------------------------------------
1513// Convenience constructors
1514// ---------------------------------------------------------------------
1515
1516/// A jsonic parser with the plugin installed over `options`.
1517pub fn make_with(options: MultiSourceOptions) -> Tabnas {
1518 let mut parser = tabnas_jsonic::make();
1519 multisource(&mut parser, options).expect("the MultiSource plugin installs on jsonic");
1520 parser
1521}
1522
1523/// A jsonic parser with the plugin installed over default options: no
1524/// sources, so every reference raises `multisource_not_found`.
1525pub fn make() -> Tabnas {
1526 make_with(MultiSourceOptions::default())
1527}
1528
1529/// Parse `src` with `options`.
1530///
1531/// Every call builds an instance. Building the grammar dominates a
1532/// parse, so a loop should call [`make_with`] once and reuse the
1533/// instance; `tests/perf_test.rs` measures the difference.
1534pub fn parse(src: &str, options: MultiSourceOptions) -> Result<Value, TabnasError> {
1535 make_with(options).parse(src)
1536}
1537
1538#[cfg(doctest)]
1539#[doc = include_str!("../README.md")]
1540mod readme_examples {}