4 use ide_db::RootDatabase;
6 algo::find_node_at_offset, ast, ted, AstNode, NodeOrToken, SyntaxKind, SyntaxKind::*,
7 SyntaxNode, 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);
31 let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
32 let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
34 let expanded = expand_macro_recur(&sema, &mac)?;
37 // macro expansion may lose all white space information
38 // But we hope someday we can use ra_fmt for that
39 let expansion = insert_whitespaces(expanded);
40 Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
43 fn expand_macro_recur(
44 sema: &Semantics<RootDatabase>,
45 macro_call: &ast::MacroCall,
46 ) -> Option<SyntaxNode> {
47 let expanded = sema.expand(macro_call)?.clone_for_update();
49 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
50 let mut replacements = Vec::new();
52 for child in children {
53 if let Some(new_node) = expand_macro_recur(sema, &child) {
54 // check if the whole original syntax is replaced
55 if expanded == *child.syntax() {
56 return Some(new_node);
58 replacements.push((child, new_node));
62 replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
66 // FIXME: It would also be cool to share logic here and in the mbe tests,
67 // which are pretty unreadable at the moment.
68 fn insert_whitespaces(syn: SyntaxNode) -> String {
69 let mut res = String::new();
70 let mut token_iter = syn
71 .preorder_with_tokens()
73 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
82 let mut last: Option<SyntaxKind> = None;
84 while let Some(token) = token_iter.next() {
85 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
86 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
89 |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
92 k if is_text(k) && is_next(|it| !it.is_punct(), true) => {
93 res.push_str(token.text());
96 L_CURLY if is_next(|it| it != R_CURLY, true) => {
98 if is_last(is_text, false) {
102 res.extend(iter::repeat(" ").take(2 * indent));
104 R_CURLY if is_last(|it| it != L_CURLY, true) => {
105 indent = indent.saturating_sub(1);
107 res.extend(iter::repeat(" ").take(2 * indent));
112 res.extend(iter::repeat(" ").take(2 * indent));
114 LIFETIME_IDENT if is_next(|it| it == IDENT, true) => {
115 res.push_str(token.text());
120 res.extend(iter::repeat(" ").take(2 * indent));
122 T![->] => res.push_str(" -> "),
123 T![=] => res.push_str(" = "),
124 T![=>] => res.push_str(" => "),
125 _ => res.push_str(token.text()),
128 last = Some(token.kind());
133 fn is_text(k: SyntaxKind) -> bool {
134 k.is_keyword() || k.is_literal() || k == IDENT
140 use expect_test::{expect, Expect};
144 fn check(ra_fixture: &str, expect: Expect) {
145 let (analysis, pos) = fixture::position(ra_fixture);
146 let expansion = analysis.expand_macro(pos).unwrap().unwrap();
147 let actual = format!("{}\n{}", expansion.name, expansion.expansion);
148 expect.assert_eq(&actual);
152 fn macro_expand_recursive_expansion() {
174 fn macro_expand_multiple_lines() {
179 fn some_thing() -> u32 {
189 fn some_thing() -> u32 {
197 fn macro_expand_match_ast() {
200 macro_rules! match_ast {
201 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
202 (match ($node:expr) {
203 $( ast::$ast:ident($it:ident) => $res:block, )*
204 _ => $catch_all:expr $(,)?
206 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
214 ast::TraitDef(it) => {},
215 ast::ImplDef(it) => {},
224 if let Some(it) = ast::TraitDef::cast(container.clone()){}
225 else if let Some(it) = ast::ImplDef::cast(container.clone()){}
236 fn macro_expand_match_ast_inside_let_statement() {
239 macro_rules! match_ast {
240 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
241 (match ($node:expr) {}) => {{}};
246 let res = mat$0ch_ast! { match c {}};
259 fn macro_expand_inner_macro_fail_to_expand() {
280 fn macro_expand_with_dollar_crate() {
288 () => {$crate::bar!()};