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