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
//! Resource budgets: how much work one expander may do before it refuses.
//!
//! Macro expansion is driven by input the compiler does not control, and a
//! two-line macro can describe unbounded work. The recursion limit alone does
//! not stop that: a macro that doubles its argument (`dup!($($t)*) =>
//! dup!($($t)* $($t)*)`) reaches `2^128` tokens long before it reaches depth
//! 128, and a macro that expands into two calls of itself performs `2^128`
//! expansions without ever nesting deeper than 128. A [`Budget`] caps all three
//! quantities, so the total time and memory an expander spends is bounded no
//! matter what the macros say.
use fmt;
/// The limits an [`Expander`](crate::Expander) enforces on the work it does.
///
/// | Field | Limits | Default | Exceeding it reports |
/// |---|---|---:|---|
/// | [`max_depth`](Budget::max_depth) | How deeply invocations may nest. | 128 | [`ExpandError::RecursionLimit`](crate::ExpandError::RecursionLimit) |
/// | [`max_expansions`](Budget::max_expansions) | Successful expansions since creation or the last `reset_usage`. | 1 048 576 (`2^20`) | [`ExpandError::Budget`](crate::ExpandError::Budget)`(`[`Limit::Expansions`]`)` |
/// | [`max_tokens`](Budget::max_tokens) | Tokens written since creation or the last `reset_usage`. | 4 194 304 (`2^22`) | [`ExpandError::Budget`](crate::ExpandError::Budget)`(`[`Limit::Tokens`]`)` |
///
/// Every expander has a budget; [`Expander::new`](crate::Expander::new) uses
/// [`Budget::DEFAULT`]. The expansion and token counts are **cumulative**: they
/// accumulate in the expander's [`Usage`] until
/// [`Expander::reset_usage`](crate::Expander::reset_usage) zeroes them. A
/// batch compiler uses one expander per compilation and never resets, so the
/// budget bounds the compilation's total macro output; a long-lived host (a
/// language server, a REPL, a watch-mode compiler) resets once per unit of
/// work — per document parse, per REPL entry, per compilation — so the budget
/// bounds each unit instead of the host's lifetime.
///
/// The defaults are well above what typical programs expand to, and stop a
/// runaway macro quickly: the doubling macro in `examples/budget` stops in
/// about 0.2 s (release build) with a whole-process peak of about 400 MB.
/// Memory grows in proportion to `max_tokens`, so lower it where that is too
/// much; a unit of work that legitimately needs more can raise the budget with
/// [`Expander::set_budget`](crate::Expander::set_budget).
///
/// Tokens are counted as they are written: one per token, two per group (its
/// delimiters), and every token of a substituted capture. An expansion that
/// would push the total past `max_tokens` stops as soon as it does, so even a
/// single enormous expansion allocates no more than the budget allows.
///
/// A failed expansion is not charged: like every other error it leaves the
/// expander exactly as it was.
///
/// The struct is `#[non_exhaustive]` so that further limits can be added in a
/// minor release. Start from [`Budget::DEFAULT`] (or [`Budget::default`]) and
/// adjust it with the `with_*` methods, or assign the public fields.
///
/// # Examples
///
/// ```
/// use macro_lang::{Budget, Expander};
///
/// let budget = Budget::DEFAULT.with_max_depth(32).with_max_tokens(1 << 16);
/// let expander: Expander<char> = Expander::with_budget(budget);
/// assert_eq!(expander.budget().max_depth, 32);
/// assert_eq!(expander.budget().max_tokens, 65_536);
/// assert_eq!(expander.budget().max_expansions, Budget::DEFAULT.max_expansions);
/// assert_eq!(expander.limit(), 32);
/// ```
/// The work an [`Expander`](crate::Expander) has charged against its
/// [`Budget`]: successful expansions and the tokens they wrote, since the
/// expander was created or
/// [`reset_usage`](crate::Expander::reset_usage) was last called.
///
/// Returned by [`Expander::usage`](crate::Expander::usage). Failed expansions
/// are never charged. The struct is `#[non_exhaustive]` so that further
/// counters can be added in a minor release; read the fields directly.
///
/// Added in 1.1.0.
///
/// # Examples
///
/// ```
/// use macro_lang::{Expander, Usage};
///
/// let expander: Expander<char> = Expander::new();
/// let usage = expander.usage();
/// assert_eq!((usage.expansions, usage.tokens), (0, 0));
/// assert_eq!(usage, Usage::NONE);
/// assert_eq!(Usage::default(), Usage::NONE);
/// ```
/// Which part of a [`Budget`] an expansion ran out of, reported by
/// [`ExpandError::Budget`](crate::ExpandError::Budget).
///
/// Depth is not listed: exceeding [`Budget::max_depth`] keeps reporting
/// [`ExpandError::RecursionLimit`](crate::ExpandError::RecursionLimit), as it
/// did before budgets existed. The enum is `#[non_exhaustive]` so that further
/// limits can be added in a minor release.
///
/// # Examples
///
/// ```
/// use macro_lang::{Budget, Context, ExpandError, Expander, Limit, Macro, Rule, Template};
/// use intern_lang::Interner;
/// use token_lang::Span;
///
/// let mut names = Interner::new();
/// // three!() => a b c
/// let three = Macro::new(names.intern("three"), vec![Rule {
/// pattern: vec![],
/// template: "abc".chars().map(|c| Template::token(c, Span::new(0, 1))).collect(),
/// }])?;
///
/// let mut expander = Expander::with_budget(Budget::DEFAULT.with_max_tokens(5));
/// assert!(expander.expand(&three, &[], Span::new(0, 1), Context::ROOT).is_ok());
/// // Three more tokens would make six, one more than the budget allows.
/// assert_eq!(
/// expander.expand(&three, &[], Span::new(0, 1), Context::ROOT),
/// Err(ExpandError::Budget(Limit::Tokens { max: 5 })),
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```