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.0";
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.
577pub fn resolve_path_spec(reference: Option<&str>, base: &str) -> PathSpec {
578    let path = reference.map(str::to_string);
579    let abs = path
580        .as_deref()
581        .map(|path| path.starts_with('/') || path.starts_with('\\'))
582        .unwrap_or(false);
583    let full = match path.as_deref() {
584        Some(path) if abs => Some(path.to_string()),
585        Some(path) if !path.is_empty() => Some(if base.is_empty() {
586            path.to_string()
587        } else {
588            format!("{base}/{path}")
589        }),
590        _ => None,
591    };
592    PathSpec {
593        kind: ext_kind(full.as_deref()),
594        path,
595        full,
596        base: base.to_string(),
597        abs,
598    }
599}
600
601/// Every path a reference could name: the path itself, then the implicit
602/// extensions, then a folder index file, then a folder index file that
603/// repeats the folder name.
604///
605/// Whether a reference already has an extension is a property of its LAST
606/// segment, not of the whole path, for the reason [`ext_kind`] gives.
607pub fn build_potentials(full: &str, implicit_ext: &[String]) -> Vec<String> {
608    if full.is_empty() {
609        return Vec::new();
610    }
611    let mut potentials = vec![full.to_string()];
612    let segment = match full.rfind(['/', '\\']) {
613        Some(index) => &full[index + 1..],
614        None => full,
615    };
616    if segment.contains('.') {
617        return potentials;
618    }
619    for ext in implicit_ext {
620        potentials.push(format!("{full}{ext}"));
621    }
622    for ext in implicit_ext {
623        potentials.push(format!("{full}/index{ext}"));
624    }
625    if !segment.is_empty() && segment != "." {
626        for ext in implicit_ext {
627            potentials.push(format!("{full}/index.{segment}{ext}"));
628        }
629    }
630    potentials
631}
632
633/// The directory a relative reference inside `path` resolves against.
634///
635/// A path with no separator (an in-memory key such as `a.jsonic`) yields
636/// the empty string, so a bare nested reference resolves plainly; a
637/// separator at index zero yields the root separator. Mirrors Go's
638/// `sourceDir` and the TypeScript mem resolver's `resolvefolder`.
639pub fn source_dir(path: &str) -> String {
640    let trimmed = path.trim_end_matches(['/', '\\']);
641    match trimmed.rfind(['/', '\\']) {
642        None => String::new(),
643        Some(0) => trimmed[..1].to_string(),
644        Some(index) => trimmed[..index].to_string(),
645    }
646}
647
648// ---------------------------------------------------------------------
649// Parse metadata
650// ---------------------------------------------------------------------
651
652fn meta_object(meta: &Value) -> Option<&IndexMap<String, Value>> {
653    match meta {
654        Value::Object(map) => Some(map),
655        Value::MapRef(map) => Some(&map.value),
656        _ => None,
657    }
658}
659
660fn meta_get<'a>(meta: &'a Value, key: &str) -> Option<&'a Value> {
661    meta_object(meta).and_then(|map| map.get(key))
662}
663
664fn meta_multisource_string(meta: &Value, key: &str) -> Option<String> {
665    match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, key)) {
666        Some(Value::String(text)) => Some(text.clone()),
667        Some(Value::Text(text)) => Some(text.string.clone()),
668        _ => None,
669    }
670}
671
672/// Was this metadata built by [`child_meta`], rather than handed in by
673/// a caller?
674fn is_nested_meta(meta: &Value) -> bool {
675    matches!(
676        meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, NESTED_MARK)),
677        Some(Value::Bool(true))
678    )
679}
680
681fn meta_parents(meta: &Value) -> Vec<String> {
682    match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, "parents")) {
683        Some(Value::Array(items)) => items
684            .iter()
685            .filter_map(|item| match item {
686                Value::String(text) => Some(text.clone()),
687                Value::Text(text) => Some(text.string.clone()),
688                _ => None,
689            })
690            .collect(),
691        _ => Vec::new(),
692    }
693}
694
695/// The key marking metadata this plugin built for a nested parse.
696///
697/// The prepare hook needs to tell a nested parse from a top-level one,
698/// and `multisource.path` cannot do it: a caller may legitimately set
699/// that at the top level to choose the base a relative reference
700/// resolves against, exactly as the canonical TypeScript tests do.
701const NESTED_MARK: &str = "nested";
702
703/// The metadata a nested parse gets: the parent's metadata with the
704/// multisource entry updated to name this source and its ancestors.
705/// Mirrors the TypeScript action's `meta` construction and Go's
706/// `childMeta`; the parent metadata is never mutated.
707fn child_meta(
708    parent: &Value,
709    resolution: &Resolution,
710    parents: &[String],
711    dive: Option<&Value>,
712    ticket: &str,
713) -> Value {
714    let mut child = meta_object(parent).cloned().unwrap_or_default();
715
716    let previous = meta_get(parent, RULE_NAME)
717        .and_then(meta_object)
718        .cloned()
719        .unwrap_or_default();
720    let mut entry = previous;
721    entry.insert(
722        "parents".to_string(),
723        Value::array(parents.iter().cloned().map(Value::String).collect()),
724    );
725    entry.insert(
726        "path".to_string(),
727        match &resolution.spec.full {
728            Some(full) => Value::String(full.clone()),
729            None => Value::Undefined,
730        },
731    );
732    entry.insert(NESTED_MARK.to_string(), Value::Bool(true));
733    // The slot this nested parse records a diagnostic under, so the
734    // load below reads back its own report and no other parse's.
735    entry.insert(REPORT_TICKET.to_string(), Value::String(ticket.to_string()));
736    child.insert(RULE_NAME.to_string(), Value::object(entry));
737
738    if let Some(path) = &resolution.spec.path {
739        child.insert("fileName".to_string(), Value::String(path.clone()));
740    }
741
742    // The path-diving plugin reads `meta.path.base` to seed the path of
743    // the root value. Carrying the current dive down means a reference
744    // that lands at a dived key keeps its place in the tree.
745    if let Some(Value::Array(segments)) = dive {
746        let mut path = IndexMap::new();
747        path.insert("base".to_string(), Value::array(segments.as_ref().clone()));
748        child.insert("path".to_string(), Value::object(path));
749    }
750
751    Value::object(child)
752}
753
754// ---------------------------------------------------------------------
755// The nested-parser slot
756// ---------------------------------------------------------------------
757
758/// The live parser, published for the duration of a top-level parse so
759/// that a processor which re-parses its source uses the instance the
760/// document is being parsed by, plugins installed after this one
761/// included.
762///
763/// The canonical TypeScript closes over the instance, and a JavaScript
764/// closure sees every later change to it. A Rust callback cannot hold a
765/// borrow across a parse, so the instance is cloned once per top-level
766/// parse that could contain a reference at all, and nested parses reuse
767/// what the top-level parse published.
768#[derive(Default)]
769struct NestedParser {
770    current: Mutex<Option<Arc<Tabnas>>>,
771}
772
773impl NestedParser {
774    fn publish(&self, parser: &Tabnas) {
775        if let Ok(mut slot) = self.current.lock() {
776            *slot = Some(Arc::new(parser.clone()));
777        }
778    }
779
780    fn get(&self) -> Option<Arc<Tabnas>> {
781        self.current.lock().ok().and_then(|slot| slot.clone())
782    }
783}
784
785/// A raised diagnostic: its code and the detail bag its message and
786/// hint are rendered from.
787type Report = (String, Vec<(String, Value)>);
788
789/// The diagnostics this plugin has raised inside nested parses, so that
790/// an outer load can re-raise one unchanged.
791///
792/// In the canonical TypeScript a nested parse throws and the exception
793/// travels out untouched, so the caller reads the innermost report: the
794/// loop of a cycle, the search paths of a missing source. Here a nested
795/// parse RETURNS its error, whose rendered text an outer level can read
796/// but whose detail bag it cannot, so the bag is recorded as it is
797/// raised and taken again when the same code comes back.
798///
799/// Each nested load gets its OWN slot, keyed by a ticket the loading
800/// action mints and threads to the nested parse through its metadata.
801/// One slot per instance was not enough: this type is shared by every
802/// parse of an instance, and an instance is explicitly shareable
803/// between threads, so two parses failing at the same time overwrote
804/// each other and an error could come back naming the other document's
805/// path, search list or loop. The ticket also survives the segment
806/// thread `processor::parse_nested` runs a level on, which a
807/// thread-local slot would not.
808///
809/// A slot is TAKEN, not read, so a report is used once, and the loading
810/// action drops its ticket whether or not the load failed.
811#[derive(Default)]
812struct LastReport {
813    slots: Mutex<BTreeMap<String, Report>>,
814    next: std::sync::atomic::AtomicU64,
815}
816
817impl LastReport {
818    /// A ticket for one nested load, unique within this instance.
819    fn ticket(&self) -> String {
820        let count = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
821        format!("{count}")
822    }
823
824    fn record(&self, ticket: &str, code: &str, details: &[(String, Value)]) {
825        if let Ok(mut slots) = self.slots.lock() {
826            slots.insert(ticket.to_string(), (code.to_string(), details.to_vec()));
827        }
828    }
829
830    /// The report a nested parse left under `ticket`, if it carries the
831    /// code that came back. The slot is freed either way.
832    fn take(&self, ticket: &str, code: &str) -> Option<Vec<(String, Value)>> {
833        let mut slots = self.slots.lock().ok()?;
834        match slots.remove(ticket) {
835            Some((recorded, details)) if recorded == code => Some(details),
836            _ => None,
837        }
838    }
839
840    /// Drop a ticket whose load did not fail, so a slot cannot outlive
841    /// the parse that minted it.
842    fn discard(&self, ticket: &str) {
843        if let Ok(mut slots) = self.slots.lock() {
844            slots.remove(ticket);
845        }
846    }
847}
848
849/// The metadata key carrying the ticket a nested parse records its
850/// report under. The loading action mints it; the nested parse only
851/// reads it back.
852const REPORT_TICKET: &str = "report";
853
854// ---------------------------------------------------------------------
855// The plugin
856// ---------------------------------------------------------------------
857
858/// Build the plugin for `options`.
859///
860/// The returned [`Plugin`] installs through [`Tabnas::use_plugin`], so a
861/// derived instance rebuilds it. Typed option data lives in the returned
862/// closure rather than in the engine's serialized plugin-option bag,
863/// because a resolver and a processor are Rust callbacks and no
864/// [`Value`] can carry one.
865pub fn plugin_with(options: MultiSourceOptions) -> Plugin {
866    let options = Arc::new(normalize(options));
867    Plugin::new(PLUGIN_NAME, move |parser, _plugin_options| {
868        install(parser, Arc::clone(&options)).map_err(PluginError::from)
869    })
870}
871
872/// Build the plugin with default options: no sources, so every reference
873/// raises `multisource_not_found`.
874pub fn plugin() -> Plugin {
875    plugin_with(MultiSourceOptions::default())
876}
877
878/// Install the plugin on `parser`.
879///
880/// The convenience constructor mirroring `tn.use(MultiSource, options)`.
881/// The host grammar must already supply the `val`, `map` and `pair` rules
882/// (a jsonic parser does, for example), or this returns an error rather
883/// than registering a directive that could never match.
884pub fn multisource(
885    parser: &mut Tabnas,
886    options: MultiSourceOptions,
887) -> Result<(), MultiSourceError> {
888    parser
889        .use_plugin(plugin_with(options), None)
890        .map(|_| ())
891        .map_err(MultiSourceError::from)
892}
893
894/// A registration failure: a host grammar without the rules the plugin
895/// modifies, a directive character already taken, or a grammar the
896/// engine refused.
897#[derive(Clone, Debug, PartialEq, Eq)]
898pub struct MultiSourceError(pub String);
899
900impl fmt::Display for MultiSourceError {
901    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
902        formatter.write_str(&self.0)
903    }
904}
905
906impl std::error::Error for MultiSourceError {}
907
908impl From<PluginError> for MultiSourceError {
909    fn from(error: PluginError) -> Self {
910        Self(error.0)
911    }
912}
913
914impl From<MultiSourceError> for PluginError {
915    fn from(error: MultiSourceError) -> Self {
916        Self(error.0)
917    }
918}
919
920/// Fill in what the plugin would otherwise have to guess at parse time.
921fn normalize(mut options: MultiSourceOptions) -> MultiSourceOptions {
922    if options.markchar.is_empty() {
923        options.markchar = DEFAULT_MARKCHAR.to_string();
924    }
925    for ext in &mut options.implicit_ext {
926        if !ext.starts_with('.') {
927            *ext = format!(".{ext}");
928        }
929    }
930    if options.max_depth == 0 {
931        options.max_depth = DEFAULT_MAX_DEPTH;
932    }
933    options
934}
935
936fn install(parser: &mut Tabnas, options: Arc<MultiSourceOptions>) -> Result<(), MultiSourceError> {
937    // The plugin modifies `val`, `map` and `pair`: it defines no value
938    // grammar of its own. Installing it on a bare engine would register
939    // a directive that can never match, so say so instead.
940    let rules = parser.rule_names();
941    for required in ["val", "map", "pair"] {
942        if !rules.iter().any(|name| name == required) {
943            return Err(MultiSourceError(format!(
944                "MultiSource needs a host grammar supplying the {required:?} rule: \
945                 install one that defines val, map and pair (tabnas-jsonic, for \
946                 example) before this plugin"
947            )));
948        }
949    }
950
951    // One slot per install, so two instances never share a published
952    // parser, and a derived instance gets its own.
953    let nested = Arc::new(NestedParser::default());
954    let reports = Arc::new(LastReport::default());
955
956    parser
957        .set_options(|engine| {
958            engine.error.insert(
959                "multisource_not_found".to_string(),
960                "source not found: {path}".to_string(),
961            );
962            engine.error.insert(
963                "multisource_cycle".to_string(),
964                "source includes itself: {path}".to_string(),
965            );
966            engine.error.insert(
967                "multisource_depth".to_string(),
968                "source nesting is too deep: {path}".to_string(),
969            );
970            engine.hint.insert(
971                "multisource_not_found".to_string(),
972                "The source path {path} was not found.\n\nSearch paths:\n{searchstr}".to_string(),
973            );
974            engine.hint.insert(
975                "multisource_cycle".to_string(),
976                "Including {path} here would loop forever:\n\n{loop}\n\n\
977                 A source may be included from more than one place, but it cannot \
978                 be an ancestor of itself."
979                    .to_string(),
980            );
981            engine.hint.insert(
982                "multisource_depth".to_string(),
983                "Loading {path} would nest sources more than {max} deep.\n\n\
984                 Each source is loaded inside the parse that referenced it, so an \
985                 unbounded chain would exhaust the stack. Raise max_depth if the \
986                 chain is genuine."
987                    .to_string(),
988            );
989        })
990        .map_err(|error| MultiSourceError(error.to_string()))?;
991
992    // Publish the live instance for nested parses, once per top-level
993    // parse of a document that could hold a reference at all. A nested
994    // parse carries `multisource.path` in its metadata and skips.
995    {
996        let options = Arc::clone(&options);
997        let nested = Arc::clone(&nested);
998        parser.parse_prepare_with_instance(move |instance, context, _meta| {
999            if !context.source.contains(options.markchar.as_str()) {
1000                return;
1001            }
1002            if is_nested_meta(&context.meta) {
1003                return;
1004            }
1005            nested.publish(instance);
1006        });
1007    }
1008
1009    let name = RULE_NAME.to_string();
1010    let markchar = options.markchar.clone();
1011    let action_options = Arc::clone(&options);
1012    let action_nested = Arc::clone(&nested);
1013    let action_reports = Arc::clone(&reports);
1014
1015    let directive = DirectiveOptions::new(name.clone(), markchar)
1016        .with_rules(
1017            RulesOption::new()
1018                .open_rule("val", RuleMod::new())
1019                // A `@` in key position only opens a directive while the
1020                // rule is not already diving into a key, which is what
1021                // `pk` counts.
1022                .open_rule("pair", RuleMod::when(|rule, _context| rule.lte("pk", 0))),
1023        )
1024        .with_token_action(move |rule, context| {
1025            directive_action(
1026                &action_options,
1027                &action_nested,
1028                &action_reports,
1029                rule,
1030                context,
1031            )
1032        })
1033        .with_custom(move |parser, config| {
1034            if let Err(error) = install_grammar(parser, &config.name) {
1035                // The custom hook cannot return, so a refusal here is a
1036                // programming error in this crate rather than a caller
1037                // mistake: the document below is a constant.
1038                panic!("MultiSource grammar: {error}");
1039            }
1040        });
1041
1042    tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
1043}
1044
1045/// The grammar that lets a reference stand where a value, a bare
1046/// top-level key, or a pair value can.
1047fn install_grammar(parser: &mut Tabnas, name: &str) -> Result<(), MultiSourceError> {
1048    let open_token = format!("#OD_{name}");
1049    let top_counter = format!("{name}_top");
1050
1051    // Back-track the mark up a path dive only when the rule is inside a
1052    // dive AND the mark is not already a pair's value. In a colon chain
1053    // (`a: b: @"f"`) the value-position `val` has `pk > 0` but its
1054    // parent IS the pair for that key, so this stays false and the load
1055    // lands under the key instead of unwinding to depth zero.
1056    parser.alt_condition("@ms-pk-val", |rule, _context| {
1057        rule.gt("pk", 0)
1058            && rule
1059                .parent_rule
1060                .as_ref()
1061                .map(|parent| parent.name.as_ref() != "pair")
1062                .unwrap_or(true)
1063    });
1064    parser.alt_condition("@ms-pk", |rule, _context| rule.gt("pk", 0));
1065    parser.alt_condition("@ms-top", |rule, _context| rule.d == 0);
1066    let counter = top_counter.clone();
1067    parser.alt_condition("@ms-top-map", move |rule, _context| {
1068        rule.d == 1 && rule.eq(&counter, 1)
1069    });
1070
1071    let document = json!({
1072        "rule": {
1073            "val": {
1074                "open": [
1075                    { "s": open_token, "c": "@ms-pk-val", "b": 1 },
1076                    {
1077                        "s": open_token,
1078                        "c": "@ms-top",
1079                        "p": "map",
1080                        "b": 1,
1081                        "n": { top_counter.clone(): 1 },
1082                    },
1083                ],
1084            },
1085            "map": {
1086                "open": [{
1087                    "s": open_token,
1088                    "c": "@ms-top-map",
1089                    "p": "pair",
1090                    "b": 1,
1091                    // Allocate the implicit top-level map here. The core
1092                    // only auto-allocates for `{`, so without this the
1093                    // pushed `pair` is seeded with an undefined node and
1094                    // a pair following a leading `@` has nowhere to go.
1095                    // The action's merge writes into this same node.
1096                    "a": "@object$",
1097                    "k": { "object$": { "implicit": true } },
1098                }],
1099                "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1100            },
1101            "pair": {
1102                "close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
1103            },
1104        },
1105    });
1106
1107    let spec =
1108        GrammarSpec::from_value(document).map_err(|error| MultiSourceError(error.to_string()))?;
1109    parser
1110        .grammar_with_setting(&spec, &GrammarSetting::groups(name))
1111        .map(|_| ())
1112        .map_err(|error| MultiSourceError(error.to_string()))
1113}
1114
1115// ---------------------------------------------------------------------
1116// The directive action
1117// ---------------------------------------------------------------------
1118
1119/// The reference a directive body names: a bare string, or an object
1120/// with a `path` key (`@{path:"a.jsonic"}`).
1121///
1122/// Neither the canonical nor this port requires the value to be a
1123/// string, so the coercion decides which source is named and has to be
1124/// the canonical one: `'' + spec.path`, whose rules are JavaScript's.
1125/// A number goes through [`format_number`]; a boolean is `true` or
1126/// `false`; a null is an absent path, which is what the canonical's
1127/// `null != spec.path` guard makes of it.
1128fn reference_of(value: &Value) -> Option<String> {
1129    match value {
1130        Value::Object(_) | Value::MapRef(_) => coerce_reference(meta_get(value, "path").as_ref()?),
1131        other => coerce_reference(other),
1132    }
1133}
1134
1135/// `'' + value` for the one value a directive body can carry.
1136fn coerce_reference(value: &Value) -> Option<String> {
1137    match value {
1138        Value::String(text) => Some(text.clone()),
1139        Value::Text(text) => Some(text.string.clone()),
1140        Value::Number(number) => Some(format_number(*number)),
1141        Value::Bool(flag) => Some(flag.to_string()),
1142        _ => None,
1143    }
1144}
1145
1146/// JavaScript's `Number::toString` (ECMA-262 6.1.6.1.20), which is what
1147/// the canonical `'' + spec.path` spells for a numeric reference, and so
1148/// what such a reference names.
1149///
1150/// Rust's own `f64` formatting differs from it in ways that reach a map
1151/// key. `number as i64` SATURATES, so every integral value above
1152/// `i64::MAX` became `9223372036854775807` and named the wrong source.
1153/// Plain `{}` keeps the sign of negative zero (`-0`, where JavaScript
1154/// says `0`) and never switches to exponent form, where JavaScript does
1155/// so at `1e21` and at `1e-7`.
1156///
1157/// The same implementation, for the same reason, is in `tabnas-csv` and
1158/// `tabnas-xml`; keep the three in step.
1159fn format_number(number: f64) -> String {
1160    if number.is_nan() {
1161        return "NaN".to_string();
1162    }
1163    // Catches -0.0 as well: JavaScript spells both zeros "0".
1164    if number == 0.0 {
1165        return "0".to_string();
1166    }
1167    if number < 0.0 {
1168        return format!("-{}", format_number(-number));
1169    }
1170    if number.is_infinite() {
1171        return "Infinity".to_string();
1172    }
1173
1174    // The specification wants the shortest digit string `s` that
1175    // round-trips (length `k`), and `n`, the position of the decimal
1176    // point relative to it. Rust's `{:e}` yields digits of exactly that
1177    // shortest length.
1178    let shortest = format!("{number:e}");
1179    let shortest_k = shortest
1180        .split_once('e')
1181        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
1182        .expect("a finite f64 always formats with an exponent");
1183
1184    // Re-render to that same length to settle a tie. Where two digit
1185    // strings of length `k` are equally close to `number`, the
1186    // specification takes the one ending in an even digit; Rust's
1187    // shortest form does not, but its exactly-rounded fixed-precision
1188    // form does.
1189    let exponential = format!("{:.*e}", shortest_k - 1, number);
1190    let (mantissa, exponent) = exponential
1191        .split_once('e')
1192        .expect("a finite f64 always formats with an exponent");
1193    // Rounding can leave trailing zeros (and, on a carry, one digit too
1194    // many); dropping them keeps `s` shortest, which is what `k` means.
1195    let digits = mantissa
1196        .chars()
1197        .filter(|digit| *digit != '.')
1198        .collect::<String>();
1199    let digits = digits.trim_end_matches('0');
1200    let digits = if digits.is_empty() { "0" } else { digits };
1201    let k = digits.len() as i32;
1202    let n = exponent
1203        .parse::<i32>()
1204        .expect("a formatted exponent is an integer")
1205        + 1;
1206
1207    // The four cases of the specification, in its order. The range
1208    // bounds are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
1209    if (k..=21).contains(&n) {
1210        // Integral, with n - k trailing zeros to restore.
1211        let mut text = digits.to_string();
1212        text.push_str(&"0".repeat((n - k) as usize));
1213        text
1214    } else if (1..=21).contains(&n) {
1215        let point = n as usize;
1216        format!("{}.{}", &digits[..point], &digits[point..])
1217    } else if (-5..=0).contains(&n) {
1218        format!("0.{}{}", "0".repeat(-n as usize), digits)
1219    } else {
1220        // Exponent form. `n - 1` is never 0 here, so the sign is never
1221        // "+0".
1222        let sign = if n - 1 < 0 { '-' } else { '+' };
1223        let power = (n - 1).abs();
1224        if k == 1 {
1225            format!("{digits}e{sign}{power}")
1226        } else {
1227            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
1228        }
1229    }
1230}
1231
1232/// The token a diagnostic is reported against: the enclosing rule's
1233/// opening token, as `rule.parent?.o0` names in TypeScript, then this
1234/// rule's own, then whatever the lexer is looking at.
1235fn error_token(rule: &Rule, context: &Context) -> Option<Token> {
1236    rule.parent_rule
1237        .as_ref()
1238        .and_then(|parent| parent.o.first())
1239        .or_else(|| rule.o.first())
1240        .cloned()
1241        .or_else(|| context.t0().cloned())
1242}
1243
1244fn fail(
1245    reports: &LastReport,
1246    rule: &Rule,
1247    context: &Context,
1248    code: &str,
1249    details: Vec<(String, Value)>,
1250) -> Result<Option<Token>, ActionError> {
1251    // Only a NESTED parse has a ticket, and only a nested report is
1252    // ever taken: a top-level failure is raised to the caller whole.
1253    if let Some(ticket) = meta_multisource_string(&context.meta, REPORT_TICKET) {
1254        reports.record(&ticket, code, &details);
1255    }
1256    match error_token(rule, context) {
1257        Some(mut token) => {
1258            token.bad_with_details(code, details);
1259            Ok(Some(token))
1260        }
1261        // No token to hang the report on, which the engine's own error
1262        // path still has to be told about.
1263        None => Err(ActionError::new(code, format!("[{code}]"))),
1264    }
1265}
1266
1267fn directive_action(
1268    options: &Arc<MultiSourceOptions>,
1269    nested: &Arc<NestedParser>,
1270    reports: &Arc<LastReport>,
1271    rule: &mut Rule,
1272    context: &mut Context,
1273) -> Result<Option<Token>, ActionError> {
1274    let from = rule
1275        .parent_rule
1276        .as_ref()
1277        .map(|parent| parent.name.to_string())
1278        .unwrap_or_default();
1279
1280    let reference = reference_of(&rule.child_node);
1281
1282    let mut resolution = {
1283        let input = ResolverInput {
1284            options,
1285            meta: &context.meta,
1286        };
1287        options.resolver.resolve(reference.as_deref(), &input)
1288    };
1289
1290    if !resolution.found {
1291        let mut search = resolution.search.clone();
1292        if search.is_empty() {
1293            if let Some(full) = &resolution.spec.full {
1294                search.push(full.clone());
1295            }
1296        }
1297        let named = resolution
1298            .spec
1299            .path
1300            .clone()
1301            .or_else(|| reference.clone())
1302            .unwrap_or_default();
1303        return fail(
1304            reports,
1305            rule,
1306            context,
1307            "multisource_not_found",
1308            vec![
1309                ("path".to_string(), Value::String(named)),
1310                (
1311                    "full".to_string(),
1312                    Value::String(resolution.spec.full.clone().unwrap_or_default()),
1313                ),
1314                ("searchstr".to_string(), Value::String(search.join("\n"))),
1315            ],
1316        );
1317    }
1318
1319    let fullpath = resolution.full_path();
1320
1321    if resolution.spec.kind.is_empty() {
1322        resolution.spec.kind = NONE.to_string();
1323    }
1324
1325    // Copy rather than extend in place: the inherited chain is shared
1326    // with every sibling include at this level, so mutating it would
1327    // make `parents` an accumulating visit log rather than the ancestor
1328    // chain, and the cycle check below would then fire on a diamond.
1329    let mut parents = meta_parents(&context.meta);
1330    if let Some(path) = meta_multisource_string(&context.meta, "path") {
1331        parents.push(path);
1332    }
1333
1334    // Cycle check. Without it, a -> b -> a recurses until the stack
1335    // overflows, with no source position and no indication of which
1336    // sources are at fault. Compared against the ancestor chain, so a
1337    // source included from two branches is reuse, not a cycle.
1338    if let Some(index) = parents.iter().position(|parent| parent == &fullpath) {
1339        let mut loop_path: Vec<String> = parents[index..].to_vec();
1340        loop_path.push(fullpath.clone());
1341        return fail(
1342            reports,
1343            rule,
1344            context,
1345            "multisource_cycle",
1346            vec![
1347                ("path".to_string(), Value::String(fullpath)),
1348                ("loop".to_string(), Value::String(loop_path.join(" -> "))),
1349            ],
1350        );
1351    }
1352
1353    // An acyclic chain can still be arbitrarily long, and each link runs
1354    // inside the parse that referenced it.
1355    if parents.len() >= options.max_depth {
1356        return fail(
1357            reports,
1358            rule,
1359            context,
1360            "multisource_depth",
1361            vec![
1362                ("path".to_string(), Value::String(fullpath)),
1363                ("max".to_string(), Value::Number(options.max_depth as f64)),
1364            ],
1365        );
1366    }
1367
1368    if let Some(deps) = &options.deps {
1369        let target = parents.last().cloned().unwrap_or_else(|| TOP.to_string());
1370        if let Ok(mut deps) = deps.lock() {
1371            deps.entry(target.clone()).or_default().insert(
1372                fullpath.clone(),
1373                Dependency {
1374                    tar: target,
1375                    src: fullpath.clone(),
1376                    wen: now_millis(),
1377                },
1378            );
1379        }
1380    }
1381
1382    let dive = rule.k.get("path").cloned();
1383    let ticket = reports.ticket();
1384    let meta = child_meta(&context.meta, &resolution, &parents, dive.as_ref(), &ticket);
1385
1386    let Some(parser) = nested.get() else {
1387        // The prepare hook publishes the instance for every parse whose
1388        // source holds the mark character, and a directive cannot fire
1389        // on a source that does not, so this is unreachable rather than
1390        // a condition a document can provoke.
1391        return Err(ActionError::new(
1392            "internal",
1393            "MultiSource: no parser was published for the nested parse",
1394        ));
1395    };
1396
1397    if let Some(processor) = options.processor_for(&resolution.spec.kind) {
1398        let input = ProcessorInput {
1399            options,
1400            meta: &meta,
1401            parser: &parser,
1402            depth: parents.len(),
1403        };
1404        processor.process(&mut resolution, &input);
1405    }
1406
1407    if let Some(error) = resolution.err.take() {
1408        // A source resolved but failed to process, typically a nested
1409        // reference inside it. Re-raise the nested code rather than
1410        // silently substituting the raw source text.
1411        let code = if error.code.is_empty() {
1412            "unexpected".to_string()
1413        } else {
1414            error.code.clone()
1415        };
1416        // Re-raise the nested report as it was raised, so the caller
1417        // reads the loop of a cycle or the search paths of a missing
1418        // source rather than a summary of them, exactly as the
1419        // canonical TypeScript exception carries them out. The ticket
1420        // is what makes it THIS load's report and no other parse's.
1421        let details = reports.take(&ticket, &code).unwrap_or_else(|| {
1422            vec![
1423                ("path".to_string(), Value::String(fullpath)),
1424                ("searchstr".to_string(), Value::String(error.detail.clone())),
1425            ]
1426        });
1427        return fail(reports, rule, context, &code, details);
1428    }
1429
1430    // The load succeeded, so nothing will ever ask for its slot.
1431    reports.discard(&ticket);
1432
1433    let value = std::mem::replace(&mut resolution.val, Value::Undefined);
1434
1435    if from == "pair" {
1436        splice_into_parent(rule, context, value);
1437    } else {
1438        set_node(rule, value);
1439    }
1440
1441    Ok(None)
1442}
1443
1444fn now_millis() -> u64 {
1445    SystemTime::now()
1446        .duration_since(UNIX_EPOCH)
1447        .map(|since| since.as_millis() as u64)
1448        .unwrap_or(0)
1449}
1450
1451/// Merge a loaded map into the enclosing map, for the `{@foo}` form.
1452///
1453/// TypeScript assigns the merged object back to `rule.parent.parent.node`
1454/// and its `deep` mutates the base in place, so the enclosing map keeps
1455/// its identity and a pair that follows the directive writes into the
1456/// same node. A Rust rule reaches its grandparent only through a
1457/// snapshot, which cannot be assigned to, so the merge is written
1458/// through the shared node cell instead. The cell is the same one, so
1459/// the identity the following pair depends on is preserved.
1460fn splice_into_parent(rule: &mut Rule, context: &mut Context, value: Value) {
1461    let Some(target) = rule
1462        .parent_rule
1463        .as_ref()
1464        .and_then(|parent| parent.parent_rule.as_ref())
1465        .map(|grandparent| grandparent.node.clone())
1466    else {
1467        return;
1468    };
1469
1470    let merge = context.options.map.merge.clone();
1471    let extend = context.options.map.extend;
1472
1473    if let Some(merge) = merge {
1474        let base = target.borrow().clone();
1475        let merged = merge(base, value, rule, context);
1476        *target.borrow_mut() = merged;
1477        return;
1478    }
1479
1480    if extend {
1481        let base = target.borrow().clone();
1482        let merged = deep_merge(base, value);
1483        *target.borrow_mut() = merged;
1484        return;
1485    }
1486
1487    // `Object.assign`: a shallow per-key overwrite.
1488    let Some(entries) = object_entries(&value) else {
1489        return;
1490    };
1491    let mut node = target.borrow_mut();
1492    match &mut *node {
1493        Value::Object(map) => {
1494            let map = Arc::make_mut(map);
1495            for (key, item) in entries {
1496                map.insert(key, item);
1497            }
1498        }
1499        Value::MapRef(map) => {
1500            let map = Arc::make_mut(map);
1501            for (key, item) in entries {
1502                map.value.insert(key, item);
1503            }
1504        }
1505        _ => {}
1506    }
1507}
1508
1509fn object_entries(value: &Value) -> Option<Vec<(String, Value)>> {
1510    match value {
1511        Value::Object(map) => Some(
1512            map.iter()
1513                .map(|(key, item)| (key.clone(), item.clone()))
1514                .collect(),
1515        ),
1516        Value::MapRef(map) => Some(
1517            map.value
1518                .iter()
1519                .map(|(key, item)| (key.clone(), item.clone()))
1520                .collect(),
1521        ),
1522        _ => None,
1523    }
1524}
1525
1526/// Recursively merge `overlay` into `base`, for the `map.extend` splice:
1527/// objects by key, arrays by index, and anything else replaced by the
1528/// overlay. The base keeps its container kind, so a `MapRef` stays a
1529/// `MapRef` with its metadata, and a `ListRef` a `ListRef`. The
1530/// prototype-pollution guard of the TypeScript `deep()` utility is kept:
1531/// `__proto__`, `constructor` and `prototype` keys of the overlay are
1532/// skipped.
1533///
1534/// Ported from `deep_merge` in `tabnas-jsonic` (`jsonic/rs/src/lib.rs`),
1535/// itself the port of the `deep()` the TypeScript grammar merges with, so
1536/// that the plugin needs no grammar crate at run time. The engine's
1537/// `tabnas::utility::deep` is not a substitute: it merges `serde_json`
1538/// values, not the engine's native [`Value`], and would lose the
1539/// container metadata.
1540fn deep_merge(base: Value, overlay: Value) -> Value {
1541    const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
1542
1543    fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
1544        for (key, value) in overlay {
1545            if DANGEROUS.contains(&key.as_str()) {
1546                continue;
1547            }
1548            let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
1549            base.insert(key, deep_merge(previous, value));
1550        }
1551    }
1552
1553    fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
1554        for (index, value) in overlay.into_iter().enumerate() {
1555            if index < base.len() {
1556                let previous = std::mem::replace(&mut base[index], Value::Undefined);
1557                base[index] = deep_merge(previous, value);
1558            } else {
1559                base.push(value);
1560            }
1561        }
1562    }
1563
1564    match (base, overlay) {
1565        (base, Value::Undefined) => base,
1566        (Value::Object(base), Value::Object(overlay)) => {
1567            let mut base = unwrap_arc(base);
1568            merge_entries(&mut base, unwrap_arc(overlay));
1569            Value::object(base)
1570        }
1571        (Value::Object(base), Value::MapRef(overlay)) => {
1572            let mut base = unwrap_arc(base);
1573            merge_entries(&mut base, unwrap_arc(overlay).value);
1574            Value::object(base)
1575        }
1576        (Value::MapRef(base), Value::Object(overlay)) => {
1577            let mut base = unwrap_arc(base);
1578            merge_entries(&mut base.value, unwrap_arc(overlay));
1579            Value::MapRef(Arc::new(base))
1580        }
1581        (Value::MapRef(base), Value::MapRef(overlay)) => {
1582            let mut base = unwrap_arc(base);
1583            merge_entries(&mut base.value, unwrap_arc(overlay).value);
1584            Value::MapRef(Arc::new(base))
1585        }
1586        (Value::Array(base), Value::Array(overlay)) => {
1587            let mut base = unwrap_arc(base);
1588            merge_items(&mut base, unwrap_arc(overlay));
1589            Value::array(base)
1590        }
1591        (Value::Array(base), Value::ListRef(overlay)) => {
1592            let mut base = unwrap_arc(base);
1593            merge_items(&mut base, unwrap_arc(overlay).value);
1594            Value::array(base)
1595        }
1596        (Value::ListRef(base), Value::Array(overlay)) => {
1597            let mut base = unwrap_arc(base);
1598            merge_items(&mut base.value, unwrap_arc(overlay));
1599            Value::ListRef(Arc::new(base))
1600        }
1601        (Value::ListRef(base), Value::ListRef(overlay)) => {
1602            let mut base = unwrap_arc(base);
1603            merge_items(&mut base.value, unwrap_arc(overlay).value);
1604            Value::ListRef(Arc::new(base))
1605        }
1606        (_, overlay) => overlay,
1607    }
1608}
1609
1610/// The value behind a shared container, copied only when another holder
1611/// still shares it.
1612fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
1613    Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618    use super::*;
1619
1620    fn object(entries: &[(&str, Value)]) -> Value {
1621        Value::object(
1622            entries
1623                .iter()
1624                .map(|(key, value)| (key.to_string(), value.clone()))
1625                .collect(),
1626        )
1627    }
1628
1629    fn number(value: f64) -> Value {
1630        Value::Number(value)
1631    }
1632
1633    /// The splice under `map.extend` is the jsonic `deep_merge` this port
1634    /// replaces, so the two must agree on every shape it can be handed.
1635    #[test]
1636    fn deep_merge_agrees_with_the_jsonic_merge_it_replaces() {
1637        let cases: Vec<(Value, Value)> = vec![
1638            (
1639                object(&[("a", number(1.0)), ("n", object(&[("x", number(1.0))]))]),
1640                object(&[("b", number(2.0)), ("n", object(&[("y", number(2.0))]))]),
1641            ),
1642            (
1643                Value::array(vec![number(1.0), object(&[("a", number(1.0))])]),
1644                Value::array(vec![
1645                    number(9.0),
1646                    object(&[("b", number(2.0))]),
1647                    number(3.0),
1648                ]),
1649            ),
1650            (
1651                object(&[("a", number(1.0))]),
1652                Value::array(vec![number(1.0)]),
1653            ),
1654            (object(&[("a", number(1.0))]), Value::Undefined),
1655            (Value::Null, object(&[("a", number(1.0))])),
1656            (number(1.0), Value::String("s".to_string())),
1657            (
1658                object(&[("a", number(1.0))]),
1659                object(&[
1660                    ("__proto__", object(&[("polluted", Value::Bool(true))])),
1661                    ("constructor", number(1.0)),
1662                    ("prototype", number(2.0)),
1663                    ("ok", number(3.0)),
1664                ]),
1665            ),
1666        ];
1667        for (base, overlay) in cases {
1668            let ours = deep_merge(base.clone(), overlay.clone());
1669            let theirs = tabnas_jsonic::deep_merge(base.clone(), overlay.clone());
1670            assert_eq!(ours, theirs, "deep_merge({base}, {overlay})");
1671        }
1672    }
1673
1674    /// The base keeps its container kind and its metadata: a `MapRef`
1675    /// overlaid with a plain object is still that `MapRef`.
1676    #[test]
1677    fn deep_merge_keeps_the_base_container_and_its_metadata() {
1678        let mut meta = IndexMap::new();
1679        meta.insert("tag".to_string(), Value::String("kept".to_string()));
1680        let mut entries = IndexMap::new();
1681        entries.insert("a".to_string(), number(1.0));
1682        let base = Value::MapRef(Arc::new(tabnas::MapRef {
1683            value: entries,
1684            implicit: true,
1685            meta,
1686        }));
1687
1688        match deep_merge(base, object(&[("b", number(2.0))])) {
1689            Value::MapRef(map) => {
1690                assert!(map.implicit);
1691                assert_eq!(map.meta.get("tag"), Some(&Value::String("kept".into())));
1692                assert_eq!(map.value.get("a"), Some(&number(1.0)));
1693                assert_eq!(map.value.get("b"), Some(&number(2.0)));
1694            }
1695            other => panic!("the base container kind is kept, got {other:?}"),
1696        }
1697    }
1698}
1699
1700#[cfg(doctest)]
1701#[doc = include_str!("../README.md")]
1702mod readme_examples {}