Add expr, pat, ty and macro_stmts

This commit is contained in:
Edwin Cheng 2019-04-19 03:49:56 +08:00
parent 3ff5440a50
commit c0f19d7005
5 changed files with 156 additions and 15 deletions

View file

@ -32,11 +32,11 @@ pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, Toke
// The following items are what `rustc` macro can be parsed into :
// link: https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/libsyntax/ext/expand.rs#L141
// * Expr(P<ast::Expr>)
// * Pat(P<ast::Pat>)
// * Ty(P<ast::Ty>)
// * Stmts(SmallVec<[ast::Stmt; 1]>)
// * Items(SmallVec<[P<ast::Item>; 1]>)
// * Expr(P<ast::Expr>) -> token_tree_to_expr
// * Pat(P<ast::Pat>) -> token_tree_to_pat
// * Ty(P<ast::Ty>) -> token_tree_to_ty
// * Stmts(SmallVec<[ast::Stmt; 1]>) -> token_tree_to_stmts
// * Items(SmallVec<[P<ast::Item>; 1]>) -> token_tree_to_items
//
// * TraitItems(SmallVec<[ast::TraitItem; 1]>)
// * ImplItems(SmallVec<[ast::ImplItem; 1]>)
@ -44,6 +44,42 @@ pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, Toke
//
//
/// Parses the token tree (result of macro expansion) to an expression
pub fn token_tree_to_expr(tt: &tt::Subtree) -> TreeArc<ast::Expr> {
let token_source = SubtreeTokenSource::new(tt);
let mut tree_sink = TtTreeSink::new(token_source.querier());
ra_parser::parse_expr(&token_source, &mut tree_sink);
let syntax = tree_sink.inner.finish();
ast::Expr::cast(&syntax).unwrap().to_owned()
}
/// Parses the token tree (result of macro expansion) to a Pattern
pub fn token_tree_to_pat(tt: &tt::Subtree) -> TreeArc<ast::Pat> {
let token_source = SubtreeTokenSource::new(tt);
let mut tree_sink = TtTreeSink::new(token_source.querier());
ra_parser::parse_pat(&token_source, &mut tree_sink);
let syntax = tree_sink.inner.finish();
ast::Pat::cast(&syntax).unwrap().to_owned()
}
/// Parses the token tree (result of macro expansion) to a Type
pub fn token_tree_to_ty(tt: &tt::Subtree) -> TreeArc<ast::TypeRef> {
let token_source = SubtreeTokenSource::new(tt);
let mut tree_sink = TtTreeSink::new(token_source.querier());
ra_parser::parse_ty(&token_source, &mut tree_sink);
let syntax = tree_sink.inner.finish();
ast::TypeRef::cast(&syntax).unwrap().to_owned()
}
/// Parses the token tree (result of macro expansion) as a sequence of stmts
pub fn token_tree_to_macro_stmts(tt: &tt::Subtree) -> TreeArc<ast::MacroStmts> {
let token_source = SubtreeTokenSource::new(tt);
let mut tree_sink = TtTreeSink::new(token_source.querier());
ra_parser::parse_macro_stmts(&token_source, &mut tree_sink);
let syntax = tree_sink.inner.finish();
ast::MacroStmts::cast(&syntax).unwrap().to_owned()
}
/// Parses the token tree (result of macro expansion) as a sequence of items
pub fn token_tree_to_macro_items(tt: &tt::Subtree) -> TreeArc<ast::MacroItems> {
let token_source = SubtreeTokenSource::new(tt);