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!
17 pub use tt::{Delimiter, DelimiterKind, Punct};
20 parser::{parse_pattern, parse_template, Op},
24 #[derive(Debug, PartialEq, Eq)]
27 RepetitionEmptyTokenTree,
30 #[derive(Debug, PartialEq, Eq, Clone)]
31 pub enum ExpandError {
37 ProcMacroError(tt::ExpansionError),
42 impl From<tt::ExpansionError> for ExpandError {
43 fn from(it: tt::ExpansionError) -> Self {
44 ExpandError::ProcMacroError(it)
48 impl fmt::Display for ExpandError {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
52 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
53 ExpandError::BindingError(e) => f.write_str(e),
54 ExpandError::ConversionError => f.write_str("could not convert tokens"),
55 ExpandError::InvalidRepeat => f.write_str("invalid repeat expression"),
56 ExpandError::ProcMacroError(e) => e.fmt(f),
57 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
58 ExpandError::Other(e) => f.write_str(e),
63 pub use crate::syntax_bridge::{
64 ast_to_token_tree, parse_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node,
68 /// This struct contains AST for a single `macro_rules` definition. What might
69 /// be very confusing is that AST has almost exactly the same shape as
70 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
71 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
72 #[derive(Clone, Debug, PartialEq, Eq)]
73 pub struct MacroRules {
75 /// Highest id of the token we have in TokenMap
79 #[derive(Clone, Debug, PartialEq, Eq)]
85 #[derive(Clone, Debug, PartialEq, Eq)]
87 delimiter: Option<Delimiter>,
88 tokens: Vec<Result<Op, ExpandError>>,
91 impl<'a> MetaTemplate {
92 fn iter(&self) -> impl Iterator<Item = &Result<Op, ExpandError>> {
96 fn delimiter_kind(&self) -> Option<DelimiterKind> {
97 self.delimiter.map(|it| it.kind)
101 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
105 fn new(tt: &tt::Subtree) -> Shift {
106 // Note that TokenId is started from zero,
107 // We have to add 1 to prevent duplication.
108 let value = max_id(tt).map_or(0, |it| it + 1);
111 // Find the max token id inside a subtree
112 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
116 .filter_map(|tt| match tt {
117 tt::TokenTree::Subtree(subtree) => {
118 let tree_id = max_id(subtree);
119 match subtree.delimiter {
120 Some(it) if it.id != tt::TokenId::unspecified() => {
121 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
126 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
127 if ident.id != tt::TokenId::unspecified() =>
137 /// Shift given TokenTree token id
138 fn shift_all(self, tt: &mut tt::Subtree) {
139 for t in tt.token_trees.iter_mut() {
141 tt::TokenTree::Leaf(leaf) => match leaf {
142 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
143 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
144 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
146 tt::TokenTree::Subtree(tt) => {
147 if let Some(it) = tt.delimiter.as_mut() {
148 it.id = self.shift(it.id);
156 fn shift(self, id: tt::TokenId) -> tt::TokenId {
157 if id == tt::TokenId::unspecified() {
160 tt::TokenId(id.0 + self.0)
163 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
164 id.0.checked_sub(self.0).map(tt::TokenId)
168 #[derive(Debug, Eq, PartialEq)]
175 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
176 // Note: this parsing can be implemented using mbe machinery itself, by
177 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
178 // manually seems easier.
179 let mut src = TtIter::new(tt);
180 let mut rules = Vec::new();
181 while src.len() > 0 {
182 let rule = Rule::parse(&mut src)?;
184 if let Err(()) = src.expect_char(';') {
186 return Err(ParseError::Expected("expected `;`".to_string()));
192 for rule in rules.iter() {
193 validate(&rule.lhs)?;
196 Ok(MacroRules { rules, shift: Shift::new(tt) })
199 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
201 let mut tt = tt.clone();
202 self.shift.shift_all(&mut tt);
203 mbe_expander::expand(self, &tt)
206 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
210 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
211 match self.shift.unshift(id) {
212 Some(id) => (id, Origin::Call),
213 None => (id, Origin::Def),
219 fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
222 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
223 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
224 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
227 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
229 let lhs = MetaTemplate { tokens: parse_pattern(&lhs), delimiter: None };
230 let rhs = MetaTemplate { tokens: parse_template(&rhs), delimiter: None };
232 Ok(crate::Rule { lhs, rhs })
236 fn to_parse_error(e: &ExpandError) -> ParseError {
238 ExpandError::InvalidRepeat => "invalid repeat".to_string(),
239 _ => "invalid macro definition".to_string(),
241 ParseError::Expected(msg)
244 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
245 for op in pattern.iter() {
246 let op = op.as_ref().map_err(|e| to_parse_error(&e))?;
249 Op::Subtree(subtree) => validate(&subtree)?,
250 Op::Repeat { subtree, separator, .. } => {
251 // Checks that no repetition which could match an empty token
252 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
254 if separator.is_none() {
255 if subtree.iter().all(|child_op| {
256 match child_op.as_ref().map_err(to_parse_error) {
257 Ok(Op::Var { kind, .. }) => {
259 if kind.as_ref().map_or(false, |it| it == "vis") {
263 Ok(Op::Repeat { kind, .. }) => {
266 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
273 return Err(ParseError::RepetitionEmptyTokenTree);
284 #[derive(Debug, Clone, Eq, PartialEq)]
285 pub struct ExpandResult<T> {
287 pub err: Option<ExpandError>,
290 impl<T> ExpandResult<T> {
291 pub fn ok(value: T) -> Self {
292 Self { value, err: None }
295 pub fn only_err(err: ExpandError) -> Self
299 Self { value: Default::default(), err: Some(err) }
302 pub fn str_err(err: String) -> Self
306 Self::only_err(ExpandError::Other(err))
309 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
310 ExpandResult { value: f(self.value), err: self.err }
313 pub fn result(self) -> Result<T, ExpandError> {
314 self.err.map(Err).unwrap_or(Ok(self.value))
318 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
319 fn from(result: Result<T, ExpandError>) -> Self {
320 result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))