Skip to content

Commit 5dd44a0

Browse files
Merge #2347
2347: More correct expand macro r=matklad a=edwin0cheng Co-authored-by: Edwin Cheng <[email protected]>
2 parents f24aa7a + a92ad59 commit 5dd44a0

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

crates/ra_ide_api/src/expand_macro.rs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ fn expand_macro_recur(
4040
let analyzer = hir::SourceAnalyzer::new(db, source, None);
4141
let expansion = analyzer.expand(db, macro_call)?;
4242
let macro_file_id = expansion.file_id();
43-
let expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?;
43+
let mut expanded: SyntaxNode = db.parse_or_expand(macro_file_id)?;
4444

4545
let children = expanded.descendants().filter_map(ast::MacroCall::cast);
4646
let mut replaces = FxHashMap::default();
@@ -49,7 +49,14 @@ fn expand_macro_recur(
4949
let node = hir::Source::new(macro_file_id, &child);
5050
let new_node = expand_macro_recur(db, source, node)?;
5151

52-
replaces.insert(child.syntax().clone().into(), new_node.into());
52+
// Replace the whole node if it is root
53+
// `replace_descendants` will not replace the parent node
54+
// but `SyntaxNode::descendants include itself
55+
if expanded == *child.syntax() {
56+
expanded = new_node;
57+
} else {
58+
replaces.insert(child.syntax().clone().into(), new_node.into());
59+
}
5360
}
5461

5562
Some(replace_descendants(&expanded, &replaces))
@@ -217,4 +224,27 @@ fn some_thing() -> u32 {
217224
}
218225
"###);
219226
}
227+
228+
#[test]
229+
fn macro_expand_match_ast_inside_let_statement() {
230+
let res = check_expand_macro(
231+
r#"
232+
//- /lib.rs
233+
macro_rules! match_ast {
234+
(match $node:ident { $($tt:tt)* }) => { match_ast!(match ($node) { $($tt)* }) };
235+
(match ($node:expr) {}) => {{}};
236+
}
237+
238+
fn main() {
239+
let p = f(|it| {
240+
let res = mat<|>ch_ast! { match c {}};
241+
Some(res)
242+
})?;
243+
}
244+
"#,
245+
);
246+
247+
assert_eq!(res.name, "match_ast");
248+
assert_snapshot!(res.expansion, @r###"{}"###);
249+
}
220250
}

0 commit comments

Comments
 (0)