]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/expand_macro.rs
Replace SyntaxRewriter with ted in exppand_macro::expand_macro_recur
[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, ast, ted, AstNode, NodeOrToken, SyntaxKind, 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 expanded = sema.expand(macro_call)?.clone_for_update();
48
49     let children = expanded.descendants().filter_map(ast::MacroCall::cast);
50     let mut replacements = Vec::new();
51
52     for child in children {
53         if let Some(new_node) = expand_macro_recur(sema, &child) {
54             // check if the whole original syntax is replaced
55             if expanded == *child.syntax() {
56                 return Some(new_node);
57             }
58             replacements.push((child, new_node));
59         }
60     }
61
62     replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
63     Some(expanded)
64 }
65
66 // FIXME: It would also be cool to share logic here and in the mbe tests,
67 // which are pretty unreadable at the moment.
68 fn insert_whitespaces(syn: SyntaxNode) -> String {
69     let mut res = String::new();
70     let mut token_iter = syn
71         .preorder_with_tokens()
72         .filter_map(|event| {
73             if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
74                 Some(token)
75             } else {
76                 None
77             }
78         })
79         .peekable();
80
81     let mut indent = 0;
82     let mut last: Option<SyntaxKind> = None;
83
84     while let Some(token) = token_iter.next() {
85         let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
86             token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
87         };
88         let is_last =
89             |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
90
91         match token.kind() {
92             k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
93                 res.push_str(token.text());
94                 res.push(' ');
95             }
96             L_CURLY if is_next(|it| it != R_CURLY, true) => {
97                 indent += 1;
98                 if is_last(is_text, false) {
99                     res.push(' ');
100                 }
101                 res.push_str("{\n");
102                 res.extend(iter::repeat(" ").take(2 * indent));
103             }
104             R_CURLY if is_last(|it| it != L_CURLY, true) => {
105                 indent = indent.saturating_sub(1);
106                 res.push('\n');
107                 res.extend(iter::repeat(" ").take(2 * indent));
108                 res.push_str("}");
109             }
110             R_CURLY => {
111                 res.push_str("}\n");
112                 res.extend(iter::repeat(" ").take(2 * indent));
113             }
114             LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
115                 res.push_str(token.text());
116                 res.push(' ');
117             }
118             T![;] => {
119                 res.push_str(";\n");
120                 res.extend(iter::repeat(" ").take(2 * indent));
121             }
122             T![->] => res.push_str(" -> "),
123             T![=] => res.push_str(" = "),
124             T![=>] => res.push_str(" => "),
125             _ => res.push_str(token.text()),
126         }
127
128         last = Some(token.kind());
129     }
130
131     return res;
132
133     fn is_text(k: SyntaxKind) -> bool {
134         k.is_keyword() || k.is_literal() || k == IDENT
135     }
136 }
137
138 #[cfg(test)]
139 mod tests {
140     use expect_test::{expect, Expect};
141
142     use crate::fixture;
143
144     fn check(ra_fixture: &str, expect: Expect) {
145         let (analysis, pos) = fixture::position(ra_fixture);
146         let expansion = analysis.expand_macro(pos).unwrap().unwrap();
147         let actual = format!("{}\n{}", expansion.name, expansion.expansion);
148         expect.assert_eq(&actual);
149     }
150
151     #[test]
152     fn macro_expand_recursive_expansion() {
153         check(
154             r#"
155 macro_rules! bar {
156     () => { fn  b() {} }
157 }
158 macro_rules! foo {
159     () => { bar!(); }
160 }
161 macro_rules! baz {
162     () => { foo!(); }
163 }
164 f$0oo!();
165 "#,
166             expect![[r#"
167                 foo
168                 fn b(){}
169             "#]],
170         );
171     }
172
173     #[test]
174     fn macro_expand_multiple_lines() {
175         check(
176             r#"
177 macro_rules! foo {
178     () => {
179         fn some_thing() -> u32 {
180             let a = 0;
181             a + 10
182         }
183     }
184 }
185 f$0oo!();
186         "#,
187             expect![[r#"
188             foo
189             fn some_thing() -> u32 {
190               let a = 0;
191               a+10
192             }"#]],
193         );
194     }
195
196     #[test]
197     fn macro_expand_match_ast() {
198         check(
199             r#"
200 macro_rules! match_ast {
201     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
202     (match ($node:expr) {
203         $( ast::$ast:ident($it:ident) => $res:block, )*
204         _ => $catch_all:expr $(,)?
205     }) => {{
206         $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
207         { $catch_all }
208     }};
209 }
210
211 fn main() {
212     mat$0ch_ast! {
213         match container {
214             ast::TraitDef(it) => {},
215             ast::ImplDef(it) => {},
216             _ => { continue },
217         }
218     }
219 }
220 "#,
221             expect![[r#"
222        match_ast
223        {
224          if let Some(it) = ast::TraitDef::cast(container.clone()){}
225          else if let Some(it) = ast::ImplDef::cast(container.clone()){}
226          else {
227            {
228              continue
229            }
230          }
231        }"#]],
232         );
233     }
234
235     #[test]
236     fn macro_expand_match_ast_inside_let_statement() {
237         check(
238             r#"
239 macro_rules! match_ast {
240     (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
241     (match ($node:expr) {}) => {{}};
242 }
243
244 fn main() {
245     let p = f(|it| {
246         let res = mat$0ch_ast! { match c {}};
247         Some(res)
248     })?;
249 }
250 "#,
251             expect![[r#"
252                 match_ast
253                 {}
254             "#]],
255         );
256     }
257
258     #[test]
259     fn macro_expand_inner_macro_fail_to_expand() {
260         check(
261             r#"
262 macro_rules! bar {
263     (BAD) => {};
264 }
265 macro_rules! foo {
266     () => {bar!()};
267 }
268
269 fn main() {
270     let res = fo$0o!();
271 }
272 "#,
273             expect![[r#"
274                 foo
275             "#]],
276         );
277     }
278
279     #[test]
280     fn macro_expand_with_dollar_crate() {
281         check(
282             r#"
283 #[macro_export]
284 macro_rules! bar {
285     () => {0};
286 }
287 macro_rules! foo {
288     () => {$crate::bar!()};
289 }
290
291 fn main() {
292     let res = fo$0o!();
293 }
294 "#,
295             expect![[r#"
296                 foo
297                 0 "#]],
298         );
299     }
300 }