markdoc/depth.rs
1//! Call stack depth: where upstream's recursion is bounded only by V8's stack, the port's
2//! stops where node's does.
3//!
4//! Upstream (markdown-it's block and inline rules, the tag grammar, the parser's
5//! `handleToken`, `walk()`, the validator's `walkWithParents`, `Node.resolve` and `resolve`,
6//! the transformer, the HTML renderer, `String()` of arrays, `JSON.stringify`) recurses until
7//! V8's stack runs out, and then throws `RangeError: Maximum call stack size exceeded`. How
8//! deep that is depends on what nests: each level of a shape puts the same frames on the stack,
9//! and different shapes put different frames (a blockquote costs less than a list item, an
10//! array in a tag's value less than a hash). This module models that stack as a budget per
11//! thread, charged at each recursion site the port shares with upstream:
12//!
13//! - [`STACK`] is node's stack and every site's cost is a share of it, chosen so that each
14//! shape on its own, called from the top of a script, stops where a fresh node 22 process
15//! throws (the shape's "pure" limit; see `per_level`). Shapes that mix sites (a tag's value
16//! inside nested blockquotes, a list inside partials, a value resolved deep in a document)
17//! then stop near node's too, as V8's frames add up the same way. Nested calls share the
18//! budget as they share node's stack: a `debug()` deep in a document has less of it left
19//! than one at the top. The port's own loops (the parser's, the validator's, `resolve`'s,
20//! the HTML renderer's, `String()`'s and `JSON.stringify`'s walks) charge their path the
21//! same way without recursing.
22//! - Where the recursion mirrors upstream's (the engine's rules, the grammar, the transform,
23//! the values' resolution, serde of the AST), `grow!` runs the next level on a new stack
24//! segment when the thread's stack runs low (the `stacker` crate), so that the budget, not
25//! the thread's stack, is the limit, whatever stack the caller runs on: a 2 MiB thread in a
26//! debug build reaches node's limits as a release build on the main thread does.
27//! - Where the stack cannot grow ([`can_grow`]: the `stack-growth` feature off, a target
28//! without stack switching such as wasm, whose call stack is the host's, or a thread whose
29//! stack bounds are unknown), each of those recursions keeps the fixed limit it had before
30//! the budget, which fits a 2 MiB stack in a debug build with a quarter spare: there those
31//! limits, below node's, are the host's limit. The loops keep node's limits everywhere.
32//!
33//! Node's own limits move with how warm V8 is (optimized frames are smaller, and a call that
34//! does much work before it nests warms V8 up within the call) and with the stack below the
35//! call, so around each limit there is a band where a fresh process throws and a warmed-up
36//! one does not; the port's limits are the fresh process's (`CONFORMANCE.md` gives the table).
37//!
38//! What it costs: a charge is a thread-local add and compare, and `grow!` reads the stack
39//! pointer and the thread's stack limit; both run once per level of what nests (a blockquote,
40//! a value in a tag, a node transformed), never per character, and segments are allocated only
41//! past the thread's own stack.
42
43use std::cell::Cell;
44
45/// Node's stack in the budget's units: V8's default `--stack-size` (984 KB), in 2^-20ths of a
46/// byte (fine enough that `n` levels of `per_level(n)` fit and `n + 1` do not for any `n` up to
47/// a million). Only the ratios of the costs to it matter.
48pub const STACK: u64 = 984 * 1024 * 1024 * 1024;
49
50/// The cost of one level of a shape that node 22, in a fresh process at the top level of a
51/// script, nests `n` levels deep and throws `RangeError` for one more: `n` levels fit
52/// [`STACK`] and `n + 1` do not.
53pub(crate) const fn per_level(n: u64) -> u64 {
54 STACK / n
55}
56
57/// What a level of a shape that nests `b` deep costs beyond one of a shape that nests `a`
58/// deep (`b < a`): the cost of a site that adds to a level of the first shape so that the two
59/// together cost `per_level(b)` (a function parameter after a comma, which costs more than
60/// the first parameter; a heading's transform, which costs more than a paragraph's).
61pub(crate) const fn extra(a: u64, b: u64) -> u64 {
62 per_level(b) - per_level(a)
63}
64
65thread_local! {
66 /// How much of [`STACK`] the levels open on this thread take.
67 static USED: Cell<u64> = const { Cell::new(0) };
68}
69
70/// One open level of a recursion, charged on the thread's budget: what it cost is given back
71/// when it is dropped (also when an error or a panic unwinds through it).
72#[must_use = "the level is given back when this is dropped"]
73#[derive(Debug)]
74pub(crate) struct Level {
75 cost: u64,
76}
77
78impl Drop for Level {
79 fn drop(&mut self) {
80 USED.with(|used| used.set(used.get().saturating_sub(self.cost)));
81 }
82}
83
84/// Opens a level costing `cost`: `None` where node's stack would run out (the caller then
85/// throws `RangeError: Maximum call stack size exceeded`).
86#[inline]
87pub(crate) fn enter(cost: u64) -> Option<Level> {
88 USED.with(|used| {
89 let now = used.get().checked_add(cost).filter(|&now| now <= STACK)?;
90 used.set(now);
91 Some(Level { cost })
92 })
93}
94
95/// How much of [`STACK`] the open levels take on this thread (0 outside any call).
96pub(crate) fn used() -> u64 {
97 USED.with(Cell::get)
98}
99
100/// What is left of [`STACK`] on this thread: what a loop that walks a path without recursing
101/// may charge its path, as its levels would on node's stack.
102pub(crate) fn left() -> u64 {
103 STACK.saturating_sub(used())
104}
105
106/// What [`grow!`] keeps free below a level: at least this much stack is left when the next
107/// level starts. A level of the port's deepest-framed recursions takes under 8 KiB in a debug
108/// build; the margin covers what runs between two levels (a rule's frames, a schema's
109/// transform written in Rust, a regular expression) with room to spare.
110#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
111const RED_ZONE: usize = 256 * 1024;
112
113/// The size of each stack segment [`grow!`] adds: a few hundred levels of the costliest
114/// recursion in a debug build, so that a deep input switches stacks rarely.
115#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
116const SEGMENT: usize = 4 * 1024 * 1024;
117
118/// The address of a byte in the caller's frame: where its stack is (stacks grow down on every
119/// target this crate supports).
120#[inline(always)]
121pub(crate) fn stack_address() -> usize {
122 let marker = 0u8;
123 std::hint::black_box(&marker) as *const u8 as usize
124}
125
126#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
127thread_local! {
128 /// The lowest address the stack in use on this thread may reach: 0 until asked, 1 where
129 /// its bounds are unknown (no growth), else the thread's stack limit or, while a level
130 /// runs on a segment [`grow!`] added, the segment's. (Kept here rather than asked of
131 /// `stacker` at every level: reading it there costs a call and a lazy thread-local, many
132 /// times a check of this.)
133 static LIMIT: Cell<usize> = const { Cell::new(0) };
134}
135
136/// How far below the stack's limit a check of [`LIMIT`] is believed: farther than any stack
137/// this crate's recursions run on, the limit is another stack's (a thread's first level run
138/// on a segment of someone else's), and `stacker` is asked again.
139#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
140const LIMIT_SPAN: usize = 1 << 30;
141
142/// [`LIMIT`] for a stack at `here`, from `stacker` (which knows the thread's bounds, and the
143/// segment's while it runs one).
144#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
145#[cold]
146fn learn_limit(here: usize) -> usize {
147 let limit = stacker::remaining_stack().map_or(1, |left| here.saturating_sub(left).max(2));
148 LIMIT.with(|l| l.set(limit));
149 limit
150}
151
152/// Whether recursion grows the stack on this thread: the `stack-growth` feature is on, the
153/// target can switch stacks (not wasm) and the thread's stack bounds are known (they are on
154/// Linux, macOS, Windows and the BSDs). Where it cannot, the recursions that mirror upstream's
155/// stop at their fixed limits (each module's `MAX_*` constants say which) instead of node's.
156pub fn can_grow() -> bool {
157 #[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
158 {
159 match LIMIT.with(Cell::get) {
160 0 => learn_limit(stack_address()) != 1,
161 limit => limit != 1,
162 }
163 }
164 #[cfg(not(all(feature = "stack-growth", not(target_family = "wasm"))))]
165 {
166 false
167 }
168}
169
170/// Runs `f`, the next level of a recursion, on a stack with at least `RED_ZONE` free: on a
171/// new segment when the thread's stack (or the current segment) is short of it (see
172/// [`grow!`]). The common case, room to spare, is a thread-local read and a compare.
173#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
174#[inline]
175pub(crate) fn grow_with<R>(f: impl FnOnce() -> R) -> R {
176 let here = stack_address();
177 let limit = LIMIT.with(Cell::get);
178 if limit > 1 && here.wrapping_sub(limit).wrapping_sub(RED_ZONE) < LIMIT_SPAN {
179 return f();
180 }
181 grow_slow(here, limit, f)
182}
183
184/// [`grow_with`] where the stack is short (or its limit not yet known).
185#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
186#[cold]
187#[inline(never)]
188fn grow_slow<R>(here: usize, limit: usize, f: impl FnOnce() -> R) -> R {
189 let limit = if limit > 1 && here.wrapping_sub(limit) < LIMIT_SPAN {
190 limit
191 } else {
192 learn_limit(here)
193 };
194 if limit == 1 || here.saturating_sub(limit) >= RED_ZONE {
195 return f();
196 }
197 /// Puts the stack's limit back when the level on the segment ends (or unwinds).
198 struct Restore(usize);
199 impl Drop for Restore {
200 fn drop(&mut self) {
201 LIMIT.with(|l| l.set(self.0));
202 }
203 }
204 stacker::grow(SEGMENT, move || {
205 let _restore = Restore(limit);
206 learn_limit(stack_address());
207 f()
208 })
209}
210
211/// `grow!(expr)`: evaluates `expr`, the next level of a recursion, on a stack with at least
212/// `RED_ZONE` free (a new segment when the thread's stack, or the current segment, is short of
213/// it). Without stack growth ([`can_grow`]), `expr` is evaluated where it is, with no frame
214/// of its own (a closure would add one to every level of a debug build), and the caller's
215/// fixed limit keeps the stack from overflowing.
216#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
217macro_rules! grow {
218 ($e:expr) => {
219 $crate::depth::grow_with(|| $e)
220 };
221}
222#[cfg(not(all(feature = "stack-growth", not(target_family = "wasm"))))]
223macro_rules! grow {
224 ($e:expr) => {
225 $e
226 };
227}
228pub(crate) use grow;
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[test]
235 fn a_shape_of_n_levels_fits_and_one_more_does_not() {
236 for n in [1, 2, 3, 300, 1_716, 2_914, 4_642, 9_820, 60_000] {
237 let cost = per_level(n);
238 assert_eq!(left() / cost, n);
239 let levels: Vec<Level> = (0..n).map(|_| enter(cost).expect("fits")).collect();
240 assert!(enter(cost).is_none(), "{n}");
241 drop(levels);
242 assert_eq!(used(), 0);
243 }
244 }
245
246 #[test]
247 fn levels_are_given_back_on_unwind() {
248 let r = std::panic::catch_unwind(|| {
249 let _a = enter(per_level(10)).unwrap();
250 let _b = enter(per_level(10)).unwrap();
251 panic!("unwinds");
252 });
253 assert!(r.is_err());
254 assert_eq!(used(), 0);
255 }
256
257 #[test]
258 fn growth_is_available_where_the_feature_and_target_allow_it() {
259 let expected = cfg!(all(feature = "stack-growth", not(target_family = "wasm")));
260 assert_eq!(can_grow(), expected);
261 // a recursion far deeper than a 2 MiB thread holds, through grow
262 fn down(n: usize) -> usize {
263 let pad = std::hint::black_box([0u8; 512]);
264 if n == 0 {
265 return 1;
266 }
267 grow!(down(n - 1)) + usize::from(pad[n % 512])
268 }
269 if expected {
270 let r = std::thread::Builder::new()
271 .stack_size(2 << 20)
272 .spawn(|| down(100_000))
273 .unwrap()
274 .join()
275 .unwrap();
276 assert!(r > 0);
277 }
278 }
279}