4 use ide_db::{helpers::pick_best_token, RootDatabase};
5 use itertools::Itertools;
6 use syntax::{ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T};
8 use crate::FilePosition;
10 pub struct ExpandedMacro {
12 pub expansion: String,
15 // Feature: Expand Macro Recursively
17 // Shows the full macro expansion of the macro at current cursor.
20 // | Editor | Action Name
22 // | VS Code | **Rust Analyzer: Expand macro recursively**
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);
30 let tok = pick_best_token(file.syntax().token_at_offset(position.offset), |kind| match kind {
31 SyntaxKind::IDENT => 1,
34 let descended = sema.descend_into_macros(tok.clone());
35 if let Some(attr) = descended.ancestors().find_map(ast::Attr::cast) {
36 if let Some((path, tt)) = attr.as_simple_call() {
38 let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
41 .expand_derive_macro(&attr)
42 .map(insert_whitespaces)
43 .map(|expansion| ExpandedMacro { name: tt, expansion });
47 let mut expanded = None;
49 for node in tok.ancestors() {
50 if let Some(item) = ast::Item::cast(node.clone()) {
51 if let Some(def) = sema.resolve_attr_macro_call(&item) {
52 name = def.name(db).map(|name| name.to_string());
53 expanded = expand_attr_macro_recur(&sema, &item);
57 if let Some(mac) = ast::MacroCall::cast(node) {
58 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
59 expanded = expand_macro_recur(&sema, &mac);
65 // macro expansion may lose all white space information
66 // But we hope someday we can use ra_fmt for that
67 let expansion = insert_whitespaces(expanded?);
68 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
71 fn expand_macro_recur(
72 sema: &Semantics<RootDatabase>,
73 macro_call: &ast::MacroCall,
74 ) -> Option<SyntaxNode> {
75 let expanded = sema.expand(macro_call)?.clone_for_update();
76 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
79 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
80 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
81 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
84 fn expand<T: AstNode>(
85 sema: &Semantics<RootDatabase>,
87 f: impl FnMut(SyntaxNode) -> Option<T>,
88 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
89 ) -> Option<SyntaxNode> {
90 let children = expanded.descendants().filter_map(f);
91 let mut replacements = Vec::new();
93 for child in children {
94 if let Some(new_node) = exp(sema, &child) {
95 // check if the whole original syntax is replaced
96 if expanded == *child.syntax() {
97 return Some(new_node);
99 replacements.push((child, new_node));
103 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
107 // FIXME: It would also be cool to share logic here and in the mbe tests,
108 // which are pretty unreadable at the moment.
109 fn insert_whitespaces(syn: SyntaxNode) -> String {
111 let mut res = String::new();
114 let mut last: Option<SyntaxKind> = None;
116 for event in syn.preorder_with_tokens() {
117 let token = match event {
118 WalkEvent::Enter(NodeOrToken::Token(token)) => token,
119 WalkEvent::Leave(NodeOrToken::Node(node))
120 if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) =>
123 res.extend(iter::repeat(" ").take(2 * indent));
128 let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
129 token.next_token().map(|it| f(it.kind())).unwrap_or(default)
132 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
135 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
136 res.push_str(token.text());
139 L_CURLY if is_next(|it| it != R_CURLY, true) => {
141 if is_last(is_text, false) {
145 res.extend(iter::repeat(" ").take(2 * indent));
147 R_CURLY if is_last(|it| it != L_CURLY, true) => {
148 indent = indent.saturating_sub(1);
150 res.extend(iter::repeat(" ").take(2 * indent));
155 res.extend(iter::repeat(" ").take(2 * indent));
157 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
158 res.push_str(token.text());
163 res.extend(iter::repeat(" ").take(2 * indent));
165 T![->] => res.push_str(" -> "),
166 T![=] => res.push_str(" = "),
167 T![=>] => res.push_str(" => "),
168 _ => res.push_str(token.text()),
171 last = Some(token.kind());
176 fn is_text(k: SyntaxKind) -> bool {
177 k.is_keyword() || k.is_literal() || k == IDENT
183 use expect_test::{expect, Expect};
188 fn check(ra_fixture: &str, expect: Expect) {
189 let (analysis, pos) = fixture::position(ra_fixture);
190 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
191 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
192 expect.assert_eq(&actual);
196 fn macro_expand_recursive_expansion() {
219 fn macro_expand_multiple_lines() {
224 fn some_thing() -> u32 {
234 fn some_thing() -> u32 {
243 fn macro_expand_match_ast() {
246 macro_rules! match_ast {
247 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
248 (match ($node:expr) {
249 $( ast::$ast:ident($it:ident) => $res:block, )*
250 _ => $catch_all:expr $(,)?
252 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
260 ast::TraitDef(it) => {},
261 ast::ImplDef(it) => {},
270 if let Some(it) = ast::TraitDef::cast(container.clone()){}
271 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
282 fn macro_expand_match_ast_inside_let_statement() {
285 macro_rules! match_ast {
286 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
287 (match ($node:expr) {}) => {{}};
292 let res = mat$0ch_ast! { match c {}};
305 fn macro_expand_inner_macro_fail_to_expand() {
326 fn macro_expand_with_dollar_crate() {
334 () => {$crate::bar!()};
348 fn macro_expand_derive() {
351 #[rustc_builtin_macro]
359 impl< >crate::clone::Clone for Foo< >{}
366 fn macro_expand_derive2() {
369 #[rustc_builtin_macro]
371 #[rustc_builtin_macro]
380 impl< >crate::marker::Copy for Foo< >{}