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!
12 pub use tt::{Delimiter, Punct};
15 parser::{parse_pattern, Op},
19 #[derive(Debug, PartialEq, Eq)]
24 #[derive(Debug, PartialEq, Eq)]
25 pub enum ExpandError {
33 pub use crate::syntax_bridge::{
34 ast_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node, TokenMap,
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 {
44 /// Highest id of the token we have in TokenMap
48 #[derive(Clone, Debug, PartialEq, Eq)]
54 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
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);
64 // Find the max token id inside a subtree
65 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
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)))
79 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
80 if ident.id != tt::TokenId::unspecified() =>
90 /// Shift given TokenTree token id
91 fn shift_all(self, tt: &mut tt::Subtree) {
92 for t in tt.token_trees.iter_mut() {
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),
99 tt::TokenTree::Subtree(tt) => {
100 tt.delimiter.as_mut().map(|it: &mut Delimiter| it.id = self.shift(it.id));
107 fn shift(self, id: tt::TokenId) -> tt::TokenId {
108 if id == tt::TokenId::unspecified() {
111 tt::TokenId(id.0 + self.0)
114 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
115 id.0.checked_sub(self.0).map(tt::TokenId)
119 #[derive(Debug, Eq, PartialEq)]
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)?;
135 if let Err(()) = src.expect_char(';') {
137 return Err(ParseError::Expected("expected `:`".to_string()));
143 for rule in rules.iter() {
144 validate(&rule.lhs)?;
147 Ok(MacroRules { rules, shift: Shift::new(tt) })
150 pub fn expand(&self, tt: &tt::Subtree) -> Result<tt::Subtree, ExpandError> {
152 let mut tt = tt.clone();
153 self.shift.shift_all(&mut tt);
154 mbe_expander::expand(self, &tt)
157 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
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),
170 fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
173 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
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()))?;
180 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
182 rhs.delimiter = None;
183 Ok(crate::Rule { lhs, rhs })
187 fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
188 for op in parse_pattern(pattern) {
193 ExpandError::InvalidRepeat => "invalid repeat".to_string(),
194 _ => "invalid macro definition".to_string(),
196 return Err(ParseError::Expected(msg));
200 Op::TokenTree(tt::TokenTree::Subtree(subtree)) | Op::Repeat { subtree, .. } => {