]> git.lizzy.rs Git - rust.git/blobdiff - crates/mbe/src/lib.rs
internal: remove accidental code re-use
[rust.git] / crates / mbe / src / lib.rs
index 19543d777a42c87fe20b7577f7f728bd3885b64e..13fec269faba764d22878568f26ce33bf2340a7e 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;
 
-use std::fmt;
+#[cfg(test)]
+mod benchmark;
+mod token_map;
 
-pub use tt::{Delimiter, DelimiterKind, Punct};
+use std::fmt;
 
 use crate::{
-    parser::{parse_pattern, parse_template, Op},
+    parser::{parse_pattern, parse_template, MetaTemplate, Op},
     tt_iter::TtIter,
 };
 
+// FIXME: we probably should re-think  `token_tree_to_syntax_node` interfaces
+pub use ::parser::FragmentKind;
+pub use tt::{Delimiter, DelimiterKind, Punct};
+
 #[derive(Debug, PartialEq, Eq)]
 pub enum ParseError {
+    UnexpectedToken(String),
     Expected(String),
+    InvalidRepeat,
     RepetitionEmptyTokenTree,
 }
 
@@ -33,18 +41,11 @@ pub enum ExpandError {
     UnexpectedToken,
     BindingError(String),
     ConversionError,
-    InvalidRepeat,
-    ProcMacroError(tt::ExpansionError),
+    // FIXME: no way mbe should know about proc macros.
     UnresolvedProcMacro,
     Other(String),
 }
 
-impl From<tt::ExpansionError> for ExpandError {
-    fn from(it: tt::ExpansionError) -> Self {
-        ExpandError::ProcMacroError(it)
-    }
-}
-
 impl fmt::Display for ExpandError {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
@@ -52,17 +53,18 @@ 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),
         }
     }
 }
 
-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::{
+        parse_exprs_with_sep, parse_to_token_tree, syntax_node_to_token_tree,
+        syntax_node_to_token_tree_censored, token_tree_to_syntax_node,
+    },
+    token_map::TokenMap,
 };
 
 /// This struct contains AST for a single `macro_rules` definition. What might
@@ -76,33 +78,25 @@ pub struct MacroRules {
     shift: Shift,
 }
 
+/// For Macro 2.0
 #[derive(Clone, Debug, PartialEq, Eq)]
-struct Rule {
-    lhs: MetaTemplate,
-    rhs: MetaTemplate,
+pub struct MacroDef {
+    rules: Vec<Rule>,
+    /// Highest id of the token we have in TokenMap
+    shift: Shift,
 }
 
 #[derive(Clone, Debug, PartialEq, Eq)]
-struct MetaTemplate {
-    delimiter: Option<Delimiter>,
-    tokens: Vec<Result<Op, ExpandError>>,
-}
-
-impl<'a> MetaTemplate {
-    fn iter(&self) -> impl Iterator<Item = &Result<Op, ExpandError>> {
-        self.tokens.iter()
-    }
-
-    fn delimiter_kind(&self) -> Option<DelimiterKind> {
-        self.delimiter.map(|it| it.kind)
-    }
+struct Rule {
+    lhs: MetaTemplate,
+    rhs: MetaTemplate,
 }
 
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-struct Shift(u32);
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct Shift(u32);
 
 impl Shift {
-    fn new(tt: &tt::Subtree) -> Shift {
+    pub fn new(tt: &tt::Subtree) -> Shift {
         // Note that TokenId is started from zero,
         // We have to add 1 to prevent duplication.
         let value = max_id(tt).map_or(0, |it| it + 1);
@@ -135,8 +129,8 @@ 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() {
+    pub fn shift_all(self, tt: &mut tt::Subtree) {
+        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),
@@ -153,14 +147,14 @@ fn shift_all(self, tt: &mut tt::Subtree) {
         }
     }
 
-    fn shift(self, id: tt::TokenId) -> tt::TokenId {
+    pub fn shift(self, id: tt::TokenId) -> tt::TokenId {
         if id == tt::TokenId::unspecified() {
             return id;
         }
         tt::TokenId(id.0 + self.0)
     }
 
-    fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
+    pub fn unshift(self, id: tt::TokenId) -> Option<tt::TokenId> {
         id.0.checked_sub(self.0).map(tt::TokenId)
     }
 }
@@ -179,7 +173,7 @@ 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 {
@@ -189,7 +183,7 @@ pub fn parse(tt: &tt::Subtree) -> Result<MacroRules, ParseError> {
             }
         }
 
-        for rule in rules.iter() {
+        for rule in &rules {
             validate(&rule.lhs)?;
         }
 
@@ -200,7 +194,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 {
@@ -216,62 +263,55 @@ pub fn map_id_up(&self, id: tt::TokenId) -> (tt::TokenId, Origin) {
 }
 
 impl Rule {
-    fn parse(src: &mut TtIter) -> Result<Rule, ParseError> {
+    fn parse(src: &mut TtIter, expect_arrow: bool) -> Result<Self, ParseError> {
         let lhs = src
             .expect_subtree()
             .map_err(|()| ParseError::Expected("expected subtree".to_string()))?;
-        src.expect_char('=').map_err(|()| ParseError::Expected("expected `=`".to_string()))?;
-        src.expect_char('>').map_err(|()| ParseError::Expected("expected `>`".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()))?;
 
-        let lhs = MetaTemplate { tokens: parse_pattern(&lhs), delimiter: None };
-        let rhs = MetaTemplate { tokens: parse_template(&rhs), delimiter: None };
+        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: &MetaTemplate) -> Result<(), ParseError> {
     for op in pattern.iter() {
-        let op = op.as_ref().map_err(|e| to_parse_error(&e))?;
-
         match op {
-            Op::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 subtree.iter().all(|child_op| {
-                        match child_op.as_ref().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.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::RepetitionEmptyTokenTree);
-                    }
+                    })
+                {
+                    return Err(ParseError::RepetitionEmptyTokenTree);
                 }
                 validate(subtree)?
             }
@@ -311,12 +351,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)
     }
 }