1 //! This modules implements "expand macro" functionality in the IDE
3 use crate::{db::RootDatabase, FilePosition};
4 use hir::db::AstDatabase;
5 use ra_db::SourceDatabase;
6 use rustc_hash::FxHashMap;
9 algo::{find_node_at_offset, replace_descendants},
11 AstNode, NodeOrToken, SyntaxKind, SyntaxNode, WalkEvent, T,
14 pub struct ExpandedMacro {
16 pub expansion: String,
19 pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<ExpandedMacro> {
20 let parse = db.parse(position.file_id);
21 let file = parse.tree();
22 let name_ref = find_node_at_offset::<ast::NameRef>(file.syntax(), position.offset)?;
23 let mac = name_ref.syntax().ancestors().find_map(ast::MacroCall::cast)?;
25 let source = hir::InFile::new(position.file_id.into(), mac.syntax());
26 let expanded = expand_macro_recur(db, source, source.with_value(&mac))?;
29 // macro expansion may lose all white space information
30 // But we hope someday we can use ra_fmt for that
31 let expansion = insert_whitespaces(expanded);
32 Some(ExpandedMacro { name: name_ref.text().to_string(), expansion })
35 fn expand_macro_recur(
37 source: hir::InFile<&SyntaxNode>,
38 macro_call: hir::InFile<&ast::MacroCall>,
39 ) -> Option<SyntaxNode> {
40 let analyzer = hir::SourceAnalyzer::new(db, source, None);
41 let expansion = analyzer.expand(db, macro_call)?;
42 let macro_file_id = expansion.file_id();
43 let mut expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?;
45 let children = expanded.descendants().filter_map(ast::MacroCall::cast);
46 let mut replaces = FxHashMap::default();
48 for child in children.into_iter() {
49 let node = hir::InFile::new(macro_file_id, &child);
50 if let Some(new_node) = expand_macro_recur(db, source, node) {
51 // Replace the whole node if it is root
52 // `replace_descendants` will not replace the parent node
53 // but `SyntaxNode::descendants include itself
54 if expanded == *child.syntax() {
57 replaces.insert(child.syntax().clone().into(), new_node.into());
62 Some(replace_descendants(&expanded, &replaces))
65 // FIXME: It would also be cool to share logic here and in the mbe tests,
66 // which are pretty unreadable at the moment.
67 fn insert_whitespaces(syn: SyntaxNode) -> String {
70 let mut res = String::new();
71 let mut token_iter = syn
72 .preorder_with_tokens()
74 if let WalkEvent::Enter(NodeOrToken::Token(token)) = event {
83 let mut last: Option<SyntaxKind> = None;
85 while let Some(token) = token_iter.next() {
86 let mut is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
87 token_iter.peek().map(|it| f(it.kind())).unwrap_or(default)
89 let is_last = |f: fn(SyntaxKind) -> bool, default| -> bool {
90 last.map(|it| f(it)).unwrap_or(default)
93 res += &match token.kind() {
94 k @ _ if is_text(k) && is_next(|it| !it.is_punct(), true) => {
95 token.text().to_string() + " "
97 L_CURLY if is_next(|it| it != R_CURLY, true) => {
99 let leading_space = if is_last(|it| is_text(it), false) { " " } else { "" };
100 format!("{}{{\n{}", leading_space, " ".repeat(indent))
102 R_CURLY if is_last(|it| it != L_CURLY, true) => {
103 indent = indent.checked_sub(1).unwrap_or(0);
104 format!("\n{}}}", " ".repeat(indent))
106 R_CURLY => format!("}}\n{}", " ".repeat(indent)),
107 T![;] => format!(";\n{}", " ".repeat(indent)),
108 T![->] => " -> ".to_string(),
109 T![=] => " = ".to_string(),
110 T![=>] => " => ".to_string(),
111 _ => token.text().to_string(),
114 last = Some(token.kind());
119 fn is_text(k: SyntaxKind) -> bool {
120 k.is_keyword() || k.is_literal() || k == IDENT
127 use crate::mock_analysis::analysis_and_position;
128 use insta::assert_snapshot;
130 fn check_expand_macro(fixture: &str) -> ExpandedMacro {
131 let (analysis, pos) = analysis_and_position(fixture);
132 analysis.expand_macro(pos).unwrap().unwrap()
136 fn macro_expand_recursive_expansion() {
137 let res = check_expand_macro(
153 assert_eq!(res.name, "foo");
154 assert_snapshot!(res.expansion, @r###"
160 fn macro_expand_multiple_lines() {
161 let res = check_expand_macro(
166 fn some_thing() -> u32 {
176 assert_eq!(res.name, "foo");
177 assert_snapshot!(res.expansion, @r###"
178 fn some_thing() -> u32 {
186 fn macro_expand_match_ast() {
187 let res = check_expand_macro(
190 macro_rules! match_ast {
191 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
193 (match ($node:expr) {
194 $( ast::$ast:ident($it:ident) => $res:block, )*
195 _ => $catch_all:expr $(,)?
197 $( if let Some($it) = ast::$ast::cast($node.clone()) $res else )*
205 ast::TraitDef(it) => {},
206 ast::ImplBlock(it) => {},
214 assert_eq!(res.name, "match_ast");
215 assert_snapshot!(res.expansion, @r###"
217 if let Some(it) = ast::TraitDef::cast(container.clone()){}
218 else if let Some(it) = ast::ImplBlock::cast(container.clone()){}
229 fn macro_expand_match_ast_inside_let_statement() {
230 let res = check_expand_macro(
233 macro_rules! match_ast {
234 (match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
235 (match ($node:expr) {}) => {{}};
240 let res = mat<|>ch_ast! { match c {}};
247 assert_eq!(res.name, "match_ast");
248 assert_snapshot!(res.expansion, @r###"{}"###);
252 fn macro_expand_inner_macro_fail_to_expand() {
253 let res = check_expand_macro(
269 assert_eq!(res.name, "foo");
270 assert_snapshot!(res.expansion, @r###"bar!()"###);
274 fn macro_expand_with_dollar_crate() {
275 let res = check_expand_macro(
283 () => {$crate::bar!()};
292 assert_eq!(res.name, "foo");
293 assert_snapshot!(res.expansion, @r###"0"###);