]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/expand_macro.rs
Merge #8352
[rust.git] / crates / ide / src / expand_macro.rs
1 use hir::Semantics;
2 use ide_db::RootDatabase;
3 use syntax::{
4     algo::{find_node_at_offset, SyntaxRewriter},
5     ast, AstNode, NodeOrToken, SyntaxKind,
6     SyntaxKind::*,
7     SyntaxNode, WalkEvent, T,
8 };
9
10 use crate::FilePosition;
11
12 pub struct ExpandedMacro {
13     pub name: String,
14     pub expansion: String,
15 }
16
17 // Feature: Expand Macro Recursively
18 //
19 // Shows the full macro expansion of the macro at current cursor.
20 //
21 // |===
22 // | Editor  | Action Name
23 //
24 // | VS Code | **Rust Analyzer: Expand macro recursively**
25 // |===
26 //
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)?;
33
34     let expanded = expand_macro_recur(&sema, &mac)?;
35
36     // FIXME:
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 })
41 }
42
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)?;
48
49     let children = expanded.descendants().filter_map(ast::MacroCall::cast);
50     let mut rewriter = SyntaxRewriter::default();
51
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() {
58                 expanded = new_node;
59             } else {
60                 rewriter.replace(child.syntax(), &new_node)
61             }
62         }
63     }
64
65     let res = rewriter.rewrite(&expanded);
66     Some(res)
67 }
68
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()
75         .filter_map(|event| {
76             if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
77                 Some(token)
78             } else {
79                 None
80             }
81         })
82         .peekable();
83
84     let mut indent = 0;
85     let mut last: Option<SyntaxKind> = None;
86
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)
90         };
91         let is_last =
92             |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
93
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) => {
97                 indent += 1;
98                 let leading_space = if is_last(is_text, false) { " " } else { "" };
99                 format!("{}{{\n{}", leading_space, "  ".repeat(indent))
100             }
101             R_CURLY if is_last(|it| it != L_CURLY, true) => {
102                 indent = indent.saturating_sub(1);
103                 format!("\n{}}}", "  ".repeat(indent))
104             }
105             R_CURLY => format!("}}\n{}", "  ".repeat(indent)),
106             T![;] => format!(";\n{}", "  ".repeat(indent)),
107             T![->] => " -> ".to_string(),
108             T![=] => " = ".to_string(),
109             T![=>] => " => ".to_string(),
110             _ => token.text().to_string(),
111         };
112
113         last = Some(token.kind());
114     }
115
116     return res;
117
118     fn is_text(k: SyntaxKind) -> bool {
119         k.is_keyword() || k.is_literal() || k == IDENT
120     }
121 }
122
123 #[cfg(test)]
124 mod tests {
125     use expect_test::{expect, Expect};
126
127     use crate::fixture;
128
129     fn check(ra_fixture: &str, expect: Expect) {
130         let (analysis, pos) = fixture::position(ra_fixture);
131         let expansion = analysis.expand_macro(pos).unwrap().unwrap();
132         let actual = format!("{}\n{}", expansion.name, expansion.expansion);
133         expect.assert_eq(&actual);
134     }
135
136     #[test]
137     fn macro_expand_recursive_expansion() {
138         check(
139             r#"
140 macro_rules! bar {
141     () => { fn  b() {} }
142 }
143 macro_rules! foo {
144     () => { bar!(); }
145 }
146 macro_rules! baz {
147     () => { foo!(); }
148 }
149 f$0oo!();
150 "#,
151             expect![[r#"
152                 foo
153                 fn b(){}
154             "#]],
155         );
156     }
157
158     #[test]
159     fn macro_expand_multiple_lines() {
160         check(
161             r#"
162 macro_rules! foo {
163     () => {
164         fn some_thing() -> u32 {
165             let a = 0;
166             a + 10
167         }
168     }
169 }
170 f$0oo!();
171         "#,
172             expect![[r#"
173             foo
174             fn some_thing() -> u32 {
175               let a = 0;
176               a+10
177             }"#]],
178         );
179     }
180
181     #[test]
182     fn macro_expand_match_ast() {
183         check(
184             r#"
185 macro_rules! match_ast {
186     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
187     (match ($node:expr) {
188         $( ast::$ast:ident($it:ident) => $res:block, )*
189         _ => $catch_all:expr $(,)?
190     }) => {{
191         $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
192         { $catch_all }
193     }};
194 }
195
196 fn main() {
197     mat$0ch_ast! {
198         match container {
199             ast::TraitDef(it) => {},
200             ast::ImplDef(it) => {},
201             _ => { continue },
202         }
203     }
204 }
205 "#,
206             expect![[r#"
207        match_ast
208        {
209          if let Some(it) = ast::TraitDef::cast(container.clone()){}
210          else if let Some(it) = ast::ImplDef::cast(container.clone()){}
211          else {
212            {
213              continue
214            }
215          }
216        }"#]],
217         );
218     }
219
220     #[test]
221     fn macro_expand_match_ast_inside_let_statement() {
222         check(
223             r#"
224 macro_rules! match_ast {
225     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
226     (match ($node:expr) {}) => {{}};
227 }
228
229 fn main() {
230     let p = f(|it| {
231         let res = mat$0ch_ast! { match c {}};
232         Some(res)
233     })?;
234 }
235 "#,
236             expect![[r#"
237                 match_ast
238                 {}
239             "#]],
240         );
241     }
242
243     #[test]
244     fn macro_expand_inner_macro_fail_to_expand() {
245         check(
246             r#"
247 macro_rules! bar {
248     (BAD) => {};
249 }
250 macro_rules! foo {
251     () => {bar!()};
252 }
253
254 fn main() {
255     let res = fo$0o!();
256 }
257 "#,
258             expect![[r#"
259                 foo
260             "#]],
261         );
262     }
263
264     #[test]
265     fn macro_expand_with_dollar_crate() {
266         check(
267             r#"
268 #[macro_export]
269 macro_rules! bar {
270     () => {0};
271 }
272 macro_rules! foo {
273     () => {$crate::bar!()};
274 }
275
276 fn main() {
277     let res = fo$0o!();
278 }
279 "#,
280             expect![[r#"
281                 foo
282                 0 "#]],
283         );
284     }
285 }