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 // due to how Rust Analyzer works internally, we need to special case derive attributes,
36 // otherwise they might not get found, e.g. here only `#[attr]` would expand:
43 let derive = sema.descend_into_macros(tok.clone()).iter().find_map(|descended| {
44 let attr = descended.ancestors().find_map(ast::Attr::cast)?;
45 let (path, tt) = attr.as_simple_call()?;
47 let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
49 let expansions = sema.expand_derive_macro(&attr)?;
50 return Some(ExpandedMacro {
52 expansion: expansions.into_iter().map(insert_whitespaces).join(""),
63 // FIXME: Intermix attribute and bang! expansions
64 // currently we only recursively expand one of the two types
65 let mut expanded = None;
67 for node in tok.ancestors() {
68 if let Some(item) = ast::Item::cast(node.clone()) {
69 if let Some(def) = sema.resolve_attr_macro_call(&item) {
70 name = def.name(db).map(|name| name.to_string());
71 expanded = expand_attr_macro_recur(&sema, &item);
75 if let Some(mac) = ast::MacroCall::cast(node) {
76 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
77 expanded = expand_macro_recur(&sema, &mac);
83 // macro expansion may lose all white space information
84 // But we hope someday we can use ra_fmt for that
85 let expansion = insert_whitespaces(expanded?);
86 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
89 fn expand_macro_recur(
90 sema: &Semantics<RootDatabase>,
91 macro_call: &ast::MacroCall,
92 ) -> Option<SyntaxNode> {
93 let expanded = sema.expand(macro_call)?.clone_for_update();
94 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
97 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
98 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
99 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
102 fn expand<T: AstNode>(
103 sema: &Semantics<RootDatabase>,
104 expanded: SyntaxNode,
105 f: impl FnMut(SyntaxNode) -> Option<T>,
106 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
107 ) -> Option<SyntaxNode> {
108 let children = expanded.descendants().filter_map(f);
109 let mut replacements = Vec::new();
111 for child in children {
112 if let Some(new_node) = exp(sema, &child) {
113 // check if the whole original syntax is replaced
114 if expanded == *child.syntax() {
115 return Some(new_node);
117 replacements.push((child, new_node));
121 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
125 // FIXME: It would also be cool to share logic here and in the mbe tests,
126 // which are pretty unreadable at the moment.
127 fn insert_whitespaces(syn: SyntaxNode) -> String {
129 let mut res = String::new();
132 let mut last: Option<SyntaxKind> = None;
134 for event in syn.preorder_with_tokens() {
135 let token = match event {
136 WalkEvent::Enter(NodeOrToken::Token(token)) => token,
137 WalkEvent::Leave(NodeOrToken::Node(node))
138 if matches!(node.kind(), ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL) =>
141 res.extend(iter::repeat(" ").take(2 * indent));
146 let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
147 token.next_token().map(|it| f(it.kind())).unwrap_or(default)
150 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
153 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
154 res.push_str(token.text());
157 L_CURLY if is_next(|it| it != R_CURLY, true) => {
159 if is_last(is_text, false) {
163 res.extend(iter::repeat(" ").take(2 * indent));
165 R_CURLY if is_last(|it| it != L_CURLY, true) => {
166 indent = indent.saturating_sub(1);
168 res.extend(iter::repeat(" ").take(2 * indent));
173 res.extend(iter::repeat(" ").take(2 * indent));
175 LIFETIME_IDENT if is_next(|it| it == IDENT || it == MUT_KW, true) => {
176 res.push_str(token.text());
181 res.extend(iter::repeat(" ").take(2 * indent));
183 T![->] => res.push_str(" -> "),
184 T![=] => res.push_str(" = "),
185 T![=>] => res.push_str(" => "),
186 _ => res.push_str(token.text()),
189 last = Some(token.kind());
194 fn is_text(k: SyntaxKind) -> bool {
195 k.is_keyword() || k.is_literal() || k == IDENT
201 use expect_test::{expect, Expect};
206 fn check(ra_fixture: &str, expect: Expect) {
207 let (analysis, pos) = fixture::position(ra_fixture);
208 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
209 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
210 expect.assert_eq(&actual);
214 fn macro_expand_recursive_expansion() {
237 fn macro_expand_multiple_lines() {
242 fn some_thing() -> u32 {
252 fn some_thing() -> u32 {
261 fn macro_expand_match_ast() {
264 macro_rules! match_ast {
265 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
266 (match ($node:expr) {
267 $( ast::$ast:ident($it:ident) => $res:block, )*
268 _ => $catch_all:expr $(,)?
270 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
278 ast::TraitDef(it) => {},
279 ast::ImplDef(it) => {},
288 if let Some(it) = ast::TraitDef::cast(container.clone()){}
289 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
300 fn macro_expand_match_ast_inside_let_statement() {
303 macro_rules! match_ast {
304 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
305 (match ($node:expr) {}) => {{}};
310 let res = mat$0ch_ast! { match c {}};
323 fn macro_expand_inner_macro_fail_to_expand() {
344 fn macro_expand_with_dollar_crate() {
352 () => {$crate::bar!()};
366 fn macro_expand_derive() {
369 #[rustc_builtin_macro]
378 impl< >crate::clone::Clone for Foo< >{}
385 fn macro_expand_derive2() {
388 #[rustc_builtin_macro]
390 #[rustc_builtin_macro]
399 impl< >crate::marker::Copy for Foo< >{}
406 fn macro_expand_derive_multi() {
409 #[rustc_builtin_macro]
411 #[rustc_builtin_macro]
414 #[derive(Cop$0y, Clone)]
419 impl< >crate::marker::Copy for Foo< >{}
421 impl< >crate::clone::Clone for Foo< >{}