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::ParserEntryPoint;
28 pub use tt::{Delimiter, DelimiterKind, Punct};
30 #[derive(Debug, PartialEq, Eq, Clone)]
32 UnexpectedToken(String),
35 RepetitionEmptyTokenTree,
38 impl fmt::Display for ParseError {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 ParseError::UnexpectedToken(it) => f.write_str(it),
42 ParseError::Expected(it) => f.write_str(it),
43 ParseError::InvalidRepeat => f.write_str("invalid repeat"),
44 ParseError::RepetitionEmptyTokenTree => f.write_str("empty token tree in repetition"),
49 #[derive(Debug, PartialEq, Eq, Clone)]
50 pub enum ExpandError {
55 // FIXME: no way mbe should know about proc macros.
60 impl fmt::Display for ExpandError {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 ExpandError::NoMatchingRule => f.write_str("no rule matches input tokens"),
64 ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
65 ExpandError::BindingError(e) => f.write_str(e),
66 ExpandError::ConversionError => f.write_str("could not convert tokens"),
67 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
68 ExpandError::Other(e) => f.write_str(e),
75 parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
76 syntax_node_to_token_tree_censored, token_tree_to_syntax_node,
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(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)]
171 impl DeclarativeMacro {
172 /// The old, `macro_rules! m {}` flavor.
173 pub fn parse_macro_rules(tt: &tt::Subtree) -> Result<DeclarativeMacro, ParseError> {
174 // Note: this parsing can be implemented using mbe machinery itself, by
175 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
176 // manually seems easier.
177 let mut src = TtIter::new(tt);
178 let mut rules = Vec::new();
179 while src.len() > 0 {
180 let rule = Rule::parse(&mut src, true)?;
182 if let Err(()) = src.expect_char(';') {
184 return Err(ParseError::Expected("expected `;`".to_string()));
191 validate(&rule.lhs)?;
194 Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
197 /// The new, unstable `macro m {}` flavor.
198 pub fn parse_macro2(tt: &tt::Subtree) -> Result<DeclarativeMacro, ParseError> {
199 let mut src = TtIter::new(tt);
200 let mut rules = Vec::new();
202 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
203 cov_mark::hit!(parse_macro_def_rules);
204 while src.len() > 0 {
205 let rule = Rule::parse(&mut src, true)?;
207 if let Err(()) = src.expect_any_char(&[';', ',']) {
209 return Err(ParseError::Expected(
210 "expected `;` or `,` to delimit rules".to_string(),
217 cov_mark::hit!(parse_macro_def_simple);
218 let rule = Rule::parse(&mut src, false)?;
220 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
225 validate(&rule.lhs)?;
228 Ok(DeclarativeMacro { rules, shift: Shift::new(tt) })
231 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
233 let mut tt = tt.clone();
234 self.shift.shift_all(&mut tt);
235 expander::expand_rules(&self.rules, &tt)
238 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
242 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
243 match self.shift.unshift(id) {
244 Some(id) => (id, Origin::Call),
245 None => (id, Origin::Def),
251 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
254 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
256 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
257 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
261 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
263 let lhs = MetaTemplate::parse_pattern(lhs)?;
264 let rhs = MetaTemplate::parse_template(rhs)?;
266 Ok(crate::Rule { lhs, rhs })
270 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
271 for op in pattern.iter() {
273 Op::Subtree { tokens, .. } => validate(tokens)?,
274 Op::Repeat { tokens: subtree, separator, .. } => {
275 // Checks that no repetition which could match an empty token
276 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
278 if separator.is_none()
279 && subtree.iter().all(|child_op| {
281 Op::Var { kind, .. } => {
283 if kind.as_ref().map_or(false, |it| it == "vis") {
287 Op::Repeat { kind, .. } => {
290 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
294 Op::Subtree { .. } => {}
299 return Err(ParseError::RepetitionEmptyTokenTree);
309 #[derive(Debug, Clone, Eq, PartialEq)]
310 pub struct ExpandResult<T> {
312 pub err: Option<ExpandError>,
315 impl<T> ExpandResult<T> {
316 pub fn ok(value: T) -> Self {
317 Self { value, err: None }
320 pub fn only_err(err: ExpandError) -> Self
324 Self { value: Default::default(), err: Some(err) }
327 pub fn str_err(err: String) -> Self
331 Self::only_err(ExpandError::Other(err))
334 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
335 ExpandResult { value: f(self.value), err: self.err }
338 pub fn result(self) -> Result<T, ExpandError> {
339 self.err.map_or(Ok(self.value), Err)
343 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
344 fn from(result: Result<T, ExpandError>) -> Self {
345 result.map_or_else(Self::only_err, Self::ok)