4 use ide_db::RootDatabase;
6 ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxKind::*, SyntaxNode, SyntaxToken,
7 TokenAtOffset, WalkEvent, T,
10 use crate::FilePosition;
12 pub struct ExpandedMacro {
14 pub expansion: String,
17 // Feature: Expand Macro Recursively
19 // Shows the full macro expansion of the macro at current cursor.
22 // | Editor | Action Name
24 // | VS Code | **Rust Analyzer: Expand macro recursively**
27 // image::https://user-images.githubusercontent.com/48062697/113020648-b3973180-917a-11eb-84a9-ecb921293dc5.gif[]
28 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
29 let sema = Semantics::new(db);
30 let file = sema.parse(position.file_id);
32 let tok = pick_best(file.syntax().token_at_offset(position.offset))?;
33 let mut expanded = None;
35 for node in tok.ancestors() {
36 if let Some(item) = ast::Item::cast(node.clone()) {
37 expanded = sema.expand_attr_macro(&item);
38 if expanded.is_some() {
39 // FIXME: add the macro name
40 // FIXME: make this recursive too
41 name = Some("?".to_string());
46 if let Some(mac) = ast::MacroCall::cast(node) {
47 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
48 expanded = expand_macro_recur(&sema, &mac);
54 // macro expansion may lose all white space information
55 // But we hope someday we can use ra_fmt for that
56 let expansion = insert_whitespaces(expanded?);
57 Some(ExpandedMacro { name: name?, expansion })
60 fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> {
61 return tokens.max_by_key(priority);
62 fn priority(n: &SyntaxToken) -> usize {
70 fn expand_macro_recur(
71 sema: &Semantics<RootDatabase>,
72 macro_call: &ast::MacroCall,
73 ) -> Option<SyntaxNode> {
74 let expanded = sema.expand(macro_call)?.clone_for_update();
76 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
77 let mut replacements = Vec::new();
79 for child in children {
80 if let Some(new_node) = expand_macro_recur(sema, &child) {
81 // check if the whole original syntax is replaced
82 if expanded == *child.syntax() {
83 return Some(new_node);
85 replacements.push((child, new_node));
89 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
93 // FIXME: It would also be cool to share logic here and in the mbe tests,
94 // which are pretty unreadable at the moment.
95 fn insert_whitespaces(syn: SyntaxNode) -> String {
96 let mut res = String::new();
97 let mut token_iter = syn
98 .preorder_with_tokens()
100 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
109 let mut last: Option<SyntaxKind> = None;
111 while let Some(token) = token_iter.next() {
112 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
113 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
116 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
119 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
120 res.push_str(token.text());
123 L_CURLY if is_next(|it| it != R_CURLY, true) => {
125 if is_last(is_text, false) {
129 res.extend(iter::repeat(" ").take(2 * indent));
131 R_CURLY if is_last(|it| it != L_CURLY, true) => {
132 indent = indent.saturating_sub(1);
134 res.extend(iter::repeat(" ").take(2 * indent));
139 res.extend(iter::repeat(" ").take(2 * indent));
141 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
142 res.push_str(token.text());
147 res.extend(iter::repeat(" ").take(2 * indent));
149 T![->] => res.push_str(" -> "),
150 T![=] => res.push_str(" = "),
151 T![=>] => res.push_str(" => "),
152 _ => res.push_str(token.text()),
155 last = Some(token.kind());
160 fn is_text(k: SyntaxKind) -> bool {
161 k.is_keyword() || k.is_literal() || k == IDENT
167 use expect_test::{expect, Expect};
171 fn check(ra_fixture: &str, expect: Expect) {
172 let (analysis, pos) = fixture::position(ra_fixture);
173 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
174 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
175 expect.assert_eq(&actual);
179 fn macro_expand_recursive_expansion() {
201 fn macro_expand_multiple_lines() {
206 fn some_thing() -> u32 {
216 fn some_thing() -> u32 {
224 fn macro_expand_match_ast() {
227 macro_rules! match_ast {
228 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
229 (match ($node:expr) {
230 $( ast::$ast:ident($it:ident) => $res:block, )*
231 _ => $catch_all:expr $(,)?
233 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
241 ast::TraitDef(it) => {},
242 ast::ImplDef(it) => {},
251 if let Some(it) = ast::TraitDef::cast(container.clone()){}
252 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
263 fn macro_expand_match_ast_inside_let_statement() {
266 macro_rules! match_ast {
267 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
268 (match ($node:expr) {}) => {{}};
273 let res = mat$0ch_ast! { match c {}};
286 fn macro_expand_inner_macro_fail_to_expand() {
307 fn macro_expand_with_dollar_crate() {
315 () => {$crate::bar!()};