]> git.lizzy.rs Git - rust.git/blobdiff - crates/mbe/src/lib.rs
Merge #9165
[rust.git] / crates / mbe / src / lib.rs
index 3ad609a005d604c1289ec9384ef10a899ab50887..fcc596756ca7d025777d891f337215e45e1e1345 100644 (file)
@@ -4,7 +4,7 @@
 //! `TokenTree`s as well!
 
 mod parser;
-mod mbe_expander;
+mod expander;
 mod syntax_bridge;
 mod tt_iter;
 mod subtree_source;
 #[cfg(test)]
 mod tests;
 
+#[cfg(test)]
+mod benchmark;
+mod token_map;
+
 use std::fmt;
 
-pub use tt::{Delimiter, Punct};
+pub use tt::{Delimiter, DelimiterKind, Punct};
 
 use crate::{
-    parser::{parse_pattern, Op},
+    parser::{parse_pattern, parse_template, MetaTemplate, Op},
     tt_iter::TtIter,
 };
 
 #[derive(Debug, PartialEq, Eq)]
 pub enum ParseError {
+    UnexpectedToken(String),
     Expected(String),
-    RepetitionEmtpyTokenTree,
+    InvalidRepeat,
+    RepetitionEmptyTokenTree,
 }
 
 #[derive(Debug, PartialEq, Eq, Clone)]
@@ -33,7 +39,6 @@ pub enum ExpandError {
     UnexpectedToken,
     BindingError(String),
     ConversionError,
-    InvalidRepeat,
     ProcMacroError(tt::ExpansionError),
     UnresolvedProcMacro,
     Other(String),
@@ -52,7 +57,6 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
             ExpandError::UnexpectedToken => f.write_str("unexpected token in input"),
             ExpandError::BindingError(e) => f.write_str(e),
             ExpandError::ConversionError => f.write_str("could not convert tokens"),
-            ExpandError::InvalidRepeat => f.write_str("invalid repeat expression"),
             ExpandError::ProcMacroError(e) => e.fmt(f),
             ExpandError::UnresolvedProcMacro => f.write_str("unresolved proc macro"),
             ExpandError::Other(e) => f.write_str(e),
@@ -60,9 +64,12 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     }
 }
 
-pub use crate::syntax_bridge::{
-    ast_to_token_tree, parse_to_token_tree, syntax_node_to_token_tree, token_tree_to_syntax_node,
-    TokenMap,
+pub use crate::{
+    syntax_bridge::{
+        ast_to_token_tree, parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
+        token_tree_to_syntax_node,
+    },
+    token_map::TokenMap,
 };
 
 /// This struct contains AST for a single `macro_rules` definition. What might
@@ -76,10 +83,18 @@ pub struct MacroRules {
     shift: Shift,
 }
 
+/// For Macro 2.0
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct MacroDef {
+    rules: Vec<Rule>,
+    /// Highest id of the token we have in TokenMap
+    shift: Shift,
+}
+
 #[derive(Clone, Debug, PartialEq, Eq)]
 struct Rule {
-    lhs: tt::Subtree,
-    rhs: tt::Subtree,
+    lhs: MetaTemplate,
+    rhs: MetaTemplate,
 }
 
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -120,7 +135,7 @@ fn max_id(subtree: &tt::Subtree) -> Option<u32> {
 
     /// Shift given TokenTree token id
     fn shift_all(self, tt: &mut tt::Subtree) {
-        for t in tt.token_trees.iter_mut() {
+        for t in &mut tt.token_trees {
             match t {
                 tt::TokenTree::Leaf(leaf) => match leaf {
                     tt::Leaf::Ident(ident) => ident.id = self.shift(ident.id),
@@ -163,17 +178,17 @@ pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
         let mut src = TtIter::new(tt);
         let mut rules = Vec::new();
         while src.len() > 0 {
-            let rule = Rule::parse(&mut src)?;
+            let rule = Rule::parse(&mut src, true)?;
             rules.push(rule);
             if let Err(()) = src.expect_char(';') {
                 if src.len() > 0 {
-                    return Err(ParseError::Expected("expected `:`".to_string()));
+                    return Err(ParseError::Expected("expected `;`".to_string()));
                 }
                 break;
             }
         }
 
-        for rule in rules.iter() {
+        for rule in &rules {
             validate(&rule.lhs)?;
         }
 
@@ -184,7 +199,60 @@ pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
         // apply shift
         let mut tt = tt.clone();
         self.shift.shift_all(&mut tt);
-        mbe_expander::expand(self, &tt)
+        expander::expand_rules(&self.rules, &tt)
+    }
+
+    pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
+        self.shift.shift(id)
+    }
+
+    pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
+        match self.shift.unshift(id) {
+            Some(id) => (id, Origin::Call),
+            None => (id, Origin::Def),
+        }
+    }
+}
+
+impl MacroDef {
+    pub fn parse(tt: &tt::Subtree) -> Result<MacroDef, ParseError> {
+        let mut src = TtIter::new(tt);
+        let mut rules = Vec::new();
+
+        if Some(tt::DelimiterKind::Brace) == tt.delimiter_kind() {
+            cov_mark::hit!(parse_macro_def_rules);
+            while src.len() > 0 {
+                let rule = Rule::parse(&mut src, true)?;
+                rules.push(rule);
+                if let Err(()) = src.expect_any_char(&[';', ',']) {
+                    if src.len() > 0 {
+                        return Err(ParseError::Expected(
+                            "expected `;` or `,` to delimit rules".to_string(),
+                        ));
+                    }
+                    break;
+                }
+            }
+        } else {
+            cov_mark::hit!(parse_macro_def_simple);
+            let rule = Rule::parse(&mut src, false)?;
+            if src.len() != 0 {
+                return Err(ParseError::Expected("remain tokens in macro def".to_string()));
+            }
+            rules.push(rule);
+        }
+        for rule in &rules {
+            validate(&rule.lhs)?;
+        }
+
+        Ok(MacroDef { rules, shift: Shift::new(tt) })
+    }
+
+    pub fn expand(&self, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {
+        // apply shift
+        let mut tt = tt.clone();
+        self.shift.shift_all(&mut tt);
+        expander::expand_rules(&self.rules, &tt)
     }
 
     pub fn map_id_down(&self, id: tt::TokenId) -> tt::TokenId {
@@ -200,62 +268,55 @@ pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
 }
 
 impl Rule {
-    fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
-        let mut lhs = src
+    fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
+        let lhs = src
             .expect_subtree()
-            .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
-            .clone();
-        lhs.delimiter = None;
-        src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
-        src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
-        let mut rhs = src
+            .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
+        if expect_arrow {
+            src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
+            src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".to_string()))?;
+        }
+        let rhs = src
             .expect_subtree()
-            .map_err(|()| ParseError::Expected("expected subtree".to_string()))?
-            .clone();
-        rhs.delimiter = None;
+            .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
+
+        let lhs = MetaTemplate(parse_pattern(lhs)?);
+        let rhs = MetaTemplate(parse_template(rhs)?);
+
         Ok(crate::Rule { lhs, rhs })
     }
 }
 
-fn to_parse_error(e: ExpandError) -> ParseError {
-    let msg = match e {
-        ExpandError::InvalidRepeat => "invalid repeat".to_string(),
-        _ => "invalid macro definition".to_string(),
-    };
-    ParseError::Expected(msg)
-}
-
-fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
-    for op in parse_pattern(pattern) {
-        let op = op.map_err(to_parse_error)?;
-
+fn validate(pattern: &MetaTemplate) -> Result<(), ParseError> {
+    for op in pattern.iter() {
         match op {
-            Op::TokenTree(tt::TokenTree::Subtree(subtree)) => validate(subtree)?,
-            Op::Repeat { subtree, separator, .. } => {
+            Op::Subtree { tokens, .. } => validate(tokens)?,
+            Op::Repeat { tokens: subtree, separator, .. } => {
                 // Checks that no repetition which could match an empty token
                 // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
 
-                if separator.is_none() {
-                    if parse_pattern(subtree).all(|child_op| {
-                        match child_op.map_err(to_parse_error) {
-                            Ok(Op::Var { kind, .. }) => {
+                if separator.is_none()
+                    && subtree.iter().all(|child_op| {
+                        match child_op {
+                            Op::Var { kind, .. } => {
                                 // vis is optional
-                                if kind.map_or(false, |it| it == "vis") {
+                                if kind.as_ref().map_or(false, |it| it == "vis") {
                                     return true;
                                 }
                             }
-                            Ok(Op::Repeat { kind, .. }) => {
+                            Op::Repeat { kind, .. } => {
                                 return matches!(
                                     kind,
                                     parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
                                 )
                             }
-                            _ => {}
+                            Op::Leaf(_) => {}
+                            Op::Subtree { .. } => {}
                         }
                         false
-                    }) {
-                        return Err(ParseError::RepetitionEmtpyTokenTree);
-                    }
+                    })
+                {
+                    return Err(ParseError::RepetitionEmptyTokenTree);
                 }
                 validate(subtree)?
             }
@@ -295,12 +356,12 @@ pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ExpandResult<U> {
     }
 
     pub fn result(self) -> Result<T, ExpandError> {
-        self.err.map(Err).unwrap_or(Ok(self.value))
+        self.err.map_or(Ok(self.value), Err)
     }
 }
 
 impl<T: Default> From<Result<T, ExpandError>> for ExpandResult<T> {
     fn from(result: Result<T, ExpandError>) -> Self {
-        result.map_or_else(|e| Self::only_err(e), |it| Self::ok(it))
+        result.map_or_else(Self::only_err, Self::ok)
     }
 }