4 use ide_db::RootDatabase;
6 ast, match_ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxKind::*, SyntaxNode, WalkEvent, T,
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 = file.syntax().token_at_offset(position.offset).left_biased()?;
32 let mut expanded = None;
34 for node in tok.ancestors() {
37 ast::MacroCall(mac) => {
38 name = Some(mac.path()?.segment()?.name_ref()?.to_string());
39 expanded = expand_macro_recur(&sema, &mac);
43 // FIXME: add the macro name
44 // FIXME: make this recursive too
45 name = Some("?".to_string());
46 expanded = sema.expand_attr_macro(&item);
47 if expanded.is_some() {
57 // macro expansion may lose all white space information
58 // But we hope someday we can use ra_fmt for that
59 let expansion = insert_whitespaces(expanded?);
60 Some(ExpandedMacro { name: name?, expansion })
63 fn expand_macro_recur(
64 sema: &Semantics<RootDatabase>,
65 macro_call: &ast::MacroCall,
66 ) -> Option<SyntaxNode> {
67 let expanded = sema.expand(macro_call)?.clone_for_update();
69 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
70 let mut replacements = Vec::new();
72 for child in children {
73 if let Some(new_node) = expand_macro_recur(sema, &child) {
74 // check if the whole original syntax is replaced
75 if expanded == *child.syntax() {
76 return Some(new_node);
78 replacements.push((child, new_node));
82 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
86 // FIXME: It would also be cool to share logic here and in the mbe tests,
87 // which are pretty unreadable at the moment.
88 fn insert_whitespaces(syn: SyntaxNode) -> String {
89 let mut res = String::new();
90 let mut token_iter = syn
91 .preorder_with_tokens()
93 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
102 let mut last: Option<SyntaxKind> = None;
104 while let Some(token) = token_iter.next() {
105 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
106 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
109 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
112 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
113 res.push_str(token.text());
116 L_CURLY if is_next(|it| it != R_CURLY, true) => {
118 if is_last(is_text, false) {
122 res.extend(iter::repeat(" ").take(2 * indent));
124 R_CURLY if is_last(|it| it != L_CURLY, true) => {
125 indent = indent.saturating_sub(1);
127 res.extend(iter::repeat(" ").take(2 * indent));
132 res.extend(iter::repeat(" ").take(2 * indent));
134 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
135 res.push_str(token.text());
140 res.extend(iter::repeat(" ").take(2 * indent));
142 T![->] => res.push_str(" -> "),
143 T![=] => res.push_str(" = "),
144 T![=>] => res.push_str(" => "),
145 _ => res.push_str(token.text()),
148 last = Some(token.kind());
153 fn is_text(k: SyntaxKind) -> bool {
154 k.is_keyword() || k.is_literal() || k == IDENT
160 use expect_test::{expect, Expect};
164 fn check(ra_fixture: &str, expect: Expect) {
165 let (analysis, pos) = fixture::position(ra_fixture);
166 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
167 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
168 expect.assert_eq(&actual);
172 fn macro_expand_recursive_expansion() {
194 fn macro_expand_multiple_lines() {
199 fn some_thing() -> u32 {
209 fn some_thing() -> u32 {
217 fn macro_expand_match_ast() {
220 macro_rules! match_ast {
221 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
222 (match ($node:expr) {
223 $( ast::$ast:ident($it:ident) => $res:block, )*
224 _ => $catch_all:expr $(,)?
226 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
234 ast::TraitDef(it) => {},
235 ast::ImplDef(it) => {},
244 if let Some(it) = ast::TraitDef::cast(container.clone()){}
245 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
256 fn macro_expand_match_ast_inside_let_statement() {
259 macro_rules! match_ast {
260 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
261 (match ($node:expr) {}) => {{}};
266 let res = mat$0ch_ast! { match c {}};
279 fn macro_expand_inner_macro_fail_to_expand() {
300 fn macro_expand_with_dollar_crate() {
308 () => {$crate::bar!()};