Rollup merge of #69989 - petrochenkov:nolegacy, r=eddyb,matthewjasper

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
This commit is contained in:
Dylan DPC 2020-03-16 13:16:44 +01:00 committed by GitHub
commit 8872d90572
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 260 additions and 211 deletions

View File

@ -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
@ -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
}
@ -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)
}

View File

@ -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)]

View File

@ -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);
}

View File

@ -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);
@ -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 {
@ -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());

View File

@ -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>,
@ -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;
}
@ -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);

View File

@ -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);
}

View File

@ -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);

View File

@ -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;
@ -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)
}

View File

@ -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(
@ -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
@ -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;

View File

@ -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!(),
};
@ -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),
@ -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,
@ -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))

View File

@ -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,
}
}
@ -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,
}
}

View File

@ -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;
}

View File

@ -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?
@ -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)?; // `!`
@ -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.

View File

@ -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;
}

View File

@ -7,7 +7,7 @@
use crate::def_collector::collect_definitions;
use crate::imports::{Import, ImportKind};
use crate::macros::{LegacyBinding, LegacyScope};
use crate::macros::{MacroRulesBinding, MacroRulesScope};
use crate::Namespace::{self, MacroNS, TypeNS, ValueNS};
use crate::{CrateLint, Determinacy, PathResult, ResolutionError, VisResolutionError};
use crate::{
@ -165,11 +165,11 @@ impl<'a> Resolver<'a> {
&mut self,
fragment: &AstFragment,
parent_scope: ParentScope<'a>,
) -> LegacyScope<'a> {
) -> MacroRulesScope<'a> {
collect_definitions(&mut self.definitions, fragment, parent_scope.expansion);
let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
fragment.visit_with(&mut visitor);
visitor.parent_scope.legacy
visitor.parent_scope.macro_rules
}
crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
@ -624,7 +624,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
};
let used = self.process_legacy_macro_imports(item, module);
let used = self.process_macro_use_imports(item, module);
let binding =
(module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
let import = self.r.arenas.alloc_import(Import {
@ -645,7 +645,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.r.potentially_unused_imports.push(import);
let imported_binding = self.r.import(binding, import);
if ptr::eq(parent, self.r.graph_root) {
if let Some(entry) = self.r.extern_prelude.get(&ident.modern()) {
if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0())
{
if expansion != ExpnId::root()
&& orig_name.is_some()
&& entry.extern_crate_item.is_none()
@ -656,10 +657,12 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
}
}
let entry =
self.r.extern_prelude.entry(ident.modern()).or_insert(ExternPreludeEntry {
extern_crate_item: None,
introduced_by_item: true,
});
self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert(
ExternPreludeEntry {
extern_crate_item: None,
introduced_by_item: true,
},
);
entry.extern_crate_item = Some(imported_binding);
if orig_name.is_some() {
entry.introduced_by_item = true;
@ -913,7 +916,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
}
}
fn legacy_import_macro(
fn add_macro_use_binding(
&mut self,
name: ast::Name,
binding: &'a NameBinding<'a>,
@ -929,7 +932,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
}
/// Returns `true` if we should consider the underlying `extern crate` to be used.
fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool {
let mut import_all = None;
let mut single_imports = Vec::new();
for attr in &item.attrs {
@ -1004,7 +1007,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
module.for_each_child(self, |this, ident, ns, binding| {
if ns == MacroNS {
let imported_binding = this.r.import(binding, import);
this.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing);
}
});
} else {
@ -1021,7 +1024,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
let import = macro_use_import(self, ident.span);
self.r.potentially_unused_imports.push(import);
let imported_binding = self.r.import(binding, import);
self.legacy_import_macro(
self.add_macro_use_binding(
ident.name,
imported_binding,
ident.span,
@ -1060,7 +1063,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
false
}
fn visit_invoc(&mut self, id: NodeId) -> LegacyScope<'a> {
fn visit_invoc(&mut self, id: NodeId) -> MacroRulesScope<'a> {
let invoc_id = id.placeholder_to_expn_id();
self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id);
@ -1068,7 +1071,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
LegacyScope::Invocation(invoc_id)
MacroRulesScope::Invocation(invoc_id)
}
fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
@ -1095,20 +1098,20 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
}
}
fn define_macro(&mut self, item: &ast::Item) -> LegacyScope<'a> {
fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScope<'a> {
let parent_scope = self.parent_scope;
let expansion = parent_scope.expansion;
let (ext, ident, span, is_legacy) = match &item.kind {
let (ext, ident, span, macro_rules) = match &item.kind {
ItemKind::MacroDef(def) => {
let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition()));
(ext, item.ident, item.span, def.legacy)
(ext, item.ident, item.span, def.macro_rules)
}
ItemKind::Fn(..) => match Self::proc_macro_stub(item) {
Some((macro_kind, ident, span)) => {
self.r.proc_macro_stubs.insert(item.id);
(self.r.dummy_ext(macro_kind), ident, span, false)
}
None => return parent_scope.legacy,
None => return parent_scope.macro_rules,
},
_ => unreachable!(),
};
@ -1118,8 +1121,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.r.macro_map.insert(def_id, ext);
self.r.local_macro_def_scopes.insert(item.id, parent_scope.module);
if is_legacy {
let ident = ident.modern();
if macro_rules {
let ident = ident.normalize_to_macros_2_0();
self.r.macro_names.insert(ident);
let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export);
let vis = if is_macro_export {
@ -1137,8 +1140,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.r.check_reserved_macro_name(ident, res);
self.insert_unused_macro(ident, item.id, span);
}
LegacyScope::Binding(self.r.arenas.alloc_legacy_binding(LegacyBinding {
parent_legacy_scope: parent_scope.legacy,
MacroRulesScope::Binding(self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding {
parent_macro_rules_scope: parent_scope.macro_rules,
binding,
ident,
}))
@ -1149,7 +1152,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.insert_unused_macro(ident, item.id, span);
}
self.r.define(module, ident, MacroNS, (res, vis, span, expansion));
self.parent_scope.legacy
self.parent_scope.macro_rules
}
}
}
@ -1174,29 +1177,29 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
fn visit_item(&mut self, item: &'b Item) {
let macro_use = match item.kind {
ItemKind::MacroDef(..) => {
self.parent_scope.legacy = self.define_macro(item);
self.parent_scope.macro_rules = self.define_macro(item);
return;
}
ItemKind::MacCall(..) => {
self.parent_scope.legacy = self.visit_invoc(item.id);
self.parent_scope.macro_rules = self.visit_invoc(item.id);
return;
}
ItemKind::Mod(..) => self.contains_macro_use(&item.attrs),
_ => false,
};
let orig_current_module = self.parent_scope.module;
let orig_current_legacy_scope = self.parent_scope.legacy;
let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
self.build_reduced_graph_for_item(item);
visit::walk_item(self, item);
self.parent_scope.module = orig_current_module;
if !macro_use {
self.parent_scope.legacy = orig_current_legacy_scope;
self.parent_scope.macro_rules = orig_current_macro_rules_scope;
}
}
fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
if let ast::StmtKind::MacCall(..) = stmt.kind {
self.parent_scope.legacy = self.visit_invoc(stmt.id);
self.parent_scope.macro_rules = self.visit_invoc(stmt.id);
} else {
visit::walk_stmt(self, stmt);
}
@ -1214,11 +1217,11 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
fn visit_block(&mut self, block: &'b Block) {
let orig_current_module = self.parent_scope.module;
let orig_current_legacy_scope = self.parent_scope.legacy;
let orig_current_macro_rules_scope = self.parent_scope.macro_rules;
self.build_reduced_graph_for_block(block);
visit::walk_block(self, block);
self.parent_scope.module = orig_current_module;
self.parent_scope.legacy = orig_current_legacy_scope;
self.parent_scope.macro_rules = orig_current_macro_rules_scope;
}
fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) {

View File

@ -21,7 +21,9 @@ use rustc_span::{BytePos, MultiSpan, Span};
use crate::imports::{Import, ImportKind, ImportResolver};
use crate::path_names_to_string;
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
use crate::{
BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot,
};
use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment};
@ -498,12 +500,12 @@ impl<'a> Resolver<'a> {
}
}
}
Scope::MacroRules(legacy_scope) => {
if let LegacyScope::Binding(legacy_binding) = legacy_scope {
let res = legacy_binding.binding.res();
Scope::MacroRules(macro_rules_scope) => {
if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope {
let res = macro_rules_binding.binding.res();
if filter_fn(res) {
suggestions
.push(TypoSuggestion::from_res(legacy_binding.ident.name, res))
.push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res))
}
}
}
@ -756,7 +758,7 @@ impl<'a> Resolver<'a> {
let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
err.span_note(ident.span, &msg);
}
if self.macro_names.contains(&ident.modern()) {
if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
err.help("have you added the `#[macro_use]` on the module/import?");
}
}

View File

@ -416,7 +416,8 @@ impl<'a> Resolver<'a> {
None => return Err((Undetermined, Weak::Yes)),
};
let tmp_parent_scope;
let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern());
let (mut adjusted_parent_scope, mut ident) =
(parent_scope, ident.normalize_to_macros_2_0());
match ident.span.glob_adjust(module.expansion, glob_import.span) {
Some(Some(def)) => {
tmp_parent_scope =

View File

@ -935,7 +935,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
_ => unreachable!(),
};
let ident = param.ident.modern();
let ident = param.ident.normalize_to_macros_2_0();
debug!("with_generic_param_rib: {}", param.id);
if seen_bindings.contains_key(&ident) {
@ -1464,7 +1464,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
// Add the binding to the local ribs, if it doesn't already exist in the bindings map.
// (We must not add it if it's in the bindings map because that breaks the assumptions
// later passes make about or-patterns.)
let ident = ident.modern_and_legacy();
let ident = ident.normalize_to_macro_rules();
let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
// Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
@ -1873,7 +1873,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
}
self.with_label_rib(NormalRibKind, |this| {
let ident = label.ident.modern_and_legacy();
let ident = label.ident.normalize_to_macro_rules();
this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
f(this);
});
@ -1949,7 +1949,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
let node_id = self.search_label(label.ident, |rib, ident| {
rib.bindings.get(&ident.modern_and_legacy()).cloned()
rib.bindings.get(&ident.normalize_to_macro_rules()).cloned()
});
match node_id {
None => {
@ -2115,7 +2115,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
}
}
ident.span = ident.span.modern();
ident.span = ident.span.normalize_to_macros_2_0();
let mut search_module = self.parent_scope.module;
loop {
self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);

View File

@ -62,7 +62,7 @@ impl RegionExt for Region {
let def_id = hir_map.local_def_id(param.hir_id);
let origin = LifetimeDefOrigin::from_param(param);
debug!("Region::early: index={} def_id={:?}", i, def_id);
(param.name.modern(), Region::EarlyBound(i, def_id, origin))
(param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id, origin))
}
fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) {
@ -73,7 +73,7 @@ impl RegionExt for Region {
"Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
param, depth, def_id, origin,
);
(param.name.modern(), Region::LateBound(depth, def_id, origin))
(param.name.normalize_to_macros_2_0(), Region::LateBound(depth, def_id, origin))
}
fn late_anon(index: &Cell<u32>) -> Region {
@ -1174,7 +1174,9 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
Scope::Binder { ref lifetimes, s, .. } => {
// FIXME (#24278): non-hygienic comparison
if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
if let Some(def) =
lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
{
let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
signal_shadowing_problem(
@ -1253,7 +1255,7 @@ fn object_lifetime_defaults_for_item(
fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound<'_>]) {
for bound in bounds {
if let hir::GenericBound::Outlives(ref lifetime) = *bound {
set.insert(lifetime.name.modern());
set.insert(lifetime.name.normalize_to_macros_2_0());
}
}
}
@ -1791,7 +1793,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
Scope::Binder { ref lifetimes, s, .. } => {
match lifetime_ref.name {
LifetimeName::Param(param_name) => {
if let Some(&def) = lifetimes.get(&param_name.modern()) {
if let Some(&def) = lifetimes.get(&param_name.normalize_to_macros_2_0())
{
break Some(def.shifted(late_depth));
}
}
@ -2542,7 +2545,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
let lifetimes: Vec<_> = params
.iter()
.filter_map(|param| match param.kind {
GenericParamKind::Lifetime { .. } => Some((param, param.name.modern())),
GenericParamKind::Lifetime { .. } => {
Some((param, param.name.normalize_to_macros_2_0()))
}
_ => None,
})
.collect();
@ -2659,7 +2664,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
}
Scope::Binder { ref lifetimes, s, .. } => {
if let Some(&def) = lifetimes.get(&param.name.modern()) {
if let Some(&def) = lifetimes.get(&param.name.normalize_to_macros_2_0()) {
let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
signal_shadowing_problem(
@ -2797,7 +2802,7 @@ fn insert_late_bound_lifetimes(
// `'a: 'b` means both `'a` and `'b` are referenced
appears_in_where_clause
.regions
.insert(hir::LifetimeName::Param(param.name.modern()));
.insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()));
}
}
}
@ -2819,7 +2824,7 @@ fn insert_late_bound_lifetimes(
hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue,
}
let lt_name = hir::LifetimeName::Param(param.name.modern());
let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0());
// appears in the where clauses? early-bound.
if appears_in_where_clause.regions.contains(&lt_name) {
continue;
@ -2883,7 +2888,7 @@ fn insert_late_bound_lifetimes(
}
fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
self.regions.insert(lifetime_ref.name.modern());
self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
}
}
@ -2900,7 +2905,7 @@ fn insert_late_bound_lifetimes(
}
fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) {
self.regions.insert(lifetime_ref.name.modern());
self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0());
}
}
}

View File

@ -58,7 +58,7 @@ use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_ne
use diagnostics::{ImportSuggestion, Suggestion};
use imports::{Import, ImportKind, ImportResolver, NameResolution};
use late::{HasGenericParams, PathSource, Rib, RibKind::*};
use macros::{LegacyBinding, LegacyScope};
use macros::{MacroRulesBinding, MacroRulesScope};
type Res = def::Res<NodeId>;
@ -94,7 +94,7 @@ impl Determinacy {
enum Scope<'a> {
DeriveHelpers(ExpnId),
DeriveHelpersCompat,
MacroRules(LegacyScope<'a>),
MacroRules(MacroRulesScope<'a>),
CrateRoot,
Module(Module<'a>),
RegisteredAttrs,
@ -127,7 +127,7 @@ enum ScopeSet {
pub struct ParentScope<'a> {
module: Module<'a>,
expansion: ExpnId,
legacy: LegacyScope<'a>,
macro_rules: MacroRulesScope<'a>,
derives: &'a [ast::Path],
}
@ -135,7 +135,12 @@ impl<'a> ParentScope<'a> {
/// Creates a parent scope with the passed argument used as the module scope component,
/// and other scope components set to default empty values.
pub fn module(module: Module<'a>) -> ParentScope<'a> {
ParentScope { module, expansion: ExpnId::root(), legacy: LegacyScope::Empty, derives: &[] }
ParentScope {
module,
expansion: ExpnId::root(),
macro_rules: MacroRulesScope::Empty,
derives: &[],
}
}
}
@ -419,7 +424,7 @@ impl ModuleKind {
/// program) if all but one of them come from glob imports.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
struct BindingKey {
/// The identifier for the binding, aways the `modern` version of the
/// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the
/// identifier.
ident: Ident,
ns: Namespace,
@ -613,7 +618,7 @@ enum AmbiguityKind {
Import,
BuiltinAttr,
DeriveHelper,
LegacyVsModern,
MacroRulesVsModularized,
GlobVsOuter,
GlobVsGlob,
GlobVsExpanded,
@ -626,7 +631,9 @@ impl AmbiguityKind {
AmbiguityKind::Import => "name vs any other name during import resolution",
AmbiguityKind::BuiltinAttr => "built-in attribute vs any other name",
AmbiguityKind::DeriveHelper => "derive helper attribute vs any other name",
AmbiguityKind::LegacyVsModern => "`macro_rules` vs non-`macro_rules` from other module",
AmbiguityKind::MacroRulesVsModularized => {
"`macro_rules` vs non-`macro_rules` from other module"
}
AmbiguityKind::GlobVsOuter => {
"glob import vs any other name from outer scope during import/macro resolution"
}
@ -930,9 +937,9 @@ pub struct Resolver<'a> {
/// Parent scopes in which the macros were invoked.
/// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
invocation_parent_scopes: FxHashMap<ExpnId, ParentScope<'a>>,
/// Legacy scopes *produced* by expanding the macro invocations,
/// `macro_rules` scopes *produced* by expanding the macro invocations,
/// include all the `macro_rules` items and other invocations generated by them.
output_legacy_scopes: FxHashMap<ExpnId, LegacyScope<'a>>,
output_macro_rules_scopes: FxHashMap<ExpnId, MacroRulesScope<'a>>,
/// Helper attributes that are in scope for the given expansion.
helper_attrs: FxHashMap<ExpnId, Vec<Ident>>,
@ -965,7 +972,7 @@ pub struct ResolverArenas<'a> {
name_bindings: arena::TypedArena<NameBinding<'a>>,
imports: arena::TypedArena<Import<'a>>,
name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
macro_rules_bindings: arena::TypedArena<MacroRulesBinding<'a>>,
ast_paths: arena::TypedArena<ast::Path>,
}
@ -989,8 +996,11 @@ impl<'a> ResolverArenas<'a> {
fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
self.name_resolutions.alloc(Default::default())
}
fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
self.legacy_bindings.alloc(binding)
fn alloc_macro_rules_binding(
&'a self,
binding: MacroRulesBinding<'a>,
) -> &'a MacroRulesBinding<'a> {
self.macro_rules_bindings.alloc(binding)
}
fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
self.ast_paths.alloc_from_iter(paths.iter().cloned())
@ -1210,7 +1220,7 @@ impl<'a> Resolver<'a> {
dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
invocation_parent_scopes,
output_legacy_scopes: Default::default(),
output_macro_rules_scopes: Default::default(),
helper_attrs: Default::default(),
macro_defs,
local_macro_def_scopes: FxHashMap::default(),
@ -1352,7 +1362,7 @@ impl<'a> Resolver<'a> {
}
fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
let ident = ident.modern();
let ident = ident.normalize_to_macros_2_0();
let disambiguator = if ident.name == kw::Underscore {
self.underscore_disambiguator += 1;
self.underscore_disambiguator
@ -1403,7 +1413,7 @@ impl<'a> Resolver<'a> {
// Avoid marking `extern crate` items that refer to a name from extern prelude,
// but not introduce it, as used if they are accessed from lexical scope.
if is_lexical_scope {
if let Some(entry) = self.extern_prelude.get(&ident.modern()) {
if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
if let Some(crate_item) = entry.extern_crate_item {
if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
return;
@ -1465,7 +1475,7 @@ impl<'a> Resolver<'a> {
// derives (you need to resolve the derive first to add helpers into scope), but they
// should be available before the derive is expanded for compatibility.
// It's mess in general, so we are being conservative for now.
// 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
// 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher
// priority than prelude macros, but create ambiguities with macros in modules.
// 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
// (open, not controlled). Have higher priority than prelude macros, but create
@ -1490,7 +1500,7 @@ impl<'a> Resolver<'a> {
TypeNS | ValueNS => Scope::Module(module),
MacroNS => Scope::DeriveHelpers(parent_scope.expansion),
};
let mut ident = ident.modern();
let mut ident = ident.normalize_to_macros_2_0();
let mut use_prelude = !module.no_implicit_prelude;
loop {
@ -1530,16 +1540,18 @@ impl<'a> Resolver<'a> {
}
}
Scope::DeriveHelpers(..) => Scope::DeriveHelpersCompat,
Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.legacy),
Scope::MacroRules(legacy_scope) => match legacy_scope {
LegacyScope::Binding(binding) => Scope::MacroRules(binding.parent_legacy_scope),
LegacyScope::Invocation(invoc_id) => Scope::MacroRules(
self.output_legacy_scopes
Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules),
Scope::MacroRules(macro_rules_scope) => match macro_rules_scope {
MacroRulesScope::Binding(binding) => {
Scope::MacroRules(binding.parent_macro_rules_scope)
}
MacroRulesScope::Invocation(invoc_id) => Scope::MacroRules(
self.output_macro_rules_scopes
.get(&invoc_id)
.cloned()
.unwrap_or(self.invocation_parent_scopes[&invoc_id].legacy),
.unwrap_or(self.invocation_parent_scopes[&invoc_id].macro_rules),
),
LegacyScope::Empty => Scope::Module(module),
MacroRulesScope::Empty => Scope::Module(module),
},
Scope::CrateRoot => match ns {
TypeNS => {
@ -1610,18 +1622,18 @@ impl<'a> Resolver<'a> {
if ident.name == kw::Invalid {
return Some(LexicalScopeBinding::Res(Res::Err));
}
let (general_span, modern_span) = if ident.name == kw::SelfUpper {
let (general_span, normalized_span) = if ident.name == kw::SelfUpper {
// FIXME(jseyfried) improve `Self` hygiene
let empty_span = ident.span.with_ctxt(SyntaxContext::root());
(empty_span, empty_span)
} else if ns == TypeNS {
let modern_span = ident.span.modern();
(modern_span, modern_span)
let normalized_span = ident.span.normalize_to_macros_2_0();
(normalized_span, normalized_span)
} else {
(ident.span.modern_and_legacy(), ident.span.modern())
(ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0())
};
ident.span = general_span;
let modern_ident = Ident { span: modern_span, ..ident };
let normalized_ident = Ident { span: normalized_span, ..ident };
// Walk backwards up the ribs in scope.
let record_used = record_used_id.is_some();
@ -1629,8 +1641,8 @@ impl<'a> Resolver<'a> {
for i in (0..ribs.len()).rev() {
debug!("walk rib\n{:?}", ribs[i].bindings);
// Use the rib kind to determine whether we are resolving parameters
// (modern hygiene) or local variables (legacy hygiene).
let rib_ident = if ribs[i].kind.contains_params() { modern_ident } else { ident };
// (macro 2.0 hygiene) or local variables (`macro_rules` hygiene).
let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident };
if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() {
// The ident resolves to a type parameter or local variable.
return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs(
@ -1673,7 +1685,7 @@ impl<'a> Resolver<'a> {
}
}
ident = modern_ident;
ident = normalized_ident;
let mut poisoned = None;
loop {
let opt_module = if let Some(node_id) = record_used_id {
@ -1842,14 +1854,14 @@ impl<'a> Resolver<'a> {
let mut adjusted_parent_scope = parent_scope;
match module {
ModuleOrUniformRoot::Module(m) => {
if let Some(def) = ident.span.modernize_and_adjust(m.expansion) {
if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) {
tmp_parent_scope =
ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
adjusted_parent_scope = &tmp_parent_scope;
}
}
ModuleOrUniformRoot::ExternPrelude => {
ident.span.modernize_and_adjust(ExpnId::root());
ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root());
}
ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => {
// No adjustments
@ -1872,14 +1884,14 @@ impl<'a> Resolver<'a> {
let mark = if ident.name == kw::DollarCrate {
// When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
// we don't want to pretend that the `macro_rules!` definition is in the `macro`
// as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks.
// as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
// FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
// definitions actually produced by `macro` and `macro` definitions produced by
// `macro_rules!`, but at least such configurations are not stable yet.
ctxt = ctxt.modern_and_legacy();
ctxt = ctxt.normalize_to_macro_rules();
let mut iter = ctxt.marks().into_iter().rev().peekable();
let mut result = None;
// Find the last modern mark from the end if it exists.
// Find the last opaque mark from the end if it exists.
while let Some(&(mark, transparency)) = iter.peek() {
if transparency == Transparency::Opaque {
result = Some(mark);
@ -1888,7 +1900,7 @@ impl<'a> Resolver<'a> {
break;
}
}
// Then find the last legacy mark from the end if it exists.
// Then find the last semi-transparent mark from the end if it exists.
for (mark, transparency) in iter {
if transparency == Transparency::SemiTransparent {
result = Some(mark);
@ -1898,7 +1910,7 @@ impl<'a> Resolver<'a> {
}
result
} else {
ctxt = ctxt.modern();
ctxt = ctxt.normalize_to_macros_2_0();
ctxt.adjust(ExpnId::root())
};
let module = match mark {
@ -1910,7 +1922,7 @@ impl<'a> Resolver<'a> {
fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
let mut module = self.get_module(module.normal_ancestor_id);
while module.span.ctxt().modern() != *ctxt {
while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark()));
module = self.get_module(parent.normal_ancestor_id);
}
@ -1978,7 +1990,7 @@ impl<'a> Resolver<'a> {
if ns == TypeNS {
if allow_super && name == kw::Super {
let mut ctxt = ident.span.ctxt().modern();
let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
let self_module = match i {
0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)),
_ => match module {
@ -2004,7 +2016,7 @@ impl<'a> Resolver<'a> {
}
if i == 0 {
if name == kw::SelfLower {
let mut ctxt = ident.span.ctxt().modern();
let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0();
module = Some(ModuleOrUniformRoot::Module(
self.resolve_self(&mut ctxt, parent_scope.module),
));
@ -2413,21 +2425,21 @@ impl<'a> Resolver<'a> {
}
}
fn disambiguate_legacy_vs_modern(
fn disambiguate_macro_rules_vs_modularized(
&self,
legacy: &'a NameBinding<'a>,
modern: &'a NameBinding<'a>,
macro_rules: &'a NameBinding<'a>,
modularized: &'a NameBinding<'a>,
) -> bool {
// Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules"
// Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
// is disambiguated to mitigate regressions from macro modularization.
// Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
match (
self.binding_parent_modules.get(&PtrKey(legacy)),
self.binding_parent_modules.get(&PtrKey(modern)),
self.binding_parent_modules.get(&PtrKey(macro_rules)),
self.binding_parent_modules.get(&PtrKey(modularized)),
) {
(Some(legacy), Some(modern)) => {
legacy.normal_ancestor_id == modern.normal_ancestor_id
&& modern.is_ancestor_of(legacy)
(Some(macro_rules), Some(modularized)) => {
macro_rules.normal_ancestor_id == modularized.normal_ancestor_id
&& modularized.is_ancestor_of(macro_rules)
}
_ => false,
}
@ -2757,7 +2769,7 @@ impl<'a> Resolver<'a> {
// Make sure `self`, `super` etc produce an error when passed to here.
return None;
}
self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| {
self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
if let Some(binding) = entry.extern_crate_item {
if !speculative && entry.introduced_by_item {
self.record_use(ident, TypeNS, binding, false);

View File

@ -33,26 +33,26 @@ use std::{mem, ptr};
type Res = def::Res<NodeId>;
/// Binding produced by a `macro_rules` item.
/// Not modularized, can shadow previous legacy bindings, etc.
/// Not modularized, can shadow previous `macro_rules` bindings, etc.
#[derive(Debug)]
pub struct LegacyBinding<'a> {
pub struct MacroRulesBinding<'a> {
crate binding: &'a NameBinding<'a>,
/// Legacy scope into which the `macro_rules` item was planted.
crate parent_legacy_scope: LegacyScope<'a>,
/// `macro_rules` scope into which the `macro_rules` item was planted.
crate parent_macro_rules_scope: MacroRulesScope<'a>,
crate ident: Ident,
}
/// The scope introduced by a `macro_rules!` macro.
/// This starts at the macro's definition and ends at the end of the macro's parent
/// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
/// Some macro invocations need to introduce legacy scopes too because they
/// Some macro invocations need to introduce `macro_rules` scopes too because they
/// can potentially expand into macro definitions.
#[derive(Copy, Clone, Debug)]
pub enum LegacyScope<'a> {
pub enum MacroRulesScope<'a> {
/// Empty "root" scope at the crate start containing no names.
Empty,
/// The scope introduced by a `macro_rules!` macro definition.
Binding(&'a LegacyBinding<'a>),
Binding(&'a MacroRulesBinding<'a>),
/// The scope introduced by a macro invocation that can potentially
/// create a `macro_rules!` macro definition.
Invocation(ExpnId),
@ -159,8 +159,8 @@ impl<'a> base::Resolver for Resolver<'a> {
// Integrate the new AST fragment into all the definition and module structures.
// We are inside the `expansion` now, but other parent scope components are still the same.
let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
let output_legacy_scope = self.build_reduced_graph(fragment, parent_scope);
self.output_legacy_scopes.insert(expansion, output_legacy_scope);
let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
}
@ -258,7 +258,13 @@ impl<'a> base::Resolver for Resolver<'a> {
force,
) {
Ok((Some(ext), _)) => {
let span = path.segments.last().unwrap().ident.span.modern();
let span = path
.segments
.last()
.unwrap()
.ident
.span
.normalize_to_macros_2_0();
helper_attrs.extend(
ext.helper_attrs.iter().map(|name| Ident::new(*name, span)),
);
@ -608,12 +614,14 @@ impl<'a> Resolver<'a> {
}
result
}
Scope::MacroRules(legacy_scope) => match legacy_scope {
LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident => {
Ok((legacy_binding.binding, Flags::MACRO_RULES))
Scope::MacroRules(macro_rules_scope) => match macro_rules_scope {
MacroRulesScope::Binding(macro_rules_binding)
if ident == macro_rules_binding.ident =>
{
Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
}
LegacyScope::Invocation(invoc_id)
if !this.output_legacy_scopes.contains_key(&invoc_id) =>
MacroRulesScope::Invocation(invoc_id)
if !this.output_macro_rules_scopes.contains_key(&invoc_id) =>
{
Err(Determinacy::Undetermined)
}
@ -759,16 +767,18 @@ impl<'a> Resolver<'a> {
Some(AmbiguityKind::DeriveHelper)
} else if innermost_flags.contains(Flags::MACRO_RULES)
&& flags.contains(Flags::MODULE)
&& !this
.disambiguate_legacy_vs_modern(innermost_binding, binding)
&& !this.disambiguate_macro_rules_vs_modularized(
innermost_binding,
binding,
)
|| flags.contains(Flags::MACRO_RULES)
&& innermost_flags.contains(Flags::MODULE)
&& !this.disambiguate_legacy_vs_modern(
&& !this.disambiguate_macro_rules_vs_modularized(
binding,
innermost_binding,
)
{
Some(AmbiguityKind::LegacyVsModern)
Some(AmbiguityKind::MacroRulesVsModularized)
} else if innermost_binding.is_glob_import() {
Some(AmbiguityKind::GlobVsOuter)
} else if innermost_binding

View File

@ -201,11 +201,11 @@ impl HygieneData {
true
}
fn modern(&self, ctxt: SyntaxContext) -> SyntaxContext {
fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
self.syntax_context_data[ctxt.0 as usize].opaque
}
fn modern_and_legacy(&self, ctxt: SyntaxContext) -> SyntaxContext {
fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
}
@ -266,9 +266,9 @@ impl HygieneData {
let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
self.modern(call_site_ctxt)
self.normalize_to_macros_2_0(call_site_ctxt)
} else {
self.modern_and_legacy(call_site_ctxt)
self.normalize_to_macro_rules(call_site_ctxt)
};
if call_site_ctxt == SyntaxContext::root() {
@ -491,10 +491,10 @@ impl SyntaxContext {
HygieneData::with(|data| data.adjust(self, expn_id))
}
/// Like `SyntaxContext::adjust`, but also modernizes `self`.
pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
/// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
HygieneData::with(|data| {
*self = data.modern(*self);
*self = data.normalize_to_macros_2_0(*self);
data.adjust(self, expn_id)
})
}
@ -527,7 +527,7 @@ impl SyntaxContext {
pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
HygieneData::with(|data| {
let mut scope = None;
let mut glob_ctxt = data.modern(glob_span.ctxt());
let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
scope = Some(data.remove_mark(&mut glob_ctxt).0);
if data.remove_mark(self).0 != scope.unwrap() {
@ -558,7 +558,7 @@ impl SyntaxContext {
return None;
}
let mut glob_ctxt = data.modern(glob_span.ctxt());
let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
let mut marks = Vec::new();
while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
marks.push(data.remove_mark(&mut glob_ctxt));
@ -574,20 +574,20 @@ impl SyntaxContext {
pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
HygieneData::with(|data| {
let mut self_modern = data.modern(self);
data.adjust(&mut self_modern, expn_id);
self_modern == data.modern(other)
let mut self_normalized = data.normalize_to_macros_2_0(self);
data.adjust(&mut self_normalized, expn_id);
self_normalized == data.normalize_to_macros_2_0(other)
})
}
#[inline]
pub fn modern(self) -> SyntaxContext {
HygieneData::with(|data| data.modern(self))
pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
HygieneData::with(|data| data.normalize_to_macros_2_0(self))
}
#[inline]
pub fn modern_and_legacy(self) -> SyntaxContext {
HygieneData::with(|data| data.modern_and_legacy(self))
pub fn normalize_to_macro_rules(self) -> SyntaxContext {
HygieneData::with(|data| data.normalize_to_macro_rules(self))
}
#[inline]

View File

@ -548,9 +548,9 @@ impl Span {
}
#[inline]
pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
let mut span = self.data();
let mark = span.ctxt.modernize_and_adjust(expn_id);
let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
*self = Span::new(span.lo, span.hi, span.ctxt);
mark
}
@ -576,15 +576,15 @@ impl Span {
}
#[inline]
pub fn modern(self) -> Span {
pub fn normalize_to_macros_2_0(self) -> Span {
let span = self.data();
span.with_ctxt(span.ctxt.modern())
span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
}
#[inline]
pub fn modern_and_legacy(self) -> Span {
pub fn normalize_to_macro_rules(self) -> Span {
let span = self.data();
span.with_ctxt(span.ctxt.modern_and_legacy())
span.with_ctxt(span.ctxt.normalize_to_macro_rules())
}
}

View File

@ -853,12 +853,12 @@ impl Ident {
}
/// "Normalize" ident for use in comparisons using "item hygiene".
/// Identifiers with same string value become same if they came from the same "modern" macro
/// Identifiers with same string value become same if they came from the same macro 2.0 macro
/// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from
/// different "modern" macros.
/// different macro 2.0 macros.
/// Technically, this operation strips all non-opaque marks from ident's syntactic context.
pub fn modern(self) -> Ident {
Ident::new(self.name, self.span.modern())
pub fn normalize_to_macros_2_0(self) -> Ident {
Ident::new(self.name, self.span.normalize_to_macros_2_0())
}
/// "Normalize" ident for use in comparisons using "local variable hygiene".
@ -866,8 +866,8 @@ impl Ident {
/// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different
/// non-transparent macros.
/// Technically, this operation strips all transparent marks from ident's syntactic context.
pub fn modern_and_legacy(self) -> Ident {
Ident::new(self.name, self.span.modern_and_legacy())
pub fn normalize_to_macro_rules(self) -> Ident {
Ident::new(self.name, self.span.normalize_to_macro_rules())
}
/// Convert the name to a `SymbolStr`. This is a slowish operation because

View File

@ -1441,12 +1441,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let (assoc_ident, def_scope) =
tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
// We have already adjusted the item name above, so compare with `ident.modern()` instead
// We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
// of calling `filter_by_name_and_kind`.
let assoc_ty = tcx
.associated_items(candidate.def_id())
.filter_by_name_unhygienic(assoc_ident.name)
.find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
.find(|i| {
i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
})
.expect("missing associated type");
if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
@ -2298,12 +2300,15 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let (assoc_ident, def_scope) =
tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
// We have already adjusted the item name above, so compare with `ident.modern()` instead
// We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
// of calling `filter_by_name_and_kind`.
let item = tcx
.associated_items(trait_did)
.in_definition_order()
.find(|i| i.kind.namespace() == Namespace::TypeNS && i.ident.modern() == assoc_ident)
.find(|i| {
i.kind.namespace() == Namespace::TypeNS
&& i.ident.normalize_to_macros_2_0() == assoc_ident
})
.expect("missing associated type");
let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);

View File

@ -1203,7 +1203,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.fields
.iter()
.enumerate()
.map(|(i, field)| (field.ident.modern(), (i, field)))
.map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
.collect::<FxHashMap<_, _>>();
let mut seen_fields = FxHashMap::default();
@ -1469,7 +1469,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let (ident, def_scope) =
self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
let fields = &base_def.non_enum_variant().fields;
if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
if let Some(index) =
fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident)
{
let field = &fields[index];
let field_ty = self.field_ty(expr.span, field, substs);
// Save the index of all fields regardless of their visibility in case

View File

@ -1023,7 +1023,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.fields
.iter()
.enumerate()
.map(|(i, field)| (field.ident.modern(), (i, field)))
.map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field)))
.collect::<FxHashMap<_, _>>();
// Keep track of which fields have already appeared in the pattern.
@ -1064,7 +1064,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut unmentioned_fields = variant
.fields
.iter()
.map(|field| field.ident.modern())
.map(|field| field.ident.normalize_to_macros_2_0())
.filter(|ident| !used_fields.contains_key(&ident))
.collect::<Vec<_>>();

View File

@ -26,7 +26,8 @@ impl InherentOverlapChecker<'tcx> {
let collision = impl_items2.filter_by_name_unhygienic(item1.ident.name).any(|item2| {
// Symbols and namespace match, compare hygienically.
item1.kind.namespace() == item2.kind.namespace()
&& item1.ident.modern() == item2.ident.modern()
&& item1.ident.normalize_to_macros_2_0()
== item2.ident.normalize_to_macros_2_0()
});
if collision {
@ -50,11 +51,12 @@ impl InherentOverlapChecker<'tcx> {
let collision = impl_items2.filter_by_name_unhygienic(item1.ident.name).find(|item2| {
// Symbols and namespace match, compare hygienically.
item1.kind.namespace() == item2.kind.namespace()
&& item1.ident.modern() == item2.ident.modern()
&& item1.ident.normalize_to_macros_2_0()
== item2.ident.normalize_to_macros_2_0()
});
if let Some(item2) = collision {
let name = item1.ident.modern();
let name = item1.ident.normalize_to_macros_2_0();
let mut err = struct_span_err!(
self.tcx.sess,
self.tcx.span_of_impl(item1.def_id).unwrap(),

View File

@ -828,7 +828,7 @@ fn convert_variant(
.iter()
.map(|f| {
let fid = tcx.hir().local_def_id(f.hir_id);
let dup_span = seen_fields.get(&f.ident.modern()).cloned();
let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
if let Some(prev_span) = dup_span {
struct_span_err!(
tcx.sess,
@ -841,7 +841,7 @@ fn convert_variant(
.span_label(prev_span, format!("`{}` first declared here", f.ident))
.emit();
} else {
seen_fields.insert(f.ident.modern(), f.span);
seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
}
ty::FieldDef {

View File

@ -227,7 +227,7 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI
hir::ImplItemKind::TyAlias(_) => &mut seen_type_items,
_ => &mut seen_value_items,
};
match seen_items.entry(impl_item.ident.modern()) {
match seen_items.entry(impl_item.ident.normalize_to_macros_2_0()) {
Occupied(entry) => {
let mut err = struct_span_err!(
tcx.sess,