Skip to main content

macro_lang/
error.rs

1//! The two ways macro work fails: a bad definition, or a bad invocation.
2
3use core::fmt;
4
5use intern_lang::Symbol;
6use token_lang::Span;
7
8use crate::Limit;
9
10/// Why [`Macro::new`](crate::Macro::new) rejected a macro definition.
11///
12/// Every check that can be made without an invocation is made when the macro is
13/// defined, so a macro that compiles can only fail to expand for reasons that
14/// depend on the input. Each variant names the offending rule by its index in
15/// the list passed to `Macro::new`; metavariable names are reported as the
16/// [`Symbol`] the definition used, which the caller resolves through its own
17/// interner.
18///
19/// The enum is `#[non_exhaustive]`: later releases may add checks.
20///
21/// # Examples
22///
23/// ```
24/// use macro_lang::{Macro, MacroError, Rule, Template};
25/// use intern_lang::Interner;
26///
27/// let mut names = Interner::new();
28/// let x = names.intern("x");
29///
30/// // The template uses `$x`, but the pattern never binds it.
31/// let err = Macro::<char>::new(names.intern("m"), vec![Rule {
32///     pattern: vec![],
33///     template: vec![Template::Var(x)],
34/// }]).unwrap_err();
35/// assert_eq!(err, MacroError::UnboundVariable { rule: 0, name: x });
36/// ```
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38#[non_exhaustive]
39pub enum MacroError {
40    /// The macro has no rules, so no invocation could ever match it. Give it at
41    /// least one rule.
42    NoRules,
43    /// A pattern binds the same metavariable name twice, so a template use of it
44    /// would be ambiguous. Rename one of the bindings.
45    DuplicateBinding {
46        /// Index of the offending rule.
47        rule: usize,
48        /// The name bound twice.
49        name: Symbol,
50    },
51    /// A template uses a metavariable its rule's pattern never binds. Bind it in
52    /// the pattern, or write the token literally.
53    UnboundVariable {
54        /// Index of the offending rule.
55        rule: usize,
56        /// The unbound name.
57        name: Symbol,
58    },
59    /// A template uses a repeating metavariable outside enough repetitions to
60    /// expand it: the pattern captured it inside `n` repetitions, but the
61    /// template uses it inside fewer. Wrap the use in a `Template::Repeat`.
62    StillRepeating {
63        /// Index of the offending rule.
64        rule: usize,
65        /// The metavariable used too shallowly.
66        name: Symbol,
67    },
68    /// A template repetition contains no metavariable that repeats at its
69    /// depth, so there is no way to know how many times to write it. Use a
70    /// repeating metavariable inside it, or remove the repetition.
71    NoRepeatingVariable {
72        /// Index of the offending rule.
73        rule: usize,
74    },
75    /// A pattern repetition can match without consuming anything, so it could
76    /// repeat forever. Give its body at least one token, group, or binding that
77    /// must be present.
78    EmptyRepetition {
79        /// Index of the offending rule.
80        rule: usize,
81    },
82    /// A pattern repetition uses [`Kleene::ZeroOrOne`](crate::Kleene::ZeroOrOne)
83    /// together with a separator. An optional element never repeats, so the
84    /// separator could never appear. Remove the separator.
85    OptionalSeparator {
86        /// Index of the offending rule.
87        rule: usize,
88    },
89}
90
91impl fmt::Display for MacroError {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self {
94            Self::NoRules => f.write_str("macro has no rules"),
95            Self::DuplicateBinding { rule, name } => {
96                write!(
97                    f,
98                    "rule {rule}: metavariable {name:?} is bound more than once"
99                )
100            }
101            Self::UnboundVariable { rule, name } => {
102                write!(
103                    f,
104                    "rule {rule}: metavariable {name:?} is not bound by the pattern"
105                )
106            }
107            Self::StillRepeating { rule, name } => write!(
108                f,
109                "rule {rule}: metavariable {name:?} is still repeating at this depth"
110            ),
111            Self::NoRepeatingVariable { rule } => write!(
112                f,
113                "rule {rule}: template repetition contains no metavariable that repeats at its depth"
114            ),
115            Self::EmptyRepetition { rule } => write!(
116                f,
117                "rule {rule}: pattern repetition can match without consuming input"
118            ),
119            Self::OptionalSeparator { rule } => write!(
120                f,
121                "rule {rule}: an at-most-once repetition cannot have a separator"
122            ),
123        }
124    }
125}
126
127impl core::error::Error for MacroError {}
128
129/// Why [`Expander::expand`](crate::Expander::expand) could not expand an
130/// invocation.
131///
132/// A failed expansion leaves the expander exactly as it was: no contexts are
133/// minted and no expansion is recorded. The enum is `#[non_exhaustive]`.
134///
135/// # Examples
136///
137/// ```
138/// use macro_lang::{Context, ExpandError, Expander, Macro, Pattern, Rule};
139/// use intern_lang::Interner;
140/// use token_lang::Span;
141/// use macro_lang::Tree;
142///
143/// let mut names = Interner::new();
144/// // A macro that accepts exactly `a`.
145/// let mac = Macro::new(names.intern("only_a"), vec![Rule {
146///     pattern: vec![Pattern::Token('a')],
147///     template: vec![],
148/// }])?;
149///
150/// let mut expander = Expander::new();
151/// let input = [Tree::token('b', Span::new(9, 10))];
152/// let err = expander.expand(&mac, &input, Span::new(0, 11), Context::ROOT).unwrap_err();
153/// // The error points at the token no rule could get past.
154/// assert_eq!(err, ExpandError::NoMatch { span: Span::new(9, 10) });
155/// # Ok::<(), macro_lang::MacroError>(())
156/// ```
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
158#[non_exhaustive]
159pub enum ExpandError {
160    /// No rule matched the invocation.
161    ///
162    /// `span` locates the furthest point any rule reached before failing: the
163    /// token no rule could accept, or an empty span at the end of the input if
164    /// every rule wanted more. Report it as "no rules expected this token".
165    NoMatch {
166        /// Where matching got stuck.
167        span: Span,
168    },
169    /// A rule matched the invocation in more than one way, so the captures are
170    /// ambiguous — for example `$($a:tt)* $($b:tt)*` cannot tell where `a`
171    /// ends. Rules are tried in order, and an ambiguous rule stops the search
172    /// rather than falling through. Make the rule's repetitions unambiguous,
173    /// typically with a separator or a literal token between them.
174    Ambiguous {
175        /// Index of the ambiguous rule.
176        rule: usize,
177    },
178    /// A template repetition uses metavariables that captured different numbers
179    /// of repetitions, so they cannot be expanded in lockstep. Match them in the
180    /// same pattern repetition, or expand them in separate template
181    /// repetitions.
182    RepetitionMismatch {
183        /// Index of the rule that matched.
184        rule: usize,
185    },
186    /// The invocation is nested deeper than the expander's recursion limit
187    /// ([`Budget::max_depth`](crate::Budget::max_depth)) — almost always a
188    /// macro that expands to an invocation of itself without a base case. Fix
189    /// the macro, or raise the limit with
190    /// [`Expander::with_limit`](crate::Expander::with_limit).
191    RecursionLimit {
192        /// The limit that was exceeded.
193        limit: u32,
194    },
195    /// The expander has used up part of its [`Budget`](crate::Budget): it has
196    /// already performed [`max_expansions`](crate::Budget::max_expansions)
197    /// expansions, or this one would take the number of tokens written past
198    /// [`max_tokens`](crate::Budget::max_tokens). Almost always a macro whose
199    /// output grows without bound, such as one that doubles its argument on
200    /// every round, or one that expands into several calls of itself. Fix the
201    /// macro, or raise the budget with
202    /// [`Expander::set_budget`](crate::Expander::set_budget). A long-lived host
203    /// should call [`Expander::reset_usage`](crate::Expander::reset_usage) once
204    /// per unit of work, or legitimate input eventually exhausts the budget.
205    ///
206    /// Added in 1.1.0.
207    Budget(Limit),
208    /// The expander has minted all `u32::MAX` hygiene contexts it can address.
209    /// Contexts are never reclaimed, so this takes billions of expansions;
210    /// start a fresh [`Expander`](crate::Expander).
211    ContextOverflow,
212}
213
214impl fmt::Display for ExpandError {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        match self {
217            Self::NoMatch { span } => write!(f, "no rule matched the invocation (stuck at {span})"),
218            Self::Ambiguous { rule } => {
219                write!(f, "rule {rule} matches the invocation in more than one way")
220            }
221            Self::RepetitionMismatch { rule } => write!(
222                f,
223                "rule {rule}: metavariables repeat a different number of times"
224            ),
225            Self::RecursionLimit { limit } => {
226                write!(f, "macro expansion exceeded the recursion limit of {limit}")
227            }
228            Self::Budget(limit) => {
229                write!(f, "macro expansion exceeded its budget of {limit}")
230            }
231            Self::ContextOverflow => f.write_str("hygiene context space exhausted"),
232        }
233    }
234}
235
236impl core::error::Error for ExpandError {}
237
238#[cfg(test)]
239mod tests {
240    #![allow(clippy::unwrap_used)]
241
242    use alloc::string::ToString;
243
244    use super::*;
245
246    #[test]
247    fn test_macro_error_messages_name_the_rule() {
248        let name = Symbol::from_u32(3).unwrap();
249        let cases = [
250            (MacroError::NoRules, "macro has no rules"),
251            (
252                MacroError::DuplicateBinding { rule: 1, name },
253                "rule 1: metavariable Symbol(3) is bound more than once",
254            ),
255            (
256                MacroError::UnboundVariable { rule: 0, name },
257                "rule 0: metavariable Symbol(3) is not bound by the pattern",
258            ),
259            (
260                MacroError::StillRepeating { rule: 2, name },
261                "rule 2: metavariable Symbol(3) is still repeating at this depth",
262            ),
263            (
264                MacroError::EmptyRepetition { rule: 4 },
265                "rule 4: pattern repetition can match without consuming input",
266            ),
267        ];
268        for (err, text) in cases {
269            assert_eq!(err.to_string(), text);
270        }
271        assert!(
272            MacroError::NoRepeatingVariable { rule: 0 }
273                .to_string()
274                .contains("no metavariable")
275        );
276        assert!(
277            MacroError::OptionalSeparator { rule: 0 }
278                .to_string()
279                .contains("separator")
280        );
281    }
282
283    #[test]
284    fn test_expand_error_messages() {
285        assert_eq!(
286            ExpandError::NoMatch {
287                span: Span::new(2, 5)
288            }
289            .to_string(),
290            "no rule matched the invocation (stuck at 2..5)"
291        );
292        assert!(
293            ExpandError::Ambiguous { rule: 1 }
294                .to_string()
295                .contains("rule 1")
296        );
297        assert!(
298            ExpandError::RepetitionMismatch { rule: 0 }
299                .to_string()
300                .contains("repeat")
301        );
302        assert!(
303            ExpandError::RecursionLimit { limit: 8 }
304                .to_string()
305                .contains('8')
306        );
307        assert!(
308            ExpandError::ContextOverflow
309                .to_string()
310                .contains("exhausted")
311        );
312        assert_eq!(
313            ExpandError::Budget(Limit::Tokens { max: 64 }).to_string(),
314            "macro expansion exceeded its budget of 64 output tokens"
315        );
316        assert_eq!(
317            ExpandError::Budget(Limit::Expansions { max: 3 }).to_string(),
318            "macro expansion exceeded its budget of 3 expansions"
319        );
320    }
321
322    #[test]
323    fn test_errors_are_std_errors() {
324        fn assert_error<E: core::error::Error>() {}
325        assert_error::<MacroError>();
326        assert_error::<ExpandError>();
327    }
328}