1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! This module provides the recursion guard of FLM, which reports an error for
//! deeply nested content before the content overflows the stack, along with the
//! worker threads on which every guarded operation runs.
//!
//! Parsing, traversing, rewriting and serializing a tree are recursive
//! operations, so deeply nested content uses much stack. A stack overflow ends
//! the process, and the program that embeds FLM cannot recover from it. To
//! prevent the overflow, techy provides a *descent guard*: the guard measures
//! the stack that a recursive operation has used since it started, and stops the
//! operation when this amount exceeds a budget. The operation then reports an
//! error, for instance [`NestingTooDeep`] (`flm.blocks.nesting-too-deep`) for a
//! parse. See also [the recursion guard and worker
//! threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads).
//!
//! # Guarded construction
//!
//! techy's default budget is small, and the budget of a language or of a
//! traversal can only be set when the language or the traversal is constructed.
//! FLM therefore constructs every recursive operation with one of the following
//! functions of this module, which install the guard:
//!
//! - [`language`], for parsing;
//! - [`walker`], [`restager`] and [`recomposer`], for traversals of a tree;
//! - [`serde_session`], for serialization.
//!
//! The limit is selected with the [`GuardPolicy`] argument that each function
//! takes.
//! [`GuardPolicy::StackBudget`] limits the stack use and is the policy for
//! normal use. [`GuardPolicy::DepthLimit`] limits the number of nested descents
//! and is used in tests only.
//!
//! # The worker-thread requirement
//!
//! The guard cannot ask the operating system how much stack a thread has.
//! Whoever creates a thread for guarded operations therefore declares the
//! thread's stack once, where the thread starts, with [`mark_worker_thread`]
//! and a [`WorkerStack`]. A thread marked in this way is a *worker thread*.
//! Every guarded operation must run on a worker thread.
//!
//! The declared stack has three parts, and each is stated by the party that
//! knows it:
//!
//! - The *reserved share* is for what the host runs on the thread outside the
//! guarded operations, such as the stack of a JavaScript engine that a
//! handler runs on. The host states it, in bytes
//! ([`WorkerStack::with_reserved`]). If the host states none, the reserved
//! share is one quarter of the declared size ([`WorkerStack::new`]).
//! - The *library's margin* is for the library's own work that the guard does
//! not measure: the work between two checks of the guard, and the report of a
//! refusal. The library states it, and takes it off in every case, so that
//! deep content is refused rather than overflowing the stack even with a
//! reserved share of zero.
//! - The rest is for the guarded operations, which together use at most that
//! much, measured from the place where the thread was marked. Each guarded
//! operation therefore gets, as its budget, the stack that remains on the
//! thread when it starts, less the reserved share and the margin: an
//! operation started inside another one gets less than one started at the top
//! of the thread.
//!
//! On a thread that is not marked, a guarded operation gets techy's small
//! default budget (250 KiB), which fits in the stack of an ordinary thread but
//! refuses content that is only moderately nested.
//!
//! The entry points of the library meet this requirement for their callers. They
//! run each guarded operation through [`on_worker_thread`], which runs the
//! operation on the current thread if this thread is marked as a worker thread,
//! and otherwise on a new thread of [`WORKER_STACK_SIZE`] bytes of stack, marked
//! with this size and the default reserved share. The [parse functions](crate::lang::parse),
//! the [rewrite passes](crate::lang::rewrites), the run of a plan
//! ([`Run`](crate::core::run::Run)) and the emitters of the standard backends work
//! in this way. A program that embeds FLM therefore does not need to create
//! worker threads.
//!
//! If you construct a guarded operation with a function of this module, or if
//! you call [`copy_run_into_value`](crate::lang::copy::copy_run_into_value), run
//! the operation inside [`on_worker_thread`].
//!
//! # A host with one thread
//!
//! A program that cannot create threads, such as a WebAssembly module, marks
//! its one thread itself: call [`mark_worker_thread`] once, with the stack of
//! the thread, before the first call of the host into the library (where the
//! thread starts, or at the entry of that first call). Marking the thread again
//! at the entry of a later call is also allowed, and replaces the declaration.
//! [`on_worker_thread`] then runs every operation in place, and no thread is
//! created. The size declared is at most the stack that is really available
//! below the place of the mark; a WebAssembly module states the size that it is
//! linked with (the linker's `-z stack-size`), from the same number that the
//! build script gives to the linker. The reserved share declared is what the
//! host's extensions need on that stack, which the host measures in its
//! engine; a host that runs no JavaScript extension can declare a reserved
//! share of zero.
//!
//! On `wasm32`, the guard measures the addresses of local variables. These lie
//! in the stack inside the module's linear memory, so the guard protects that
//! stack. It does not see the call stack of the engine that runs the module, so
//! the host chooses a stack small enough that the guard refuses deep content
//! before the engine's call stack is used up, and verifies this in its engine.
//! The host links the stack that the guarded work needs together with the
//! reserved share that it declares.
//!
//! # Content that exceeds the limit
//!
//! When the guard stops an operation, the operation does not panic. It reports
//! an error and produces no result. For instance, a parse returns
//! [`FragmentError::NestingTooDeep`](crate::lang::FragmentError::NestingTooDeep),
//! which contains the error [`NestingTooDeep`]. A rewrite pass records the same
//! error, and the tree that the pass was rewriting is absent from the output of
//! the run.
use Cell;
use thread;
use Language;
use StdDescentGuardInit;
use DiagnosticInfo;
use TreeRecomposer;
use ;
use TreeRestager;
use TreeWalker;
use crateFlm;
/// The stack size of the threads that the library creates for guarded
/// operations, in bytes (64 MiB).
///
/// [`run_with_worker_stack`] and the thread pool of the runner create their
/// threads with this much stack, and mark them with this size and the default
/// reserved share (see [the
/// worker-thread requirement](self#the-worker-thread-requirement)).
pub const WORKER_STACK_SIZE: usize = 64 * 1024 * 1024;
/// The stack that the library keeps for its own work that the recursion guard
/// does not measure, in bytes: the work between two checks of the guard, and
/// the report of a refusal. Taken off every budget, whatever the reserved share.
const LIBRARY_MARGIN: usize = 256 * 1024;
/// A `WorkerStack` is what a worker thread declares about its stack: its size,
/// and the reserved share of it that guarded operations leave unused, both in
/// bytes.
///
/// The reserved share is for what the host runs on the thread outside the
/// guarded operations, such as the stack of a JavaScript engine that a handler
/// runs on. Pass the declaration to [`mark_worker_thread`]; [`worker_stack`]
/// answers it back (see [the worker-thread
/// requirement](self#the-worker-thread-requirement)).
///
/// No value is refused. A reserved share as large as the declared size leaves
/// no budget to guarded operations, and the recursion guard then refuses all
/// nesting.
///
/// ```
/// use flm_core::lang::guard::WorkerStack;
///
/// let stack = WorkerStack::new(8 * 1024 * 1024).with_reserved(0);
/// assert_eq!(stack.size(), 8 * 1024 * 1024);
/// assert_eq!(stack.reserved(), 0);
/// ```
/// The stack that a worker thread declares, and the stack position where the
/// thread was marked.
thread_local!
/// Returns the address of a local of its own frame, as the current stack
/// position. Never inlined, so that the local lies in a frame of its own below
/// the caller's.
/// Marks the current thread as a worker thread with the declared `stack`.
/// [`on_worker_thread`] then runs guarded operations directly on this thread,
/// and their budget is derived from `stack`.
///
/// The current stack position is recorded as the top of the thread's stack:
/// guarded operations together use at most the declared size less the reserved
/// share and the library's margin, measured from this place. Call this function
/// where the thread starts, or at the entry of the host's call into the
/// library, and never inside a guarded operation. The declared size must be at
/// most the stack that is really available below that place, for instance the
/// size given to `std::thread::Builder::stack_size`, to the corresponding
/// setting of a thread pool, or to the linker of a WebAssembly module. With a
/// larger value, a guarded operation can overflow the stack before the
/// recursion guard stops it (see [the worker-thread
/// requirement](self#the-worker-thread-requirement)). A small size, or a large
/// reserved share, is safe: the guard then refuses content that is less deeply
/// nested.
///
/// Marking a thread again replaces its declaration. [`run_with_worker_stack`]
/// marks the thread that it creates, so you do not need to call this function
/// on that thread.
///
/// ```
/// use flm_core::lang::guard::{self, WorkerStack};
///
/// let stack = WorkerStack::new(16 * 1024 * 1024).with_reserved(4 * 1024 * 1024);
/// let declared = std::thread::Builder::new()
/// .stack_size(stack.size())
/// .spawn(move || {
/// guard::mark_worker_thread(stack);
/// guard::worker_stack()
/// })
/// .unwrap()
/// .join()
/// .unwrap();
/// assert_eq!(declared, Some(stack));
/// ```
/// Returns the stack that the current thread declared with
/// [`mark_worker_thread`], or `None` if the current thread is not marked as a
/// worker thread.
/// Returns the stack, in bytes, that remains on the current thread for guarded
/// operations: the declared size, less the stack used since the thread was
/// marked, less the reserved share, less [`LIBRARY_MARGIN`], saturating at
/// zero. Returns `None` if the current thread is not marked as a worker thread.
///
/// The distance between the two positions is taken as an absolute difference,
/// so no direction of stack growth is assumed.
pub
/// Returns the number of levels that a recursive walk started here may open
/// when one level uses at most `level_stack` bytes of stack: [`stack_budget`]
/// divided by `level_stack`, or zero if the current thread is not marked as a
/// worker thread.
///
/// The emitters, which count their own levels rather than use the guard of
/// techy, read their limit with it once, when a walk starts.
pub
/// Runs `f` on a worker thread and returns its result.
///
/// If the current thread is marked as a worker thread ([`worker_stack`]
/// answers a declaration), `f` runs on the current thread. Otherwise, `f` runs on a
/// new thread created with [`run_with_worker_stack`].
///
/// The entry points of the library call this function before they run a
/// guarded operation (see [the worker-thread
/// requirement](self#the-worker-thread-requirement)). Call it yourself around a
/// guarded operation that you construct with the functions of this module.
///
/// # Errors
///
/// Returns the error of the operating system if a new thread is needed and the
/// operating system fails to create it. In this case, `f` does not run.
///
/// # Panics
///
/// A panic inside `f` propagates to the caller, on whichever thread `f` ran.
/// The error that is reported when content is nested too deeply to be
/// processed (`flm.blocks.nesting-too-deep`).
///
/// Reported by a parse and by the rewrite passes when the recursion guard stops
/// them (see the [module documentation](self)).
///
/// A parse that reports this error returns no fragment. When a rewrite pass
/// reports this error, the tree that the pass was rewriting is absent from the
/// output of the run.
/// A `GuardPolicy` is the kind of limit that the recursion guard sets on a
/// guarded operation. The default policy,
/// [`StackBudget`](GuardPolicy::StackBudget), is the policy for normal use.
/// Returns `language` with a recursion guard that applies `policy` to every
/// parse with this language.
///
/// [`build_language`](crate::lang::build_language) calls this function on the
/// language that it builds.
/// Returns a [`TreeWalker`] for `visitor`, with a recursion guard that applies
/// `policy`.
///
/// A tree walker traverses a tree without changing it. Use this function in
/// place of `TreeWalker::new`, which installs techy's small default budget.
Sized>
/// Returns a [`TreeRestager`] for `visitor`, with a recursion guard that
/// applies `policy`.
///
/// A tree restager traverses a tree and builds a new tree from it, with
/// changes applied. Use this function in place of `TreeRestager::new`, which
/// installs techy's small default budget.
Sized>
/// Returns a [`TreeRecomposer`] for `recomposer`, with a recursion guard that
/// applies `policy`.
///
/// A tree recomposer traverses a tree and combines it into one value, for
/// instance a string of source text. Use this function in place of
/// `TreeRecomposer::new`, which installs techy's small default budget.
Sized>
/// Returns `session` with a recursion guard that applies `policy` when the
/// session serializes or deserializes a tree.
/// Runs `f` on a new worker thread and returns its result.
///
/// The new thread is created with [`WORKER_STACK_SIZE`] bytes of stack, and it
/// is marked as a worker thread with this size and the default reserved share
/// (`WorkerStack::new(WORKER_STACK_SIZE)`, [`mark_worker_thread`]) as its first
/// action. This function always creates a thread. In most cases, prefer
/// [`on_worker_thread`], which creates a thread only if the current thread is
/// not a worker thread.
///
/// # Errors
///
/// Returns the error of the operating system if the operating system fails to
/// create the thread. In this case, `f` does not run.
///
/// # Panics
///
/// A panic inside `f` is caught on the new thread and resumed on the calling
/// thread. The caller therefore observes the panic as if `f` had run on the
/// calling thread.