Skip to main content

tabnas_multisource/
processor.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! Turning resolved source text into a value.
4//!
5//! The default table is the TypeScript one: raw text for an unknown
6//! kind, and a re-parse with the live engine for `jsonic` and `jsc`.
7//! There is no JSON reader here: a caller that loads `.json` sources
8//! registers a [`Processor`] for the `json` kind, built with the JSON
9//! parser of its choice, and until it does a `.json` source is raw text.
10
11use std::fmt;
12use std::sync::Arc;
13
14use tabnas::{Tabnas, TabnasError, Value};
15
16use crate::{MultiSourceOptions, Resolution};
17
18/// How many levels of nesting share one stack.
19///
20/// A nested source is parsed inside the parse that referenced it, and a
21/// parse frame is large: a debug build of the engine uses around a third
22/// of a megabyte per level, so six levels exhaust the two megabytes a
23/// spawned thread gets by default and the process aborts. Neither the
24/// canonical TypeScript nor the Go port has this problem in the same
25/// way (a JavaScript engine throws a catchable RangeError; a goroutine
26/// stack grows), so the port solves it rather than inheriting it: every
27/// `SEGMENT` levels the nested parse moves to a fresh thread with a
28/// generous stack, and the chain is then bounded by
29/// [`crate::MultiSourceOptions::max_depth`] rather than by whatever
30/// stack the caller happened to have.
31const SEGMENT: usize = 2;
32
33/// The stack a segment thread gets. Virtual address space, committed
34/// only as it is used.
35const SEGMENT_STACK: usize = 8 * 1024 * 1024;
36
37/// What a [`Processor`] is given.
38///
39/// The canonical TypeScript hands a processor the whole parse
40/// `Context`, of which processors read only `ctx.meta`, plus the
41/// instance. Narrowing it keeps a processor callable, and therefore
42/// testable, outside a parse.
43#[derive(Clone, Copy)]
44pub struct ProcessorInput<'a> {
45    /// The plugin options in force for this parse.
46    pub options: &'a MultiSourceOptions,
47    /// The metadata for this load. `multisource.path` names the source
48    /// being processed, which is how a relative reference inside it
49    /// resolves against its own directory.
50    pub meta: &'a Value,
51    /// The parser the document is being read by, for a processor that
52    /// re-parses its source.
53    pub parser: &'a Arc<Tabnas>,
54    /// How many sources enclose this one. Zero for a reference in the
55    /// document the caller handed to `parse`.
56    pub depth: usize,
57}
58
59impl ProcessorInput<'_> {
60    /// Re-parse `src` as a nested source of this load.
61    ///
62    /// Use this rather than calling the parser directly: it threads the
63    /// metadata through, so a relative reference inside `src` resolves
64    /// against this source's own directory, and it keeps the chain off
65    /// one stack. See [`parse_nested`].
66    pub fn parse_source(&self, src: &str) -> Result<Value, TabnasError> {
67        parse_nested(self.parser, src, self.meta, self.depth)
68    }
69}
70
71/// Parse `src` as a source nested `depth` levels inside the document.
72///
73/// Every `SEGMENT` levels the parse is run on a fresh thread with a
74/// large stack and joined, so a long chain of sources cannot exhaust
75/// the caller's stack. The call is synchronous either way: nothing
76/// outlives it, and the value comes back on the caller's thread.
77pub fn parse_nested(
78    parser: &Arc<Tabnas>,
79    src: &str,
80    meta: &Value,
81    depth: usize,
82) -> Result<Value, TabnasError> {
83    if depth % SEGMENT != 1 {
84        return parser.parse_with_meta(src, meta.clone());
85    }
86
87    let handle = match spawn_segment(parser, src, meta) {
88        Ok(handle) => handle,
89        Err(reason) => {
90            // No thread to be had. Carrying on where we are is not the
91            // safe fallback it looks like: the measurements this module
92            // records put about six levels in a spawned thread's stack,
93            // well inside the default `max_depth`, so resuming the
94            // chain here is how an ACYCLIC document aborts the process,
95            // and it does it exactly when the machine is already under
96            // pressure. Fail the parse instead, with a reason.
97            let mut error = TabnasError::new("internal", src, src, 0, 1, 1);
98            error.detail =
99                format!("the nested parse could not be given a thread to run on: {reason}");
100            return Err(error);
101        }
102    };
103
104    match handle.join() {
105        Ok(result) => result,
106        Err(_) => {
107            // The engine converts a panic inside a parse into an error
108            // itself, so reaching here means something outside it, and
109            // the parse has no result to report.
110            let mut error = TabnasError::new("internal", src, src, 0, 1, 1);
111            error.detail = "the nested parse did not complete".to_string();
112            Err(error)
113        }
114    }
115}
116
117/// Run one segment of the chain on a thread of its own.
118///
119/// A seam rather than a call, so the test below can exercise the failure
120/// path without having to exhaust the process's threads to reach it.
121fn spawn_segment(
122    parser: &Arc<Tabnas>,
123    src: &str,
124    meta: &Value,
125) -> std::io::Result<std::thread::JoinHandle<Result<Value, TabnasError>>> {
126    #[cfg(test)]
127    {
128        if REFUSE_SPAWN.with(std::cell::Cell::get) {
129            return Err(std::io::Error::other("refused by a test"));
130        }
131    }
132
133    let owned_parser = Arc::clone(parser);
134    let owned_src = src.to_string();
135    let owned_meta = meta.clone();
136    std::thread::Builder::new()
137        .name("tabnas-multisource".to_string())
138        .stack_size(SEGMENT_STACK)
139        .spawn(move || owned_parser.parse_with_meta(&owned_src, owned_meta))
140}
141
142#[cfg(test)]
143thread_local! {
144    /// Set by the test that pins the spawn-failure path.
145    static REFUSE_SPAWN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
146}
147
148impl fmt::Debug for ProcessorInput<'_> {
149    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150        formatter
151            .debug_struct("ProcessorInput")
152            .field("meta", self.meta)
153            .finish_non_exhaustive()
154    }
155}
156
157/// Convert resolved source content into a value.
158///
159/// Write the result to `resolution.val`. A failure goes in
160/// `resolution.err`, which fails the whole parse: TypeScript lets a
161/// nested parse error escape rather than substituting the raw text, and
162/// so does this.
163///
164/// Implementations must be `Send + Sync`, for the reason [`crate::Resolver`]
165/// gives.
166pub trait Processor: Send + Sync {
167    /// Process `resolution` in place.
168    fn process(&self, resolution: &mut Resolution, input: &ProcessorInput<'_>);
169}
170
171impl<F> Processor for F
172where
173    F: Fn(&mut Resolution, &ProcessorInput<'_>) + Send + Sync,
174{
175    fn process(&self, resolution: &mut Resolution, input: &ProcessorInput<'_>) {
176        self(resolution, input);
177    }
178}
179
180/// The fallback: the source text, as a string.
181pub fn default_processor(resolution: &mut Resolution, _input: &ProcessorInput<'_>) {
182    resolution.val = match &resolution.src {
183        Some(src) => Value::String(src.clone()),
184        None => Value::Undefined,
185    };
186}
187
188/// Re-parse the source with the live engine, so a nested reference is
189/// resolved by the same plugin and every plugin installed beside it.
190///
191/// The metadata is threaded through, which is what makes a relative
192/// reference inside the source resolve against that source's own
193/// directory. Mirrors the TypeScript `jsonic` processor's
194/// `tn.parse(res.src, ctx.meta)`.
195pub fn jsonic_processor(resolution: &mut Resolution, input: &ProcessorInput<'_>) {
196    let (Some(src), Some(_)) = (resolution.src.clone(), resolution.spec.full.clone()) else {
197        // The canonical processor leaves `val` untouched when either is
198        // missing, and the rule's node is then the empty map its `bo`
199        // hook seeded.
200        return;
201    };
202    match input.parse_source(&src) {
203        Ok(value) => resolution.val = value,
204        Err(error) => {
205            // Keep the raw text for a caller inspecting the resolution
206            // directly; the error is what fails the parse.
207            resolution.val = Value::String(src);
208            resolution.err = Some(Box::new(error));
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    /// A process at its thread limit must not resume the nested chain on
218    /// the current stack. Six levels fit a spawned thread's two
219    /// megabytes, and `max_depth` allows sixty-four, so the fallback
220    /// turned "no thread available" into an aborted process for a
221    /// perfectly acyclic document. It is a parse error instead.
222    #[test]
223    fn a_segment_that_cannot_be_spawned_fails_the_parse() {
224        // The host grammar is the caller's to build; jsonic is the one
225        // the tests use, as a dev-dependency.
226        let mut parser = tabnas_jsonic::make();
227        crate::multisource(&mut parser, MultiSourceOptions::default())
228            .expect("the MultiSource plugin installs on jsonic");
229        let parser = Arc::new(parser);
230        let meta = Value::Undefined;
231
232        REFUSE_SPAWN.with(|refuse| refuse.set(true));
233        let error = parse_nested(&parser, "a:1", &meta, 1)
234            .expect_err("a segment with no thread to run on is an error");
235        assert!(!error.code.is_empty(), "the failure carries a code");
236        assert!(
237            error.detail.contains("thread"),
238            "the failure says why: {}",
239            error.detail
240        );
241
242        // A level that shares the caller's stack is unaffected: it never
243        // asks for a thread.
244        assert!(parse_nested(&parser, "a:1", &meta, 0).is_ok());
245
246        REFUSE_SPAWN.with(|refuse| refuse.set(false));
247        assert!(
248            parse_nested(&parser, "a:1", &meta, 1).is_ok(),
249            "and with a thread to be had the segment runs"
250        );
251    }
252}