Also support statements and patterns for macro expansion

This commit is contained in:
Guillaume Gomez
2025-08-01 16:57:39 +02:00
parent bd5f3d7678
commit 0e9b126695
2 changed files with 46 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
use rustc_ast::visit::{Visitor, walk_crate, walk_expr, walk_item};
use rustc_ast::{Crate, Expr, Item};
use rustc_ast::visit::{Visitor, walk_crate, walk_expr, walk_item, walk_pat, walk_stmt};
use rustc_ast::{Crate, Expr, Item, Pat, Stmt};
use rustc_data_structures::fx::FxHashMap;
use rustc_span::source_map::SourceMap;
use rustc_span::{BytePos, Span};
@@ -137,4 +137,20 @@ impl<'ast> Visitor<'ast> for ExpandedCodeVisitor<'ast> {
walk_item(self, item);
}
}
fn visit_stmt(&mut self, stmt: &'ast Stmt) {
if stmt.span.from_expansion() {
self.handle_new_span(stmt.span, || rustc_ast_pretty::pprust::stmt_to_string(stmt));
} else {
walk_stmt(self, stmt);
}
}
fn visit_pat(&mut self, pat: &'ast Pat) {
if pat.span.from_expansion() {
self.handle_new_span(pat.span, || rustc_ast_pretty::pprust::pat_to_string(pat));
} else {
walk_pat(self, pat);
}
}
}

View File

@@ -0,0 +1,28 @@
// This test checks that patterns and statements are also getting expanded.
//@ compile-flags: -Zunstable-options --generate-macro-expansion
#![crate_name = "foo"]
//@ has 'src/foo/macro_expansion.rs.html'
//@ count - '//span[@class="expansion"]' 2
macro_rules! pat {
($x:literal) => {
Some($x)
}
}
macro_rules! stmt {
($x:expr) => {{
let _ = $x;
}}
}
fn bar() {
match Some("hello") {
pat!("blolb") => {}
_ => {}
}
stmt!(1)
}