]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/expand_macro.rs
fd9d1ff45667e8de34a8e3b0650a12f441fd9dce
[rust.git] / crates / ide / src / expand_macro.rs
1 use std::iter;
2
3 use hir::Semantics;
4 use ide_db::{helpers::pick_best_token, RootDatabase};
5 use itertools::Itertools;
6 use syntax::{ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T};
7
8 use crate::FilePosition;
9
10 pub struct ExpandedMacro {
11     pub name: String,
12     pub expansion: String,
13 }
14
15 // Feature: Expand Macro Recursively
16 //
17 // Shows the full macro expansion of the macro at current cursor.
18 //
19 // |===
20 // | Editor  | Action Name
21 //
22 // | VS Code | **Rust Analyzer: Expand macro recursively**
23 // |===
24 //
25 // image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[]
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
30     let tok = pick_best_token(file.syntax().token_at_offset(position.offset), |kind| match kind {
31         SyntaxKind::IDENT => 1,
32         _ => 0,
33     })?;
34
35     // due to how Rust Analyzer works internally, we need to special case derive attributes,
36     // otherwise they might not get found, e.g. here only `#[attr]` would expand:
37     // ```
38     // #[attr]
39     // #[derive($0Foo)]
40     // struct Bar;
41     // ```
42
43     let derive = sema.descend_into_macros(tok.clone()).iter().find_map(|descended| {
44         let attr = descended.ancestors().find_map(ast::Attr::cast)?;
45         let (path, tt) = attr.as_simple_call()?;
46         if path == "derive" {
47             let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
48             tt.pop();
49             let expansions = sema.expand_derive_macro(&attr)?;
50             return Some(ExpandedMacro {
51                 name: tt,
52                 expansion: expansions.into_iter().map(insert_whitespaces).join(""),
53             });
54         } else {
55             None
56         }
57     });
58
59     if derive.is_some() {
60         return derive;
61     }
62
63     // FIXME: Intermix attribute and bang! expansions
64     // currently we only recursively expand one of the two types
65     let mut expanded = None;
66     let mut name = None;
67     for node in tok.ancestors() {
68         if let Some(item) = ast::Item::cast(node.clone()) {
69             if let Some(def) = sema.resolve_attr_macro_call(&item) {
70                 name = def.name(db).map(|name| name.to_string());
71                 expanded = expand_attr_macro_recur(&sema, &item);
72                 break;
73             }
74         }
75         if let Some(mac) = ast::MacroCall::cast(node) {
76             name = Some(mac.path()?.segment()?.name_ref()?.to_string());
77             expanded = expand_macro_recur(&sema, &mac);
78             break;
79         }
80     }
81
82     // FIXME:
83     // macro expansion may lose all white space information
84     // But we hope someday we can use ra_fmt for that
85     let expansion = insert_whitespaces(expanded?);
86     Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
87 }
88
89 fn expand_macro_recur(
90     sema: &Semantics<RootDatabase>,
91     macro_call: &ast::MacroCall,
92 ) -> Option<SyntaxNode> {
93     let expanded = sema.expand(macro_call)?.clone_for_update();
94     expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
95 }
96
97 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
98     let expanded = sema.expand_attr_macro(item)?.clone_for_update();
99     expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
100 }
101
102 fn expand<T: AstNode>(
103     sema: &Semantics<RootDatabase>,
104     expanded: SyntaxNode,
105     f: impl FnMut(SyntaxNode) -> Option<T>,
106     exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
107 ) -> Option<SyntaxNode> {
108     let children = expanded.descendants().filter_map(f);
109     let mut replacements = Vec::new();
110
111     for child in children {
112         if let Some(new_node) = exp(sema, &child) {
113             // check if the whole original syntax is replaced
114             if expanded == *child.syntax() {
115                 return Some(new_node);
116             }
117             replacements.push((child, new_node));
118         }
119     }
120
121     replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
122     Some(expanded)
123 }
124
125 // FIXME: It would also be cool to share logic here and in the mbe tests,
126 // which are pretty unreadable at the moment.
127 fn insert_whitespaces(syn: SyntaxNode) -> String {
128     use SyntaxKind::*;
129     let mut res = String::new();
130
131     let mut indent = 0;
132     let mut last: Option<SyntaxKind> = None;
133
134     for event in syn.preorder_with_tokens() {
135         let token = match event {
136             WalkEvent::Enter(NodeOrToken::Token(token)) => token,
137             WalkEvent::Leave(NodeOrToken::Node(node))
138                 if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) =>
139             {
140                 res.push('\n');
141                 res.extend(iter::repeat(" ").take(2 * indent));
142                 continue;
143             }
144             _ => continue,
145         };
146         let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
147             token.next_token().map(|it| f(it.kind())).unwrap_or(default)
148         };
149         let is_last =
150             |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
151
152         match token.kind() {
153             k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
154                 res.push_str(token.text());
155                 res.push(' ');
156             }
157             L_CURLY if is_next(|it| it != R_CURLY, true) => {
158                 indent += 1;
159                 if is_last(is_text, false) {
160                     res.push(' ');
161                 }
162                 res.push_str("{\n");
163                 res.extend(iter::repeat(" ").take(2 * indent));
164             }
165             R_CURLY if is_last(|it| it != L_CURLY, true) => {
166                 indent = indent.saturating_sub(1);
167                 res.push('\n');
168                 res.extend(iter::repeat(" ").take(2 * indent));
169                 res.push_str("}");
170             }
171             R_CURLY => {
172                 res.push_str("}\n");
173                 res.extend(iter::repeat(" ").take(2 * indent));
174             }
175             LIFETIME_IDENT if is_next(|it| it == IDENT || it == MUT_KW, true) => {
176                 res.push_str(token.text());
177                 res.push(' ');
178             }
179             T![;] => {
180                 res.push_str(";\n");
181                 res.extend(iter::repeat(" ").take(2 * indent));
182             }
183             T![->] => res.push_str(" -> "),
184             T![=] => res.push_str(" = "),
185             T![=>] => res.push_str(" => "),
186             _ => res.push_str(token.text()),
187         }
188
189         last = Some(token.kind());
190     }
191
192     return res;
193
194     fn is_text(k: SyntaxKind) -> bool {
195         k.is_keyword() || k.is_literal() || k == IDENT
196     }
197 }
198
199 #[cfg(test)]
200 mod tests {
201     use expect_test::{expect, Expect};
202
203     use crate::fixture;
204
205     #[track_caller]
206     fn check(ra_fixture: &str, expect: Expect) {
207         let (analysis, pos) = fixture::position(ra_fixture);
208         let expansion = analysis.expand_macro(pos).unwrap().unwrap();
209         let actual = format!("{}\n{}", expansion.name, expansion.expansion);
210         expect.assert_eq(&actual);
211     }
212
213     #[test]
214     fn macro_expand_recursive_expansion() {
215         check(
216             r#"
217 macro_rules! bar {
218     () => { fn  b() {} }
219 }
220 macro_rules! foo {
221     () => { bar!(); }
222 }
223 macro_rules! baz {
224     () => { foo!(); }
225 }
226 f$0oo!();
227 "#,
228             expect![[r#"
229                 foo
230                 fn b(){}
231
232             "#]],
233         );
234     }
235
236     #[test]
237     fn macro_expand_multiple_lines() {
238         check(
239             r#"
240 macro_rules! foo {
241     () => {
242         fn some_thing() -> u32 {
243             let a = 0;
244             a + 10
245         }
246     }
247 }
248 f$0oo!();
249         "#,
250             expect![[r#"
251                 foo
252                 fn some_thing() -> u32 {
253                   let a = 0;
254                   a+10
255                 }
256             "#]],
257         );
258     }
259
260     #[test]
261     fn macro_expand_match_ast() {
262         check(
263             r#"
264 macro_rules! match_ast {
265     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
266     (match ($node:expr) {
267         $( ast::$ast:ident($it:ident) => $res:block, )*
268         _ => $catch_all:expr $(,)?
269     }) => {{
270         $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
271         { $catch_all }
272     }};
273 }
274
275 fn main() {
276     mat$0ch_ast! {
277         match container {
278             ast::TraitDef(it) => {},
279             ast::ImplDef(it) => {},
280             _ => { continue },
281         }
282     }
283 }
284 "#,
285             expect![[r#"
286        match_ast
287        {
288          if let Some(it) = ast::TraitDef::cast(container.clone()){}
289          else if let Some(it) = ast::ImplDef::cast(container.clone()){}
290          else {
291            {
292              continue
293            }
294          }
295        }"#]],
296         );
297     }
298
299     #[test]
300     fn macro_expand_match_ast_inside_let_statement() {
301         check(
302             r#"
303 macro_rules! match_ast {
304     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
305     (match ($node:expr) {}) => {{}};
306 }
307
308 fn main() {
309     let p = f(|it| {
310         let res = mat$0ch_ast! { match c {}};
311         Some(res)
312     })?;
313 }
314 "#,
315             expect![[r#"
316                 match_ast
317                 {}
318             "#]],
319         );
320     }
321
322     #[test]
323     fn macro_expand_inner_macro_fail_to_expand() {
324         check(
325             r#"
326 macro_rules! bar {
327     (BAD) => {};
328 }
329 macro_rules! foo {
330     () => {bar!()};
331 }
332
333 fn main() {
334     let res = fo$0o!();
335 }
336 "#,
337             expect![[r#"
338                 foo
339             "#]],
340         );
341     }
342
343     #[test]
344     fn macro_expand_with_dollar_crate() {
345         check(
346             r#"
347 #[macro_export]
348 macro_rules! bar {
349     () => {0};
350 }
351 macro_rules! foo {
352     () => {$crate::bar!()};
353 }
354
355 fn main() {
356     let res = fo$0o!();
357 }
358 "#,
359             expect![[r#"
360                 foo
361                 0 "#]],
362         );
363     }
364
365     #[test]
366     fn macro_expand_derive() {
367         check(
368             r#"
369 #[rustc_builtin_macro]
370 pub macro Clone {}
371
372 #[doc = ""]
373 #[derive(C$0lone)]
374 struct Foo {}
375 "#,
376             expect![[r#"
377                 Clone
378                 impl< >crate::clone::Clone for Foo< >{}
379
380             "#]],
381         );
382     }
383
384     #[test]
385     fn macro_expand_derive2() {
386         check(
387             r#"
388 #[rustc_builtin_macro]
389 pub macro Clone {}
390 #[rustc_builtin_macro]
391 pub macro Copy {}
392
393 #[derive(Cop$0y)]
394 #[derive(Clone)]
395 struct Foo {}
396 "#,
397             expect![[r#"
398                 Copy
399                 impl< >crate::marker::Copy for Foo< >{}
400
401             "#]],
402         );
403     }
404
405     #[test]
406     fn macro_expand_derive_multi() {
407         check(
408             r#"
409 #[rustc_builtin_macro]
410 pub macro Clone {}
411 #[rustc_builtin_macro]
412 pub macro Copy {}
413
414 #[derive(Cop$0y, Clone)]
415 struct Foo {}
416 "#,
417             expect![[r#"
418                 Copy, Clone
419                 impl< >crate::marker::Copy for Foo< >{}
420
421                 impl< >crate::clone::Clone for Foo< >{}
422
423             "#]],
424         );
425     }
426 }