]> git.lizzy.rs Git - rust.git/blob - crates/mbe/src/lib.rs
6cd084eaeab6be3c7858f77d72828ff2106b4635
[rust.git] / crates / mbe / src / lib.rs
1 //! `mbe` (short for Macro By Example) crate contains code for handling
2 //! `macro_rules` macros. It uses `TokenTree` (from `tt` package) as the
3 //! interface, although it contains some code to bridge `SyntaxNode`s and
4 //! `TokenTree`s as well!
5 //!
6 //! The tes for this functionality live in another crate:
7 //! `hir_def::macro_expansion_tests::mbe`.
8
9 mod parser;
10 mod expander;
11 mod syntax_bridge;
12 mod tt_iter;
13 mod subtree_source;
14
15 #[cfg(test)]
16 mod benchmark;
17 mod token_map;
18
19 use std::fmt;
20
21 use crate::{
22     parser::{MetaTemplate, Op},
23     tt_iter::TtIter,
24 };
25
26 // FIXME: we probably should re-think  `token_tree_to_syntax_node` interfaces
27 pub use ::parser::ParserEntryPoint;
28 pub use tt::{Delimiter, DelimiterKind, Punct};
29
30 #[derive(Debug, PartialEq, Eq, Clone)]
31 pub enum ParseError {
32     UnexpectedToken(String),
33     Expected(String),
34     InvalidRepeat,
35     RepetitionEmptyTokenTree,
36 }
37
38 impl fmt::Display for ParseError {
39     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40         match self {
41             ParseError::UnexpectedToken(it) => f.write_str(it),
42             ParseError::Expected(it) => f.write_str(it),
43             ParseError::InvalidRepeat => f.write_str("invalid repeat"),
44             ParseError::RepetitionEmptyTokenTree => f.write_str("empty token tree in repetition"),
45         }
46     }
47 }
48
49 #[derive(Debug, PartialEq, Eq, Clone)]
50 pub enum ExpandError {
51     NoMatchingRule,
52     UnexpectedToken,
53     BindingError(String),
54     ConversionError,
55     // FIXME: no way mbe should know about proc macros.
56     UnresolvedProcMacro,
57     Other(String),
58 }
59
60 impl fmt::Display for ExpandError {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         match self {
63             ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
64             ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
65             ExpandError::BindingError(e) => f.write_str(e),
66             ExpandError::ConversionError => f.write_str("could not convert tokens"),
67             ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
68             ExpandError::Other(e) => f.write_str(e),
69         }
70     }
71 }
72
73 pub use crate::{
74     syntax_bridge::{
75         parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
76         syntax_node_to_token_tree_censored, token_tree_to_syntax_node,
77     },
78     token_map::TokenMap,
79 };
80
81 /// This struct contains AST for a single `macro_rules` definition. What might
82 /// be very confusing is that AST has almost exactly the same shape as
83 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
84 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
85 #[derive(Clone, Debug, PartialEq, Eq)]
86 pub struct MacroRules {
87     rules: Vec<Rule>,
88     /// Highest id of the token we have in TokenMap
89     shift: Shift,
90 }
91
92 /// For Macro 2.0
93 #[derive(Clone, Debug, PartialEq, Eq)]
94 pub struct MacroDef {
95     rules: Vec<Rule>,
96     /// Highest id of the token we have in TokenMap
97     shift: Shift,
98 }
99
100 #[derive(Clone, Debug, PartialEq, Eq)]
101 struct Rule {
102     lhs: MetaTemplate,
103     rhs: MetaTemplate,
104 }
105
106 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107 pub struct Shift(u32);
108
109 impl Shift {
110     pub fn new(tt: &tt::Subtree) -> Shift {
111         // Note that TokenId is started from zero,
112         // We have to add 1 to prevent duplication.
113         let value = max_id(tt).map_or(0, |it| it + 1);
114         return Shift(value);
115
116         // Find the max token id inside a subtree
117         fn max_id(subtree: &tt::Subtree) -> Option<u32> {
118             subtree
119                 .token_trees
120                 .iter()
121                 .filter_map(|tt| match tt {
122                     tt::TokenTree::Subtree(subtree) => {
123                         let tree_id = max_id(subtree);
124                         match subtree.delimiter {
125                             Some(it) if it.id != tt::TokenId::unspecified() => {
126                                 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
127                             }
128                             _ => tree_id,
129                         }
130                     }
131                     tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
132                         if ident.id != tt::TokenId::unspecified() =>
133                     {
134                         Some(ident.id.0)
135                     }
136                     _ => None,
137                 })
138                 .max()
139         }
140     }
141
142     /// Shift given TokenTree token id
143     pub fn shift_all(self, tt: &mut tt::Subtree) {
144         for t in &mut tt.token_trees {
145             match t {
146                 tt::TokenTree::Leaf(leaf) => match leaf {
147                     tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
148                     tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
149                     tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
150                 },
151                 tt::TokenTree::Subtree(tt) => {
152                     if let Some(it) = tt.delimiter.as_mut() {
153                         it.id = self.shift(it.id);
154                     };
155                     self.shift_all(tt)
156                 }
157             }
158         }
159     }
160
161     pub fn shift(self, id: tt::TokenId) -> tt::TokenId {
162         if id == tt::TokenId::unspecified() {
163             return id;
164         }
165         tt::TokenId(id.0 + self.0)
166     }
167
168     pub fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
169         id.0.checked_sub(self.0).map(tt::TokenId)
170     }
171 }
172
173 #[derive(Debug, Eq, PartialEq)]
174 pub enum Origin {
175     Def,
176     Call,
177 }
178
179 impl MacroRules {
180     pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
181         // Note: this parsing can be implemented using mbe machinery itself, by
182         // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
183         // manually seems easier.
184         let mut src = TtIter::new(tt);
185         let mut rules = Vec::new();
186         while src.len() > 0 {
187             let rule = Rule::parse(&mut src, true)?;
188             rules.push(rule);
189             if let Err(()) = src.expect_char(';') {
190                 if src.len() > 0 {
191                     return Err(ParseError::Expected("expected `;`".to_string()));
192                 }
193                 break;
194             }
195         }
196
197         for rule in &rules {
198             validate(&rule.lhs)?;
199         }
200
201         Ok(MacroRules { rules, shift: Shift::new(tt) })
202     }
203
204     pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
205         // apply shift
206         let mut tt = tt.clone();
207         self.shift.shift_all(&mut tt);
208         expander::expand_rules(&self.rules, &tt)
209     }
210
211     pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
212         self.shift.shift(id)
213     }
214
215     pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
216         match self.shift.unshift(id) {
217             Some(id) => (id, Origin::Call),
218             None => (id, Origin::Def),
219         }
220     }
221 }
222
223 impl MacroDef {
224     pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
225         let mut src = TtIter::new(tt);
226         let mut rules = Vec::new();
227
228         if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
229             cov_mark::hit!(parse_macro_def_rules);
230             while src.len() > 0 {
231                 let rule = Rule::parse(&mut src, true)?;
232                 rules.push(rule);
233                 if let Err(()) = src.expect_any_char(&[';', ',']) {
234                     if src.len() > 0 {
235                         return Err(ParseError::Expected(
236                             "expected `;` or `,` to delimit rules".to_string(),
237                         ));
238                     }
239                     break;
240                 }
241             }
242         } else {
243             cov_mark::hit!(parse_macro_def_simple);
244             let rule = Rule::parse(&mut src, false)?;
245             if src.len() != 0 {
246                 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
247             }
248             rules.push(rule);
249         }
250         for rule in &rules {
251             validate(&rule.lhs)?;
252         }
253
254         Ok(MacroDef { rules, shift: Shift::new(tt) })
255     }
256
257     pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
258         // apply shift
259         let mut tt = tt.clone();
260         self.shift.shift_all(&mut tt);
261         expander::expand_rules(&self.rules, &tt)
262     }
263
264     pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
265         self.shift.shift(id)
266     }
267
268     pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
269         match self.shift.unshift(id) {
270             Some(id) => (id, Origin::Call),
271             None => (id, Origin::Def),
272         }
273     }
274 }
275
276 impl Rule {
277     fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
278         let lhs = src
279             .expect_subtree()
280             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
281         if expect_arrow {
282             src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
283             src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
284         }
285         let rhs = src
286             .expect_subtree()
287             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
288
289         let lhs = MetaTemplate::parse_pattern(lhs)?;
290         let rhs = MetaTemplate::parse_template(rhs)?;
291
292         Ok(crate::Rule { lhs, rhs })
293     }
294 }
295
296 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
297     for op in pattern.iter() {
298         match op {
299             Op::Subtree { tokens, .. } => validate(tokens)?,
300             Op::Repeat { tokens: subtree, separator, .. } => {
301                 // Checks that no repetition which could match an empty token
302                 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
303
304                 if separator.is_none()
305                     && subtree.iter().all(|child_op| {
306                         match child_op {
307                             Op::Var { kind, .. } => {
308                                 // vis is optional
309                                 if kind.as_ref().map_or(false, |it| it == "vis") {
310                                     return true;
311                                 }
312                             }
313                             Op::Repeat { kind, .. } => {
314                                 return matches!(
315                                     kind,
316                                     parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
317                                 )
318                             }
319                             Op::Leaf(_) => {}
320                             Op::Subtree { .. } => {}
321                         }
322                         false
323                     })
324                 {
325                     return Err(ParseError::RepetitionEmptyTokenTree);
326                 }
327                 validate(subtree)?
328             }
329             _ => (),
330         }
331     }
332     Ok(())
333 }
334
335 #[derive(Debug, Clone, Eq, PartialEq)]
336 pub struct ExpandResult<T> {
337     pub value: T,
338     pub err: Option<ExpandError>,
339 }
340
341 impl<T> ExpandResult<T> {
342     pub fn ok(value: T) -> Self {
343         Self { value, err: None }
344     }
345
346     pub fn only_err(err: ExpandError) -> Self
347     where
348         T: Default,
349     {
350         Self { value: Default::default(), err: Some(err) }
351     }
352
353     pub fn str_err(err: String) -> Self
354     where
355         T: Default,
356     {
357         Self::only_err(ExpandError::Other(err))
358     }
359
360     pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
361         ExpandResult { value: f(self.value), err: self.err }
362     }
363
364     pub fn result(self) -> Result<T, ExpandError> {
365         self.err.map_or(Ok(self.value), Err)
366     }
367 }
368
369 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
370     fn from(result: Result<T, ExpandError>) -> Self {
371         result.map_or_else(Self::only_err, Self::ok)
372     }
373 }