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!
18 pub use tt::{Delimiter, DelimiterKind, Punct};
21 parser::{parse_pattern, parse_template, Op},
25 #[derive(Debug, PartialEq, Eq)]
28 RepetitionEmptyTokenTree,
31 #[derive(Debug, PartialEq, Eq, Clone)]
32 pub enum ExpandError {
38 ProcMacroError(tt::ExpansionError),
43 impl From<tt::ExpansionError> for ExpandError {
44 fn from(it: tt::ExpansionError) -> Self {
45 ExpandError::ProcMacroError(it)
49 impl fmt::Display for ExpandError {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
53 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
54 ExpandError::BindingError(e) => f.write_str(e),
55 ExpandError::ConversionError => f.write_str("could not convert tokens"),
56 ExpandError::InvalidRepeat => f.write_str("invalid repeat expression"),
57 ExpandError::ProcMacroError(e) => e.fmt(f),
58 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
59 ExpandError::Other(e) => f.write_str(e),
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,
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 {
76 /// Highest id of the token we have in TokenMap
81 #[derive(Clone, Debug, PartialEq, Eq)]
84 /// Highest id of the token we have in TokenMap
88 #[derive(Clone, Debug, PartialEq, Eq)]
94 #[derive(Clone, Debug, PartialEq, Eq)]
96 delimiter: Option<Delimiter>,
97 tokens: Vec<Result<Op, ExpandError>>,
100 impl<'a> MetaTemplate {
101 fn iter(&self) -> impl Iterator<Item = &Result<Op, ExpandError>> {
105 fn delimiter_kind(&self) -> Option<DelimiterKind> {
106 self.delimiter.map(|it| it.kind)
110 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
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);
120 // Find the max token id inside a subtree
121 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
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)))
135 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
136 if ident.id != tt::TokenId::unspecified() =>
146 /// Shift given TokenTree token id
147 fn shift_all(self, tt: &mut tt::Subtree) {
148 for t in tt.token_trees.iter_mut() {
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),
155 tt::TokenTree::Subtree(tt) => {
156 if let Some(it) = tt.delimiter.as_mut() {
157 it.id = self.shift(it.id);
165 fn shift(self, id: tt::TokenId) -> tt::TokenId {
166 if id == tt::TokenId::unspecified() {
169 tt::TokenId(id.0 + self.0)
172 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
173 id.0.checked_sub(self.0).map(tt::TokenId)
177 #[derive(Debug, Eq, PartialEq)]
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)?;
193 if let Err(()) = src.expect_char(';') {
195 return Err(ParseError::Expected("expected `;`".to_string()));
201 for rule in rules.iter() {
202 validate(&rule.lhs)?;
205 Ok(MacroRules { rules, shift: Shift::new(tt) })
208 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
210 let mut tt = tt.clone();
211 self.shift.shift_all(&mut tt);
212 expander::expand_rules(&self.rules, &tt)
215 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
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),
228 pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
229 let mut src = TtIter::new(tt);
230 let mut rules = Vec::new();
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)?;
237 if let Err(()) = src.expect_char(';') {
239 return Err(ParseError::Expected("expected `;`".to_string()));
245 mark::hit!(parse_macro_def_simple);
246 let rule = Rule::parse(&mut src, false)?;
248 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
252 for rule in rules.iter() {
253 validate(&rule.lhs)?;
256 Ok(MacroDef { rules, shift: Shift::new(tt) })
259 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
261 let mut tt = tt.clone();
262 self.shift.shift_all(&mut tt);
263 expander::expand_rules(&self.rules, &tt)
266 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
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),
279 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Rule, ParseError> {
282 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
284 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
285 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
289 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
291 let lhs = MetaTemplate { tokens: parse_pattern(&lhs), delimiter: None };
292 let rhs = MetaTemplate { tokens: parse_template(&rhs), delimiter: None };
294 Ok(crate::Rule { lhs, rhs })
298 fn to_parse_error(e: &ExpandError) -> ParseError {
300 ExpandError::InvalidRepeat => "invalid repeat".to_string(),
301 _ => "invalid macro definition".to_string(),
303 ParseError::Expected(msg)
306 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
307 for op in pattern.iter() {
308 let op = op.as_ref().map_err(|e| to_parse_error(&e))?;
311 Op::Subtree(subtree) => validate(&subtree)?,
312 Op::Repeat { subtree, separator, .. } => {
313 // Checks that no repetition which could match an empty token
314 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
316 if separator.is_none() {
317 if subtree.iter().all(|child_op| {
318 match child_op.as_ref().map_err(to_parse_error) {
319 Ok(Op::Var { kind, .. }) => {
321 if kind.as_ref().map_or(false, |it| it == "vis") {
325 Ok(Op::Repeat { kind, .. }) => {
328 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
335 return Err(ParseError::RepetitionEmptyTokenTree);
346 #[derive(Debug, Clone, Eq, PartialEq)]
347 pub struct ExpandResult<T> {
349 pub err: Option<ExpandError>,
352 impl<T> ExpandResult<T> {
353 pub fn ok(value: T) -> Self {
354 Self { value, err: None }
357 pub fn only_err(err: ExpandError) -> Self
361 Self { value: Default::default(), err: Some(err) }
364 pub fn str_err(err: String) -> Self
368 Self::only_err(ExpandError::Other(err))
371 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
372 ExpandResult { value: f(self.value), err: self.err }
375 pub fn result(self) -> Result<T, ExpandError> {
376 self.err.map(Err).unwrap_or(Ok(self.value))
380 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
381 fn from(result: Result<T, ExpandError>) -> Self {
382 result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))