3 helpers::{insert_whitespace_into_node::insert_ws_into, pick_best_token},
6 use itertools::Itertools;
7 use syntax::{ast, ted, AstNode, SyntaxKind, SyntaxNode};
9 use crate::FilePosition;
11 pub struct ExpandedMacro {
13 pub expansion: String,
16 // Feature: Expand Macro Recursively
18 // Shows the full macro expansion of the macro at current cursor.
21 // | Editor | Action Name
23 // | VS Code | **Rust Analyzer: Expand macro recursively**
26 // image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[]
27 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
28 let sema = Semantics::new(db);
29 let file = sema.parse(position.file_id);
31 let tok = pick_best_token(file.syntax().token_at_offset(position.offset), |kind| match kind {
32 SyntaxKind::IDENT => 1,
36 // due to how Rust Analyzer works internally, we need to special case derive attributes,
37 // otherwise they might not get found, e.g. here with the cursor at $0 `#[attr]` would expand:
44 let derive = sema.descend_into_macros(tok.clone()).iter().find_map(|descended| {
45 let attr = descended.ancestors().find_map(ast::Attr::cast)?;
46 let (path, tt) = attr.as_simple_call()?;
48 let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
50 let expansions = sema.expand_derive_macro(&attr)?;
53 expansion: expansions.into_iter().map(insert_ws_into).join(""),
64 // FIXME: Intermix attribute and bang! expansions
65 // currently we only recursively expand one of the two types
66 let mut expanded = None;
68 for node in tok.ancestors() {
69 if let Some(item) = ast::Item::cast(node.clone()) {
70 if let Some(def) = sema.resolve_attr_macro_call(&item) {
71 name = def.name(db).map(|name| name.to_string());
72 expanded = expand_attr_macro_recur(&sema, &item);
76 if let Some(mac) = ast::MacroCall::cast(node) {
77 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
78 expanded = expand_macro_recur(&sema, &mac);
84 // macro expansion may lose all white space information
85 // But we hope someday we can use ra_fmt for that
86 let expansion = insert_ws_into(expanded?).to_string();
87 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
90 fn expand_macro_recur(
91 sema: &Semantics<RootDatabase>,
92 macro_call: &ast::MacroCall,
93 ) -> Option<SyntaxNode> {
94 let expanded = sema.expand(macro_call)?.clone_for_update();
95 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
98 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
99 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
100 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
103 fn expand<T: AstNode>(
104 sema: &Semantics<RootDatabase>,
105 expanded: SyntaxNode,
106 f: impl FnMut(SyntaxNode) -> Option<T>,
107 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
108 ) -> Option<SyntaxNode> {
109 let children = expanded.descendants().filter_map(f);
110 let mut replacements = Vec::new();
112 for child in children {
113 if let Some(new_node) = exp(sema, &child) {
114 // check if the whole original syntax is replaced
115 if expanded == *child.syntax() {
116 return Some(new_node);
118 replacements.push((child, new_node));
122 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
128 use expect_test::{expect, Expect};
133 fn check(ra_fixture: &str, expect: Expect) {
134 let (analysis, pos) = fixture::position(ra_fixture);
135 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
136 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
137 expect.assert_eq(&actual);
141 fn macro_expand_as_keyword() {
145 ($i:tt) => { $i as _ }
148 let x: u64 = ba$0r!(5i64);
158 fn macro_expand_recursive_expansion() {
181 fn macro_expand_multiple_lines() {
186 fn some_thing() -> u32 {
196 fn some_thing() -> u32 {
205 fn macro_expand_match_ast() {
208 macro_rules! match_ast {
209 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
210 (match ($node:expr) {
211 $( ast::$ast:ident($it:ident) => $res:block, )*
212 _ => $catch_all:expr $(,)?
214 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
222 ast::TraitDef(it) => {},
223 ast::ImplDef(it) => {},
232 if let Some(it) = ast::TraitDef::cast(container.clone()){}
233 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
244 fn macro_expand_match_ast_inside_let_statement() {
247 macro_rules! match_ast {
248 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
249 (match ($node:expr) {}) => {{}};
254 let res = mat$0ch_ast! { match c {}};
267 fn macro_expand_inner_macro_fail_to_expand() {
288 fn macro_expand_with_dollar_crate() {
296 () => {$crate::bar!()};
310 fn macro_expand_with_dyn_absolute_path() {
314 () => {fn f<T>(_: &dyn ::std::marker::Copy) {}};
323 fn f<T>(_: &dyn ::std::marker::Copy){}
329 fn macro_expand_derive() {
332 //- proc_macros: identity
333 //- minicore: clone, derive
335 #[proc_macros::identity]
341 impl < >core::clone::Clone for Foo< >{}
348 fn macro_expand_derive2() {
351 //- minicore: copy, clone, derive
359 impl < >core::marker::Copy for Foo< >{}
366 fn macro_expand_derive_multi() {
369 //- minicore: copy, clone, derive
371 #[derive(Cop$0y, Clone)]
376 impl < >core::marker::Copy for Foo< >{}
378 impl < >core::clone::Clone for Foo< >{}