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, Punct};
20 parser::{parse_pattern, Op},
24 #[derive(Debug, PartialEq, Eq)]
27 RepetitionEmtpyTokenTree,
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, Copy, Debug, PartialEq, Eq)]
89 fn new(tt: &tt::Subtree) -> Shift {
90 // Note that TokenId is started from zero,
91 // We have to add 1 to prevent duplication.
92 let value = max_id(tt).map_or(0, |it| it + 1);
95 // Find the max token id inside a subtree
96 fn max_id(subtree: &tt::Subtree) -> Option<u32> {
100 .filter_map(|tt| match tt {
101 tt::TokenTree::Subtree(subtree) => {
102 let tree_id = max_id(subtree);
103 match subtree.delimiter {
104 Some(it) if it.id != tt::TokenId::unspecified() => {
105 Some(tree_id.map_or(it.id.0, |t| t.max(it.id.0)))
110 tt::TokenTree::Leaf(tt::Leaf::Ident(ident))
111 if ident.id != tt::TokenId::unspecified() =>
121 /// Shift given TokenTree token id
122 fn shift_all(self, tt: &mut tt::Subtree) {
123 for t in tt.token_trees.iter_mut() {
125 tt::TokenTree::Leaf(leaf) => match leaf {
126 tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
127 tt::Leaf::Punct(punct) => punct.id = self.shift(punct.id),
128 tt::Leaf::Literal(lit) => lit.id = self.shift(lit.id),
130 tt::TokenTree::Subtree(tt) => {
131 if let Some(it) = tt.delimiter.as_mut() {
132 it.id = self.shift(it.id);
140 fn shift(self, id: tt::TokenId) -> tt::TokenId {
141 if id == tt::TokenId::unspecified() {
144 tt::TokenId(id.0 + self.0)
147 fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
148 id.0.checked_sub(self.0).map(tt::TokenId)
152 #[derive(Debug, Eq, PartialEq)]
159 pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
160 // Note: this parsing can be implemented using mbe machinery itself, by
161 // matching against `$($lhs:tt => $rhs:tt);*` pattern, but implementing
162 // manually seems easier.
163 let mut src = TtIter::new(tt);
164 let mut rules = Vec::new();
165 while src.len() > 0 {
166 let rule = Rule::parse(&mut src)?;
168 if let Err(()) = src.expect_char(';') {
170 return Err(ParseError::Expected("expected `:`".to_string()));
176 for rule in rules.iter() {
177 validate(&rule.lhs)?;
180 Ok(MacroRules { rules, shift: Shift::new(tt) })
183 pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
185 let mut tt = tt.clone();
186 self.shift.shift_all(&mut tt);
187 mbe_expander::expand(self, &tt)
190 pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
194 pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
195 match self.shift.unshift(id) {
196 Some(id) => (id, Origin::Call),
197 None => (id, Origin::Def),
203 fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
206 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
208 lhs.delimiter = None;
209 src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
210 src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
213 .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
215 rhs.delimiter = None;
216 Ok(crate::Rule { lhs, rhs })
220 fn to_parse_error(e: ExpandError) -> ParseError {
222 ExpandError::InvalidRepeat => "invalid repeat".to_string(),
223 _ => "invalid macro definition".to_string(),
225 ParseError::Expected(msg)
228 fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
229 for op in parse_pattern(pattern) {
230 let op = op.map_err(to_parse_error)?;
233 Op::TokenTree(tt::TokenTree::Subtree(subtree)) => validate(subtree)?,
234 Op::Repeat { subtree, separator, .. } => {
235 // Checks that no repetition which could match an empty token
236 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
238 if separator.is_none() {
239 if parse_pattern(subtree).all(|child_op| {
240 match child_op.map_err(to_parse_error) {
241 Ok(Op::Var { kind, .. }) => {
243 if kind.map_or(false, |it| it == "vis") {
247 Ok(Op::Repeat { kind, .. }) => {
250 parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
257 return Err(ParseError::RepetitionEmtpyTokenTree);
268 #[derive(Debug, Clone, Eq, PartialEq)]
269 pub struct ExpandResult<T> {
271 pub err: Option<ExpandError>,
274 impl<T> ExpandResult<T> {
275 pub fn ok(value: T) -> Self {
276 Self { value, err: None }
279 pub fn only_err(err: ExpandError) -> Self
283 Self { value: Default::default(), err: Some(err) }
286 pub fn str_err(err: String) -> Self
290 Self::only_err(ExpandError::Other(err))
293 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
294 ExpandResult { value: f(self.value), err: self.err }
297 pub fn result(self) -> Result<T, ExpandError> {
298 self.err.map(Err).unwrap_or(Ok(self.value))
302 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
303 fn from(result: Result<T, ExpandError>) -> Self {
304 result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))