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