cleanup the api

This commit is contained in:
Aleksey Kladov 2019-01-31 22:14:28 +03:00
parent a16f6bb27d
commit b4b522fb39
3 changed files with 70 additions and 56 deletions

View file

@ -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<Rule>,
}
impl MacroRules {
pub fn parse(tt: &tt::Subtree) -> Option<MacroRules> {
mbe_parser::parse(tt)
}
pub fn expand(&self, tt: &tt::Subtree) -> Option<tt::Subtree> {
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<SmolStr>,
}
#[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)}}"
)
}
}