2 use ide_db::RootDatabase;
4 algo::{find_node_at_offset, SyntaxRewriter},
5 ast, AstNode, NodeOrToken, SyntaxKind,
7 SyntaxNode, WalkEvent, T,
10 use crate::FilePosition;
12 pub struct ExpandedMacro {
14 pub expansion: String,
17 // Feature: Expand Macro Recursively
19 // Shows the full macro expansion of the macro at current cursor.
22 // | Editor | Action Name
24 // | VS Code | **Rust Analyzer: Expand macro recursively**
27 // image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[]
28 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
29 let sema = Semantics::new(db);
30 let file = sema.parse(position.file_id);
31 let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
32 let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
34 let expanded = expand_macro_recur(&sema, &mac)?;
37 // macro expansion may lose all white space information
38 // But we hope someday we can use ra_fmt for that
39 let expansion = insert_whitespaces(expanded);
40 Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
43 fn expand_macro_recur(
44 sema: &Semantics<RootDatabase>,
45 macro_call: &ast::MacroCall,
46 ) -> Option<SyntaxNode> {
47 let mut expanded = sema.expand(macro_call)?;
49 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
50 let mut rewriter = SyntaxRewriter::default();
52 for child in children.into_iter() {
53 if let Some(new_node) = expand_macro_recur(sema, &child) {
54 // Replace the whole node if it is root
55 // `replace_descendants` will not replace the parent node
56 // but `SyntaxNode::descendants include itself
57 if expanded == *child.syntax() {
60 rewriter.replace(child.syntax(), &new_node)
65 let res = rewriter.rewrite(&expanded);
69 // FIXME: It would also be cool to share logic here and in the mbe tests,
70 // which are pretty unreadable at the moment.
71 fn insert_whitespaces(syn: SyntaxNode) -> String {
72 let mut res = String::new();
73 let mut token_iter = syn
74 .preorder_with_tokens()
76 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
85 let mut last: Option<SyntaxKind> = None;
87 while let Some(token) = token_iter.next() {
88 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
89 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
92 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
94 res += &match token.kind() {
95 k if is_text(k) && is_next(|it| !it.is_punct(), true) => token.text().to_string() + " ",
96 L_CURLY if is_next(|it| it != R_CURLY, true) => {
98 let leading_space = if is_last(is_text, false) { " " } else { "" };
99 format!("{}{{\n{}", leading_space, " ".repeat(indent))
101 R_CURLY if is_last(|it| it != L_CURLY, true) => {
102 indent = indent.saturating_sub(1);
103 format!("\n{}}}", " ".repeat(indent))
105 R_CURLY => format!("}}\n{}", " ".repeat(indent)),
106 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
107 format!("{} ", token.text().to_string())
109 T![;] => format!(";\n{}", " ".repeat(indent)),
110 T![->] => " -> ".to_string(),
111 T![=] => " = ".to_string(),
112 T![=>] => " => ".to_string(),
113 _ => token.text().to_string(),
116 last = Some(token.kind());
121 fn is_text(k: SyntaxKind) -> bool {
122 k.is_keyword() || k.is_literal() || k == IDENT
128 use expect_test::{expect, Expect};
132 fn check(ra_fixture: &str, expect: Expect) {
133 let (analysis, pos) = fixture::position(ra_fixture);
134 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
135 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
136 expect.assert_eq(&actual);
140 fn macro_expand_recursive_expansion() {
162 fn macro_expand_multiple_lines() {
167 fn some_thing() -> u32 {
177 fn some_thing() -> u32 {
185 fn macro_expand_match_ast() {
188 macro_rules! match_ast {
189 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
190 (match ($node:expr) {
191 $( ast::$ast:ident($it:ident) => $res:block, )*
192 _ => $catch_all:expr $(,)?
194 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
202 ast::TraitDef(it) => {},
203 ast::ImplDef(it) => {},
212 if let Some(it) = ast::TraitDef::cast(container.clone()){}
213 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
224 fn macro_expand_match_ast_inside_let_statement() {
227 macro_rules! match_ast {
228 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
229 (match ($node:expr) {}) => {{}};
234 let res = mat$0ch_ast! { match c {}};
247 fn macro_expand_inner_macro_fail_to_expand() {
268 fn macro_expand_with_dollar_crate() {
276 () => {$crate::bar!()};