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!
20 pub use tt::{Delimiter, DelimiterKind, Punct};
23 parser::{parse_pattern, parse_template, MetaTemplate, Op},
27 #[derive(Debug, PartialEq, Eq)]
29 UnexpectedToken(String),
32 RepetitionEmptyTokenTree,
35 #[derive(Debug, PartialEq, Eq, Clone)]
36 pub enum ExpandError {
41 ProcMacroError(tt::ExpansionError),
46 impl From<tt::ExpansionError> for ExpandError {
47 fn from(it: tt::ExpansionError) -> Self {
48 ExpandError::ProcMacroError(it)
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::ProcMacroError(e) => e.fmt(f),
60 ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
61 ExpandError::Other(e) => f.write_str(e),
66 pub use crate::syntax_bridge::{
67 ast_to_token_tree, parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
68 token_tree_to_syntax_node, TokenMap,
71 /// This struct contains AST for a single `macro_rules` definition. What might
72 /// be very confusing is that AST has almost exactly the same shape as
73 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
74 /// and `$()*` have special meaning (see `Var` and `Repeat` data structures)
75 #[derive(Clone, Debug, PartialEq, Eq)]
76 pub struct MacroRules {
78 /// Highest id of the token we have in TokenMap
83 #[derive(Clone, Debug, PartialEq, Eq)]
86 /// Highest id of the token we have in TokenMap
90 #[derive(Clone, Debug, PartialEq, Eq)]
96 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
100 fn new(tt: &tt::Subtree) -> Shift {
101 // Note that TokenId is started from zero,
102 // We have to add 1 to prevent duplication.
103 let value = max_id(tt).map_or(0, |it| it + 1);
106 // Find the max token id inside a subtree
107 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
111 .filter_map(|tt| match tt {
112 tt::TokenTree::Subtree(subtree) => {
113 let tree_id = max_id(subtree);
114 match subtree.delimiter {
115 Some(it) if it.id != tt::TokenId::unspecified() => {
116 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
121 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
122 if ident.id != tt::TokenId::unspecified() =>
132 /// Shift given TokenTree token id
133 fn shift_all(self, tt: &mut tt::Subtree) {
134 for t in tt.token_trees.iter_mut() {
136 tt::TokenTree::Leaf(leaf) => match leaf {
137 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
138 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
139 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
141 tt::TokenTree::Subtree(tt) => {
142 if let Some(it) = tt.delimiter.as_mut() {
143 it.id = self.shift(it.id);
151 fn shift(self, id: tt::TokenId) -> tt::TokenId {
152 if id == tt::TokenId::unspecified() {
155 tt::TokenId(id.0 + self.0)
158 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
159 id.0.checked_sub(self.0).map(tt::TokenId)
163 #[derive(Debug, Eq, PartialEq)]
170 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
171 // Note: this parsing can be implemented using mbe machinery itself, by
172 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
173 // manually seems easier.
174 let mut src = TtIter::new(tt);
175 let mut rules = Vec::new();
176 while src.len() > 0 {
177 let rule = Rule::parse(&mut src, true)?;
179 if let Err(()) = src.expect_char(';') {
181 return Err(ParseError::Expected("expected `;`".to_string()));
187 for rule in rules.iter() {
188 validate(&rule.lhs)?;
191 Ok(MacroRules { rules, shift: Shift::new(tt) })
194 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
196 let mut tt = tt.clone();
197 self.shift.shift_all(&mut tt);
198 expander::expand_rules(&self.rules, &tt)
201 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
205 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
206 match self.shift.unshift(id) {
207 Some(id) => (id, Origin::Call),
208 None => (id, Origin::Def),
214 pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
215 let mut src = TtIter::new(tt);
216 let mut rules = Vec::new();
218 if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
219 cov_mark::hit!(parse_macro_def_rules);
220 while src.len() > 0 {
221 let rule = Rule::parse(&mut src, true)?;
223 if let Err(()) = src.expect_char(';') {
225 return Err(ParseError::Expected("expected `;`".to_string()));
231 cov_mark::hit!(parse_macro_def_simple);
232 let rule = Rule::parse(&mut src, false)?;
234 return Err(ParseError::Expected("remain tokens in macro def".to_string()));
238 for rule in rules.iter() {
239 validate(&rule.lhs)?;
242 Ok(MacroDef { rules, shift: Shift::new(tt) })
245 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
247 let mut tt = tt.clone();
248 self.shift.shift_all(&mut tt);
249 expander::expand_rules(&self.rules, &tt)
252 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
256 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
257 match self.shift.unshift(id) {
258 Some(id) => (id, Origin::Call),
259 None => (id, Origin::Def),
265 fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Rule, ParseError> {
268 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
270 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
271 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
275 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
277 let lhs = MetaTemplate(parse_pattern(&lhs)?);
278 let rhs = MetaTemplate(parse_template(&rhs)?);
280 Ok(crate::Rule { lhs, rhs })
284 fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
285 for op in pattern.iter() {
287 Op::Subtree { tokens, .. } => validate(&tokens)?,
288 Op::Repeat { tokens: subtree, separator, .. } => {
289 // Checks that no repetition which could match an empty token
290 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
292 if separator.is_none() {
293 if subtree.iter().all(|child_op| {
295 Op::Var { kind, .. } => {
297 if kind.as_ref().map_or(false, |it| it == "vis") {
301 Op::Repeat { kind, .. } => {
304 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
308 Op::Subtree { .. } => {}
312 return Err(ParseError::RepetitionEmptyTokenTree);
323 #[derive(Debug, Clone, Eq, PartialEq)]
324 pub struct ExpandResult<T> {
326 pub err: Option<ExpandError>,
329 impl<T> ExpandResult<T> {
330 pub fn ok(value: T) -> Self {
331 Self { value, err: None }
334 pub fn only_err(err: ExpandError) -> Self
338 Self { value: Default::default(), err: Some(err) }
341 pub fn str_err(err: String) -> Self
345 Self::only_err(ExpandError::Other(err))
348 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
349 ExpandResult { value: f(self.value), err: self.err }
352 pub fn result(self) -> Result<T, ExpandError> {
353 self.err.map(Err).unwrap_or(Ok(self.value))
357 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
358 fn from(result: Result<T, ExpandError>) -> Self {
359 result.map_or_else(Self::only_err, Self::ok)