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!
21 pub use tt::{Delimiter, DelimiterKind, Punct};
24 parser::{parse_pattern, parse_template, Op},
28 #[derive(Debug, PartialEq, Eq)]
30 UnexpectedToken(String),
33 RepetitionEmptyTokenTree,
36 #[derive(Debug, PartialEq, Eq, Clone)]
37 pub enum ExpandError {
42 ProcMacroError(tt::ExpansionError),
47 impl From<tt::ExpansionError> for ExpandError {
48 fn from(it: tt::ExpansionError) -> Self {
49 ExpandError::ProcMacroError(it)
53 impl fmt::Display for ExpandError {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
57 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
58 ExpandError::BindingError(e) => f.write_str(e),
59 ExpandError::ConversionError => f.write_str("could not convert tokens"),
60 ExpandError::ProcMacroError(e) => e.fmt(f),
61 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
62 ExpandError::Other(e) => f.write_str(e),
67 pub use crate::syntax_bridge::{
68 ast_to_token_tree, parse_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node,
72 /// This struct contains AST for a single `macro_rules` definition. What might
73 /// be very confusing is that AST has almost exactly the same shape as
74 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
75 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
76 #[derive(Clone, Debug, PartialEq, Eq)]
77 pub struct MacroRules {
79 /// Highest id of the token we have in TokenMap
84 #[derive(Clone, Debug, PartialEq, Eq)]
87 /// Highest id of the token we have in TokenMap
91 #[derive(Clone, Debug, PartialEq, Eq)]
97 #[derive(Clone, Debug, PartialEq, Eq)]
98 struct MetaTemplate(Vec<Op>);
100 impl<'a> MetaTemplate {
101 fn iter(&self) -> impl Iterator<Item = &Op> {
106 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
110 fn new(tt: &tt::Subtree) -> Shift {
111 // Note that TokenId is started from zero,
112 // We have to add 1 to prevent duplication.
113 let value = max_id(tt).map_or(0, |it| it + 1);
116 // Find the max token id inside a subtree
117 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
121 .filter_map(|tt| match tt {
122 tt::TokenTree::Subtree(subtree) => {
123 let tree_id = max_id(subtree);
124 match subtree.delimiter {
125 Some(it) if it.id != tt::TokenId::unspecified() => {
126 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
131 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
132 if ident.id != tt::TokenId::unspecified() =>
142 /// Shift given TokenTree token id
143 fn shift_all(self, tt: &mut tt::Subtree) {
144 for t in tt.token_trees.iter_mut() {
146 tt::TokenTree::Leaf(leaf) => match leaf {
147 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
148 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
149 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
151 tt::TokenTree::Subtree(tt) => {
152 if let Some(it) = tt.delimiter.as_mut() {
153 it.id = self.shift(it.id);
161 fn shift(self, id: tt::TokenId) -> tt::TokenId {
162 if id == tt::TokenId::unspecified() {
165 tt::TokenId(id.0 + self.0)
168 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
169 id.0.checked_sub(self.0).map(tt::TokenId)
173 #[derive(Debug, Eq, PartialEq)]
180 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
181 // Note: this parsing can be implemented using mbe machinery itself, by
182 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
183 // manually seems easier.
184 let mut src = TtIter::new(tt);
185 let mut rules = Vec::new();
186 while src.len() > 0 {
187 let rule = Rule::parse(&mut src, true)?;
189 if let Err(()) = src.expect_char(';') {
191 return Err(ParseError::Expected("expected `;`".to_string()));
197 for rule in rules.iter() {
198 validate(&rule.lhs)?;
201 Ok(MacroRules { rules, shift: Shift::new(tt) })
204 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
206 let mut tt = tt.clone();
207 self.shift.shift_all(&mut tt);
208 expander::expand_rules(&self.rules, &tt)
211 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
215 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
216 match self.shift.unshift(id) {
217 Some(id) => (id, Origin::Call),
218 None => (id, Origin::Def),
224 pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
225 let mut src = TtIter::new(tt);
226 let mut rules = Vec::new();
228 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
229 mark::hit!(parse_macro_def_rules);
230 while src.len() > 0 {
231 let rule = Rule::parse(&mut src, true)?;
233 if let Err(()) = src.expect_char(';') {
235 return Err(ParseError::Expected("expected `;`".to_string()));
241 mark::hit!(parse_macro_def_simple);
242 let rule = Rule::parse(&mut src, false)?;
244 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
248 for rule in rules.iter() {
249 validate(&rule.lhs)?;
252 Ok(MacroDef { rules, shift: Shift::new(tt) })
255 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
257 let mut tt = tt.clone();
258 self.shift.shift_all(&mut tt);
259 expander::expand_rules(&self.rules, &tt)
262 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
266 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
267 match self.shift.unshift(id) {
268 Some(id) => (id, Origin::Call),
269 None => (id, Origin::Def),
275 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Rule, ParseError> {
278 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
280 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
281 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
285 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
287 let lhs = MetaTemplate(parse_pattern(&lhs)?);
288 let rhs = MetaTemplate(parse_template(&rhs)?);
290 Ok(crate::Rule { lhs, rhs })
294 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
295 for op in pattern.iter() {
297 Op::Subtree { tokens, .. } => validate(&tokens)?,
298 Op::Repeat { tokens: subtree, separator, .. } => {
299 // Checks that no repetition which could match an empty token
300 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
302 if separator.is_none() {
303 if subtree.iter().all(|child_op| {
305 Op::Var { kind, .. } => {
307 if kind.as_ref().map_or(false, |it| it == "vis") {
311 Op::Repeat { kind, .. } => {
314 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
318 Op::Subtree { .. } => {}
322 return Err(ParseError::RepetitionEmptyTokenTree);
333 #[derive(Debug, Clone, Eq, PartialEq)]
334 pub struct ExpandResult<T> {
336 pub err: Option<ExpandError>,
339 impl<T> ExpandResult<T> {
340 pub fn ok(value: T) -> Self {
341 Self { value, err: None }
344 pub fn only_err(err: ExpandError) -> Self
348 Self { value: Default::default(), err: Some(err) }
351 pub fn str_err(err: String) -> Self
355 Self::only_err(ExpandError::Other(err))
358 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
359 ExpandResult { value: f(self.value), err: self.err }
362 pub fn result(self) -> Result<T, ExpandError> {
363 self.err.map(Err).unwrap_or(Ok(self.value))
367 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
368 fn from(result: Result<T, ExpandError>) -> Self {
369 result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))