Skip to main content

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.
6//!
7//! A directive character (`@` by default) marks a reference in the
8//! input. The plugin **resolves** the reference to a source, **processes**
9//! that source into a value, and splices the value into the output,
10//! recursively, so a loaded source can reference more sources.
11//!
12//! The plugin defines no value grammar of its own. It installs on a host
13//! grammar the caller builds, which must supply the `val`, `map` and
14//! `pair` rules: the [jsonic](https://github.com/tabnas/jsonic)
15//! relaxed-JSON grammar, for example.
16//!
17//! ```
18//! use tabnas_multisource::{multisource, MapResolver, MultiSourceOptions};
19//!
20//! fn main() -> Result<(), Box<dyn std::error::Error>> {
21//!     let mut parser = tabnas_jsonic::make();
22//!     let sources = MapResolver::from([("a.jsonic", "a:1")]);
23//!     multisource(&mut parser, MultiSourceOptions::new(sources))?;
24//!     assert_eq!(parser.parse(r#"@"a.jsonic" b:2"#)?.to_string(), r#"{"a":1,"b":2}"#);
25//!     Ok(())
26//! }
27//! ```
28//!
29//! No JSON reader ships with the plugin either. A `.json` source is raw
30//! text, as any kind without a processor is, until the caller registers
31//! a processor for the `json` kind with
32//! [`MultiSourceOptions::with_processor`].
33//!
34//! TypeScript is canonical: `ts/src/multisource.ts` defines behaviour,
35//! option names and defaults. The shared fixtures in `test/spec/*.tsv`
36//! are the parity contract across TypeScript, Go and Rust. Differences
37//! are recorded in `DIVERGENCE.md` at the repository root.
38//!
39//! # Untrusted input
40//!
41//! Following `@` references is this plugin's whole job, which is exactly
42//! why the boundary matters. A reference reaches only what the configured
43//! [`Resolver`] can see, so the resolver is the sandbox:
44//!
45//! - [`MapResolver`] and a [`FileResolver`] over a [`MapFs`] touch no
46//!   disk at all.
47//! - [`FileResolver::with_root`] confines every candidate path to one
48//!   directory, so `@"../../etc/passwd"` resolves to nothing rather than
49//!   to a file. The root and the candidate are both resolved through the
50//!   filesystem before they are compared, so a symbolic link inside the
51//!   root is judged by where it points; a link created between that
52//!   check and the read is beyond what a resolver can see.
53//! - A cycle between sources raises `multisource_cycle`, and a chain
54//!   longer than [`MultiSourceOptions::max_depth`] raises
55//!   `multisource_depth`, so neither hangs nor overflows the stack.
56//!
57//! A loaded value is still data, never instructions, and splicing is not
58//! sanitising: escaping for SQL, HTML or a shell remains the caller's job.
59
60#![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
86/// VERSION is this crate's version. It MUST equal `ts/package.json`
87/// "version" and the `version` field in `rs/Cargo.toml`: the release
88/// orchestrator rewrites all of them, and `tests/version_test.rs` fails
89/// the build if they drift. Mirrors `VERSION` in `ts/src/multisource.ts`
90/// and `const VERSION` in `go/multisource.go`.
91pub const VERSION: &str = "0.6.4";
92
93/// An unknown or missing source-reference extension.
94pub const NONE: &str = "";
95
96/// The top of the dependency tree: the [`DependencyMap`] target key used
97/// for sources referenced directly by the top-level parse.
98///
99/// The TypeScript export is a `Symbol`, which Rust has no counterpart
100/// for, so this mirrors the Go port's sentinel. The leading NUL byte
101/// guarantees it cannot collide with a real source path.
102pub const TOP: &str = "\0TOP";
103
104/// The plugin name, as the engine records it.
105pub const PLUGIN_NAME: &str = "MultiSource";
106
107/// The rule and directive this plugin installs.
108pub const RULE_NAME: &str = "multisource";
109
110/// The default directive character.
111pub const DEFAULT_MARKCHAR: &str = "@";
112
113/// How deep a chain of sources may nest before the parse is failed.
114///
115/// Each nested source is parsed inside the parse that referenced it, so
116/// the chain runs on the call stack. Without a cap a chain of a few
117/// thousand sources with no cycle in it overflows that stack and aborts
118/// the process, which is why this is a cap rather than a note. See
119/// `DIVERGENCE.md`.
120pub const DEFAULT_MAX_DEPTH: usize = 64;
121
122// ---------------------------------------------------------------------
123// Path specs and resolutions
124// ---------------------------------------------------------------------
125
126/// The path to a source, including the base prefix when there is one.
127#[derive(Clone, Debug, Default, PartialEq, Eq)]
128pub struct PathSpec {
129    /// The source kind, normally the extension of the last path segment.
130    pub kind: String,
131    /// The reference exactly as written, which may be relative.
132    pub path: Option<String>,
133    /// The normalized full path.
134    pub full: Option<String>,
135    /// The base the reference resolved against.
136    pub base: String,
137    /// Whether the reference was absolute.
138    pub abs: bool,
139}
140
141/// A source and where it was found.
142#[derive(Clone, Debug)]
143pub struct Resolution {
144    /// The normalized path, rewritten by the resolver when an implicit
145    /// extension or an index file matched.
146    pub spec: PathSpec,
147    /// The source text. `None` when nothing was found.
148    pub src: Option<String>,
149    /// The processed value, filled by a [`Processor`].
150    pub val: Value,
151    /// Whether a source was found.
152    pub found: bool,
153    /// Every path that was tried, for the not-found report.
154    pub search: Vec<String>,
155    /// A failure while PROCESSING found source, for example a nested
156    /// reference inside it that could not be resolved. The plugin
157    /// propagates it so the parse fails, matching TypeScript, which lets
158    /// a nested parse error escape rather than substituting raw text.
159    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    /// A resolution that found nothing, for the spec it was built from.
170    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    /// A resolution that found `src` at `full`.
182    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    /// Record the paths that were searched.
197    pub fn with_search(mut self, search: Vec<String>) -> Self {
198        self.search = search;
199        self
200    }
201
202    /// The path this resolution is known by: the normalized full path,
203    /// else the reference as written, else `no-path`. Mirrors the
204    /// TypeScript `fullpath` fallback chain.
205    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/// What a [`Resolver`] is given: the plugin options and the parse
215/// metadata for the enclosing source.
216///
217/// The canonical TypeScript hands a resolver the whole parse `Context`,
218/// of which resolvers read only `ctx.meta`. Narrowing it to the metadata
219/// keeps a resolver callable, and therefore testable, outside a parse.
220#[derive(Clone, Copy)]
221pub struct ResolverInput<'a> {
222    /// The plugin options in force for this parse.
223    pub options: &'a MultiSourceOptions,
224    /// The parse metadata. `multisource.path` names the source that
225    /// contains this reference, when there is one.
226    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    /// The full path of the source that contains this reference, when
240    /// the reference was found inside another source.
241    pub fn source_path(&self) -> Option<String> {
242        meta_multisource_string(self.meta, "path")
243    }
244}
245
246/// Find the source content a reference names.
247///
248/// Implementations must be `Send + Sync`: a `Tabnas` instance parses
249/// through `&self`, so the plugin, its options and every callback they
250/// hold are shared across threads. Nothing is held in global state, so
251/// two parsers configured differently never see each other's sources.
252pub trait Resolver: Send + Sync {
253    /// Resolve `reference` to a [`Resolution`]. A reference that names
254    /// nothing returns [`Resolution::not_found`]; raising the error is
255    /// the plugin's job, not the resolver's.
256    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
268/// A shared resolver handle.
269pub type SharedResolver = Arc<dyn Resolver>;
270
271// ---------------------------------------------------------------------
272// Dependencies
273// ---------------------------------------------------------------------
274
275/// One record that target `tar` pulled in source `src` during a parse.
276#[derive(Clone, Debug, PartialEq, Eq)]
277pub struct Dependency {
278    /// The target that depends on the source; [`TOP`] at the top level.
279    pub tar: String,
280    /// The source the target depends on.
281    pub src: String,
282    /// When the source resolved, in Unix milliseconds.
283    pub wen: u64,
284}
285
286/// A flattened dependency tree, keyed by target full path and then by
287/// source full path.
288///
289/// The TypeScript plugin fills an object the caller passes in the parse
290/// metadata. A Rust parse metadata value cannot be written back to, so
291/// the sink is a typed option instead:
292/// [`MultiSourceOptions::with_deps`].
293pub type DependencyMap = BTreeMap<String, BTreeMap<String, Dependency>>;
294
295// ---------------------------------------------------------------------
296// Options
297// ---------------------------------------------------------------------
298
299/// How one source kind becomes a value.
300#[derive(Clone)]
301pub enum ProcessorEntry {
302    /// A processor callback.
303    Call(Arc<dyn Processor>),
304    /// Another kind's processor, by name. One level of aliasing, as in
305    /// the canonical TypeScript, where a processor entry may be a string
306    /// naming another kind.
307    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/// Configuration for the plugin.
320#[derive(Clone)]
321pub struct MultiSourceOptions {
322    /// Resolves a reference to a source.
323    pub resolver: SharedResolver,
324    /// The base path references resolve against at the top level.
325    pub path: String,
326    /// The character that starts a reference.
327    pub markchar: String,
328    /// Per-kind processors. The empty kind is the fallback.
329    pub processor: IndexMap<String, ProcessorEntry>,
330    /// Extensions tried for a reference with none, in order.
331    pub implicit_ext: Vec<String>,
332    /// A declarative record of a folder preload. As in TypeScript and
333    /// Go, the plugin does not consume it: call [`preload_files`] and
334    /// hand the result to [`FileResolver::with_preload`].
335    pub preload: Option<PreloadOptions>,
336    /// The filesystem the `file` and `pkg` resolvers read, when they
337    /// carry none of their own. `None` is the real filesystem.
338    ///
339    /// This is the Rust spelling of the TypeScript `ctx.meta.fs`
340    /// injection point and of Go's `MultiSourceOptions.FS`.
341    pub fs: Option<SharedFs>,
342    /// Where to record the `tar` to `src` dependency tree, when the
343    /// caller wants one.
344    pub deps: Option<Arc<Mutex<DependencyMap>>>,
345    /// How deep a chain of sources may nest. See [`DEFAULT_MAX_DEPTH`].
346    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    /// Options resolving through `resolver`, everything else default.
373    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    /// Options resolving through an already shared resolver.
388    pub fn with_resolver(mut self, resolver: SharedResolver) -> Self {
389        self.resolver = resolver;
390        self
391    }
392
393    /// Set the base path references resolve against.
394    pub fn with_path(mut self, path: impl Into<String>) -> Self {
395        self.path = path.into();
396        self
397    }
398
399    /// Set the directive character.
400    pub fn with_markchar(mut self, markchar: impl Into<String>) -> Self {
401        self.markchar = markchar.into();
402        self
403    }
404
405    /// Register a processor for one kind, replacing any entry for it.
406    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    /// Point one kind at another kind's processor.
417    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    /// Replace the whole processor table.
428    pub fn with_processors(mut self, processors: IndexMap<String, ProcessorEntry>) -> Self {
429        self.processor = processors;
430        self
431    }
432
433    /// Replace the implicit extension list. A missing leading dot is
434    /// added, as the TypeScript plugin does when it installs.
435    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    /// Record a preload configuration. The plugin does not act on it.
448    pub fn with_preload(mut self, preload: PreloadOptions) -> Self {
449        self.preload = Some(preload);
450        self
451    }
452
453    /// Set the filesystem the file and pkg resolvers read.
454    pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
455        self.fs = Some(Arc::new(filesystem));
456        self
457    }
458
459    /// Set the filesystem from an already shared handle.
460    pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
461        self.fs = Some(filesystem);
462        self
463    }
464
465    /// Collect the dependency tree into `deps` as the parse runs.
466    pub fn with_deps(mut self, deps: Arc<Mutex<DependencyMap>>) -> Self {
467        self.deps = Some(deps);
468        self
469    }
470
471    /// Set how deep a chain of sources may nest.
472    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
473        self.max_depth = max_depth;
474        self
475    }
476
477    /// The processor for `kind`, resolving one level of aliasing and
478    /// falling back to the [`NONE`] entry, as `getProcessor` does.
479    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                // An alias to an alias is one level too many, exactly as
489                // in TypeScript, where the second lookup yields a string
490                // and nothing callable comes back.
491                _ => fallback,
492            },
493            None => fallback,
494        }
495    }
496}
497
498/// The default processor table: raw text for an unknown kind, and a
499/// re-parse with the live engine for `jsonic` and `jsc`.
500///
501/// There is no `json` entry. A `.json` source is raw text, as any kind
502/// without a processor is, until the caller registers one with
503/// [`MultiSourceOptions::with_processor`], built with the JSON parser of
504/// its choice.
505pub 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
522/// The default implicit extensions.
523///
524/// `.json` stays in the list although no `json` processor is registered
525/// by default: an extensionless reference still finds a `.json` file, and
526/// the processor the caller registers for that kind, if any, reads it.
527///
528/// `.js` is deliberately absent: the TypeScript `js` kind `require`s,
529/// which is to say executes, the module, and Rust has no JavaScript
530/// runtime to do that in. The Go port leaves it out for the same reason.
531/// See `DIVERGENCE.md`.
532pub 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
548// ---------------------------------------------------------------------
549// Path helpers
550// ---------------------------------------------------------------------
551
552/// The source kind: the extension of the LAST path segment, without the
553/// dot, or [`NONE`] when that segment has no dot.
554///
555/// It must be segment-scoped. Matching the whole path makes a dot in a
556/// parent folder (`a.d/foo`) produce a kind that is not [`NONE`], so the
557/// implicit-extension search is skipped and an extensionless reference
558/// under a dotted folder is wrongly reported as missing.
559pub 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
573/// Normalize a reference into a [`PathSpec`] against `base`.
574///
575/// The counterpart of the TypeScript `resolvePathSpec` and Go's
576/// `ResolvePathSpec`. An absolute reference ignores the base: one that
577/// starts with a slash, a backslash or a drive root.
578pub 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
602/// Whether `path` starts at a drive root, `C:\` or `C:/`, which makes it
603/// absolute on any platform. `C:x` is relative to the drive's working
604/// folder. The counterpart of the TypeScript `isDriveAbsolute`.
605fn is_drive_absolute(path: &str) -> bool {
606    matches!(path.as_bytes(), [drive, b':', b'/' | b'\\', ..] if drive.is_ascii_alphabetic())
607}
608
609/// Every path a reference could name: the path itself, then the implicit
610/// extensions, then a folder index file, then a folder index file that
611/// repeats the folder name.
612///
613/// Whether a reference already has an extension is a property of its LAST
614/// segment, not of the whole path, for the reason [`ext_kind`] gives.
615pub 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
641/// The directory a relative reference inside `path` resolves against.
642///
643/// A path with no separator (an in-memory key such as `a.jsonic`) yields
644/// the empty string, so a bare nested reference resolves plainly; a
645/// separator at index zero yields the root separator. Mirrors Go's
646/// `sourceDir` and the TypeScript mem resolver's `resolvefolder`.
647pub 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
656// ---------------------------------------------------------------------
657// Parse metadata
658// ---------------------------------------------------------------------
659
660fn 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
680/// Was this metadata built by [`child_meta`], rather than handed in by
681/// a caller?
682fn 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
703/// The key marking metadata this plugin built for a nested parse.
704///
705/// The prepare hook needs to tell a nested parse from a top-level one,
706/// and `multisource.path` cannot do it: a caller may legitimately set
707/// that at the top level to choose the base a relative reference
708/// resolves against, exactly as the canonical TypeScript tests do.
709const NESTED_MARK: &str = "nested";
710
711/// The metadata a nested parse gets: the parent's metadata with the
712/// multisource entry updated to name this source and its ancestors.
713/// Mirrors the TypeScript action's `meta` construction and Go's
714/// `childMeta`; the parent metadata is never mutated.
715fn 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    // The slot this nested parse records a diagnostic under, so the
742    // load below reads back its own report and no other parse's.
743    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    // The path-diving plugin reads `meta.path.base` to seed the path of
751    // the root value. Carrying the current dive down means a reference
752    // that lands at a dived key keeps its place in the tree.
753    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// ---------------------------------------------------------------------
763// The nested-parser slot
764// ---------------------------------------------------------------------
765
766/// The live parser, published for the duration of a top-level parse so
767/// that a processor which re-parses its source uses the instance the
768/// document is being parsed by, plugins installed after this one
769/// included.
770///
771/// The canonical TypeScript closes over the instance, and a JavaScript
772/// closure sees every later change to it. A Rust callback cannot hold a
773/// borrow across a parse, so the instance is cloned once per top-level
774/// parse that could contain a reference at all, and nested parses reuse
775/// what the top-level parse published.
776#[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
793/// A raised diagnostic: its code and the detail bag its message and
794/// hint are rendered from.
795type Report = (String, Vec<(String, Value)>);
796
797/// The diagnostics this plugin has raised inside nested parses, so that
798/// an outer load can re-raise one unchanged.
799///
800/// In the canonical TypeScript a nested parse throws and the exception
801/// travels out untouched, so the caller reads the innermost report: the
802/// loop of a cycle, the search paths of a missing source. Here a nested
803/// parse RETURNS its error, whose rendered text an outer level can read
804/// but whose detail bag it cannot, so the bag is recorded as it is
805/// raised and taken again when the same code comes back.
806///
807/// Each nested load gets its OWN slot, keyed by a ticket the loading
808/// action mints and threads to the nested parse through its metadata.
809/// One slot per instance was not enough: this type is shared by every
810/// parse of an instance, and an instance is explicitly shareable
811/// between threads, so two parses failing at the same time overwrote
812/// each other and an error could come back naming the other document's
813/// path, search list or loop. The ticket also survives the segment
814/// thread `processor::parse_nested` runs a level on, which a
815/// thread-local slot would not.
816///
817/// A slot is TAKEN, not read, so a report is used once, and the loading
818/// action drops its ticket whether or not the load failed.
819#[derive(Default)]
820struct LastReport {
821    slots: Mutex<BTreeMap<String, Report>>,
822    next: std::sync::atomic::AtomicU64,
823}
824
825impl LastReport {
826    /// A ticket for one nested load, unique within this instance.
827    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    /// The report a nested parse left under `ticket`, if it carries the
839    /// code that came back. The slot is freed either way.
840    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    /// Drop a ticket whose load did not fail, so a slot cannot outlive
849    /// the parse that minted it.
850    fn discard(&self, ticket: &str) {
851        if let Ok(mut slots) = self.slots.lock() {
852            slots.remove(ticket);
853        }
854    }
855}
856
857/// The metadata key carrying the ticket a nested parse records its
858/// report under. The loading action mints it; the nested parse only
859/// reads it back.
860const REPORT_TICKET: &str = "report";
861
862// ---------------------------------------------------------------------
863// The plugin
864// ---------------------------------------------------------------------
865
866/// Build the plugin for `options`.
867///
868/// The returned [`Plugin`] installs through [`Tabnas::use_plugin`], so a
869/// derived instance rebuilds it. Typed option data lives in the returned
870/// closure rather than in the engine's serialized plugin-option bag,
871/// because a resolver and a processor are Rust callbacks and no
872/// [`Value`] can carry one.
873pub 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
880/// Build the plugin with default options: no sources, so every reference
881/// raises `multisource_not_found`.
882pub fn plugin() -> Plugin {
883    plugin_with(MultiSourceOptions::default())
884}
885
886/// Install the plugin on `parser`.
887///
888/// The convenience constructor mirroring `tn.use(MultiSource, options)`.
889/// The host grammar must already supply the `val`, `map` and `pair` rules
890/// (a jsonic parser does, for example), or this returns an error rather
891/// than registering a directive that could never match.
892pub 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/// A registration failure: a host grammar without the rules the plugin
903/// modifies, a directive character already taken, or a grammar the
904/// engine refused.
905#[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
928/// Fill in what the plugin would otherwise have to guess at parse time.
929fn 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    // The plugin modifies `val`, `map` and `pair`: it defines no value
946    // grammar of its own. Installing it on a bare engine would register
947    // a directive that can never match, so say so instead.
948    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    // One slot per install, so two instances never share a published
960    // parser, and a derived instance gets its own.
961    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    // Publish the live instance for nested parses, once per top-level
1001    // parse of a document that could hold a reference at all. A nested
1002    // parse carries `multisource.path` in its metadata and skips.
1003    {
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                // A `@` in key position only opens a directive while the
1028                // rule is not already diving into a key, which is what
1029                // `pk` counts.
1030                .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                // The custom hook cannot return, so a refusal here is a
1044                // programming error in this crate rather than a caller
1045                // mistake: the document below is a constant.
1046                panic!("MultiSource grammar: {error}");
1047            }
1048        });
1049
1050    tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
1051}
1052
1053/// The grammar that lets a reference stand where a value, a bare
1054/// top-level key, or a pair value can.
1055fn 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    // Back-track the mark up a path dive only when the rule is inside a
1060    // dive AND the mark is not already a pair's value. In a colon chain
1061    // (`a: b: @"f"`) the value-position `val` has `pk > 0` but its
1062    // parent IS the pair for that key, so this stays false and the load
1063    // lands under the key instead of unwinding to depth zero.
1064    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                    // Allocate the implicit top-level map here. The core
1100                    // only auto-allocates for `{`, so without this the
1101                    // pushed `pair` is seeded with an undefined node and
1102                    // a pair following a leading `@` has nowhere to go.
1103                    // The action's merge writes into this same node.
1104                    "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
1123// ---------------------------------------------------------------------
1124// The directive action
1125// ---------------------------------------------------------------------
1126
1127/// The reference a directive body names: a bare string, or an object
1128/// with a `path` key (`@{path:"a.jsonic"}`).
1129///
1130/// Neither the canonical nor this port requires the value to be a
1131/// string, so the coercion decides which source is named and has to be
1132/// the canonical one: `'' + spec.path`, whose rules are JavaScript's.
1133/// A number goes through [`format_number`]; a boolean is `true` or
1134/// `false`; a null is an absent path, which is what the canonical's
1135/// `null != spec.path` guard makes of it.
1136fn 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
1143/// `'' + value` for the one value a directive body can carry.
1144fn 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
1154/// JavaScript's `Number::toString` (ECMA-262 6.1.6.1.20), which is what
1155/// the canonical `'' + spec.path` spells for a numeric reference, and so
1156/// what such a reference names.
1157///
1158/// Rust's own `f64` formatting differs from it in ways that reach a map
1159/// key. `number as i64` SATURATES, so every integral value above
1160/// `i64::MAX` became `9223372036854775807` and named the wrong source.
1161/// Plain `{}` keeps the sign of negative zero (`-0`, where JavaScript
1162/// says `0`) and never switches to exponent form, where JavaScript does
1163/// so at `1e21` and at `1e-7`.
1164///
1165/// The same implementation, for the same reason, is in `tabnas-csv` and
1166/// `tabnas-xml`; keep the three in step.
1167fn format_number(number: f64) -> String {
1168    if number.is_nan() {
1169        return "NaN".to_string();
1170    }
1171    // Catches -0.0 as well: JavaScript spells both zeros "0".
1172    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    // The specification wants the shortest digit string `s` that
1183    // round-trips (length `k`), and `n`, the position of the decimal
1184    // point relative to it. Rust's `{:e}` yields digits of exactly that
1185    // shortest length.
1186    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    // Re-render to that same length to settle a tie. Where two digit
1193    // strings of length `k` are equally close to `number`, the
1194    // specification takes the one ending in an even digit; Rust's
1195    // shortest form does not, but its exactly-rounded fixed-precision
1196    // form does.
1197    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    // Rounding can leave trailing zeros (and, on a carry, one digit too
1202    // many); dropping them keeps `s` shortest, which is what `k` means.
1203    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    // The four cases of the specification, in its order. The range
1216    // bounds are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
1217    if (k..=21).contains(&n) {
1218        // Integral, with n - k trailing zeros to restore.
1219        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        // Exponent form. `n - 1` is never 0 here, so the sign is never
1229        // "+0".
1230        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
1240/// The token a diagnostic is reported against: the enclosing rule's
1241/// opening token, as `rule.parent?.o0` names in TypeScript, then this
1242/// rule's own, then whatever the lexer is looking at.
1243fn 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    // Only a NESTED parse has a ticket, and only a nested report is
1260    // ever taken: a top-level failure is raised to the caller whole.
1261    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        // No token to hang the report on, which the engine's own error
1270        // path still has to be told about.
1271        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    // Copy rather than extend in place: the inherited chain is shared
1334    // with every sibling include at this level, so mutating it would
1335    // make `parents` an accumulating visit log rather than the ancestor
1336    // chain, and the cycle check below would then fire on a diamond.
1337    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    // Cycle check. Without it, a -> b -> a recurses until the stack
1343    // overflows, with no source position and no indication of which
1344    // sources are at fault. Compared against the ancestor chain, so a
1345    // source included from two branches is reuse, not a cycle.
1346    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    // An acyclic chain can still be arbitrarily long, and each link runs
1362    // inside the parse that referenced it.
1363    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        // The prepare hook publishes the instance for every parse whose
1396        // source holds the mark character, and a directive cannot fire
1397        // on a source that does not, so this is unreachable rather than
1398        // a condition a document can provoke.
1399        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        // A source resolved but failed to process, typically a nested
1417        // reference inside it. Re-raise the nested code rather than
1418        // silently substituting the raw source text.
1419        let code = if error.code.is_empty() {
1420            "unexpected".to_string()
1421        } else {
1422            error.code.clone()
1423        };
1424        // Re-raise the nested report as it was raised, so the caller
1425        // reads the loop of a cycle or the search paths of a missing
1426        // source rather than a summary of them, exactly as the
1427        // canonical TypeScript exception carries them out. The ticket
1428        // is what makes it THIS load's report and no other parse's.
1429        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    // The load succeeded, so nothing will ever ask for its slot.
1439    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
1459/// Merge a loaded map into the enclosing map, for the `{@foo}` form.
1460///
1461/// TypeScript assigns the merged object back to `rule.parent.parent.node`
1462/// and its `deep` mutates the base in place, so the enclosing map keeps
1463/// its identity and a pair that follows the directive writes into the
1464/// same node. A Rust rule reaches its grandparent only through a
1465/// snapshot, which cannot be assigned to, so the merge is written
1466/// through the shared node cell instead. The cell is the same one, so
1467/// the identity the following pair depends on is preserved.
1468fn 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    // `Object.assign`: a shallow per-key overwrite.
1496    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
1534/// Recursively merge `overlay` into `base`, for the `map.extend` splice:
1535/// objects by key, arrays by index, and anything else replaced by the
1536/// overlay. The base keeps its container kind, so a `MapRef` stays a
1537/// `MapRef` with its metadata, and a `ListRef` a `ListRef`. The
1538/// prototype-pollution guard of the TypeScript `deep()` utility is kept:
1539/// `__proto__`, `constructor` and `prototype` keys of the overlay are
1540/// skipped.
1541///
1542/// Ported from `deep_merge` in `tabnas-jsonic` (`jsonic/rs/src/lib.rs`),
1543/// itself the port of the `deep()` the TypeScript grammar merges with, so
1544/// that the plugin needs no grammar crate at run time. The engine's
1545/// `tabnas::utility::deep` is not a substitute: it merges `serde_json`
1546/// values, not the engine's native [`Value`], and would lose the
1547/// container metadata.
1548fn 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
1618/// The value behind a shared container, copied only when another holder
1619/// still shares it.
1620fn 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    /// The splice under `map.extend` is the jsonic `deep_merge` this port
1642    /// replaces, so the two must agree on every shape it can be handed.
1643    #[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    /// The base keeps its container kind and its metadata: a `MapRef`
1683    /// overlaid with a plain object is still that `MapRef`.
1684    #[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 {}