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