]> git.lizzy.rs Git - rust.git/blob - crates/mbe/src/expander.rs
Merge #9130
[rust.git] / 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::{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 an `&[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 }
108
109 #[derive(Debug, Clone, PartialEq, Eq)]
110 enum Fragment {
111     /// token fragments are just copy-pasted into the output
112     Tokens(tt::TokenTree),
113     /// Ast fragments are inserted with fake delimiters, so as to make things
114     /// like `$i * 2` where `$i = 1 + 1` work as expectd.
115     Ast(tt::TokenTree),
116 }
117
118 #[cfg(test)]
119 mod tests {
120     use syntax::{ast, AstNode};
121
122     use super::*;
123     use crate::ast_to_token_tree;
124
125     #[test]
126     fn test_expand_rule() {
127         assert_err(
128             "($($i:ident);*) => ($i)",
129             "foo!{a}",
130             ExpandError::BindingError(String::from(
131                 "expected simple binding, found nested binding `i`",
132             )),
133         );
134
135         // FIXME:
136         // Add an err test case for ($($i:ident)) => ($())
137     }
138
139     fn assert_err(macro_body: &str, invocation: &str, err: ExpandError) {
140         assert_eq!(
141             expand_first(&create_rules(&format_macro(macro_body)), invocation).err,
142             Some(err)
143         );
144     }
145
146     fn format_macro(macro_body: &str) -> String {
147         format!(
148             "
149         macro_rules! foo {{
150             {}
151         }}
152 ",
153             macro_body
154         )
155     }
156
157     fn create_rules(macro_definition: &str) -> crate::MacroRules {
158         let source_file = ast::SourceFile::parse(macro_definition).ok().unwrap();
159         let macro_definition =
160             source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
161
162         let (definition_tt, _) = ast_to_token_tree(&macro_definition.token_tree().unwrap());
163         crate::MacroRules::parse(&definition_tt).unwrap()
164     }
165
166     fn expand_first(rules: &crate::MacroRules, invocation: &str) -> ExpandResult<tt::Subtree> {
167         let source_file = ast::SourceFile::parse(invocation).ok().unwrap();
168         let macro_invocation =
169             source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
170
171         let (invocation_tt, _) = ast_to_token_tree(&macro_invocation.token_tree().unwrap());
172
173         expand_rules(&rules.rules, &invocation_tt)
174     }
175 }