4 use ide_db::{helpers::pick_best_token, RootDatabase};
5 use itertools::Itertools;
6 use syntax::{ast, ted, AstNode, NodeOrToken, SyntaxKind, 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 mut expanded = None;
36 for node in tok.ancestors() {
37 if let Some(attr) = ast::Attr::cast(node.clone()) {
38 if let Some((path, tt)) = attr.as_simple_call() {
40 let mut tt = tt.syntax().children_with_tokens().skip(1).join("");
43 expanded = sema.expand_derive_macro(&attr);
49 if let Some(item) = ast::Item::cast(node.clone()) {
50 if let Some(def) = sema.resolve_attr_macro_call(&item) {
51 name = def.name(db).map(|name| name.to_string());
52 expanded = expand_attr_macro_recur(&sema, &item);
57 if let Some(mac) = ast::MacroCall::cast(node) {
58 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
59 expanded = expand_macro_recur(&sema, &mac);
65 // macro expansion may lose all white space information
66 // But we hope someday we can use ra_fmt for that
67 let expansion = insert_whitespaces(expanded?);
68 Some(ExpandedMacro { name: name.unwrap_or_else(|| "???".to_owned()), expansion })
71 fn expand_macro_recur(
72 sema: &Semantics<RootDatabase>,
73 macro_call: &ast::MacroCall,
74 ) -> Option<SyntaxNode> {
75 let expanded = sema.expand(macro_call)?.clone_for_update();
76 expand(sema, expanded, ast::MacroCall::cast, expand_macro_recur)
79 fn expand_attr_macro_recur(sema: &Semantics<RootDatabase>, item: &ast::Item) -> Option<SyntaxNode> {
80 let expanded = sema.expand_attr_macro(item)?.clone_for_update();
81 expand(sema, expanded, ast::Item::cast, expand_attr_macro_recur)
84 fn expand<T: AstNode>(
85 sema: &Semantics<RootDatabase>,
87 f: impl FnMut(SyntaxNode) -> Option<T>,
88 exp: impl Fn(&Semantics<RootDatabase>, &T) -> Option<SyntaxNode>,
89 ) -> Option<SyntaxNode> {
90 let children = expanded.descendants().filter_map(f);
91 let mut replacements = Vec::new();
93 for child in children {
94 if let Some(new_node) = exp(sema, &child) {
95 // check if the whole original syntax is replaced
96 if expanded == *child.syntax() {
97 return Some(new_node);
99 replacements.push((child, new_node));
103 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
107 // FIXME: It would also be cool to share logic here and in the mbe tests,
108 // which are pretty unreadable at the moment.
109 fn insert_whitespaces(syn: SyntaxNode) -> String {
110 let mut res = String::new();
111 let mut token_iter = syn
112 .preorder_with_tokens()
113 .filter_map(|event| {
114 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
123 let mut last: Option<SyntaxKind> = None;
125 while let Some(token) = token_iter.next() {
126 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
127 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
130 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
133 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
134 res.push_str(token.text());
137 L_CURLY if is_next(|it| it != R_CURLY, true) => {
139 if is_last(is_text, false) {
143 res.extend(iter::repeat(" ").take(2 * indent));
145 R_CURLY if is_last(|it| it != L_CURLY, true) => {
146 indent = indent.saturating_sub(1);
148 res.extend(iter::repeat(" ").take(2 * indent));
153 res.extend(iter::repeat(" ").take(2 * indent));
155 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
156 res.push_str(token.text());
161 res.extend(iter::repeat(" ").take(2 * indent));
163 T![->] => res.push_str(" -> "),
164 T![=] => res.push_str(" = "),
165 T![=>] => res.push_str(" => "),
166 _ => res.push_str(token.text()),
169 last = Some(token.kind());
174 fn is_text(k: SyntaxKind) -> bool {
175 k.is_keyword() || k.is_literal() || k == IDENT
181 use expect_test::{expect, Expect};
185 fn check(ra_fixture: &str, expect: Expect) {
186 let (analysis, pos) = fixture::position(ra_fixture);
187 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
188 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
189 expect.assert_eq(&actual);
193 fn macro_expand_recursive_expansion() {
215 fn macro_expand_multiple_lines() {
220 fn some_thing() -> u32 {
230 fn some_thing() -> u32 {
238 fn macro_expand_match_ast() {
241 macro_rules! match_ast {
242 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
243 (match ($node:expr) {
244 $( ast::$ast:ident($it:ident) => $res:block, )*
245 _ => $catch_all:expr $(,)?
247 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
255 ast::TraitDef(it) => {},
256 ast::ImplDef(it) => {},
265 if let Some(it) = ast::TraitDef::cast(container.clone()){}
266 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
277 fn macro_expand_match_ast_inside_let_statement() {
280 macro_rules! match_ast {
281 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
282 (match ($node:expr) {}) => {{}};
287 let res = mat$0ch_ast! { match c {}};
300 fn macro_expand_inner_macro_fail_to_expand() {
321 fn macro_expand_with_dollar_crate() {
329 () => {$crate::bar!()};
343 fn macro_expand_derive() {
347 #[rustc_builtin_macro]
355 impl< >crate::clone::Clone for Foo< >{}