flm_core/lang/guard.rs
1//! This module provides the recursion guard of FLM, which reports an error for
2//! deeply nested content before the content overflows the stack, along with the
3//! worker threads on which every guarded operation runs.
4//!
5//! Parsing, traversing, rewriting and serializing a tree are recursive
6//! operations, so deeply nested content uses much stack. A stack overflow ends
7//! the process, and the program that embeds FLM cannot recover from it. To
8//! prevent the overflow, techy provides a *descent guard*: the guard measures
9//! the stack that a recursive operation has used since it started, and stops the
10//! operation when this amount exceeds a budget. The operation then reports an
11//! error, for instance [`NestingTooDeep`] (`flm.blocks.nesting-too-deep`) for a
12//! parse. See also [the recursion guard and worker
13//! threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads).
14//!
15//! # Guarded construction
16//!
17//! techy's default budget is small, and the budget of a language or of a
18//! traversal can only be set when the language or the traversal is constructed.
19//! FLM therefore constructs every recursive operation with one of the following
20//! functions of this module, which install the guard with the budget
21//! [`STACK_BUDGET`]:
22//!
23//! - [`language`], for parsing;
24//! - [`walker`], [`restager`] and [`recomposer`], for traversals of a tree;
25//! - [`serde_session`], for serialization.
26//!
27//! The limit is selected with the [`GuardPolicy`] argument that each function
28//! takes.
29//! [`GuardPolicy::StackBudget`] limits the stack use and is the policy for
30//! normal use. [`GuardPolicy::DepthLimit`] limits the number of nested descents
31//! and is used in tests only.
32//!
33//! # The worker-thread requirement
34//!
35//! The guard limits the stack that an operation uses, but it does not check the
36//! size of the stack of the current thread. On a thread with less stack than the
37//! budget, an operation overflows the stack before the guard stops it. Every
38//! guarded operation must therefore run on a *worker thread*: a thread created
39//! with at least [`WORKER_STACK_SIZE`] bytes of stack.
40//!
41//! The entry points of the library meet this requirement for their callers. They
42//! run each guarded operation through [`on_worker_thread`], which runs the
43//! operation on the current thread if this thread is marked as a worker thread,
44//! and otherwise on a new worker thread. The [parse functions](crate::lang::parse),
45//! the [rewrite passes](crate::lang::rewrites), the run of a plan
46//! ([`Run`](crate::core::run::Run)) and the emitters of the standard backends work
47//! in this way. A program that embeds FLM therefore does not need to create
48//! worker threads.
49//!
50//! If you construct a guarded operation with a function of this module, or if
51//! you call [`copy_run_into_value`](crate::lang::copy::copy_run_into_value), run
52//! the operation inside [`on_worker_thread`].
53//!
54//! # Content that exceeds the limit
55//!
56//! When the guard stops an operation, the operation does not panic. It reports
57//! an error and produces no result. For instance, a parse returns
58//! [`FragmentError::NestingTooDeep`](crate::lang::FragmentError::NestingTooDeep),
59//! which contains the error [`NestingTooDeep`]. A rewrite pass records the same
60//! error, and the tree that the pass was rewriting is absent from the output of
61//! the run.
62
63use std::cell::Cell;
64use std::thread;
65
66use techy::core::Language;
67use techy::core::StdDescentGuardInit;
68use techy::error::DiagnosticInfo;
69use techy::recompose::TreeRecomposer;
70use techy::serialize::{SerdeSession, SerializableLang};
71use techy::transform::TreeRestager;
72use techy::visit::TreeWalker;
73
74use crate::lang::flm::Flm;
75
76/// The stack size of a worker thread, in bytes (64 MiB).
77///
78/// A thread that is marked as a worker thread with [`mark_worker_thread`] must
79/// have at least this much stack (see [the worker-thread
80/// requirement](self#the-worker-thread-requirement)).
81pub const WORKER_STACK_SIZE: usize = 64 * 1024 * 1024;
82
83/// The amount of stack, in bytes, that a guarded operation may use before the
84/// recursion guard stops it (48 MiB).
85///
86/// This budget is smaller than [`WORKER_STACK_SIZE`]. The difference leaves room
87/// for the stack that the operation uses between two checks of the guard, and
88/// for the stack that is used to report the error.
89pub const STACK_BUDGET: usize = 48 * 1024 * 1024;
90
91// The budget must leave headroom below the worker stack (checked at compile time).
92const _: () = assert!(STACK_BUDGET < WORKER_STACK_SIZE);
93
94thread_local! {
95 /// Whether the current thread is marked as a worker thread.
96 static WORKER_THREAD: Cell<bool> = const { Cell::new(false) };
97}
98
99/// Marks the current thread as a worker thread. [`on_worker_thread`] then runs
100/// guarded operations directly on this thread.
101///
102/// Call this function only on a thread that was created with at least
103/// [`WORKER_STACK_SIZE`] bytes of stack, for instance with
104/// `std::thread::Builder::stack_size` or with the corresponding setting of a
105/// thread pool. On a thread with a smaller stack, a guarded operation can
106/// overflow the stack before the recursion guard stops it (see [the
107/// worker-thread requirement](self#the-worker-thread-requirement)).
108///
109/// [`run_with_worker_stack`] marks the thread that it creates, so you do not
110/// need to call this function on that thread.
111pub fn mark_worker_thread() {
112 WORKER_THREAD.with(|marker| marker.set(true));
113}
114
115/// Returns whether the current thread has been marked as a worker thread with
116/// [`mark_worker_thread`].
117pub fn is_worker_thread() -> bool {
118 WORKER_THREAD.with(|marker| marker.get())
119}
120
121/// Runs `f` on a worker thread and returns its result.
122///
123/// If the current thread is marked as a worker thread ([`is_worker_thread`]),
124/// `f` runs on the current thread. Otherwise, `f` runs on a new thread created
125/// with [`run_with_worker_stack`].
126///
127/// The entry points of the library call this function before they run a
128/// guarded operation (see [the worker-thread
129/// requirement](self#the-worker-thread-requirement)). Call it yourself around a
130/// guarded operation that you construct with the functions of this module.
131///
132/// # Errors
133///
134/// Returns the error of the operating system if a new thread is needed and the
135/// operating system fails to create it. In this case, `f` does not run.
136///
137/// # Panics
138///
139/// A panic inside `f` propagates to the caller, on whichever thread `f` ran.
140pub fn on_worker_thread<T, F>(f: F) -> std::io::Result<T>
141where
142 T: Send,
143 F: FnOnce() -> T + Send,
144{
145 if is_worker_thread() {
146 Ok(f())
147 } else {
148 run_with_worker_stack(f)
149 }
150}
151
152/// The error that is reported when content is nested too deeply to be
153/// processed (`flm.blocks.nesting-too-deep`).
154///
155/// Reported by a parse and by the rewrite passes when the recursion guard stops
156/// them (see the [module documentation](self)).
157///
158/// A parse that reports this error returns no fragment. When a rewrite pass
159/// reports this error, the tree that the pass was rewriting is absent from the
160/// output of the run.
161#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
162#[diagnostic(
163 id = "flm.blocks.nesting-too-deep",
164 message = "Content too deeply nested: {detail}"
165)]
166pub struct NestingTooDeep {
167 /// techy's description of the limit that was reached.
168 pub detail: String,
169}
170
171/// A `GuardPolicy` is the kind of limit that the recursion guard sets on a
172/// guarded operation. The default policy,
173/// [`StackBudget`](GuardPolicy::StackBudget), is the policy for normal use.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
175pub enum GuardPolicy {
176 /// Stops the operation once it has used more than [`STACK_BUDGET`] bytes of
177 /// stack.
178 #[default]
179 StackBudget,
180 /// Stops the operation when it would open more than the given number of
181 /// descents at the same time. A parse opens about two descents for each
182 /// level of nesting, and a traversal opens one descent for each level of the
183 /// tree.
184 ///
185 /// Use this policy in tests only. It stops an operation at the same input on
186 /// every platform and with every build profile, which a test needs. However,
187 /// the number of descents does not measure the stack that each level uses, so
188 /// this policy does not protect against a stack overflow.
189 DepthLimit(usize),
190}
191
192impl GuardPolicy {
193 /// Returns this policy as a [`StdDescentGuardInit`], the configuration of
194 /// the descent guard that techy's constructors take.
195 pub fn init(self) -> StdDescentGuardInit {
196 match self {
197 GuardPolicy::StackBudget => StdDescentGuardInit::fixed_stack_budget(STACK_BUDGET),
198 GuardPolicy::DepthLimit(levels) => StdDescentGuardInit::depth_limit(levels),
199 }
200 }
201}
202
203/// Returns `language` with a recursion guard that applies `policy` to every
204/// parse with this language.
205///
206/// [`build_language`](crate::lang::build_language) calls this function on the
207/// language that it builds.
208pub fn language(language: Language<Flm>, policy: GuardPolicy) -> Language<Flm> {
209 language.with_descent_guard_init(policy.init())
210}
211
212/// Returns a [`TreeWalker`] for `visitor`, with a recursion guard that applies
213/// `policy`.
214///
215/// A tree walker traverses a tree without changing it. Use this function in
216/// place of `TreeWalker::new`, which installs techy's small default budget.
217pub fn walker<V: ?Sized>(visitor: &mut V, policy: GuardPolicy) -> TreeWalker<'_, V> {
218 TreeWalker::new(visitor).with_descent_guard_init(policy.init())
219}
220
221/// Returns a [`TreeRestager`] for `visitor`, with a recursion guard that
222/// applies `policy`.
223///
224/// A tree restager traverses a tree and builds a new tree from it, with
225/// changes applied. Use this function in place of `TreeRestager::new`, which
226/// installs techy's small default budget.
227pub fn restager<V: ?Sized>(visitor: &mut V, policy: GuardPolicy) -> TreeRestager<'_, V> {
228 TreeRestager::new(visitor).with_descent_guard_init(policy.init())
229}
230
231/// Returns a [`TreeRecomposer`] for `recomposer`, with a recursion guard that
232/// applies `policy`.
233///
234/// A tree recomposer traverses a tree and combines it into one value, for
235/// instance a string of source text. Use this function in place of
236/// `TreeRecomposer::new`, which installs techy's small default budget.
237pub fn recomposer<R: ?Sized>(recomposer: &mut R, policy: GuardPolicy) -> TreeRecomposer<'_, R> {
238 TreeRecomposer::new(recomposer).with_descent_guard_init(policy.init())
239}
240
241/// Returns `session` with a recursion guard that applies `policy` when the
242/// session serializes or deserializes a tree.
243pub fn serde_session<L: SerializableLang>(
244 session: SerdeSession<L>,
245 policy: GuardPolicy,
246) -> SerdeSession<L> {
247 session.with_descent_guard_init(policy.init())
248}
249
250/// Runs `f` on a new worker thread and returns its result.
251///
252/// The new thread is created with [`WORKER_STACK_SIZE`] bytes of stack, and it
253/// is marked as a worker thread with [`mark_worker_thread`]. This function
254/// always creates a thread. In most cases, prefer [`on_worker_thread`], which
255/// creates a thread only if the current thread is not a worker thread.
256///
257/// # Errors
258///
259/// Returns the error of the operating system if the operating system fails to
260/// create the thread. In this case, `f` does not run.
261///
262/// # Panics
263///
264/// A panic inside `f` is caught on the new thread and resumed on the calling
265/// thread. The caller therefore observes the panic as if `f` had run on the
266/// calling thread.
267pub fn run_with_worker_stack<T, F>(f: F) -> std::io::Result<T>
268where
269 T: Send,
270 F: FnOnce() -> T + Send,
271{
272 thread::scope(|scope| {
273 let handle = thread::Builder::new().stack_size(WORKER_STACK_SIZE).spawn_scoped(scope, || {
274 mark_worker_thread();
275 f()
276 })?;
277 match handle.join() {
278 Ok(value) => Ok(value),
279 Err(payload) => std::panic::resume_unwind(payload),
280 }
281 })
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 #[test]
289 fn a_worker_run_returns_its_value() {
290 assert_eq!(run_with_worker_stack(|| 41 + 1).unwrap(), 42);
291 }
292
293 #[test]
294 fn a_worker_run_is_marked_and_the_caller_is_not() {
295 assert!(!is_worker_thread());
296 assert!(run_with_worker_stack(is_worker_thread).unwrap());
297 assert!(!is_worker_thread());
298 }
299
300 #[test]
301 fn a_marked_thread_runs_the_closure_in_place() {
302 let outside = thread::current().id();
303 let (ran_on, spawned) = run_with_worker_stack(|| {
304 let inner = thread::current().id();
305 let ran_on = on_worker_thread(|| thread::current().id()).unwrap();
306 (ran_on == inner, inner != outside)
307 })
308 .unwrap();
309 assert!(ran_on);
310 assert!(spawned);
311 }
312}