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,
35 let descended = sema.descend_into_macros_single(tok.clone());
36 if let Some(attr) = descended.ancestors().find_map(ast::Attr::cast) {
37 if let Some((path, tt)) = attr.as_simple_call() {
39 let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
41 let expansions = sema.expand_derive_macro(&attr)?;
42 return Some(ExpandedMacro {
44 expansion: expansions.into_iter().map(insert_whitespaces).join(""),
50 // FIXME: Intermix attribute and bang! expansions
51 // currently we only recursively expand one of the two types
52 let mut expanded = None;
54 for node in tok.ancestors() {
55 if let Some(item) = ast::Item::cast(node.clone()) {
56 if let Some(def) = sema.resolve_attr_macro_call(&item) {
57 name = def.name(db).map(|name| name.to_string());
58 expanded = expand_attr_macro_recur(&sema, &item);
62 if let Some(mac) = ast::MacroCall::cast(node) {
63 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
64 expanded = expand_macro_recur(&sema, &mac);
70 // macro expansion may lose all white space information
71 // But we hope someday we can use ra_fmt for that
72 let expansion = insert_whitespaces(expanded?);
73 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
76 fn expand_macro_recur(
77 sema: &Semantics<RootDatabase>,
78 macro_call: &ast::MacroCall,
79 ) -> Option<SyntaxNode> {
80 let expanded = sema.expand(macro_call)?.clone_for_update();
81 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
84 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
85 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
86 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
89 fn expand<T: AstNode>(
90 sema: &Semantics<RootDatabase>,
92 f: impl FnMut(SyntaxNode) -> Option<T>,
93 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
94 ) -> Option<SyntaxNode> {
95 let children = expanded.descendants().filter_map(f);
96 let mut replacements = Vec::new();
98 for child in children {
99 if let Some(new_node) = exp(sema, &child) {
100 // check if the whole original syntax is replaced
101 if expanded == *child.syntax() {
102 return Some(new_node);
104 replacements.push((child, new_node));
108 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
112 // FIXME: It would also be cool to share logic here and in the mbe tests,
113 // which are pretty unreadable at the moment.
114 fn insert_whitespaces(syn: SyntaxNode) -> String {
116 let mut res = String::new();
119 let mut last: Option<SyntaxKind> = None;
121 for event in syn.preorder_with_tokens() {
122 let token = match event {
123 WalkEvent::Enter(NodeOrToken::Token(token)) => token,
124 WalkEvent::Leave(NodeOrToken::Node(node))
125 if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) =>
128 res.extend(iter::repeat(" ").take(2 * indent));
133 let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
134 token.next_token().map(|it| f(it.kind())).unwrap_or(default)
137 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
140 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
141 res.push_str(token.text());
144 L_CURLY if is_next(|it| it != R_CURLY, true) => {
146 if is_last(is_text, false) {
150 res.extend(iter::repeat(" ").take(2 * indent));
152 R_CURLY if is_last(|it| it != L_CURLY, true) => {
153 indent = indent.saturating_sub(1);
155 res.extend(iter::repeat(" ").take(2 * indent));
160 res.extend(iter::repeat(" ").take(2 * indent));
162 LIFETIME_IDENT if is_next(|it| it == IDENT || it == MUT_KW, true) => {
163 res.push_str(token.text());
168 res.extend(iter::repeat(" ").take(2 * indent));
170 T![->] => res.push_str(" -> "),
171 T![=] => res.push_str(" = "),
172 T![=>] => res.push_str(" => "),
173 _ => res.push_str(token.text()),
176 last = Some(token.kind());
181 fn is_text(k: SyntaxKind) -> bool {
182 k.is_keyword() || k.is_literal() || k == IDENT
188 use expect_test::{expect, Expect};
193 fn check(ra_fixture: &str, expect: Expect) {
194 let (analysis, pos) = fixture::position(ra_fixture);
195 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
196 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
197 expect.assert_eq(&actual);
201 fn macro_expand_recursive_expansion() {
224 fn macro_expand_multiple_lines() {
229 fn some_thing() -> u32 {
239 fn some_thing() -> u32 {
248 fn macro_expand_match_ast() {
251 macro_rules! match_ast {
252 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
253 (match ($node:expr) {
254 $( ast::$ast:ident($it:ident) => $res:block, )*
255 _ => $catch_all:expr $(,)?
257 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
265 ast::TraitDef(it) => {},
266 ast::ImplDef(it) => {},
275 if let Some(it) = ast::TraitDef::cast(container.clone()){}
276 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
287 fn macro_expand_match_ast_inside_let_statement() {
290 macro_rules! match_ast {
291 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
292 (match ($node:expr) {}) => {{}};
297 let res = mat$0ch_ast! { match c {}};
310 fn macro_expand_inner_macro_fail_to_expand() {
331 fn macro_expand_with_dollar_crate() {
339 () => {$crate::bar!()};
353 fn macro_expand_derive() {
356 #[rustc_builtin_macro]
364 impl< >crate::clone::Clone for Foo< >{}
371 fn macro_expand_derive2() {
374 #[rustc_builtin_macro]
376 #[rustc_builtin_macro]
385 impl< >crate::marker::Copy for Foo< >{}
392 fn macro_expand_derive_multi() {
395 #[rustc_builtin_macro]
397 #[rustc_builtin_macro]
400 #[derive(Cop$0y, Clone)]
405 impl< >crate::marker::Copy for Foo< >{}
407 impl< >crate::clone::Clone for Foo< >{}