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