From b4b522fb3952fae365e02ffdc6ef05c8d75b7674 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 31 Jan 2019 22:14:28 +0300 Subject: cleanup the api --- crates/ra_mbe/src/lib.rs | 71 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 5 deletions(-) (limited to 'crates/ra_mbe/src/lib.rs') diff --git a/crates/ra_mbe/src/lib.rs b/crates/ra_mbe/src/lib.rs index c7be33b19..af3ccc0f5 100644 --- a/crates/ra_mbe/src/lib.rs +++ b/crates/ra_mbe/src/lib.rs @@ -24,17 +24,26 @@ use ra_syntax::SmolStr; pub use tt::{Delimiter, Punct}; -pub use crate::{ - mbe_parser::parse, - mbe_expander::exapnd, - syntax_bridge::macro_call_to_tt, -}; +pub use crate::syntax_bridge::ast_to_token_tree; +/// This struct contains AST for a single `macro_rules` defenition. What might +/// be very confusing is that AST has almost exactly the same shape as +/// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident` +/// and `$()*` have special meaning (see `Var` and `Repeat` data structures) #[derive(Debug)] pub struct MacroRules { pub(crate) rules: Vec, } +impl MacroRules { + pub fn parse(tt: &tt::Subtree) -> Option { + mbe_parser::parse(tt) + } + pub fn expand(&self, tt: &tt::Subtree) -> Option { + mbe_expander::exapnd(self, tt) + } +} + #[derive(Debug)] pub(crate) struct Rule { pub(crate) lhs: Subtree, @@ -93,3 +102,55 @@ pub(crate) struct Var { pub(crate) text: SmolStr, pub(crate) kind: Option, } + +#[cfg(test)] +mod tests { + use ra_syntax::{ast, AstNode}; + + use super::*; + + #[test] + fn test_convert_tt() { + let macro_definition = r#" +macro_rules! impl_froms { + ($e:ident: $($v:ident),*) => { + $( + impl From<$v> for $e { + fn from(it: $v) -> $e { + $e::$v(it) + } + } + )* + } +} +"#; + + let macro_invocation = r#" +impl_froms!(TokenTree: Leaf, Subtree); +"#; + + let source_file = ast::SourceFile::parse(macro_definition); + let macro_definition = source_file + .syntax() + .descendants() + .find_map(ast::MacroCall::cast) + .unwrap(); + + let source_file = ast::SourceFile::parse(macro_invocation); + let macro_invocation = source_file + .syntax() + .descendants() + .find_map(ast::MacroCall::cast) + .unwrap(); + + let definition_tt = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap(); + let invocation_tt = ast_to_token_tree(macro_invocation.token_tree().unwrap()).unwrap(); + let rules = crate::MacroRules::parse(&definition_tt).unwrap(); + let expansion = rules.expand(&invocation_tt).unwrap(); + assert_eq!( + expansion.to_string(), + "impl From < Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree :: Leaf (it)}} \ + impl From < Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree :: Subtree (it)}}" + ) + } +} -- cgit v1.2.3