]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/mbe/src/expander.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / rust-analyzer / crates / mbe / src / expander.rs
1 //! This module takes a (parsed) definition of `macro_rules` invocation, a
2 //! `tt::TokenTree` representing an argument of macro invocation, and produces a
3 //! `tt::TokenTree` for the result of the expansion.
4
5 mod matcher;
6 mod transcriber;
7
8 use rustc_hash::FxHashMap;
9 use syntax::SmolStr;
10
11 use crate::{parser::MetaVarKind, ExpandError, ExpandResult};
12
13 pub(crate) fn expand_rules(
14     rules: &[crate::Rule],
15     input: &tt::Subtree,
16 ) -> ExpandResult<tt::Subtree> {
17     let mut match_: Option<(matcher::Match, &crate::Rule)> = None;
18     for rule in rules {
19         let new_match = matcher::match_(&rule.lhs, input);
20
21         if new_match.err.is_none() {
22             // If we find a rule that applies without errors, we're done.
23             // Unconditionally returning the transcription here makes the
24             // `test_repeat_bad_var` test fail.
25             let ExpandResult { value, err: transcribe_err } =
26                 transcriber::transcribe(&rule.rhs, &new_match.bindings);
27             if transcribe_err.is_none() {
28                 return ExpandResult::ok(value);
29             }
30         }
31         // Use the rule if we matched more tokens, or bound variables count
32         if let Some((prev_match, _)) = &match_ {
33             if (new_match.unmatched_tts, -(new_match.bound_count as i32))
34                 < (prev_match.unmatched_tts, -(prev_match.bound_count as i32))
35             {
36                 match_ = Some((new_match, rule));
37             }
38         } else {
39             match_ = Some((new_match, rule));
40         }
41     }
42     if let Some((match_, rule)) = match_ {
43         // if we got here, there was no match without errors
44         let ExpandResult { value, err: transcribe_err } =
45             transcriber::transcribe(&rule.rhs, &match_.bindings);
46         ExpandResult { value, err: match_.err.or(transcribe_err) }
47     } else {
48         ExpandResult::only_err(ExpandError::NoMatchingRule)
49     }
50 }
51
52 /// The actual algorithm for expansion is not too hard, but is pretty tricky.
53 /// `Bindings` structure is the key to understanding what we are doing here.
54 ///
55 /// On the high level, it stores mapping from meta variables to the bits of
56 /// syntax it should be substituted with. For example, if `$e:expr` is matched
57 /// with `1 + 1` by macro_rules, the `Binding` will store `$e -> 1 + 1`.
58 ///
59 /// The tricky bit is dealing with repetitions (`$()*`). Consider this example:
60 ///
61 /// ```not_rust
62 /// macro_rules! foo {
63 ///     ($($ i:ident $($ e:expr),*);*) => {
64 ///         $(fn $ i() { $($ e);*; })*
65 ///     }
66 /// }
67 /// foo! { foo 1,2,3; bar 4,5,6 }
68 /// ```
69 ///
70 /// Here, the `$i` meta variable is matched first with `foo` and then with
71 /// `bar`, and `$e` is matched in turn with `1`, `2`, `3`, `4`, `5`, `6`.
72 ///
73 /// To represent such "multi-mappings", we use a recursive structures: we map
74 /// variables not to values, but to *lists* of values or other lists (that is,
75 /// to the trees).
76 ///
77 /// For the above example, the bindings would store
78 ///
79 /// ```not_rust
80 /// i -> [foo, bar]
81 /// e -> [[1, 2, 3], [4, 5, 6]]
82 /// ```
83 ///
84 /// We construct `Bindings` in the `match_lhs`. The interesting case is
85 /// `TokenTree::Repeat`, where we use `push_nested` to create the desired
86 /// nesting structure.
87 ///
88 /// The other side of the puzzle is `expand_subtree`, where we use the bindings
89 /// to substitute meta variables in the output template. When expanding, we
90 /// maintain a `nesting` stack of indices which tells us which occurrence from
91 /// the `Bindings` we should take. We push to the stack when we enter a
92 /// repetition.
93 ///
94 /// In other words, `Bindings` is a *multi* mapping from `SmolStr` to
95 /// `tt::TokenTree`, where the index to select a particular `TokenTree` among
96 /// many is not a plain `usize`, but a `&[usize]`.
97 #[derive(Debug, Default, Clone, PartialEq, Eq)]
98 struct Bindings {
99     inner: FxHashMap<SmolStr, Binding>,
100 }
101
102 #[derive(Debug, Clone, PartialEq, Eq)]
103 enum Binding {
104     Fragment(Fragment),
105     Nested(Vec<Binding>),
106     Empty,
107     Missing(MetaVarKind),
108 }
109
110 #[derive(Debug, Clone, PartialEq, Eq)]
111 enum Fragment {
112     /// token fragments are just copy-pasted into the output
113     Tokens(tt::TokenTree),
114     /// Expr ast fragments are surrounded with `()` on insertion to preserve
115     /// precedence. Note that this impl is different from the one currently in
116     /// `rustc` -- `rustc` doesn't translate fragments into token trees at all.
117     ///
118     /// At one point in time, we tried to to use "fake" delimiters here a-la
119     /// proc-macro delimiter=none. As we later discovered, "none" delimiters are
120     /// tricky to handle in the parser, and rustc doesn't handle those either.
121     Expr(tt::TokenTree),
122 }