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**
26 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
27 let sema = Semantics::new(db);
28 let file = sema.parse(position.file_id);
29 let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
30 let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
32 let expanded = expand_macro_recur(&sema, &mac)?;
35 // macro expansion may lose all white space information
36 // But we hope someday we can use ra_fmt for that
37 let expansion = insert_whitespaces(expanded);
38 Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
41 fn expand_macro_recur(
42 sema: &Semantics<RootDatabase>,
43 macro_call: &ast::MacroCall,
44 ) -> Option<SyntaxNode> {
45 let mut expanded = sema.expand(macro_call)?;
47 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
48 let mut rewriter = SyntaxRewriter::default();
50 for child in children.into_iter() {
51 if let Some(new_node) = expand_macro_recur(sema, &child) {
52 // Replace the whole node if it is root
53 // `replace_descendants` will not replace the parent node
54 // but `SyntaxNode::descendants include itself
55 if expanded == *child.syntax() {
58 rewriter.replace(child.syntax(), &new_node)
63 let res = rewriter.rewrite(&expanded);
67 // FIXME: It would also be cool to share logic here and in the mbe tests,
68 // which are pretty unreadable at the moment.
69 fn insert_whitespaces(syn: SyntaxNode) -> String {
70 let mut res = String::new();
71 let mut token_iter = syn
72 .preorder_with_tokens()
74 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
83 let mut last: Option<SyntaxKind> = None;
85 while let Some(token) = token_iter.next() {
86 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
87 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
90 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
92 res += &match token.kind() {
93 k if is_text(k) && is_next(|it| !it.is_punct(), true) => token.text().to_string() + " ",
94 L_CURLY if is_next(|it| it != R_CURLY, true) => {
96 let leading_space = if is_last(is_text, false) { " " } else { "" };
97 format!("{}{{\n{}", leading_space, " ".repeat(indent))
99 R_CURLY if is_last(|it| it != L_CURLY, true) => {
100 indent = indent.saturating_sub(1);
101 format!("\n{}}}", " ".repeat(indent))
103 R_CURLY => format!("}}\n{}", " ".repeat(indent)),
104 T![;] => format!(";\n{}", " ".repeat(indent)),
105 T![->] => " -> ".to_string(),
106 T![=] => " = ".to_string(),
107 T![=>] => " => ".to_string(),
108 _ => token.text().to_string(),
111 last = Some(token.kind());
116 fn is_text(k: SyntaxKind) -> bool {
117 k.is_keyword() || k.is_literal() || k == IDENT
123 use expect_test::{expect, Expect};
127 fn check(ra_fixture: &str, expect: Expect) {
128 let (analysis, pos) = fixture::position(ra_fixture);
129 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
130 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
131 expect.assert_eq(&actual);
135 fn macro_expand_recursive_expansion() {
157 fn macro_expand_multiple_lines() {
162 fn some_thing() -> u32 {
172 fn some_thing() -> u32 {
180 fn macro_expand_match_ast() {
183 macro_rules! match_ast {
184 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
185 (match ($node:expr) {
186 $( ast::$ast:ident($it:ident) => $res:block, )*
187 _ => $catch_all:expr $(,)?
189 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
197 ast::TraitDef(it) => {},
198 ast::ImplDef(it) => {},
207 if let Some(it) = ast::TraitDef::cast(container.clone()){}
208 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
219 fn macro_expand_match_ast_inside_let_statement() {
222 macro_rules! match_ast {
223 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
224 (match ($node:expr) {}) => {{}};
229 let res = mat<|>ch_ast! { match c {}};
242 fn macro_expand_inner_macro_fail_to_expand() {
263 fn macro_expand_with_dollar_crate() {
271 () => {$crate::bar!()};