Skip to content

Commit

Permalink
Rollup merge of #69989 - petrochenkov:nolegacy, r=eddyb,matthewjasper
Browse files Browse the repository at this point in the history
resolve/hygiene: `macro_rules` are not "legacy"

The "modern" vs "legacy" naming was introduced by jseyfried during initial implementation of macros 2.0.
At this point it's clear that `macro_rules` are not going anywhere and won't be deprecated in the near future.
So this PR changes the naming "legacy" (when it implies "macro_rules") to "macro_rules".
This should also help people reading this code because it's wasn't obvious that "legacy" actually meant "macro_rules" in these contexts.

The most contentious renaming here is probably
```
fn modern -> fn normalize_to_macros_2_0
fn modern_and_legacy -> fn normalize_to_macro_rules
```
Other alternatives that I could think of are `normalize_to_opaque`/`normalize_to_semitransparent`, or `strip_non_opaque`/`strip_transparent`, but they seemed less intuitive.
The documentation to these functions can be found in `symbol.rs`.

r? @matthewjasper
  • Loading branch information
Dylan-DPC authored Mar 16, 2020
2 parents 8f2482b + db638bd commit 8872d90
Show file tree
Hide file tree
Showing 30 changed files with 260 additions and 211 deletions.
18 changes: 10 additions & 8 deletions src/librustc/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3083,7 +3083,7 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool {
// We could use `Ident::eq` here, but we deliberately don't. The name
// comparison fails frequently, and we want to avoid the expensive
// `modern()` calls required for the span comparison whenever possible.
// `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
use_name.name == def_name.name
&& use_name
.span
Expand All @@ -3099,7 +3099,7 @@ impl<'tcx> TyCtxt<'tcx> {
}

pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
ident.span.modernize_and_adjust(self.expansion_that_defined(scope));
ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope));
ident
}

Expand All @@ -3109,12 +3109,14 @@ impl<'tcx> TyCtxt<'tcx> {
scope: DefId,
block: hir::HirId,
) -> (Ident, DefId) {
let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) {
Some(actual_expansion) => {
self.hir().definitions().parent_module_of_macro_def(actual_expansion)
}
None => self.parent_module(block),
};
let scope =
match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope))
{
Some(actual_expansion) => {
self.hir().definitions().parent_module_of_macro_def(actual_expansion)
}
None => self.parent_module(block),
};
(ident, scope)
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc_ast/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1450,7 +1450,7 @@ impl MacDelimiter {
pub struct MacroDef {
pub body: P<MacArgs>,
/// `true` if macro was defined with `macro_rules`.
pub legacy: bool,
pub macro_rules: bool,
}

#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_ast/mut_visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ pub fn noop_visit_mac<T: MutVisitor>(mac: &mut MacCall, vis: &mut T) {
}

pub fn noop_visit_macro_def<T: MutVisitor>(macro_def: &mut MacroDef, vis: &mut T) {
let MacroDef { body, legacy: _ } = macro_def;
let MacroDef { body, macro_rules: _ } = macro_def;
visit_mac_args(body, vis);
}

Expand Down
8 changes: 4 additions & 4 deletions src/librustc_ast_lowering/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
_ => &[],
};
let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind {
hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()),
hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()),
_ => None,
});
self.in_scope_lifetimes.extend(lt_def_names);
Expand Down Expand Up @@ -220,8 +220,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
let mut vis = self.lower_visibility(&i.vis, None);
let attrs = self.lower_attrs(&i.attrs);

if let ItemKind::MacroDef(MacroDef { ref body, legacy }) = i.kind {
if !legacy || attr::contains_name(&i.attrs, sym::macro_export) {
if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind {
if !macro_rules || attr::contains_name(&i.attrs, sym::macro_export) {
let hir_id = self.lower_node_id(i.id);
let body = P(self.lower_mac_args(body));
self.exported_macros.push(hir::MacroDef {
Expand All @@ -230,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
attrs,
hir_id,
span: i.span,
ast: MacroDef { body, legacy },
ast: MacroDef { body, macro_rules },
});
} else {
self.non_exported_macro_attrs.extend(attrs.iter().cloned());
Expand Down
13 changes: 8 additions & 5 deletions src/librustc_ast_lowering/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ struct LoweringContext<'a, 'hir: 'a> {
/// against this list to see if it is already in-scope, or if a definition
/// needs to be created for it.
///
/// We always store a `modern()` version of the param-name in this
/// We always store a `normalize_to_macros_2_0()` version of the param-name in this
/// vector.
in_scope_lifetimes: Vec<ParamName>,

Expand Down Expand Up @@ -803,14 +803,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
return;
}

if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) {
if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) {
return;
}

let hir_name = ParamName::Plain(ident);

if self.lifetimes_to_define.iter().any(|(_, lt_name)| lt_name.modern() == hir_name.modern())
{
if self.lifetimes_to_define.iter().any(|(_, lt_name)| {
lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0()
}) {
return;
}

Expand Down Expand Up @@ -838,7 +839,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
) -> T {
let old_len = self.in_scope_lifetimes.len();
let lt_def_names = params.iter().filter_map(|param| match param.kind {
GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())),
GenericParamKind::Lifetime { .. } => {
Some(ParamName::Plain(param.ident.normalize_to_macros_2_0()))
}
_ => None,
});
self.in_scope_lifetimes.extend(lt_def_names);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_ast_passes/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
}

ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => {
ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
let msg = "`macro` is experimental";
gate_feature_post!(&self, decl_macro, i.span, msg);
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_ast_pretty/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1238,7 +1238,7 @@ impl<'a> State<'a> {
}
}
ast::ItemKind::MacroDef(ref macro_def) => {
let (kw, has_bang) = if macro_def.legacy {
let (kw, has_bang) = if macro_def.macro_rules {
("macro_rules", true)
} else {
self.print_visibility(&item.vis);
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_attr/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,7 @@ pub enum TransparencyError {

pub fn find_transparency(
attrs: &[Attribute],
is_legacy: bool,
macro_rules: bool,
) -> (Transparency, Option<TransparencyError>) {
let mut transparency = None;
let mut error = None;
Expand All @@ -1049,7 +1049,7 @@ pub fn find_transparency(
}
}
}
let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque };
let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque };
(transparency.map_or(fallback, |t| t.0), error)
}

Expand Down
12 changes: 6 additions & 6 deletions src/librustc_expand/mbe/macro_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,10 +419,10 @@ fn check_nested_occurrences(
| (NestedMacroState::MacroName, &TokenTree::Delimited(_, ref del))
if del.delim == DelimToken::Brace =>
{
let legacy = state == NestedMacroState::MacroRulesNotName;
let macro_rules = state == NestedMacroState::MacroRulesNotName;
state = NestedMacroState::Empty;
let rest =
check_nested_macro(sess, node_id, legacy, &del.tts, &nested_macros, valid);
check_nested_macro(sess, node_id, macro_rules, &del.tts, &nested_macros, valid);
// If we did not check the whole macro definition, then check the rest as if outside
// the macro definition.
check_nested_occurrences(
Expand Down Expand Up @@ -493,21 +493,21 @@ fn check_nested_occurrences(
/// Arguments:
/// - `sess` is used to emit diagnostics and lints
/// - `node_id` is used to emit lints
/// - `legacy` specifies whether the macro is legacy
/// - `macro_rules` specifies whether the macro is `macro_rules`
/// - `tts` is checked as a list of (LHS) => {RHS}
/// - `macros` is the stack of outer macros
/// - `valid` is set in case of errors
fn check_nested_macro(
sess: &ParseSess,
node_id: NodeId,
legacy: bool,
macro_rules: bool,
tts: &[TokenTree],
macros: &Stack<'_, MacroState<'_>>,
valid: &mut bool,
) -> usize {
let n = tts.len();
let mut i = 0;
let separator = if legacy { TokenKind::Semi } else { TokenKind::Comma };
let separator = if macro_rules { TokenKind::Semi } else { TokenKind::Comma };
loop {
// We expect 3 token trees: `(LHS) => {RHS}`. The separator is checked after.
if i + 2 >= n
Expand All @@ -522,7 +522,7 @@ fn check_nested_macro(
let mut binders = Binders::default();
check_binders(sess, node_id, lhs, macros, &mut binders, &Stack::Empty, valid);
check_occurrences(sess, node_id, rhs, macros, &binders, &Stack::Empty, valid);
// Since the last semicolon is optional for legacy macros and decl_macro are not terminated,
// Since the last semicolon is optional for `macro_rules` macros and decl_macro are not terminated,
// we increment our checked position by how many token trees we already checked (the 3
// above) before checking for the separator.
i += 3;
Expand Down
10 changes: 5 additions & 5 deletions src/librustc_expand/mbe/macro_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,8 +350,8 @@ pub fn compile_declarative_macro(
let tt_spec = ast::Ident::new(sym::tt, def.span);

// Parse the macro_rules! invocation
let (is_legacy, body) = match &def.kind {
ast::ItemKind::MacroDef(macro_def) => (macro_def.legacy, macro_def.body.inner_tokens()),
let (macro_rules, body) = match &def.kind {
ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()),
_ => unreachable!(),
};

Expand All @@ -370,7 +370,7 @@ pub fn compile_declarative_macro(
mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
],
separator: Some(Token::new(
if is_legacy { token::Semi } else { token::Comma },
if macro_rules { token::Semi } else { token::Comma },
def.span,
)),
kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
Expand All @@ -382,7 +382,7 @@ pub fn compile_declarative_macro(
DelimSpan::dummy(),
Lrc::new(mbe::SequenceRepetition {
tts: vec![mbe::TokenTree::token(
if is_legacy { token::Semi } else { token::Comma },
if macro_rules { token::Semi } else { token::Comma },
def.span,
)],
separator: None,
Expand Down Expand Up @@ -456,7 +456,7 @@ pub fn compile_declarative_macro(
// that is not lint-checked and trigger the "failed to process buffered lint here" bug.
valid &= macro_check::check_meta_variables(sess, ast::CRATE_NODE_ID, def.span, &lhses, &rhses);

let (transparency, transparency_error) = attr::find_transparency(&def.attrs, is_legacy);
let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
match transparency_error {
Some(TransparencyError::UnknownTransparency(value, span)) => {
diag.span_err(span, &format!("unknown macro transparency: `{}`", value))
Expand Down
10 changes: 6 additions & 4 deletions src/librustc_hir/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ impl ParamName {
}
}

pub fn modern(&self) -> ParamName {
pub fn normalize_to_macros_2_0(&self) -> ParamName {
match *self {
ParamName::Plain(ident) => ParamName::Plain(ident.modern()),
ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
param_name => param_name,
}
}
Expand Down Expand Up @@ -151,9 +151,11 @@ impl LifetimeName {
self == &LifetimeName::Static
}

pub fn modern(&self) -> LifetimeName {
pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
match *self {
LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()),
LifetimeName::Param(param_name) => {
LifetimeName::Param(param_name.normalize_to_macros_2_0())
}
lifetime_name => lifetime_name,
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_mir/monomorphize/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,9 +1088,9 @@ fn create_mono_items_for_default_impls<'tcx>(
let param_env = ty::ParamEnv::reveal_all();
let trait_ref = tcx.normalize_erasing_regions(param_env, trait_ref);
let overridden_methods: FxHashSet<_> =
items.iter().map(|iiref| iiref.ident.modern()).collect();
items.iter().map(|iiref| iiref.ident.normalize_to_macros_2_0()).collect();
for method in tcx.provided_trait_methods(trait_ref.def_id) {
if overridden_methods.contains(&method.ident.modern()) {
if overridden_methods.contains(&method.ident.normalize_to_macros_2_0()) {
continue;
}

Expand Down
6 changes: 3 additions & 3 deletions src/librustc_parse/parser/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,7 @@ impl<'a> Parser<'a> {
};

self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span));
Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false })))
Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false })))
}

/// Is this unambiguously the start of a `macro_rules! foo` item defnition?
Expand All @@ -1270,7 +1270,7 @@ impl<'a> Parser<'a> {
&& self.look_ahead(2, |t| t.is_ident())
}

/// Parses a legacy `macro_rules! foo { ... }` declarative macro.
/// Parses a `macro_rules! foo { ... }` declarative macro.
fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> {
self.expect_keyword(kw::MacroRules)?; // `macro_rules`
self.expect(&token::Not)?; // `!`
Expand All @@ -1280,7 +1280,7 @@ impl<'a> Parser<'a> {
self.eat_semi_for_macro_if_needed(&body);
self.complain_if_pub_macro(vis, true);

Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true })))
Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true })))
}

/// Item macro invocations or `macro_rules!` definitions need inherited visibility.
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_privacy/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -920,7 +920,7 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> {
}

fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
if attr::find_transparency(&md.attrs, md.ast.legacy).0 != Transparency::Opaque {
if attr::find_transparency(&md.attrs, md.ast.macro_rules).0 != Transparency::Opaque {
self.update(md.hir_id, Some(AccessLevel::Public));
return;
}
Expand Down
Loading

0 comments on commit 8872d90

Please sign in to comment.