]> git.lizzy.rs Git - rust.git/blob - crates/mbe/src/lib.rs
Merge #10824
[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 DeclarativeMacro {
87     rules: Vec<Rule>,
88     /// Highest id of the token we have in TokenMap
89     shift: Shift,
90 }
91
92 #[derive(Clone, Debug, PartialEq, Eq)]
93 struct Rule {
94     lhs: MetaTemplate,
95     rhs: MetaTemplate,
96 }
97
98 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
99 pub struct Shift(u32);
100
101 impl Shift {
102     pub fn new(tt: &tt::Subtree) -> Shift {
103         // Note that TokenId is started from zero,
104         // We have to add 1 to prevent duplication.
105         let value = max_id(tt).map_or(0, |it| it + 1);
106         return Shift(value);
107
108         // Find the max token id inside a subtree
109         fn max_id(subtree: &tt::Subtree) -> Option<u32> {
110             subtree
111                 .token_trees
112                 .iter()
113                 .filter_map(|tt| match tt {
114                     tt::TokenTree::Subtree(subtree) => {
115                         let tree_id = max_id(subtree);
116                         match subtree.delimiter {
117                             Some(it) if it.id != tt::TokenId::unspecified() => {
118                                 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
119                             }
120                             _ => tree_id,
121                         }
122                     }
123                     tt::TokenTree::Leaf(leaf) => {
124                         let id = match leaf {
125                             tt::Leaf::Literal(it) => it.id,
126                             tt::Leaf::Punct(it) => it.id,
127                             tt::Leaf::Ident(it) => it.id,
128                         };
129
130                         (id != tt::TokenId::unspecified()).then(|| id.0)
131                     }
132                 })
133                 .max()
134         }
135     }
136
137     /// Shift given TokenTree token id
138     pub fn shift_all(self, tt: &mut tt::Subtree) {
139         for t in &mut tt.token_trees {
140             match t {
141                 tt::TokenTree::Leaf(leaf) => match leaf {
142                     tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
143                     tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
144                     tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
145                 },
146                 tt::TokenTree::Subtree(tt) => {
147                     if let Some(it) = tt.delimiter.as_mut() {
148                         it.id = self.shift(it.id);
149                     };
150                     self.shift_all(tt)
151                 }
152             }
153         }
154     }
155
156     pub fn shift(self, id: tt::TokenId) -> tt::TokenId {
157         if id == tt::TokenId::unspecified() {
158             return id;
159         }
160         tt::TokenId(id.0 + self.0)
161     }
162
163     pub fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
164         id.0.checked_sub(self.0).map(tt::TokenId)
165     }
166 }
167
168 #[derive(Debug, Eq, PartialEq)]
169 pub enum Origin {
170     Def,
171     Call,
172 }
173
174 impl DeclarativeMacro {
175     /// The old, `macro_rules! m {}` flavor.
176     pub fn parse_macro_rules(tt: &tt::Subtree) -> Result<DeclarativeMacro, ParseError> {
177         // Note: this parsing can be implemented using mbe machinery itself, by
178         // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
179         // manually seems easier.
180         let mut src = TtIter::new(tt);
181         let mut rules = Vec::new();
182         while src.len() > 0 {
183             let rule = Rule::parse(&mut src, true)?;
184             rules.push(rule);
185             if let Err(()) = src.expect_char(';') {
186                 if src.len() > 0 {
187                     return Err(ParseError::Expected("expected `;`".to_string()));
188                 }
189                 break;
190             }
191         }
192
193         for rule in &rules {
194             validate(&rule.lhs)?;
195         }
196
197         Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
198     }
199
200     /// The new, unstable `macro m {}` flavor.
201     pub fn parse_macro2(tt: &tt::Subtree) -> Result<DeclarativeMacro, ParseError> {
202         let mut src = TtIter::new(tt);
203         let mut rules = Vec::new();
204
205         if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
206             cov_mark::hit!(parse_macro_def_rules);
207             while src.len() > 0 {
208                 let rule = Rule::parse(&mut src, true)?;
209                 rules.push(rule);
210                 if let Err(()) = src.expect_any_char(&[';', ',']) {
211                     if src.len() > 0 {
212                         return Err(ParseError::Expected(
213                             "expected `;` or `,` to delimit rules".to_string(),
214                         ));
215                     }
216                     break;
217                 }
218             }
219         } else {
220             cov_mark::hit!(parse_macro_def_simple);
221             let rule = Rule::parse(&mut src, false)?;
222             if src.len() != 0 {
223                 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
224             }
225             rules.push(rule);
226         }
227         for rule in &rules {
228             validate(&rule.lhs)?;
229         }
230
231         Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
232     }
233
234     pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
235         // apply shift
236         let mut tt = tt.clone();
237         self.shift.shift_all(&mut tt);
238         expander::expand_rules(&self.rules, &tt)
239     }
240
241     pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
242         self.shift.shift(id)
243     }
244
245     pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
246         match self.shift.unshift(id) {
247             Some(id) => (id, Origin::Call),
248             None => (id, Origin::Def),
249         }
250     }
251
252     pub fn shift(&self) -> Shift {
253         self.shift
254     }
255 }
256
257 impl Rule {
258     fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
259         let lhs = src
260             .expect_subtree()
261             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
262         if expect_arrow {
263             src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
264             src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
265         }
266         let rhs = src
267             .expect_subtree()
268             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
269
270         let lhs = MetaTemplate::parse_pattern(lhs)?;
271         let rhs = MetaTemplate::parse_template(rhs)?;
272
273         Ok(crate::Rule { lhs, rhs })
274     }
275 }
276
277 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
278     for op in pattern.iter() {
279         match op {
280             Op::Subtree { tokens, .. } => validate(tokens)?,
281             Op::Repeat { tokens: subtree, separator, .. } => {
282                 // Checks that no repetition which could match an empty token
283                 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
284
285                 if separator.is_none()
286                     && subtree.iter().all(|child_op| {
287                         match child_op {
288                             Op::Var { kind, .. } => {
289                                 // vis is optional
290                                 if kind.as_ref().map_or(false, |it| it == "vis") {
291                                     return true;
292                                 }
293                             }
294                             Op::Repeat { kind, .. } => {
295                                 return matches!(
296                                     kind,
297                                     parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
298                                 )
299                             }
300                             Op::Leaf(_) => {}
301                             Op::Subtree { .. } => {}
302                         }
303                         false
304                     })
305                 {
306                     return Err(ParseError::RepetitionEmptyTokenTree);
307                 }
308                 validate(subtree)?
309             }
310             _ => (),
311         }
312     }
313     Ok(())
314 }
315
316 #[derive(Debug, Clone, Eq, PartialEq)]
317 pub struct ExpandResult<T> {
318     pub value: T,
319     pub err: Option<ExpandError>,
320 }
321
322 impl<T> ExpandResult<T> {
323     pub fn ok(value: T) -> Self {
324         Self { value, err: None }
325     }
326
327     pub fn only_err(err: ExpandError) -> Self
328     where
329         T: Default,
330     {
331         Self { value: Default::default(), err: Some(err) }
332     }
333
334     pub fn str_err(err: String) -> Self
335     where
336         T: Default,
337     {
338         Self::only_err(ExpandError::Other(err))
339     }
340
341     pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
342         ExpandResult { value: f(self.value), err: self.err }
343     }
344
345     pub fn result(self) -> Result<T, ExpandError> {
346         self.err.map_or(Ok(self.value), Err)
347     }
348 }
349
350 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
351     fn from(result: Result<T, ExpandError>) -> Self {
352         result.map_or_else(Self::only_err, Self::ok)
353     }
354 }