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!
6 //! The tes for this functionality live in another crate:
7 //! `hir_def::macro_expansion_tests::mbe`.
22 parser::{MetaTemplate, Op},
26 // FIXME: we probably should re-think `token_tree_to_syntax_node` interfaces
27 pub use ::parser::TopEntryPoint;
28 pub use tt::{Delimiter, DelimiterKind, Punct};
32 parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
33 syntax_node_to_token_tree_censored, token_tree_to_syntax_node,
38 #[derive(Debug, PartialEq, Eq, Clone)]
40 UnexpectedToken(String),
43 RepetitionEmptyTokenTree,
46 impl fmt::Display for ParseError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 ParseError::UnexpectedToken(it) => f.write_str(it),
50 ParseError::Expected(it) => f.write_str(it),
51 ParseError::InvalidRepeat => f.write_str("invalid repeat"),
52 ParseError::RepetitionEmptyTokenTree => f.write_str("empty token tree in repetition"),
57 #[derive(Debug, PartialEq, Eq, Clone)]
58 pub enum ExpandError {
63 // FIXME: no way mbe should know about proc macros.
68 impl fmt::Display for ExpandError {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
72 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
73 ExpandError::BindingError(e) => f.write_str(e),
74 ExpandError::ConversionError => f.write_str("could not convert tokens"),
75 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
76 ExpandError::Other(e) => f.write_str(e),
81 /// This struct contains AST for a single `macro_rules` definition. What might
82 /// be very confusing is that AST has almost exactly the same shape as
83 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
84 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
85 #[derive(Clone, Debug, PartialEq, Eq)]
86 pub struct DeclarativeMacro {
88 /// Highest id of the token we have in TokenMap
92 #[derive(Clone, Debug, PartialEq, Eq)]
98 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
99 pub struct Shift(u32);
102 pub fn new(tt: &tt::Subtree) -> Shift {
103 // Note that TokenId is started from zero,
104 // We have to add 1 to prevent duplication.
105 let value = max_id(tt).map_or(0, |it| it + 1);
108 // Find the max token id inside a subtree
109 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
113 .filter_map(|tt| match tt {
114 tt::TokenTree::Subtree(subtree) => {
115 let tree_id = max_id(subtree);
116 match subtree.delimiter {
117 Some(it) if it.id != tt::TokenId::unspecified() => {
118 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
123 tt::TokenTree::Leaf(leaf) => {
124 let &(tt::Leaf::Ident(tt::Ident { id, .. })
125 | tt::Leaf::Punct(tt::Punct { id, .. })
126 | tt::Leaf::Literal(tt::Literal { id, .. })) = leaf;
128 (id != tt::TokenId::unspecified()).then(|| id.0)
135 /// Shift given TokenTree token id
136 pub fn shift_all(self, tt: &mut tt::Subtree) {
137 for t in &mut tt.token_trees {
140 tt::Leaf::Ident(tt::Ident { id, .. })
141 | tt::Leaf::Punct(tt::Punct { id, .. })
142 | tt::Leaf::Literal(tt::Literal { id, .. }),
143 ) => *id = self.shift(*id),
144 tt::TokenTree::Subtree(tt) => {
145 if let Some(it) = tt.delimiter.as_mut() {
146 it.id = self.shift(it.id);
154 pub fn shift(self, id: tt::TokenId) -> tt::TokenId {
155 if id == tt::TokenId::unspecified() {
158 tt::TokenId(id.0 + self.0)
162 pub fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
163 id.0.checked_sub(self.0).map(tt::TokenId)
167 #[derive(Debug, Eq, PartialEq)]
173 impl DeclarativeMacro {
174 /// The old, `macro_rules! m {}` flavor.
175 pub fn parse_macro_rules(tt: &tt::Subtree) -> Result<DeclarativeMacro, 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, true)?;
184 if let Err(()) = src.expect_char(';') {
186 return Err(ParseError::Expected("expected `;`".to_string()));
192 for Rule { lhs, .. } in &rules {
196 Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
199 /// The new, unstable `macro m {}` flavor.
200 pub fn parse_macro2(tt: &tt::Subtree) -> Result<DeclarativeMacro, ParseError> {
201 let mut src = TtIter::new(tt);
202 let mut rules = Vec::new();
204 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
205 cov_mark::hit!(parse_macro_def_rules);
206 while src.len() > 0 {
207 let rule = Rule::parse(&mut src, true)?;
209 if let Err(()) = src.expect_any_char(&[';', ',']) {
211 return Err(ParseError::Expected(
212 "expected `;` or `,` to delimit rules".to_string(),
219 cov_mark::hit!(parse_macro_def_simple);
220 let rule = Rule::parse(&mut src, false)?;
222 return Err(ParseError::Expected("remaining tokens in macro def".to_string()));
227 for Rule { lhs, .. } in &rules {
231 Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
234 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
236 let mut tt = tt.clone();
237 self.shift.shift_all(&mut tt);
238 expander::expand_rules(&self.rules, &tt)
241 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
245 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
246 match self.shift.unshift(id) {
247 Some(id) => (id, Origin::Call),
248 None => (id, Origin::Def),
252 pub fn shift(&self) -> Shift {
258 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
261 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
263 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
264 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
268 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
270 let lhs = MetaTemplate::parse_pattern(lhs)?;
271 let rhs = MetaTemplate::parse_template(rhs)?;
273 Ok(crate::Rule { lhs, rhs })
277 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
278 for op in pattern.iter() {
280 Op::Subtree { tokens, .. } => validate(tokens)?,
281 Op::Repeat { tokens: subtree, separator, .. } => {
282 // Checks that no repetition which could match an empty token
283 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
284 let lsh_is_empty_seq = separator.is_none() && subtree.iter().all(|child_op| {
287 Op::Var { kind: Some(kind), .. } => kind == "vis",
289 kind: parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne,
295 if lsh_is_empty_seq {
296 return Err(ParseError::RepetitionEmptyTokenTree);
306 #[derive(Debug, Clone, Eq, PartialEq)]
307 pub struct ExpandResult<T> {
309 pub err: Option<ExpandError>,
312 impl<T> ExpandResult<T> {
313 pub fn ok(value: T) -> Self {
314 Self { value, err: None }
317 pub fn only_err(err: ExpandError) -> Self
321 Self { value: Default::default(), err: Some(err) }
324 pub fn str_err(err: String) -> Self
328 Self::only_err(ExpandError::Other(err))
331 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
332 ExpandResult { value: f(self.value), err: self.err }
335 pub fn result(self) -> Result<T, ExpandError> {
336 self.err.map_or(Ok(self.value), Err)
340 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
341 fn from(result: Result<T, ExpandError>) -> Self {
342 result.map_or_else(Self::only_err, Self::ok)