3 helpers::{insert_whitespace_into_node::insert_ws_into, pick_best_token},
6 use syntax::{ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxNode, 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 with the cursor at $0 `#[attr]` would expand:
43 let derive = sema.descend_into_macros(tok.clone()).into_iter().find_map(|descended| {
44 let hir_file = sema.hir_file_for(&descended.parent()?);
45 if !hir_file.is_derive_attr_pseudo_expansion(db) {
49 let name = descended.ancestors().filter_map(ast::Path::cast).last()?.to_string();
50 // up map out of the #[derive] expansion
51 let token = hir::InFile::new(hir_file, descended).upmap(db)?.value;
52 let attr = token.ancestors().find_map(ast::Attr::cast)?;
53 let expansions = sema.expand_derive_macro(&attr)?;
56 .token_trees_and_tokens()
57 .filter_map(NodeOrToken::into_token)
58 .take_while(|it| it != &token)
59 .filter(|it| it.kind() == T![,])
63 expansion: expansions.get(idx).cloned().map(insert_ws_into)?.to_string(),
71 // FIXME: Intermix attribute and bang! expansions
72 // currently we only recursively expand one of the two types
73 let mut expanded = None;
75 for node in tok.ancestors() {
76 if let Some(item) = ast::Item::cast(node.clone()) {
77 if let Some(def) = sema.resolve_attr_macro_call(&item) {
78 name = def.name(db).map(|name| name.to_string());
79 expanded = expand_attr_macro_recur(&sema, &item);
83 if let Some(mac) = ast::MacroCall::cast(node) {
84 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
85 expanded = expand_macro_recur(&sema, &mac);
91 // macro expansion may lose all white space information
92 // But we hope someday we can use ra_fmt for that
93 let expansion = insert_ws_into(expanded?).to_string();
94 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
97 fn expand_macro_recur(
98 sema: &Semantics<RootDatabase>,
99 macro_call: &ast::MacroCall,
100 ) -> Option<SyntaxNode> {
101 let expanded = sema.expand(macro_call)?.clone_for_update();
102 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
105 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
106 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
107 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
110 fn expand<T: AstNode>(
111 sema: &Semantics<RootDatabase>,
112 expanded: SyntaxNode,
113 f: impl FnMut(SyntaxNode) -> Option<T>,
114 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
115 ) -> Option<SyntaxNode> {
116 let children = expanded.descendants().filter_map(f);
117 let mut replacements = Vec::new();
119 for child in children {
120 if let Some(new_node) = exp(sema, &child) {
121 // check if the whole original syntax is replaced
122 if expanded == *child.syntax() {
123 return Some(new_node);
125 replacements.push((child, new_node));
129 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
135 use expect_test::{expect, Expect};
140 fn check(ra_fixture: &str, expect: Expect) {
141 let (analysis, pos) = fixture::position(ra_fixture);
142 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
143 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
144 expect.assert_eq(&actual);
148 fn macro_expand_as_keyword() {
152 ($i:tt) => { $i as _ }
155 let x: u64 = ba$0r!(5i64);
165 fn macro_expand_recursive_expansion() {
188 fn macro_expand_multiple_lines() {
193 fn some_thing() -> u32 {
203 fn some_thing() -> u32 {
212 fn macro_expand_match_ast() {
215 macro_rules! match_ast {
216 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
217 (match ($node:expr) {
218 $( ast::$ast:ident($it:ident) => $res:block, )*
219 _ => $catch_all:expr $(,)?
221 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
229 ast::TraitDef(it) => {},
230 ast::ImplDef(it) => {},
239 if let Some(it) = ast::TraitDef::cast(container.clone()){}
240 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
251 fn macro_expand_match_ast_inside_let_statement() {
254 macro_rules! match_ast {
255 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
256 (match ($node:expr) {}) => {{}};
261 let res = mat$0ch_ast! { match c {}};
274 fn macro_expand_inner_macro_fail_to_expand() {
295 fn macro_expand_with_dollar_crate() {
303 () => {$crate::bar!()};
317 fn macro_expand_with_dyn_absolute_path() {
321 () => {fn f<T>(_: &dyn ::std::marker::Copy) {}};
330 fn f<T>(_: &dyn ::std::marker::Copy){}
336 fn macro_expand_derive() {
339 //- proc_macros: identity
340 //- minicore: clone, derive
342 #[proc_macros::identity]
348 impl < >core::clone::Clone for Foo< >{}
355 fn macro_expand_derive2() {
358 //- minicore: copy, clone, derive
366 impl < >core::marker::Copy for Foo< >{}
373 fn macro_expand_derive_multi() {
376 //- minicore: copy, clone, derive
378 #[derive(Cop$0y, Clone)]
383 impl < >core::marker::Copy for Foo< >{}
389 //- minicore: copy, clone, derive
391 #[derive(Copy, Cl$0one)]
396 impl < >core::clone::Clone for Foo< >{}