4 use ide_db::RootDatabase;
6 algo::{find_node_at_offset, SyntaxRewriter},
7 ast, AstNode, NodeOrToken, SyntaxKind,
9 SyntaxNode, WalkEvent, T,
12 use crate::FilePosition;
14 pub struct ExpandedMacro {
16 pub expansion: String,
19 // Feature: Expand Macro Recursively
21 // Shows the full macro expansion of the macro at current cursor.
24 // | Editor | Action Name
26 // | VS Code | **Rust Analyzer: Expand macro recursively**
29 // image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[]
30 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
31 let sema = Semantics::new(db);
32 let file = sema.parse(position.file_id);
33 let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
34 let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
36 let expanded = expand_macro_recur(&sema, &mac)?;
39 // macro expansion may lose all white space information
40 // But we hope someday we can use ra_fmt for that
41 let expansion = insert_whitespaces(expanded);
42 Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
45 fn expand_macro_recur(
46 sema: &Semantics<RootDatabase>,
47 macro_call: &ast::MacroCall,
48 ) -> Option<SyntaxNode> {
49 let mut expanded = sema.expand(macro_call)?;
51 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
52 let mut rewriter = SyntaxRewriter::default();
54 for child in children.into_iter() {
55 if let Some(new_node) = expand_macro_recur(sema, &child) {
56 // Replace the whole node if it is root
57 // `replace_descendants` will not replace the parent node
58 // but `SyntaxNode::descendants include itself
59 if expanded == *child.syntax() {
62 rewriter.replace(child.syntax(), &new_node)
67 let res = rewriter.rewrite(&expanded);
71 // FIXME: It would also be cool to share logic here and in the mbe tests,
72 // which are pretty unreadable at the moment.
73 fn insert_whitespaces(syn: SyntaxNode) -> String {
74 let mut res = String::new();
75 let mut token_iter = syn
76 .preorder_with_tokens()
78 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
87 let mut last: Option<SyntaxKind> = None;
89 while let Some(token) = token_iter.next() {
90 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
91 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
94 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
97 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
98 res.push_str(token.text());
101 L_CURLY if is_next(|it| it != R_CURLY, true) => {
103 if is_last(is_text, false) {
107 res.extend(iter::repeat(" ").take(2 * indent));
109 R_CURLY if is_last(|it| it != L_CURLY, true) => {
110 indent = indent.saturating_sub(1);
112 res.extend(iter::repeat(" ").take(2 * indent));
117 res.extend(iter::repeat(" ").take(2 * indent));
119 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
120 res.push_str(token.text());
125 res.extend(iter::repeat(" ").take(2 * indent));
127 T![->] => res.push_str(" -> "),
128 T![=] => res.push_str(" = "),
129 T![=>] => res.push_str(" => "),
130 _ => res.push_str(token.text()),
133 last = Some(token.kind());
138 fn is_text(k: SyntaxKind) -> bool {
139 k.is_keyword() || k.is_literal() || k == IDENT
145 use expect_test::{expect, Expect};
149 fn check(ra_fixture: &str, expect: Expect) {
150 let (analysis, pos) = fixture::position(ra_fixture);
151 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
152 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
153 expect.assert_eq(&actual);
157 fn macro_expand_recursive_expansion() {
179 fn macro_expand_multiple_lines() {
184 fn some_thing() -> u32 {
194 fn some_thing() -> u32 {
202 fn macro_expand_match_ast() {
205 macro_rules! match_ast {
206 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
207 (match ($node:expr) {
208 $( ast::$ast:ident($it:ident) => $res:block, )*
209 _ => $catch_all:expr $(,)?
211 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
219 ast::TraitDef(it) => {},
220 ast::ImplDef(it) => {},
229 if let Some(it) = ast::TraitDef::cast(container.clone()){}
230 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
241 fn macro_expand_match_ast_inside_let_statement() {
244 macro_rules! match_ast {
245 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
246 (match ($node:expr) {}) => {{}};
251 let res = mat$0ch_ast! { match c {}};
264 fn macro_expand_inner_macro_fail_to_expand() {
285 fn macro_expand_with_dollar_crate() {
293 () => {$crate::bar!()};