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, MetaTemplate, 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),
69 ast_to_token_tree, parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
70 token_tree_to_syntax_node,
75 /// This struct contains AST for a single `macro_rules` definition. What might
76 /// be very confusing is that AST has almost exactly the same shape as
77 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
78 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
79 #[derive(Clone, Debug, PartialEq, Eq)]
80 pub struct MacroRules {
82 /// Highest id of the token we have in TokenMap
87 #[derive(Clone, Debug, PartialEq, Eq)]
90 /// Highest id of the token we have in TokenMap
94 #[derive(Clone, Debug, PartialEq, Eq)]
100 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
104 fn new(tt: &tt::Subtree) -> Shift {
105 // Note that TokenId is started from zero,
106 // We have to add 1 to prevent duplication.
107 let value = max_id(tt).map_or(0, |it| it + 1);
110 // Find the max token id inside a subtree
111 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
115 .filter_map(|tt| match tt {
116 tt::TokenTree::Subtree(subtree) => {
117 let tree_id = max_id(subtree);
118 match subtree.delimiter {
119 Some(it) if it.id != tt::TokenId::unspecified() => {
120 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
125 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
126 if ident.id != tt::TokenId::unspecified() =>
136 /// Shift given TokenTree token id
137 fn shift_all(self, tt: &mut tt::Subtree) {
138 for t in tt.token_trees.iter_mut() {
140 tt::TokenTree::Leaf(leaf) => match leaf {
141 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
142 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
143 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
145 tt::TokenTree::Subtree(tt) => {
146 if let Some(it) = tt.delimiter.as_mut() {
147 it.id = self.shift(it.id);
155 fn shift(self, id: tt::TokenId) -> tt::TokenId {
156 if id == tt::TokenId::unspecified() {
159 tt::TokenId(id.0 + self.0)
162 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
163 id.0.checked_sub(self.0).map(tt::TokenId)
167 #[derive(Debug, Eq, PartialEq)]
174 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
175 // Note: this parsing can be implemented using mbe machinery itself, by
176 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
177 // manually seems easier.
178 let mut src = TtIter::new(tt);
179 let mut rules = Vec::new();
180 while src.len() > 0 {
181 let rule = Rule::parse(&mut src, true)?;
183 if let Err(()) = src.expect_char(';') {
185 return Err(ParseError::Expected("expected `;`".to_string()));
191 for rule in rules.iter() {
192 validate(&rule.lhs)?;
195 Ok(MacroRules { rules, shift: Shift::new(tt) })
198 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
200 let mut tt = tt.clone();
201 self.shift.shift_all(&mut tt);
202 expander::expand_rules(&self.rules, &tt)
205 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
209 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
210 match self.shift.unshift(id) {
211 Some(id) => (id, Origin::Call),
212 None => (id, Origin::Def),
218 pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
219 let mut src = TtIter::new(tt);
220 let mut rules = Vec::new();
222 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
223 cov_mark::hit!(parse_macro_def_rules);
224 while src.len() > 0 {
225 let rule = Rule::parse(&mut src, true)?;
227 if let Err(()) = src.expect_any_char(&[';', ',']) {
229 return Err(ParseError::Expected(
230 "expected `;` or `,` to delimit rules".to_string(),
237 cov_mark::hit!(parse_macro_def_simple);
238 let rule = Rule::parse(&mut src, false)?;
240 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
244 for rule in rules.iter() {
245 validate(&rule.lhs)?;
248 Ok(MacroDef { rules, shift: Shift::new(tt) })
251 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
253 let mut tt = tt.clone();
254 self.shift.shift_all(&mut tt);
255 expander::expand_rules(&self.rules, &tt)
258 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
262 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
263 match self.shift.unshift(id) {
264 Some(id) => (id, Origin::Call),
265 None => (id, Origin::Def),
271 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Rule, ParseError> {
274 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
276 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
277 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
281 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
283 let lhs = MetaTemplate(parse_pattern(&lhs)?);
284 let rhs = MetaTemplate(parse_template(&rhs)?);
286 Ok(crate::Rule { lhs, rhs })
290 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
291 for op in pattern.iter() {
293 Op::Subtree { tokens, .. } => validate(&tokens)?,
294 Op::Repeat { tokens: subtree, separator, .. } => {
295 // Checks that no repetition which could match an empty token
296 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
298 if separator.is_none()
299 && subtree.iter().all(|child_op| {
301 Op::Var { kind, .. } => {
303 if kind.as_ref().map_or(false, |it| it == "vis") {
307 Op::Repeat { kind, .. } => {
310 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
314 Op::Subtree { .. } => {}
319 return Err(ParseError::RepetitionEmptyTokenTree);
329 #[derive(Debug, Clone, Eq, PartialEq)]
330 pub struct ExpandResult<T> {
332 pub err: Option<ExpandError>,
335 impl<T> ExpandResult<T> {
336 pub fn ok(value: T) -> Self {
337 Self { value, err: None }
340 pub fn only_err(err: ExpandError) -> Self
344 Self { value: Default::default(), err: Some(err) }
347 pub fn str_err(err: String) -> Self
351 Self::only_err(ExpandError::Other(err))
354 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
355 ExpandResult { value: f(self.value), err: self.err }
358 pub fn result(self) -> Result<T, ExpandError> {
359 self.err.map(Err).unwrap_or(Ok(self.value))
363 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
364 fn from(result: Result<T, ExpandError>) -> Self {
365 result.map_or_else(Self::only_err, Self::ok)