Skip to content

Commit 2f145f6

Browse files
committed
Make macro metavars respect (non-)hygiene
1 parent c20d7ee commit 2f145f6

File tree

7 files changed

+111
-24
lines changed

7 files changed

+111
-24
lines changed

src/librustc_expand/mbe/macro_check.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ use rustc_data_structures::fx::FxHashMap;
112112
use rustc_session::lint::builtin::META_VARIABLE_MISUSE;
113113
use rustc_session::parse::ParseSess;
114114
use rustc_span::symbol::kw;
115-
use rustc_span::{symbol::Ident, MultiSpan, Span};
115+
use rustc_span::{symbol::LegacyIdent, MultiSpan, Span};
116116

117117
use smallvec::SmallVec;
118118

@@ -179,7 +179,7 @@ struct BinderInfo {
179179
}
180180

181181
/// An environment of meta-variables to their binder information.
182-
type Binders = FxHashMap<Ident, BinderInfo>;
182+
type Binders = FxHashMap<LegacyIdent, BinderInfo>;
183183

184184
/// The state at which we entered a macro definition in the RHS of another macro definition.
185185
struct MacroState<'a> {
@@ -245,6 +245,7 @@ fn check_binders(
245245
if macros.is_empty() {
246246
sess.span_diagnostic.span_bug(span, "unexpected MetaVar in lhs");
247247
}
248+
let name = LegacyIdent::new(name);
248249
// There are 3 possibilities:
249250
if let Some(prev_info) = binders.get(&name) {
250251
// 1. The meta-variable is already bound in the current LHS: This is an error.
@@ -264,6 +265,7 @@ fn check_binders(
264265
if !macros.is_empty() {
265266
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in nested lhs");
266267
}
268+
let name = LegacyIdent::new(name);
267269
if let Some(prev_info) = get_binder_info(macros, binders, name) {
268270
// Duplicate binders at the top-level macro definition are errors. The lint is only
269271
// for nested macro definitions.
@@ -300,7 +302,7 @@ fn check_binders(
300302
fn get_binder_info<'a>(
301303
mut macros: &'a Stack<'a, MacroState<'a>>,
302304
binders: &'a Binders,
303-
name: Ident,
305+
name: LegacyIdent,
304306
) -> Option<&'a BinderInfo> {
305307
binders.get(&name).or_else(|| macros.find_map(|state| state.binders.get(&name)))
306308
}
@@ -331,6 +333,7 @@ fn check_occurrences(
331333
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in rhs")
332334
}
333335
TokenTree::MetaVar(span, name) => {
336+
let name = LegacyIdent::new(name);
334337
check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name);
335338
}
336339
TokenTree::Delimited(_, ref del) => {
@@ -552,7 +555,7 @@ fn check_ops_is_prefix(
552555
binders: &Binders,
553556
ops: &Stack<'_, KleeneToken>,
554557
span: Span,
555-
name: Ident,
558+
name: LegacyIdent,
556559
) {
557560
let macros = macros.push(MacroState { binders, ops: ops.into() });
558561
// Accumulates the stacks the operators of each state until (and including when) the
@@ -598,7 +601,7 @@ fn ops_is_prefix(
598601
sess: &ParseSess,
599602
node_id: NodeId,
600603
span: Span,
601-
name: Ident,
604+
name: LegacyIdent,
602605
binder_ops: &[KleeneToken],
603606
occurrence_ops: &[KleeneToken],
604607
) {

src/librustc_expand/mbe/macro_parser.rs

+10-7
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,13 @@ use TokenTreeOrTokenTreeSlice::*;
7676

7777
use crate::mbe::{self, TokenTree};
7878

79-
use rustc_ast::ast::{Ident, Name};
79+
use rustc_ast::ast::Name;
8080
use rustc_ast::ptr::P;
8181
use rustc_ast::token::{self, DocComment, Nonterminal, Token};
8282
use rustc_ast_pretty::pprust;
8383
use rustc_parse::parser::{FollowedByType, Parser, PathStyle};
8484
use rustc_session::parse::ParseSess;
85-
use rustc_span::symbol::{kw, sym, Symbol};
85+
use rustc_span::symbol::{kw, sym, Ident, LegacyIdent, Symbol};
8686

8787
use rustc_errors::{FatalError, PResult};
8888
use rustc_span::Span;
@@ -273,9 +273,10 @@ crate enum ParseResult<T> {
273273
Error(rustc_span::Span, String),
274274
}
275275

276-
/// A `ParseResult` where the `Success` variant contains a mapping of `Ident`s to `NamedMatch`es.
277-
/// This represents the mapping of metavars to the token trees they bind to.
278-
crate type NamedParseResult = ParseResult<FxHashMap<Ident, NamedMatch>>;
276+
/// A `ParseResult` where the `Success` variant contains a mapping of
277+
/// `LegacyIdent`s to `NamedMatch`es. This represents the mapping of metavars
278+
/// to the token trees they bind to.
279+
crate type NamedParseResult = ParseResult<FxHashMap<LegacyIdent, NamedMatch>>;
279280

280281
/// Count how many metavars are named in the given matcher `ms`.
281282
pub(super) fn count_names(ms: &[TokenTree]) -> usize {
@@ -368,7 +369,7 @@ fn nameize<I: Iterator<Item = NamedMatch>>(
368369
sess: &ParseSess,
369370
m: &TokenTree,
370371
res: &mut I,
371-
ret_val: &mut FxHashMap<Ident, NamedMatch>,
372+
ret_val: &mut FxHashMap<LegacyIdent, NamedMatch>,
372373
) -> Result<(), (rustc_span::Span, String)> {
373374
match *m {
374375
TokenTree::Sequence(_, ref seq) => {
@@ -386,7 +387,9 @@ fn nameize<I: Iterator<Item = NamedMatch>>(
386387
return Err((span, "missing fragment specifier".to_string()));
387388
}
388389
}
389-
TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val.entry(bind_name) {
390+
TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val
391+
.entry(LegacyIdent::new(bind_name))
392+
{
390393
Vacant(spot) => {
391394
spot.insert(res.next().unwrap());
392395
}

src/librustc_expand/mbe/macro_rules.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use rustc_parse::Directory;
2222
use rustc_session::parse::ParseSess;
2323
use rustc_span::edition::Edition;
2424
use rustc_span::hygiene::Transparency;
25-
use rustc_span::symbol::{kw, sym, Symbol};
25+
use rustc_span::symbol::{kw, sym, LegacyIdent, Symbol};
2626
use rustc_span::Span;
2727

2828
use log::debug;
@@ -411,7 +411,7 @@ pub fn compile_declarative_macro(
411411
let mut valid = true;
412412

413413
// Extract the arguments:
414-
let lhses = match argument_map[&lhs_nm] {
414+
let lhses = match argument_map[&LegacyIdent::new(lhs_nm)] {
415415
MatchedSeq(ref s) => s
416416
.iter()
417417
.map(|m| {
@@ -428,7 +428,7 @@ pub fn compile_declarative_macro(
428428
_ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
429429
};
430430

431-
let rhses = match argument_map[&rhs_nm] {
431+
let rhses = match argument_map[&LegacyIdent::new(rhs_nm)] {
432432
MatchedSeq(ref s) => s
433433
.iter()
434434
.map(|m| {

src/librustc_expand/mbe/transcribe.rs

+12-9
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ use crate::base::ExtCtxt;
22
use crate::mbe;
33
use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq, NamedMatch};
44

5-
use rustc_ast::ast::{Ident, Mac};
5+
use rustc_ast::ast::Mac;
66
use rustc_ast::mut_visit::{self, MutVisitor};
77
use rustc_ast::token::{self, NtTT, Token};
88
use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint};
99
use rustc_data_structures::fx::FxHashMap;
1010
use rustc_data_structures::sync::Lrc;
1111
use rustc_errors::pluralize;
1212
use rustc_span::hygiene::{ExpnId, Transparency};
13+
use rustc_span::symbol::LegacyIdent;
1314
use rustc_span::Span;
1415

1516
use smallvec::{smallvec, SmallVec};
@@ -81,7 +82,7 @@ impl Iterator for Frame {
8182
/// Along the way, we do some additional error checking.
8283
pub(super) fn transcribe(
8384
cx: &ExtCtxt<'_>,
84-
interp: &FxHashMap<Ident, NamedMatch>,
85+
interp: &FxHashMap<LegacyIdent, NamedMatch>,
8586
src: Vec<mbe::TokenTree>,
8687
transparency: Transparency,
8788
) -> TokenStream {
@@ -223,9 +224,10 @@ pub(super) fn transcribe(
223224
}
224225

225226
// Replace the meta-var with the matched token tree from the invocation.
226-
mbe::TokenTree::MetaVar(mut sp, mut ident) => {
227+
mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => {
227228
// Find the matched nonterminal from the macro invocation, and use it to replace
228229
// the meta-var.
230+
let ident = LegacyIdent::new(orignal_ident);
229231
if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) {
230232
if let MatchedNonterminal(ref nt) = cur_matched {
231233
// FIXME #2887: why do we apply a mark when matching a token tree meta-var
@@ -249,9 +251,9 @@ pub(super) fn transcribe(
249251
// If we aren't able to match the meta-var, we push it back into the result but
250252
// with modified syntax context. (I believe this supports nested macros).
251253
marker.visit_span(&mut sp);
252-
marker.visit_ident(&mut ident);
254+
marker.visit_ident(&mut orignal_ident);
253255
result.push(TokenTree::token(token::Dollar, sp).into());
254-
result.push(TokenTree::Token(Token::from_ast_ident(ident)).into());
256+
result.push(TokenTree::Token(Token::from_ast_ident(orignal_ident)).into());
255257
}
256258
}
257259

@@ -287,8 +289,8 @@ pub(super) fn transcribe(
287289
/// into the right place in nested matchers. If we attempt to descend too far, the macro writer has
288290
/// made a mistake, and we return `None`.
289291
fn lookup_cur_matched<'a>(
290-
ident: Ident,
291-
interpolations: &'a FxHashMap<Ident, NamedMatch>,
292+
ident: LegacyIdent,
293+
interpolations: &'a FxHashMap<LegacyIdent, NamedMatch>,
292294
repeats: &[(usize, usize)],
293295
) -> Option<&'a NamedMatch> {
294296
interpolations.get(&ident).map(|matched| {
@@ -316,7 +318,7 @@ enum LockstepIterSize {
316318

317319
/// A `MetaVar` with an actual `MatchedSeq`. The length of the match and the name of the
318320
/// meta-var are returned.
319-
Constraint(usize, Ident),
321+
Constraint(usize, LegacyIdent),
320322

321323
/// Two `Constraint`s on the same sequence had different lengths. This is an error.
322324
Contradiction(String),
@@ -360,7 +362,7 @@ impl LockstepIterSize {
360362
/// multiple nested matcher sequences.
361363
fn lockstep_iter_size(
362364
tree: &mbe::TokenTree,
363-
interpolations: &FxHashMap<Ident, NamedMatch>,
365+
interpolations: &FxHashMap<LegacyIdent, NamedMatch>,
364366
repeats: &[(usize, usize)],
365367
) -> LockstepIterSize {
366368
use mbe::TokenTree;
@@ -376,6 +378,7 @@ fn lockstep_iter_size(
376378
})
377379
}
378380
TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => {
381+
let name = LegacyIdent::new(name);
379382
match lookup_cur_matched(name, interpolations, repeats) {
380383
Some(matched) => match matched {
381384
MatchedNonterminal(_) => LockstepIterSize::Unconstrained,

src/librustc_span/symbol.rs

+25
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,31 @@ impl fmt::Display for IdentPrinter {
980980
}
981981
}
982982

983+
/// An newtype around `Ident` that calls [Ident::modern_and_legacy] on
984+
/// construction.
985+
// FIXME(matthewj, petrochenkov) Use this more often, add a similar
986+
// `ModernIdent` struct and use that as well.
987+
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
988+
pub struct LegacyIdent(Ident);
989+
990+
impl LegacyIdent {
991+
pub fn new(ident: Ident) -> Self {
992+
Self(ident.modern_and_legacy())
993+
}
994+
}
995+
996+
impl fmt::Debug for LegacyIdent {
997+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998+
fmt::Debug::fmt(&self.0, f)
999+
}
1000+
}
1001+
1002+
impl fmt::Display for LegacyIdent {
1003+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1004+
fmt::Display::fmt(&self.0, f)
1005+
}
1006+
}
1007+
9831008
/// An interned string.
9841009
///
9851010
/// Internally, a `Symbol` is implemented as an index, and all operations
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Ensure macro metavariables are compared with legacy hygiene
2+
3+
#![feature(rustc_attrs)]
4+
5+
// run-pass
6+
7+
macro_rules! make_mac {
8+
( $($dollar:tt $arg:ident),+ ) => {
9+
macro_rules! mac {
10+
( $($dollar $arg : ident),+ ) => {
11+
$( $dollar $arg )-+
12+
}
13+
}
14+
}
15+
}
16+
17+
macro_rules! show_hygiene {
18+
( $dollar:tt $arg:ident ) => {
19+
make_mac!($dollar $arg, $dollar arg);
20+
}
21+
}
22+
23+
show_hygiene!( $arg );
24+
25+
fn main() {
26+
let x = 5;
27+
let y = 3;
28+
assert_eq!(2, mac!(x, y));
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Ensure macro metavariables are not compared without removing transparent
2+
// marks.
3+
4+
#![feature(rustc_attrs)]
5+
6+
// run-pass
7+
8+
#[rustc_macro_transparency = "transparent"]
9+
macro_rules! k {
10+
($($s:tt)*) => {
11+
macro_rules! m {
12+
($y:tt) => {
13+
$($s)*
14+
}
15+
}
16+
}
17+
}
18+
19+
k!(1 + $y);
20+
21+
fn main() {
22+
let x = 2;
23+
assert_eq!(3, m!(x));
24+
}

0 commit comments

Comments
 (0)