]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/expand_macro.rs
Merge #8394
[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             LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
107                 format!("{} ", token.text().to_string())
108             }
109             T![;] => format!(";\n{}", "  ".repeat(indent)),
110             T![->] => " -> ".to_string(),
111             T![=] => " = ".to_string(),
112             T![=>] => " => ".to_string(),
113             _ => token.text().to_string(),
114         };
115
116         last = Some(token.kind());
117     }
118
119     return res;
120
121     fn is_text(k: SyntaxKind) -> bool {
122         k.is_keyword() || k.is_literal() || k == IDENT
123     }
124 }
125
126 #[cfg(test)]
127 mod tests {
128     use expect_test::{expect, Expect};
129
130     use crate::fixture;
131
132     fn check(ra_fixture: &str, expect: Expect) {
133         let (analysis, pos) = fixture::position(ra_fixture);
134         let expansion = analysis.expand_macro(pos).unwrap().unwrap();
135         let actual = format!("{}\n{}", expansion.name, expansion.expansion);
136         expect.assert_eq(&actual);
137     }
138
139     #[test]
140     fn macro_expand_recursive_expansion() {
141         check(
142             r#"
143 macro_rules! bar {
144     () => { fn  b() {} }
145 }
146 macro_rules! foo {
147     () => { bar!(); }
148 }
149 macro_rules! baz {
150     () => { foo!(); }
151 }
152 f$0oo!();
153 "#,
154             expect![[r#"
155                 foo
156                 fn b(){}
157             "#]],
158         );
159     }
160
161     #[test]
162     fn macro_expand_multiple_lines() {
163         check(
164             r#"
165 macro_rules! foo {
166     () => {
167         fn some_thing() -> u32 {
168             let a = 0;
169             a + 10
170         }
171     }
172 }
173 f$0oo!();
174         "#,
175             expect![[r#"
176             foo
177             fn some_thing() -> u32 {
178               let a = 0;
179               a+10
180             }"#]],
181         );
182     }
183
184     #[test]
185     fn macro_expand_match_ast() {
186         check(
187             r#"
188 macro_rules! match_ast {
189     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
190     (match ($node:expr) {
191         $( ast::$ast:ident($it:ident) => $res:block, )*
192         _ => $catch_all:expr $(,)?
193     }) => {{
194         $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
195         { $catch_all }
196     }};
197 }
198
199 fn main() {
200     mat$0ch_ast! {
201         match container {
202             ast::TraitDef(it) => {},
203             ast::ImplDef(it) => {},
204             _ => { continue },
205         }
206     }
207 }
208 "#,
209             expect![[r#"
210        match_ast
211        {
212          if let Some(it) = ast::TraitDef::cast(container.clone()){}
213          else if let Some(it) = ast::ImplDef::cast(container.clone()){}
214          else {
215            {
216              continue
217            }
218          }
219        }"#]],
220         );
221     }
222
223     #[test]
224     fn macro_expand_match_ast_inside_let_statement() {
225         check(
226             r#"
227 macro_rules! match_ast {
228     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
229     (match ($node:expr) {}) => {{}};
230 }
231
232 fn main() {
233     let p = f(|it| {
234         let res = mat$0ch_ast! { match c {}};
235         Some(res)
236     })?;
237 }
238 "#,
239             expect![[r#"
240                 match_ast
241                 {}
242             "#]],
243         );
244     }
245
246     #[test]
247     fn macro_expand_inner_macro_fail_to_expand() {
248         check(
249             r#"
250 macro_rules! bar {
251     (BAD) => {};
252 }
253 macro_rules! foo {
254     () => {bar!()};
255 }
256
257 fn main() {
258     let res = fo$0o!();
259 }
260 "#,
261             expect![[r#"
262                 foo
263             "#]],
264         );
265     }
266
267     #[test]
268     fn macro_expand_with_dollar_crate() {
269         check(
270             r#"
271 #[macro_export]
272 macro_rules! bar {
273     () => {0};
274 }
275 macro_rules! foo {
276     () => {$crate::bar!()};
277 }
278
279 fn main() {
280     let res = fo$0o!();
281 }
282 "#,
283             expect![[r#"
284                 foo
285                 0 "#]],
286         );
287     }
288 }