]> git.lizzy.rs Git - rust.git/blob - crates/ra_mbe/src/lib.rs
45dad2d108bc8ffda931f94515a9c51e6dcd278e
[rust.git] / crates / ra_mbe / src / lib.rs
1 //! `mbe` (short for Macro By Example) crate contains code for handling
2 //! `macro_rules` macros. It uses `TokenTree` (from `ra_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 pub use tt::{Delimiter, Punct};
13
14 use crate::{
15     parser::{parse_pattern, Op},
16     tt_iter::TtIter,
17 };
18
19 #[derive(Debug, PartialEq, Eq)]
20 pub enum ParseError {
21     Expected(String),
22 }
23
24 #[derive(Debug, PartialEq, Eq)]
25 pub enum ExpandError {
26     NoMatchingRule,
27     UnexpectedToken,
28     BindingError(String),
29     ConversionError,
30     InvalidRepeat,
31 }
32
33 pub use crate::syntax_bridge::{
34     ast_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node, TokenMap,
35 };
36
37 /// This struct contains AST for a single `macro_rules` definition. What might
38 /// be very confusing is that AST has almost exactly the same shape as
39 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
40 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
41 #[derive(Clone, Debug, PartialEq, Eq)]
42 pub struct MacroRules {
43     rules: Vec<Rule>,
44     /// Highest id of the token we have in TokenMap
45     shift: Shift,
46 }
47
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 struct Rule {
50     lhs: tt::Subtree,
51     rhs: tt::Subtree,
52 }
53
54 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
55 struct Shift(u32);
56
57 impl Shift {
58     fn new(tt: &tt::Subtree) -> Shift {
59         // Note that TokenId is started from zero,
60         // We have to add 1 to prevent duplication.
61         let value = max_id(tt).map_or(0, |it| it + 1);
62         return Shift(value);
63
64         // Find the max token id inside a subtree
65         fn max_id(subtree: &tt::Subtree) -> Option<u32> {
66             subtree
67                 .token_trees
68                 .iter()
69                 .filter_map(|tt| match tt {
70                     tt::TokenTree::Subtree(subtree) => {
71                         let tree_id = max_id(subtree);
72                         match subtree.delimiter {
73                             Some(it) if it.id != tt::TokenId::unspecified() => {
74                                 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
75                             }
76                             _ => tree_id,
77                         }
78                     }
79                     tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
80                         if ident.id != tt::TokenId::unspecified() =>
81                     {
82                         Some(ident.id.0)
83                     }
84                     _ => None,
85                 })
86                 .max()
87         }
88     }
89
90     /// Shift given TokenTree token id
91     fn shift_all(self, tt: &mut tt::Subtree) {
92         for t in tt.token_trees.iter_mut() {
93             match t {
94                 tt::TokenTree::Leaf(leaf) => match leaf {
95                     tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
96                     tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
97                     tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
98                 },
99                 tt::TokenTree::Subtree(tt) => {
100                     tt.delimiter.as_mut().map(|it: &mut Delimiter| it.id = self.shift(it.id));
101                     self.shift_all(tt)
102                 }
103             }
104         }
105     }
106
107     fn shift(self, id: tt::TokenId) -> tt::TokenId {
108         if id == tt::TokenId::unspecified() {
109             return id;
110         }
111         tt::TokenId(id.0 + self.0)
112     }
113
114     fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
115         id.0.checked_sub(self.0).map(tt::TokenId)
116     }
117 }
118
119 #[derive(Debug, Eq, PartialEq)]
120 pub enum Origin {
121     Def,
122     Call,
123 }
124
125 impl MacroRules {
126     pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
127         // Note: this parsing can be implemented using mbe machinery itself, by
128         // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
129         // manually seems easier.
130         let mut src = TtIter::new(tt);
131         let mut rules = Vec::new();
132         while src.len() > 0 {
133             let rule = Rule::parse(&mut src)?;
134             rules.push(rule);
135             if let Err(()) = src.expect_char(';') {
136                 if src.len() > 0 {
137                     return Err(ParseError::Expected("expected `:`".to_string()));
138                 }
139                 break;
140             }
141         }
142
143         for rule in rules.iter() {
144             validate(&rule.lhs)?;
145         }
146
147         Ok(MacroRules { rules, shift: Shift::new(tt) })
148     }
149
150     pub fn expand(&self, tt: &tt::Subtree) -> Result<tt::Subtree, ExpandError> {
151         // apply shift
152         let mut tt = tt.clone();
153         self.shift.shift_all(&mut tt);
154         mbe_expander::expand(self, &tt)
155     }
156
157     pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
158         self.shift.shift(id)
159     }
160
161     pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
162         match self.shift.unshift(id) {
163             Some(id) => (id, Origin::Call),
164             None => (id, Origin::Def),
165         }
166     }
167 }
168
169 impl Rule {
170     fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
171         let mut lhs = src
172             .expect_subtree()
173             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
174             .clone();
175         lhs.delimiter = None;
176         src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
177         src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
178         let mut rhs = src
179             .expect_subtree()
180             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
181             .clone();
182         rhs.delimiter = None;
183         Ok(crate::Rule { lhs, rhs })
184     }
185 }
186
187 fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
188     for op in parse_pattern(pattern) {
189         let op = match op {
190             Ok(it) => it,
191             Err(e) => {
192                 let msg = match e {
193                     ExpandError::InvalidRepeat => "invalid repeat".to_string(),
194                     _ => "invalid macro definition".to_string(),
195                 };
196                 return Err(ParseError::Expected(msg));
197             }
198         };
199         match op {
200             Op::TokenTree(tt::TokenTree::Subtree(subtree)) | Op::Repeat { subtree, .. } => {
201                 validate(subtree)?
202             }
203             _ => (),
204         }
205     }
206     Ok(())
207 }
208
209 #[cfg(test)]
210 mod tests;