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`.
25 parser::{MetaTemplate, Op},
29 // FIXME: we probably should re-think `token_tree_to_syntax_node` interfaces
30 pub use ::parser::ParserEntryPoint;
31 pub use tt::{Delimiter, DelimiterKind, Punct};
33 #[derive(Debug, PartialEq, Eq)]
35 UnexpectedToken(String),
38 RepetitionEmptyTokenTree,
41 #[derive(Debug, PartialEq, Eq, Clone)]
42 pub enum ExpandError {
47 // FIXME: no way mbe should know about proc macros.
52 impl fmt::Display for ExpandError {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
56 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
57 ExpandError::BindingError(e) => f.write_str(e),
58 ExpandError::ConversionError => f.write_str("could not convert tokens"),
59 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
60 ExpandError::Other(e) => f.write_str(e),
67 parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
68 syntax_node_to_token_tree_censored, token_tree_to_syntax_node,
73 /// This struct contains AST for a single `macro_rules` definition. What might
74 /// be very confusing is that AST has almost exactly the same shape as
75 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
76 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
77 #[derive(Clone, Debug, PartialEq, Eq)]
78 pub struct MacroRules {
80 /// Highest id of the token we have in TokenMap
85 #[derive(Clone, Debug, PartialEq, Eq)]
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(tt::Leaf::Ident(ident))
124 if ident.id != tt::TokenId::unspecified() =>
134 /// Shift given TokenTree token id
135 pub fn shift_all(self, tt: &mut tt::Subtree) {
136 for t in &mut tt.token_trees {
138 tt::TokenTree::Leaf(leaf) => match leaf {
139 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
140 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
141 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
143 tt::TokenTree::Subtree(tt) => {
144 if let Some(it) = tt.delimiter.as_mut() {
145 it.id = self.shift(it.id);
153 pub fn shift(self, id: tt::TokenId) -> tt::TokenId {
154 if id == tt::TokenId::unspecified() {
157 tt::TokenId(id.0 + self.0)
160 pub fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
161 id.0.checked_sub(self.0).map(tt::TokenId)
165 #[derive(Debug, Eq, PartialEq)]
172 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
173 // Note: this parsing can be implemented using mbe machinery itself, by
174 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
175 // manually seems easier.
176 let mut src = TtIter::new(tt);
177 let mut rules = Vec::new();
178 while src.len() > 0 {
179 let rule = Rule::parse(&mut src, true)?;
181 if let Err(()) = src.expect_char(';') {
183 return Err(ParseError::Expected("expected `;`".to_string()));
190 validate(&rule.lhs)?;
193 Ok(MacroRules { rules, shift: Shift::new(tt) })
196 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
198 let mut tt = tt.clone();
199 self.shift.shift_all(&mut tt);
200 expander::expand_rules(&self.rules, &tt)
203 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
207 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
208 match self.shift.unshift(id) {
209 Some(id) => (id, Origin::Call),
210 None => (id, Origin::Def),
216 pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
217 let mut src = TtIter::new(tt);
218 let mut rules = Vec::new();
220 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
221 cov_mark::hit!(parse_macro_def_rules);
222 while src.len() > 0 {
223 let rule = Rule::parse(&mut src, true)?;
225 if let Err(()) = src.expect_any_char(&[';', ',']) {
227 return Err(ParseError::Expected(
228 "expected `;` or `,` to delimit rules".to_string(),
235 cov_mark::hit!(parse_macro_def_simple);
236 let rule = Rule::parse(&mut src, false)?;
238 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
243 validate(&rule.lhs)?;
246 Ok(MacroDef { rules, shift: Shift::new(tt) })
249 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
251 let mut tt = tt.clone();
252 self.shift.shift_all(&mut tt);
253 expander::expand_rules(&self.rules, &tt)
256 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
260 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
261 match self.shift.unshift(id) {
262 Some(id) => (id, Origin::Call),
263 None => (id, Origin::Def),
269 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
272 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
274 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
275 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
279 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
281 let lhs = MetaTemplate::parse_pattern(lhs)?;
282 let rhs = MetaTemplate::parse_template(rhs)?;
284 Ok(crate::Rule { lhs, rhs })
288 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
289 for op in pattern.iter() {
291 Op::Subtree { tokens, .. } => validate(tokens)?,
292 Op::Repeat { tokens: subtree, separator, .. } => {
293 // Checks that no repetition which could match an empty token
294 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
296 if separator.is_none()
297 && subtree.iter().all(|child_op| {
299 Op::Var { kind, .. } => {
301 if kind.as_ref().map_or(false, |it| it == "vis") {
305 Op::Repeat { kind, .. } => {
308 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
312 Op::Subtree { .. } => {}
317 return Err(ParseError::RepetitionEmptyTokenTree);
327 #[derive(Debug, Clone, Eq, PartialEq)]
328 pub struct ExpandResult<T> {
330 pub err: Option<ExpandError>,
333 impl<T> ExpandResult<T> {
334 pub fn ok(value: T) -> Self {
335 Self { value, err: None }
338 pub fn only_err(err: ExpandError) -> Self
342 Self { value: Default::default(), err: Some(err) }
345 pub fn str_err(err: String) -> Self
349 Self::only_err(ExpandError::Other(err))
352 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
353 ExpandResult { value: f(self.value), err: self.err }
356 pub fn result(self) -> Result<T, ExpandError> {
357 self.err.map_or(Ok(self.value), Err)
361 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
362 fn from(result: Result<T, ExpandError>) -> Self {
363 result.map_or_else(Self::only_err, Self::ok)