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