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("");
40 let expansions = sema.expand_derive_macro(&attr)?;
41 return Some(ExpandedMacro {
43 expansion: expansions.into_iter().map(insert_whitespaces).join(""),
48 let mut expanded = None;
50 for node in tok.ancestors() {
51 if let Some(item) = ast::Item::cast(node.clone()) {
52 if let Some(def) = sema.resolve_attr_macro_call(&item) {
53 name = def.name(db).map(|name| name.to_string());
54 expanded = expand_attr_macro_recur(&sema, &item);
58 if let Some(mac) = ast::MacroCall::cast(node) {
59 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
60 expanded = expand_macro_recur(&sema, &mac);
66 // macro expansion may lose all white space information
67 // But we hope someday we can use ra_fmt for that
68 let expansion = insert_whitespaces(expanded?);
69 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
72 fn expand_macro_recur(
73 sema: &Semantics<RootDatabase>,
74 macro_call: &ast::MacroCall,
75 ) -> Option<SyntaxNode> {
76 let expanded = sema.expand(macro_call)?.clone_for_update();
77 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
80 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
81 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
82 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
85 fn expand<T: AstNode>(
86 sema: &Semantics<RootDatabase>,
88 f: impl FnMut(SyntaxNode) -> Option<T>,
89 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
90 ) -> Option<SyntaxNode> {
91 let children = expanded.descendants().filter_map(f);
92 let mut replacements = Vec::new();
94 for child in children {
95 if let Some(new_node) = exp(sema, &child) {
96 // check if the whole original syntax is replaced
97 if expanded == *child.syntax() {
98 return Some(new_node);
100 replacements.push((child, new_node));
104 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
108 // FIXME: It would also be cool to share logic here and in the mbe tests,
109 // which are pretty unreadable at the moment.
110 fn insert_whitespaces(syn: SyntaxNode) -> String {
112 let mut res = String::new();
115 let mut last: Option<SyntaxKind> = None;
117 for event in syn.preorder_with_tokens() {
118 let token = match event {
119 WalkEvent::Enter(NodeOrToken::Token(token)) => token,
120 WalkEvent::Leave(NodeOrToken::Node(node))
121 if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) =>
124 res.extend(iter::repeat(" ").take(2 * indent));
129 let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
130 token.next_token().map(|it| f(it.kind())).unwrap_or(default)
133 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
136 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
137 res.push_str(token.text());
140 L_CURLY if is_next(|it| it != R_CURLY, true) => {
142 if is_last(is_text, false) {
146 res.extend(iter::repeat(" ").take(2 * indent));
148 R_CURLY if is_last(|it| it != L_CURLY, true) => {
149 indent = indent.saturating_sub(1);
151 res.extend(iter::repeat(" ").take(2 * indent));
156 res.extend(iter::repeat(" ").take(2 * indent));
158 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
159 res.push_str(token.text());
164 res.extend(iter::repeat(" ").take(2 * indent));
166 T![->] => res.push_str(" -> "),
167 T![=] => res.push_str(" = "),
168 T![=>] => res.push_str(" => "),
169 _ => res.push_str(token.text()),
172 last = Some(token.kind());
177 fn is_text(k: SyntaxKind) -> bool {
178 k.is_keyword() || k.is_literal() || k == IDENT
184 use expect_test::{expect, Expect};
189 fn check(ra_fixture: &str, expect: Expect) {
190 let (analysis, pos) = fixture::position(ra_fixture);
191 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
192 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
193 expect.assert_eq(&actual);
197 fn macro_expand_recursive_expansion() {
220 fn macro_expand_multiple_lines() {
225 fn some_thing() -> u32 {
235 fn some_thing() -> u32 {
244 fn macro_expand_match_ast() {
247 macro_rules! match_ast {
248 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
249 (match ($node:expr) {
250 $( ast::$ast:ident($it:ident) => $res:block, )*
251 _ => $catch_all:expr $(,)?
253 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
261 ast::TraitDef(it) => {},
262 ast::ImplDef(it) => {},
271 if let Some(it) = ast::TraitDef::cast(container.clone()){}
272 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
283 fn macro_expand_match_ast_inside_let_statement() {
286 macro_rules! match_ast {
287 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
288 (match ($node:expr) {}) => {{}};
293 let res = mat$0ch_ast! { match c {}};
306 fn macro_expand_inner_macro_fail_to_expand() {
327 fn macro_expand_with_dollar_crate() {
335 () => {$crate::bar!()};
349 fn macro_expand_derive() {
352 #[rustc_builtin_macro]
360 impl< >crate::clone::Clone for Foo< >{}
367 fn macro_expand_derive2() {
370 #[rustc_builtin_macro]
372 #[rustc_builtin_macro]
381 impl< >crate::marker::Copy for Foo< >{}
388 fn macro_expand_derive_multi() {
391 #[rustc_builtin_macro]
393 #[rustc_builtin_macro]
396 #[derive(Cop$0y, Clone)]
401 impl< >crate::marker::Copy for Foo< >{}
403 impl< >crate::clone::Clone for Foo< >{}