diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /compiler/rustc_resolve | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_resolve')
-rw-r--r-- | compiler/rustc_resolve/Cargo.toml | 27 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/access_levels.rs | 237 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/build_reduced_graph.rs | 1546 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/check_unused.rs | 350 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/def_collector.rs | 354 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/diagnostics.rs | 2714 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/diagnostics/tests.rs | 40 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/ident.rs | 1556 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/imports.rs | 1151 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/late.rs | 3984 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/late/diagnostics.rs | 2369 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/late/lifetimes.rs | 2144 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/lib.rs | 2089 | ||||
-rw-r--r-- | compiler/rustc_resolve/src/macros.rs | 921 |
14 files changed, 19482 insertions, 0 deletions
diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml new file mode 100644 index 000000000..5d2b606b4 --- /dev/null +++ b/compiler/rustc_resolve/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "rustc_resolve" +version = "0.0.0" +edition = "2021" + +[lib] +doctest = false + +[dependencies] +bitflags = "1.2.1" +tracing = "0.1" +rustc_ast = { path = "../rustc_ast" } +rustc_arena = { path = "../rustc_arena" } +rustc_middle = { path = "../rustc_middle" } +rustc_ast_pretty = { path = "../rustc_ast_pretty" } +rustc_attr = { path = "../rustc_attr" } +rustc_data_structures = { path = "../rustc_data_structures" } +rustc_errors = { path = "../rustc_errors" } +rustc_expand = { path = "../rustc_expand" } +rustc_feature = { path = "../rustc_feature" } +rustc_hir = { path = "../rustc_hir" } +rustc_index = { path = "../rustc_index" } +rustc_metadata = { path = "../rustc_metadata" } +rustc_query_system = { path = "../rustc_query_system" } +rustc_session = { path = "../rustc_session" } +rustc_span = { path = "../rustc_span" } +smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } diff --git a/compiler/rustc_resolve/src/access_levels.rs b/compiler/rustc_resolve/src/access_levels.rs new file mode 100644 index 000000000..3fba923d9 --- /dev/null +++ b/compiler/rustc_resolve/src/access_levels.rs @@ -0,0 +1,237 @@ +use rustc_ast::ast; +use rustc_ast::visit; +use rustc_ast::visit::Visitor; +use rustc_ast::Crate; +use rustc_ast::EnumDef; +use rustc_ast::ForeignMod; +use rustc_ast::NodeId; +use rustc_hir::def_id::LocalDefId; +use rustc_hir::def_id::CRATE_DEF_ID; +use rustc_middle::middle::privacy::AccessLevel; +use rustc_middle::ty::Visibility; +use rustc_span::sym; + +use crate::imports::ImportKind; +use crate::BindingKey; +use crate::NameBinding; +use crate::NameBindingKind; +use crate::Resolver; + +pub struct AccessLevelsVisitor<'r, 'a> { + r: &'r mut Resolver<'a>, + prev_level: Option<AccessLevel>, + changed: bool, +} + +impl<'r, 'a> AccessLevelsVisitor<'r, 'a> { + /// Fills the `Resolver::access_levels` table with public & exported items + /// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we + /// need access to a TyCtxt for that. + pub fn compute_access_levels<'c>(r: &'r mut Resolver<'a>, krate: &'c Crate) { + let mut visitor = + AccessLevelsVisitor { r, changed: false, prev_level: Some(AccessLevel::Public) }; + + visitor.set_access_level_def_id(CRATE_DEF_ID, Some(AccessLevel::Public)); + visitor.set_exports_access_level(CRATE_DEF_ID); + + while visitor.changed { + visitor.reset(); + visit::walk_crate(&mut visitor, krate); + } + + tracing::info!("resolve::access_levels: {:#?}", r.access_levels); + } + + fn reset(&mut self) { + self.changed = false; + self.prev_level = Some(AccessLevel::Public); + } + + /// Update the access level of the exports of the given module accordingly. The module access + /// level has to be Exported or Public. + /// This will also follow `use` chains (see PrivacyVisitor::set_import_binding_access_level). + fn set_exports_access_level(&mut self, module_id: LocalDefId) { + assert!(self.r.module_map.contains_key(&&module_id.to_def_id())); + + // Set the given binding access level to `AccessLevel::Public` and + // sets the rest of the `use` chain to `AccessLevel::Exported` until + // we hit the actual exported item. + let set_import_binding_access_level = + |this: &mut Self, mut binding: &NameBinding<'a>, mut access_level| { + while let NameBindingKind::Import { binding: nested_binding, import, .. } = + binding.kind + { + this.set_access_level(import.id, access_level); + if let ImportKind::Single { additional_ids, .. } = import.kind { + this.set_access_level(additional_ids.0, access_level); + this.set_access_level(additional_ids.1, access_level); + } + + access_level = Some(AccessLevel::Exported); + binding = nested_binding; + } + }; + + let module_level = self.r.access_levels.map.get(&module_id).copied(); + assert!(module_level >= Some(AccessLevel::Exported)); + + if let Some(exports) = self.r.reexport_map.get(&module_id) { + let pub_exports = exports + .iter() + .filter(|ex| ex.vis == Visibility::Public) + .cloned() + .collect::<Vec<_>>(); + + let module = self.r.get_module(module_id.to_def_id()).unwrap(); + for export in pub_exports.into_iter() { + if let Some(export_def_id) = export.res.opt_def_id().and_then(|id| id.as_local()) { + self.set_access_level_def_id(export_def_id, Some(AccessLevel::Exported)); + } + + if let Some(ns) = export.res.ns() { + let key = BindingKey { ident: export.ident, ns, disambiguator: 0 }; + let name_res = self.r.resolution(module, key); + if let Some(binding) = name_res.borrow().binding() { + set_import_binding_access_level(self, binding, module_level) + } + } + } + } + } + + /// Sets the access level of the `LocalDefId` corresponding to the given `NodeId`. + /// This function will panic if the `NodeId` does not have a `LocalDefId` + fn set_access_level( + &mut self, + node_id: NodeId, + access_level: Option<AccessLevel>, + ) -> Option<AccessLevel> { + self.set_access_level_def_id(self.r.local_def_id(node_id), access_level) + } + + fn set_access_level_def_id( + &mut self, + def_id: LocalDefId, + access_level: Option<AccessLevel>, + ) -> Option<AccessLevel> { + let old_level = self.r.access_levels.map.get(&def_id).copied(); + if old_level < access_level { + self.r.access_levels.map.insert(def_id, access_level.unwrap()); + self.changed = true; + access_level + } else { + old_level + } + } +} + +impl<'r, 'ast> Visitor<'ast> for AccessLevelsVisitor<'ast, 'r> { + fn visit_item(&mut self, item: &'ast ast::Item) { + let inherited_item_level = match item.kind { + // Resolved in rustc_privacy when types are available + ast::ItemKind::Impl(..) => return, + + // Only exported `macro_rules!` items are public, but they always are + ast::ItemKind::MacroDef(ref macro_def) if macro_def.macro_rules => { + let is_macro_export = + item.attrs.iter().any(|attr| attr.has_name(sym::macro_export)); + if is_macro_export { Some(AccessLevel::Public) } else { None } + } + + // Foreign modules inherit level from parents. + ast::ItemKind::ForeignMod(..) => self.prev_level, + + // Other `pub` items inherit levels from parents. + ast::ItemKind::ExternCrate(..) + | ast::ItemKind::Use(..) + | ast::ItemKind::Static(..) + | ast::ItemKind::Const(..) + | ast::ItemKind::Fn(..) + | ast::ItemKind::Mod(..) + | ast::ItemKind::GlobalAsm(..) + | ast::ItemKind::TyAlias(..) + | ast::ItemKind::Enum(..) + | ast::ItemKind::Struct(..) + | ast::ItemKind::Union(..) + | ast::ItemKind::Trait(..) + | ast::ItemKind::TraitAlias(..) + | ast::ItemKind::MacroDef(..) => { + if item.vis.kind.is_pub() { + self.prev_level + } else { + None + } + } + + // Should be unreachable at this stage + ast::ItemKind::MacCall(..) => panic!( + "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage" + ), + }; + + let access_level = self.set_access_level(item.id, inherited_item_level); + + // Set access level of nested items. + // If it's a mod, also make the visitor walk all of its items + match item.kind { + ast::ItemKind::Mod(..) => { + if access_level.is_some() { + self.set_exports_access_level(self.r.local_def_id(item.id)); + } + + let orig_level = std::mem::replace(&mut self.prev_level, access_level); + visit::walk_item(self, item); + self.prev_level = orig_level; + } + + ast::ItemKind::ForeignMod(ForeignMod { ref items, .. }) => { + for nested in items { + if nested.vis.kind.is_pub() { + self.set_access_level(nested.id, access_level); + } + } + } + ast::ItemKind::Enum(EnumDef { ref variants }, _) => { + for variant in variants { + let variant_level = self.set_access_level(variant.id, access_level); + if let Some(ctor_id) = variant.data.ctor_id() { + self.set_access_level(ctor_id, access_level); + } + + for field in variant.data.fields() { + self.set_access_level(field.id, variant_level); + } + } + } + ast::ItemKind::Struct(ref def, _) | ast::ItemKind::Union(ref def, _) => { + if let Some(ctor_id) = def.ctor_id() { + self.set_access_level(ctor_id, access_level); + } + + for field in def.fields() { + if field.vis.kind.is_pub() { + self.set_access_level(field.id, access_level); + } + } + } + ast::ItemKind::Trait(ref trait_kind) => { + for nested in trait_kind.items.iter() { + self.set_access_level(nested.id, access_level); + } + } + + ast::ItemKind::ExternCrate(..) + | ast::ItemKind::Use(..) + | ast::ItemKind::Static(..) + | ast::ItemKind::Const(..) + | ast::ItemKind::GlobalAsm(..) + | ast::ItemKind::TyAlias(..) + | ast::ItemKind::TraitAlias(..) + | ast::ItemKind::MacroDef(..) + | ast::ItemKind::Fn(..) => return, + + // Unreachable kinds + ast::ItemKind::Impl(..) | ast::ItemKind::MacCall(..) => unreachable!(), + } + } +} diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs new file mode 100644 index 000000000..e955a1798 --- /dev/null +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -0,0 +1,1546 @@ +//! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate +//! that fragment into the module structures that are already partially built. +//! +//! Items from the fragment are placed into modules, +//! unexpanded macros in the fragment are visited and registered. +//! Imports are also considered items and placed into modules here, but not resolved yet. + +use crate::def_collector::collect_definitions; +use crate::imports::{Import, ImportKind}; +use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; +use crate::Namespace::{self, MacroNS, TypeNS, ValueNS}; +use crate::{Determinacy, ExternPreludeEntry, Finalize, Module, ModuleKind, ModuleOrUniformRoot}; +use crate::{ + MacroData, NameBinding, NameBindingKind, ParentScope, PathResult, PerNS, ResolutionError, +}; +use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, VisResolutionError}; + +use rustc_ast::visit::{self, AssocCtxt, Visitor}; +use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind}; +use rustc_ast::{Block, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId}; +use rustc_attr as attr; +use rustc_data_structures::sync::Lrc; +use rustc_errors::{struct_span_err, Applicability}; +use rustc_expand::expand::AstFragment; +use rustc_hir::def::{self, *}; +use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_metadata::creader::LoadedMacro; +use rustc_middle::bug; +use rustc_middle::metadata::ModChild; +use rustc_middle::ty::{self, DefIdTree}; +use rustc_session::cstore::CrateStore; +use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; +use rustc_span::source_map::{respan, Spanned}; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::Span; + +use std::cell::Cell; +use std::ptr; +use tracing::debug; + +type Res = def::Res<NodeId>; + +impl<'a> ToNameBinding<'a> for (Module<'a>, ty::Visibility, Span, LocalExpnId) { + fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { + arenas.alloc_name_binding(NameBinding { + kind: NameBindingKind::Module(self.0), + ambiguity: None, + vis: self.1, + span: self.2, + expansion: self.3, + }) + } +} + +impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, LocalExpnId) { + fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { + arenas.alloc_name_binding(NameBinding { + kind: NameBindingKind::Res(self.0, false), + ambiguity: None, + vis: self.1, + span: self.2, + expansion: self.3, + }) + } +} + +struct IsMacroExport; + +impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, LocalExpnId, IsMacroExport) { + fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { + arenas.alloc_name_binding(NameBinding { + kind: NameBindingKind::Res(self.0, true), + ambiguity: None, + vis: self.1, + span: self.2, + expansion: self.3, + }) + } +} + +impl<'a> Resolver<'a> { + /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined; + /// otherwise, reports an error. + pub(crate) fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) + where + T: ToNameBinding<'a>, + { + let binding = def.to_name_binding(self.arenas); + let key = self.new_key(ident, ns); + if let Err(old_binding) = self.try_define(parent, key, binding) { + self.report_conflict(parent, ident, ns, old_binding, &binding); + } + } + + /// Walks up the tree of definitions starting at `def_id`, + /// stopping at the first encountered module. + /// Parent block modules for arbitrary def-ids are not recorded for the local crate, + /// and are not preserved in metadata for foreign crates, so block modules are never + /// returned by this function. + /// + /// For the local crate ignoring block modules may be incorrect, so use this method with care. + /// + /// For foreign crates block modules can be ignored without introducing observable differences, + /// moreover they has to be ignored right now because they are not kept in metadata. + /// Foreign parent modules are used for resolving names used by foreign macros with def-site + /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and + /// block module parents being unreachable from other crates. + /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`, + /// but they cannot use def-site hygiene, so the assumption holds + /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>). + pub fn get_nearest_non_block_module(&mut self, mut def_id: DefId) -> Module<'a> { + loop { + match self.get_module(def_id) { + Some(module) => return module, + None => def_id = self.parent(def_id), + } + } + } + + pub fn expect_module(&mut self, def_id: DefId) -> Module<'a> { + self.get_module(def_id).expect("argument `DefId` is not a module") + } + + /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum, + /// or trait), then this function returns that module's resolver representation, otherwise it + /// returns `None`. + pub(crate) fn get_module(&mut self, def_id: DefId) -> Option<Module<'a>> { + if let module @ Some(..) = self.module_map.get(&def_id) { + return module.copied(); + } + + if !def_id.is_local() { + let def_kind = self.cstore().def_kind(def_id); + match def_kind { + DefKind::Mod | DefKind::Enum | DefKind::Trait => { + let def_key = self.cstore().def_key(def_id); + let parent = def_key.parent.map(|index| { + self.get_nearest_non_block_module(DefId { index, krate: def_id.krate }) + }); + let name = if let Some(cnum) = def_id.as_crate_root() { + self.cstore().crate_name(cnum) + } else { + def_key.disambiguated_data.data.get_opt_name().expect("module without name") + }; + + Some(self.new_module( + parent, + ModuleKind::Def(def_kind, def_id, name), + self.cstore().module_expansion_untracked(def_id, &self.session), + self.cstore().get_span_untracked(def_id, &self.session), + // FIXME: Account for `#[no_implicit_prelude]` attributes. + parent.map_or(false, |module| module.no_implicit_prelude), + )) + } + _ => None, + } + } else { + None + } + } + + pub(crate) fn expn_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> { + match expn_id.expn_data().macro_def_id { + Some(def_id) => self.macro_def_scope(def_id), + None => expn_id + .as_local() + .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id)) + .unwrap_or(&self.graph_root), + } + } + + pub(crate) fn macro_def_scope(&mut self, def_id: DefId) -> Module<'a> { + if let Some(id) = def_id.as_local() { + self.local_macro_def_scopes[&id] + } else { + self.get_nearest_non_block_module(def_id) + } + } + + pub(crate) fn get_macro(&mut self, res: Res) -> Option<MacroData> { + match res { + Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)), + Res::NonMacroAttr(_) => { + Some(MacroData { ext: self.non_macro_attr.clone(), macro_rules: false }) + } + _ => None, + } + } + + pub(crate) fn get_macro_by_def_id(&mut self, def_id: DefId) -> MacroData { + if let Some(macro_data) = self.macro_map.get(&def_id) { + return macro_data.clone(); + } + + let (ext, macro_rules) = match self.cstore().load_macro_untracked(def_id, &self.session) { + LoadedMacro::MacroDef(item, edition) => ( + Lrc::new(self.compile_macro(&item, edition).0), + matches!(item.kind, ItemKind::MacroDef(def) if def.macro_rules), + ), + LoadedMacro::ProcMacro(extz) => (Lrc::new(extz), false), + }; + + let macro_data = MacroData { ext, macro_rules }; + self.macro_map.insert(def_id, macro_data.clone()); + macro_data + } + + pub(crate) fn build_reduced_graph( + &mut self, + fragment: &AstFragment, + parent_scope: ParentScope<'a>, + ) -> MacroRulesScopeRef<'a> { + collect_definitions(self, fragment, parent_scope.expansion); + let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope }; + fragment.visit_with(&mut visitor); + visitor.parent_scope.macro_rules + } + + pub(crate) fn build_reduced_graph_external(&mut self, module: Module<'a>) { + for child in self.cstore().module_children_untracked(module.def_id(), self.session) { + let parent_scope = ParentScope::module(module, self); + BuildReducedGraphVisitor { r: self, parent_scope } + .build_reduced_graph_for_external_crate_res(child); + } + } +} + +struct BuildReducedGraphVisitor<'a, 'b> { + r: &'b mut Resolver<'a>, + parent_scope: ParentScope<'a>, +} + +impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> { + fn as_mut(&mut self) -> &mut Resolver<'a> { + self.r + } +} + +impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { + fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility { + self.try_resolve_visibility(vis, true).unwrap_or_else(|err| { + self.r.report_vis_error(err); + ty::Visibility::Public + }) + } + + fn try_resolve_visibility<'ast>( + &mut self, + vis: &'ast ast::Visibility, + finalize: bool, + ) -> Result<ty::Visibility, VisResolutionError<'ast>> { + let parent_scope = &self.parent_scope; + match vis.kind { + ast::VisibilityKind::Public => Ok(ty::Visibility::Public), + ast::VisibilityKind::Inherited => { + Ok(match self.parent_scope.module.kind { + // Any inherited visibility resolved directly inside an enum or trait + // (i.e. variants, fields, and trait items) inherits from the visibility + // of the enum or trait. + ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _) => { + self.r.visibilities[&def_id.expect_local()] + } + // Otherwise, the visibility is restricted to the nearest parent `mod` item. + _ => ty::Visibility::Restricted(self.parent_scope.module.nearest_parent_mod()), + }) + } + ast::VisibilityKind::Restricted { ref path, id, .. } => { + // Make `PRIVATE_IN_PUBLIC` lint a hard error. + self.r.has_pub_restricted = true; + // For visibilities we are not ready to provide correct implementation of "uniform + // paths" right now, so on 2018 edition we only allow module-relative paths for now. + // On 2015 edition visibilities are resolved as crate-relative by default, + // so we are prepending a root segment if necessary. + let ident = path.segments.get(0).expect("empty path in visibility").ident; + let crate_root = if ident.is_path_segment_keyword() { + None + } else if ident.span.rust_2015() { + Some(Segment::from_ident(Ident::new( + kw::PathRoot, + path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()), + ))) + } else { + return Err(VisResolutionError::Relative2018(ident.span, path)); + }; + + let segments = crate_root + .into_iter() + .chain(path.segments.iter().map(|seg| seg.into())) + .collect::<Vec<_>>(); + let expected_found_error = |res| { + Err(VisResolutionError::ExpectedFound( + path.span, + Segment::names_to_string(&segments), + res, + )) + }; + match self.r.resolve_path( + &segments, + Some(TypeNS), + parent_scope, + finalize.then(|| Finalize::new(id, path.span)), + None, + ) { + PathResult::Module(ModuleOrUniformRoot::Module(module)) => { + let res = module.res().expect("visibility resolved to unnamed block"); + if finalize { + self.r.record_partial_res(id, PartialRes::new(res)); + } + if module.is_normal() { + if res == Res::Err { + Ok(ty::Visibility::Public) + } else { + let vis = ty::Visibility::Restricted(res.def_id()); + if self.r.is_accessible_from(vis, parent_scope.module) { + Ok(vis) + } else { + Err(VisResolutionError::AncestorOnly(path.span)) + } + } + } else { + expected_found_error(res) + } + } + PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)), + PathResult::NonModule(partial_res) => { + expected_found_error(partial_res.base_res()) + } + PathResult::Failed { span, label, suggestion, .. } => { + Err(VisResolutionError::FailedToResolve(span, label, suggestion)) + } + PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)), + } + } + } + } + + fn insert_field_names_local(&mut self, def_id: DefId, vdata: &ast::VariantData) { + let field_names = vdata + .fields() + .iter() + .map(|field| respan(field.span, field.ident.map_or(kw::Empty, |ident| ident.name))) + .collect(); + self.insert_field_names(def_id, field_names); + } + + fn insert_field_names(&mut self, def_id: DefId, field_names: Vec<Spanned<Symbol>>) { + self.r.field_names.insert(def_id, field_names); + } + + fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { + // If any statements are items, we need to create an anonymous module + block + .stmts + .iter() + .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_))) + } + + // Add an import to the current module. + fn add_import( + &mut self, + module_path: Vec<Segment>, + kind: ImportKind<'a>, + span: Span, + id: NodeId, + item: &ast::Item, + root_span: Span, + root_id: NodeId, + vis: ty::Visibility, + ) { + let current_module = self.parent_scope.module; + let import = self.r.arenas.alloc_import(Import { + kind, + parent_scope: self.parent_scope, + module_path, + imported_module: Cell::new(None), + span, + id, + use_span: item.span, + use_span_with_attributes: item.span_with_attributes(), + has_attributes: !item.attrs.is_empty(), + root_span, + root_id, + vis: Cell::new(vis), + used: Cell::new(false), + }); + + self.r.indeterminate_imports.push(import); + match import.kind { + // Don't add unresolved underscore imports to modules + ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {} + ImportKind::Single { target, type_ns_only, .. } => { + self.r.per_ns(|this, ns| { + if !type_ns_only || ns == TypeNS { + let key = this.new_key(target, ns); + let mut resolution = this.resolution(current_module, key).borrow_mut(); + resolution.add_single_import(import); + } + }); + } + // We don't add prelude imports to the globs since they only affect lexical scopes, + // which are not relevant to import resolution. + ImportKind::Glob { is_prelude: true, .. } => {} + ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import), + _ => unreachable!(), + } + } + + fn build_reduced_graph_for_use_tree( + &mut self, + // This particular use tree + use_tree: &ast::UseTree, + id: NodeId, + parent_prefix: &[Segment], + nested: bool, + // The whole `use` item + item: &Item, + vis: ty::Visibility, + root_span: Span, + ) { + debug!( + "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})", + parent_prefix, use_tree, nested + ); + + let mut prefix_iter = parent_prefix + .iter() + .cloned() + .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())) + .peekable(); + + // On 2015 edition imports are resolved as crate-relative by default, + // so prefixes are prepended with crate root segment if necessary. + // The root is prepended lazily, when the first non-empty prefix or terminating glob + // appears, so imports in braced groups can have roots prepended independently. + let is_glob = matches!(use_tree.kind, ast::UseTreeKind::Glob); + let crate_root = match prefix_iter.peek() { + Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.rust_2015() => { + Some(seg.ident.span.ctxt()) + } + None if is_glob && use_tree.span.rust_2015() => Some(use_tree.span.ctxt()), + _ => None, + } + .map(|ctxt| { + Segment::from_ident(Ident::new( + kw::PathRoot, + use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt), + )) + }); + + let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>(); + debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix); + + let empty_for_self = |prefix: &[Segment]| { + prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot + }; + match use_tree.kind { + ast::UseTreeKind::Simple(rename, id1, id2) => { + let mut ident = use_tree.ident(); + let mut module_path = prefix; + let mut source = module_path.pop().unwrap(); + let mut type_ns_only = false; + + self.r.visibilities.insert(self.r.local_def_id(id), vis); + if id1 != ast::DUMMY_NODE_ID { + self.r.visibilities.insert(self.r.local_def_id(id1), vis); + } + if id2 != ast::DUMMY_NODE_ID { + self.r.visibilities.insert(self.r.local_def_id(id2), vis); + } + + if nested { + // Correctly handle `self` + if source.ident.name == kw::SelfLower { + type_ns_only = true; + + if empty_for_self(&module_path) { + self.r.report_error( + use_tree.span, + ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix, + ); + return; + } + + // Replace `use foo::{ self };` with `use foo;` + source = module_path.pop().unwrap(); + if rename.is_none() { + ident = source.ident; + } + } + } else { + // Disallow `self` + if source.ident.name == kw::SelfLower { + let parent = module_path.last(); + + let span = match parent { + // only `::self` from `use foo::self as bar` + Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span), + None => source.ident.span, + }; + let span_with_rename = match rename { + // only `self as bar` from `use foo::self as bar` + Some(rename) => source.ident.span.to(rename.span), + None => source.ident.span, + }; + self.r.report_error( + span, + ResolutionError::SelfImportsOnlyAllowedWithin { + root: parent.is_none(), + span_with_rename, + }, + ); + + // Error recovery: replace `use foo::self;` with `use foo;` + if let Some(parent) = module_path.pop() { + source = parent; + if rename.is_none() { + ident = source.ident; + } + } + } + + // Disallow `use $crate;` + if source.ident.name == kw::DollarCrate && module_path.is_empty() { + let crate_root = self.r.resolve_crate_root(source.ident); + let crate_name = match crate_root.kind { + ModuleKind::Def(.., name) => name, + ModuleKind::Block => unreachable!(), + }; + // HACK(eddyb) unclear how good this is, but keeping `$crate` + // in `source` breaks `src/test/ui/imports/import-crate-var.rs`, + // while the current crate doesn't have a valid `crate_name`. + if crate_name != kw::Empty { + // `crate_name` should not be interpreted as relative. + module_path.push(Segment::from_ident_and_id( + Ident { name: kw::PathRoot, span: source.ident.span }, + self.r.next_node_id(), + )); + source.ident.name = crate_name; + } + if rename.is_none() { + ident.name = crate_name; + } + + self.r + .session + .struct_span_err(item.span, "`$crate` may not be imported") + .emit(); + } + } + + if ident.name == kw::Crate { + self.r.session.span_err( + ident.span, + "crate root imports need to be explicitly named: \ + `use crate as name;`", + ); + } + + let kind = ImportKind::Single { + source: source.ident, + target: ident, + source_bindings: PerNS { + type_ns: Cell::new(Err(Determinacy::Undetermined)), + value_ns: Cell::new(Err(Determinacy::Undetermined)), + macro_ns: Cell::new(Err(Determinacy::Undetermined)), + }, + target_bindings: PerNS { + type_ns: Cell::new(None), + value_ns: Cell::new(None), + macro_ns: Cell::new(None), + }, + type_ns_only, + nested, + additional_ids: (id1, id2), + }; + + self.add_import( + module_path, + kind, + use_tree.span, + id, + item, + root_span, + item.id, + vis, + ); + } + ast::UseTreeKind::Glob => { + let kind = ImportKind::Glob { + is_prelude: self.r.session.contains_name(&item.attrs, sym::prelude_import), + max_vis: Cell::new(ty::Visibility::Invisible), + }; + self.r.visibilities.insert(self.r.local_def_id(id), vis); + self.add_import(prefix, kind, use_tree.span, id, item, root_span, item.id, vis); + } + ast::UseTreeKind::Nested(ref items) => { + // Ensure there is at most one `self` in the list + let self_spans = items + .iter() + .filter_map(|&(ref use_tree, _)| { + if let ast::UseTreeKind::Simple(..) = use_tree.kind { + if use_tree.ident().name == kw::SelfLower { + return Some(use_tree.span); + } + } + + None + }) + .collect::<Vec<_>>(); + if self_spans.len() > 1 { + let mut e = self.r.into_struct_error( + self_spans[0], + ResolutionError::SelfImportCanOnlyAppearOnceInTheList, + ); + + for other_span in self_spans.iter().skip(1) { + e.span_label(*other_span, "another `self` import appears here"); + } + + e.emit(); + } + + for &(ref tree, id) in items { + self.build_reduced_graph_for_use_tree( + // This particular use tree + tree, id, &prefix, true, // The whole `use` item + item, vis, root_span, + ); + } + + // Empty groups `a::b::{}` are turned into synthetic `self` imports + // `a::b::c::{self as _}`, so that their prefixes are correctly + // resolved and checked for privacy/stability/etc. + if items.is_empty() && !empty_for_self(&prefix) { + let new_span = prefix[prefix.len() - 1].ident.span; + let tree = ast::UseTree { + prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)), + kind: ast::UseTreeKind::Simple( + Some(Ident::new(kw::Underscore, new_span)), + ast::DUMMY_NODE_ID, + ast::DUMMY_NODE_ID, + ), + span: use_tree.span, + }; + self.build_reduced_graph_for_use_tree( + // This particular use tree + &tree, + id, + &prefix, + true, + // The whole `use` item + item, + ty::Visibility::Invisible, + root_span, + ); + } + } + } + } + + /// Constructs the reduced graph for one item. + fn build_reduced_graph_for_item(&mut self, item: &'b Item) { + let parent_scope = &self.parent_scope; + let parent = parent_scope.module; + let expansion = parent_scope.expansion; + let ident = item.ident; + let sp = item.span; + let vis = self.resolve_visibility(&item.vis); + let local_def_id = self.r.local_def_id(item.id); + let def_id = local_def_id.to_def_id(); + + self.r.visibilities.insert(local_def_id, vis); + + match item.kind { + ItemKind::Use(ref use_tree) => { + self.build_reduced_graph_for_use_tree( + // This particular use tree + use_tree, + item.id, + &[], + false, + // The whole `use` item + item, + vis, + use_tree.span, + ); + } + + ItemKind::ExternCrate(orig_name) => { + self.build_reduced_graph_for_extern_crate( + orig_name, + item, + local_def_id, + vis, + parent, + ); + } + + ItemKind::Mod(..) => { + let module = self.r.new_module( + Some(parent), + ModuleKind::Def(DefKind::Mod, def_id, ident.name), + expansion.to_expn_id(), + item.span, + parent.no_implicit_prelude + || self.r.session.contains_name(&item.attrs, sym::no_implicit_prelude), + ); + self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); + + // Descend into the module. + self.parent_scope.module = module; + } + + // These items live in the value namespace. + ItemKind::Static(_, mt, _) => { + let res = Res::Def(DefKind::Static(mt), def_id); + self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); + } + ItemKind::Const(..) => { + let res = Res::Def(DefKind::Const, def_id); + self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); + } + ItemKind::Fn(..) => { + let res = Res::Def(DefKind::Fn, def_id); + self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); + + // Functions introducing procedural macros reserve a slot + // in the macro namespace as well (see #52225). + self.define_macro(item); + } + + // These items live in the type namespace. + ItemKind::TyAlias(..) => { + let res = Res::Def(DefKind::TyAlias, def_id); + self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); + } + + ItemKind::Enum(_, _) => { + let module = self.r.new_module( + Some(parent), + ModuleKind::Def(DefKind::Enum, def_id, ident.name), + expansion.to_expn_id(), + item.span, + parent.no_implicit_prelude, + ); + self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); + self.parent_scope.module = module; + } + + ItemKind::TraitAlias(..) => { + let res = Res::Def(DefKind::TraitAlias, def_id); + self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); + } + + // These items live in both the type and value namespaces. + ItemKind::Struct(ref vdata, _) => { + // Define a name in the type namespace. + let res = Res::Def(DefKind::Struct, def_id); + self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); + + // Record field names for error reporting. + self.insert_field_names_local(def_id, vdata); + + // If this is a tuple or unit struct, define a name + // in the value namespace as well. + if let Some(ctor_node_id) = vdata.ctor_id() { + // If the structure is marked as non_exhaustive then lower the visibility + // to within the crate. + let mut ctor_vis = if vis == ty::Visibility::Public + && self.r.session.contains_name(&item.attrs, sym::non_exhaustive) + { + ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()) + } else { + vis + }; + + let mut ret_fields = Vec::with_capacity(vdata.fields().len()); + + for field in vdata.fields() { + // NOTE: The field may be an expansion placeholder, but expansion sets + // correct visibilities for unnamed field placeholders specifically, so the + // constructor visibility should still be determined correctly. + let field_vis = self + .try_resolve_visibility(&field.vis, false) + .unwrap_or(ty::Visibility::Public); + if ctor_vis.is_at_least(field_vis, &*self.r) { + ctor_vis = field_vis; + } + ret_fields.push(field_vis); + } + let ctor_def_id = self.r.local_def_id(ctor_node_id); + let ctor_res = Res::Def( + DefKind::Ctor(CtorOf::Struct, CtorKind::from_ast(vdata)), + ctor_def_id.to_def_id(), + ); + self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion)); + self.r.visibilities.insert(ctor_def_id, ctor_vis); + + self.r.struct_constructors.insert(def_id, (ctor_res, ctor_vis, ret_fields)); + } + } + + ItemKind::Union(ref vdata, _) => { + let res = Res::Def(DefKind::Union, def_id); + self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); + + // Record field names for error reporting. + self.insert_field_names_local(def_id, vdata); + } + + ItemKind::Trait(..) => { + // Add all the items within to a new module. + let module = self.r.new_module( + Some(parent), + ModuleKind::Def(DefKind::Trait, def_id, ident.name), + expansion.to_expn_id(), + item.span, + parent.no_implicit_prelude, + ); + self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); + self.parent_scope.module = module; + } + + // These items do not add names to modules. + ItemKind::Impl(box Impl { of_trait: Some(..), .. }) => { + self.r.trait_impl_items.insert(local_def_id); + } + ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {} + + ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(), + } + } + + fn build_reduced_graph_for_extern_crate( + &mut self, + orig_name: Option<Symbol>, + item: &Item, + local_def_id: LocalDefId, + vis: ty::Visibility, + parent: Module<'a>, + ) { + let ident = item.ident; + let sp = item.span; + let parent_scope = self.parent_scope; + let expansion = parent_scope.expansion; + + let (used, module, binding) = if orig_name.is_none() && ident.name == kw::SelfLower { + self.r + .session + .struct_span_err(item.span, "`extern crate self;` requires renaming") + .span_suggestion( + item.span, + "rename the `self` crate to be able to import it", + "extern crate self as name;", + Applicability::HasPlaceholders, + ) + .emit(); + return; + } else if orig_name == Some(kw::SelfLower) { + Some(self.r.graph_root) + } else { + self.r.crate_loader.process_extern_crate(item, &self.r.definitions, local_def_id).map( + |crate_id| { + self.r.extern_crate_map.insert(local_def_id, crate_id); + self.r.expect_module(crate_id.as_def_id()) + }, + ) + } + .map(|module| { + let used = self.process_macro_use_imports(item, module); + let binding = + (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas); + (used, Some(ModuleOrUniformRoot::Module(module)), binding) + }) + .unwrap_or((true, None, self.r.dummy_binding)); + let import = self.r.arenas.alloc_import(Import { + kind: ImportKind::ExternCrate { source: orig_name, target: ident }, + root_id: item.id, + id: item.id, + parent_scope: self.parent_scope, + imported_module: Cell::new(module), + has_attributes: !item.attrs.is_empty(), + use_span_with_attributes: item.span_with_attributes(), + use_span: item.span, + root_span: item.span, + span: item.span, + module_path: Vec::new(), + vis: Cell::new(vis), + used: Cell::new(used), + }); + 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.normalize_to_macros_2_0()) { + if expansion != LocalExpnId::ROOT + && orig_name.is_some() + && entry.extern_crate_item.is_none() + { + let msg = "macro-expanded `extern crate` items cannot \ + shadow names passed with `--extern`"; + self.r.session.span_err(item.span, msg); + } + } + let entry = 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; + } + } + self.r.define(parent, ident, TypeNS, imported_binding); + } + + /// Constructs the reduced graph for one foreign item. + fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) { + let local_def_id = self.r.local_def_id(item.id); + let def_id = local_def_id.to_def_id(); + let (def_kind, ns) = match item.kind { + ForeignItemKind::Fn(..) => (DefKind::Fn, ValueNS), + ForeignItemKind::Static(_, mt, _) => (DefKind::Static(mt), ValueNS), + ForeignItemKind::TyAlias(..) => (DefKind::ForeignTy, TypeNS), + ForeignItemKind::MacCall(_) => unreachable!(), + }; + let parent = self.parent_scope.module; + let expansion = self.parent_scope.expansion; + let vis = self.resolve_visibility(&item.vis); + let res = Res::Def(def_kind, def_id); + self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); + self.r.visibilities.insert(local_def_id, vis); + } + + fn build_reduced_graph_for_block(&mut self, block: &Block) { + let parent = self.parent_scope.module; + let expansion = self.parent_scope.expansion; + if self.block_needs_anonymous_module(block) { + let module = self.r.new_module( + Some(parent), + ModuleKind::Block, + expansion.to_expn_id(), + block.span, + parent.no_implicit_prelude, + ); + self.r.block_map.insert(block.id, module); + self.parent_scope.module = module; // Descend into the block. + } + } + + /// Builds the reduced graph for a single item in an external crate. + fn build_reduced_graph_for_external_crate_res(&mut self, child: ModChild) { + let parent = self.parent_scope.module; + let ModChild { ident, res, vis, span, macro_rules } = child; + let res = res.expect_non_local(); + let expansion = self.parent_scope.expansion; + // Record primary definitions. + match res { + Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, def_id) => { + let module = self.r.expect_module(def_id); + self.r.define(parent, ident, TypeNS, (module, vis, span, expansion)); + } + Res::Def( + DefKind::Struct + | DefKind::Union + | DefKind::Variant + | DefKind::TyAlias + | DefKind::ForeignTy + | DefKind::OpaqueTy + | DefKind::TraitAlias + | DefKind::AssocTy, + _, + ) + | Res::PrimTy(..) + | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)), + Res::Def( + DefKind::Fn + | DefKind::AssocFn + | DefKind::Static(_) + | DefKind::Const + | DefKind::AssocConst + | DefKind::Ctor(..), + _, + ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)), + Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => { + if !macro_rules { + self.r.define(parent, ident, MacroNS, (res, vis, span, expansion)) + } + } + Res::Def( + DefKind::TyParam + | DefKind::ConstParam + | DefKind::ExternCrate + | DefKind::Use + | DefKind::ForeignMod + | DefKind::AnonConst + | DefKind::InlineConst + | DefKind::Field + | DefKind::LifetimeParam + | DefKind::GlobalAsm + | DefKind::Closure + | DefKind::Impl + | DefKind::Generator, + _, + ) + | Res::Local(..) + | Res::SelfTy { .. } + | Res::SelfCtor(..) + | Res::Err => bug!("unexpected resolution: {:?}", res), + } + // Record some extra data for better diagnostics. + let cstore = self.r.cstore(); + match res { + Res::Def(DefKind::Struct, def_id) => { + let field_names = + cstore.struct_field_names_untracked(def_id, self.r.session).collect(); + let ctor = cstore.ctor_def_id_and_kind_untracked(def_id); + if let Some((ctor_def_id, ctor_kind)) = ctor { + let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); + let ctor_vis = cstore.visibility_untracked(ctor_def_id); + let field_visibilities = + cstore.struct_field_visibilities_untracked(def_id).collect(); + self.r + .struct_constructors + .insert(def_id, (ctor_res, ctor_vis, field_visibilities)); + } + self.insert_field_names(def_id, field_names); + } + Res::Def(DefKind::Union, def_id) => { + let field_names = + cstore.struct_field_names_untracked(def_id, self.r.session).collect(); + self.insert_field_names(def_id, field_names); + } + Res::Def(DefKind::AssocFn, def_id) => { + if cstore.fn_has_self_parameter_untracked(def_id) { + self.r.has_self.insert(def_id); + } + } + _ => {} + } + } + + fn add_macro_use_binding( + &mut self, + name: Symbol, + binding: &'a NameBinding<'a>, + span: Span, + allow_shadowing: bool, + ) { + if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing { + let msg = format!("`{}` is already in scope", name); + let note = + "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)"; + self.r.session.struct_span_err(span, &msg).note(note).emit(); + } + } + + /// Returns `true` if we should consider the underlying `extern crate` to be used. + 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 { + if attr.has_name(sym::macro_use) { + if self.parent_scope.module.parent.is_some() { + struct_span_err!( + self.r.session, + item.span, + E0468, + "an `extern crate` loading macros must be at the crate root" + ) + .emit(); + } + if let ItemKind::ExternCrate(Some(orig_name)) = item.kind { + if orig_name == kw::SelfLower { + self.r + .session + .struct_span_err( + attr.span, + "`#[macro_use]` is not supported on `extern crate self`", + ) + .emit(); + } + } + let ill_formed = |span| { + struct_span_err!(self.r.session, span, E0466, "bad macro import").emit(); + }; + match attr.meta() { + Some(meta) => match meta.kind { + MetaItemKind::Word => { + import_all = Some(meta.span); + break; + } + MetaItemKind::List(nested_metas) => { + for nested_meta in nested_metas { + match nested_meta.ident() { + Some(ident) if nested_meta.is_word() => { + single_imports.push(ident) + } + _ => ill_formed(nested_meta.span()), + } + } + } + MetaItemKind::NameValue(..) => ill_formed(meta.span), + }, + None => ill_formed(attr.span), + } + } + } + + let macro_use_import = |this: &Self, span| { + this.r.arenas.alloc_import(Import { + kind: ImportKind::MacroUse, + root_id: item.id, + id: item.id, + parent_scope: this.parent_scope, + imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))), + use_span_with_attributes: item.span_with_attributes(), + has_attributes: !item.attrs.is_empty(), + use_span: item.span, + root_span: span, + span, + module_path: Vec::new(), + vis: Cell::new(ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id())), + used: Cell::new(false), + }) + }; + + let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT; + if let Some(span) = import_all { + let import = macro_use_import(self, span); + self.r.potentially_unused_imports.push(import); + module.for_each_child(self, |this, ident, ns, binding| { + if ns == MacroNS { + let imported_binding = this.r.import(binding, import); + this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing); + } + }); + } else { + for ident in single_imports.iter().cloned() { + let result = self.r.maybe_resolve_ident_in_module( + ModuleOrUniformRoot::Module(module), + ident, + MacroNS, + &self.parent_scope, + ); + if let Ok(binding) = result { + let import = macro_use_import(self, ident.span); + self.r.potentially_unused_imports.push(import); + let imported_binding = self.r.import(binding, import); + self.add_macro_use_binding( + ident.name, + imported_binding, + ident.span, + allow_shadowing, + ); + } else { + struct_span_err!(self.r.session, ident.span, E0469, "imported macro not found") + .emit(); + } + } + } + import_all.is_some() || !single_imports.is_empty() + } + + /// Returns `true` if this attribute list contains `macro_use`. + fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool { + for attr in attrs { + if attr.has_name(sym::macro_escape) { + let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`"; + let mut err = self.r.session.struct_span_warn(attr.span, msg); + if let ast::AttrStyle::Inner = attr.style { + err.help("try an outer attribute: `#[macro_use]`").emit(); + } else { + err.emit(); + } + } else if !attr.has_name(sym::macro_use) { + continue; + } + + if !attr.is_word() { + self.r.session.span_err(attr.span, "arguments to `macro_use` are not allowed here"); + } + return true; + } + + false + } + + fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId { + let invoc_id = id.placeholder_to_expn_id(); + 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"); + invoc_id + } + + /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`) + /// directly into its parent scope's module. + fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'a> { + let invoc_id = self.visit_invoc(id); + self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id); + self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id)) + } + + fn proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)> { + if self.r.session.contains_name(&item.attrs, sym::proc_macro) { + return Some((MacroKind::Bang, item.ident, item.span)); + } else if self.r.session.contains_name(&item.attrs, sym::proc_macro_attribute) { + return Some((MacroKind::Attr, item.ident, item.span)); + } else if let Some(attr) = self.r.session.find_by_name(&item.attrs, sym::proc_macro_derive) + { + if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) { + if let Some(ident) = nested_meta.ident() { + return Some((MacroKind::Derive, ident, ident.span)); + } + } + } + None + } + + // Mark the given macro as unused unless its name starts with `_`. + // Macro uses will remove items from this set, and the remaining + // items will be reported as `unused_macros`. + fn insert_unused_macro( + &mut self, + ident: Ident, + def_id: LocalDefId, + node_id: NodeId, + rule_spans: &[(usize, Span)], + ) { + if !ident.as_str().starts_with('_') { + self.r.unused_macros.insert(def_id, (node_id, ident)); + for (rule_i, rule_span) in rule_spans.iter() { + self.r.unused_macro_rules.insert((def_id, *rule_i), (ident, *rule_span)); + } + } + } + + fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> { + let parent_scope = self.parent_scope; + let expansion = parent_scope.expansion; + let def_id = self.r.local_def_id(item.id); + let (ext, ident, span, macro_rules, rule_spans) = match &item.kind { + ItemKind::MacroDef(def) => { + let (ext, rule_spans) = self.r.compile_macro(item, self.r.session.edition()); + let ext = Lrc::new(ext); + (ext, item.ident, item.span, def.macro_rules, rule_spans) + } + ItemKind::Fn(..) => match self.proc_macro_stub(item) { + Some((macro_kind, ident, span)) => { + self.r.proc_macro_stubs.insert(def_id); + (self.r.dummy_ext(macro_kind), ident, span, false, Vec::new()) + } + None => return parent_scope.macro_rules, + }, + _ => unreachable!(), + }; + + let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id()); + self.r.macro_map.insert(def_id.to_def_id(), MacroData { ext, macro_rules }); + self.r.local_macro_def_scopes.insert(def_id, parent_scope.module); + + if macro_rules { + let ident = ident.normalize_to_macros_2_0(); + self.r.macro_names.insert(ident); + let is_macro_export = self.r.session.contains_name(&item.attrs, sym::macro_export); + let vis = if is_macro_export { + ty::Visibility::Public + } else { + ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()) + }; + let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas); + self.r.set_binding_parent_module(binding, parent_scope.module); + if is_macro_export { + let module = self.r.graph_root; + self.r.define(module, ident, MacroNS, (res, vis, span, expansion, IsMacroExport)); + } else { + self.r.check_reserved_macro_name(ident, res); + self.insert_unused_macro(ident, def_id, item.id, &rule_spans); + } + self.r.visibilities.insert(def_id, vis); + let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding( + self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding { + parent_macro_rules_scope: parent_scope.macro_rules, + binding, + ident, + }), + )); + self.r.macro_rules_scopes.insert(def_id, scope); + scope + } else { + let module = parent_scope.module; + let vis = match item.kind { + // Visibilities must not be resolved non-speculatively twice + // and we already resolved this one as a `fn` item visibility. + ItemKind::Fn(..) => { + self.try_resolve_visibility(&item.vis, false).unwrap_or(ty::Visibility::Public) + } + _ => self.resolve_visibility(&item.vis), + }; + if vis != ty::Visibility::Public { + self.insert_unused_macro(ident, def_id, item.id, &rule_spans); + } + self.r.define(module, ident, MacroNS, (res, vis, span, expansion)); + self.r.visibilities.insert(def_id, vis); + self.parent_scope.macro_rules + } + } +} + +macro_rules! method { + ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => { + fn $visit(&mut self, node: &'b $ty) { + if let $invoc(..) = node.kind { + self.visit_invoc(node.id); + } else { + visit::$walk(self, node); + } + } + }; +} + +impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> { + method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr); + method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat); + method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty); + + fn visit_item(&mut self, item: &'b Item) { + let orig_module_scope = self.parent_scope.module; + self.parent_scope.macro_rules = match item.kind { + ItemKind::MacroDef(..) => { + let macro_rules_scope = self.define_macro(item); + visit::walk_item(self, item); + macro_rules_scope + } + ItemKind::MacCall(..) => { + let macro_rules_scope = self.visit_invoc_in_module(item.id); + visit::walk_item(self, item); + macro_rules_scope + } + _ => { + let orig_macro_rules_scope = self.parent_scope.macro_rules; + self.build_reduced_graph_for_item(item); + visit::walk_item(self, item); + match item.kind { + ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => { + self.parent_scope.macro_rules + } + _ => orig_macro_rules_scope, + } + } + }; + self.parent_scope.module = orig_module_scope; + } + + fn visit_stmt(&mut self, stmt: &'b ast::Stmt) { + if let ast::StmtKind::MacCall(..) = stmt.kind { + self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id); + } else { + visit::walk_stmt(self, stmt); + } + } + + fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) { + if let ForeignItemKind::MacCall(_) = foreign_item.kind { + self.visit_invoc_in_module(foreign_item.id); + return; + } + + self.build_reduced_graph_for_foreign_item(foreign_item); + visit::walk_foreign_item(self, foreign_item); + } + + fn visit_block(&mut self, block: &'b Block) { + let orig_current_module = self.parent_scope.module; + 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.macro_rules = orig_current_macro_rules_scope; + } + + fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) { + if let AssocItemKind::MacCall(_) = item.kind { + match ctxt { + AssocCtxt::Trait => { + self.visit_invoc_in_module(item.id); + } + AssocCtxt::Impl => { + self.visit_invoc(item.id); + } + } + return; + } + + let vis = self.resolve_visibility(&item.vis); + let local_def_id = self.r.local_def_id(item.id); + let def_id = local_def_id.to_def_id(); + + if !(ctxt == AssocCtxt::Impl + && matches!(item.vis.kind, ast::VisibilityKind::Inherited) + && self + .r + .trait_impl_items + .contains(&ty::DefIdTree::local_parent(&*self.r, local_def_id))) + { + // Trait impl item visibility is inherited from its trait when not specified + // explicitly. In that case we cannot determine it here in early resolve, + // so we leave a hole in the visibility table to be filled later. + self.r.visibilities.insert(local_def_id, vis); + } + + if ctxt == AssocCtxt::Trait { + let (def_kind, ns) = match item.kind { + AssocItemKind::Const(..) => (DefKind::AssocConst, ValueNS), + AssocItemKind::Fn(box Fn { ref sig, .. }) => { + if sig.decl.has_self() { + self.r.has_self.insert(def_id); + } + (DefKind::AssocFn, ValueNS) + } + AssocItemKind::TyAlias(..) => (DefKind::AssocTy, TypeNS), + AssocItemKind::MacCall(_) => bug!(), // handled above + }; + + let parent = self.parent_scope.module; + let expansion = self.parent_scope.expansion; + let res = Res::Def(def_kind, def_id); + self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); + } + + visit::walk_assoc_item(self, item, ctxt); + } + + fn visit_attribute(&mut self, attr: &'b ast::Attribute) { + if !attr.is_doc_comment() && attr::is_builtin_attr(attr) { + self.r + .builtin_attrs + .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope)); + } + visit::walk_attribute(self, attr); + } + + fn visit_arm(&mut self, arm: &'b ast::Arm) { + if arm.is_placeholder { + self.visit_invoc(arm.id); + } else { + visit::walk_arm(self, arm); + } + } + + fn visit_expr_field(&mut self, f: &'b ast::ExprField) { + if f.is_placeholder { + self.visit_invoc(f.id); + } else { + visit::walk_expr_field(self, f); + } + } + + fn visit_pat_field(&mut self, fp: &'b ast::PatField) { + if fp.is_placeholder { + self.visit_invoc(fp.id); + } else { + visit::walk_pat_field(self, fp); + } + } + + fn visit_generic_param(&mut self, param: &'b ast::GenericParam) { + if param.is_placeholder { + self.visit_invoc(param.id); + } else { + visit::walk_generic_param(self, param); + } + } + + fn visit_param(&mut self, p: &'b ast::Param) { + if p.is_placeholder { + self.visit_invoc(p.id); + } else { + visit::walk_param(self, p); + } + } + + fn visit_field_def(&mut self, sf: &'b ast::FieldDef) { + if sf.is_placeholder { + self.visit_invoc(sf.id); + } else { + let vis = self.resolve_visibility(&sf.vis); + self.r.visibilities.insert(self.r.local_def_id(sf.id), vis); + visit::walk_field_def(self, sf); + } + } + + // Constructs the reduced graph for one variant. Variants exist in the + // type and value namespaces. + fn visit_variant(&mut self, variant: &'b ast::Variant) { + if variant.is_placeholder { + self.visit_invoc_in_module(variant.id); + return; + } + + let parent = self.parent_scope.module; + let expn_id = self.parent_scope.expansion; + let ident = variant.ident; + + // Define a name in the type namespace. + let def_id = self.r.local_def_id(variant.id); + let res = Res::Def(DefKind::Variant, def_id.to_def_id()); + let vis = self.resolve_visibility(&variant.vis); + self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id)); + self.r.visibilities.insert(def_id, vis); + + // If the variant is marked as non_exhaustive then lower the visibility to within the crate. + let ctor_vis = if vis == ty::Visibility::Public + && self.r.session.contains_name(&variant.attrs, sym::non_exhaustive) + { + ty::Visibility::Restricted(CRATE_DEF_ID.to_def_id()) + } else { + vis + }; + + // Define a constructor name in the value namespace. + // Braced variants, unlike structs, generate unusable names in + // value namespace, they are reserved for possible future use. + // It's ok to use the variant's id as a ctor id since an + // error will be reported on any use of such resolution anyway. + let ctor_node_id = variant.data.ctor_id().unwrap_or(variant.id); + let ctor_def_id = self.r.local_def_id(ctor_node_id); + let ctor_kind = CtorKind::from_ast(&variant.data); + let ctor_res = Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id.to_def_id()); + self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id)); + if ctor_def_id != def_id { + self.r.visibilities.insert(ctor_def_id, ctor_vis); + } + // Record field names for error reporting. + self.insert_field_names_local(ctor_def_id.to_def_id(), &variant.data); + + visit::walk_variant(self, variant); + } + + fn visit_crate(&mut self, krate: &'b ast::Crate) { + if krate.is_placeholder { + self.visit_invoc_in_module(krate.id); + } else { + visit::walk_crate(self, krate); + self.contains_macro_use(&krate.attrs); + } + } +} diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs new file mode 100644 index 000000000..f2f6f1d89 --- /dev/null +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -0,0 +1,350 @@ +// +// Unused import checking +// +// Although this is mostly a lint pass, it lives in here because it depends on +// resolve data structures and because it finalises the privacy information for +// `use` items. +// +// Unused trait imports can't be checked until the method resolution. We save +// candidates here, and do the actual check in librustc_typeck/check_unused.rs. +// +// Checking for unused imports is split into three steps: +// +// - `UnusedImportCheckVisitor` walks the AST to find all the unused imports +// inside of `UseTree`s, recording their `NodeId`s and grouping them by +// the parent `use` item +// +// - `calc_unused_spans` then walks over all the `use` items marked in the +// previous step to collect the spans associated with the `NodeId`s and to +// calculate the spans that can be removed by rustfix; This is done in a +// separate step to be able to collapse the adjacent spans that rustfix +// will remove +// +// - `check_crate` finally emits the diagnostics based on the data generated +// in the last step + +use crate::imports::ImportKind; +use crate::module_to_string; +use crate::Resolver; + +use rustc_ast as ast; +use rustc_ast::node_id::NodeMap; +use rustc_ast::visit::{self, Visitor}; +use rustc_data_structures::fx::FxHashSet; +use rustc_errors::{pluralize, MultiSpan}; +use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS}; +use rustc_session::lint::BuiltinLintDiagnostics; +use rustc_span::{Span, DUMMY_SP}; + +struct UnusedImport<'a> { + use_tree: &'a ast::UseTree, + use_tree_id: ast::NodeId, + item_span: Span, + unused: FxHashSet<ast::NodeId>, +} + +impl<'a> UnusedImport<'a> { + fn add(&mut self, id: ast::NodeId) { + self.unused.insert(id); + } +} + +struct UnusedImportCheckVisitor<'a, 'b> { + r: &'a mut Resolver<'b>, + /// All the (so far) unused imports, grouped path list + unused_imports: NodeMap<UnusedImport<'a>>, + base_use_tree: Option<&'a ast::UseTree>, + base_id: ast::NodeId, + item_span: Span, +} + +impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> { + // We have information about whether `use` (import) items are actually + // used now. If an import is not used at all, we signal a lint error. + fn check_import(&mut self, id: ast::NodeId) { + let used = self.r.used_imports.contains(&id); + let def_id = self.r.local_def_id(id); + if !used { + if self.r.maybe_unused_trait_imports.contains(&def_id) { + // Check later. + return; + } + self.unused_import(self.base_id).add(id); + } else { + // This trait import is definitely used, in a way other than + // method resolution. + self.r.maybe_unused_trait_imports.remove(&def_id); + if let Some(i) = self.unused_imports.get_mut(&self.base_id) { + i.unused.remove(&id); + } + } + } + + fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> { + let use_tree_id = self.base_id; + let use_tree = self.base_use_tree.unwrap(); + let item_span = self.item_span; + + self.unused_imports.entry(id).or_insert_with(|| UnusedImport { + use_tree, + use_tree_id, + item_span, + unused: FxHashSet::default(), + }) + } +} + +impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> { + fn visit_item(&mut self, item: &'a ast::Item) { + self.item_span = item.span_with_attributes(); + + // Ignore is_public import statements because there's no way to be sure + // whether they're used or not. Also ignore imports with a dummy span + // because this means that they were generated in some fashion by the + // compiler and we don't need to consider them. + if let ast::ItemKind::Use(..) = item.kind { + if item.vis.kind.is_pub() || item.span.is_dummy() { + return; + } + } + + visit::walk_item(self, item); + } + + fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) { + // Use the base UseTree's NodeId as the item id + // This allows the grouping of all the lints in the same item + if !nested { + self.base_id = id; + self.base_use_tree = Some(use_tree); + } + + if let ast::UseTreeKind::Nested(ref items) = use_tree.kind { + if items.is_empty() { + self.unused_import(self.base_id).add(id); + } + } else { + self.check_import(id); + } + + visit::walk_use_tree(self, use_tree, id); + } +} + +enum UnusedSpanResult { + Used, + FlatUnused(Span, Span), + NestedFullUnused(Vec<Span>, Span), + NestedPartialUnused(Vec<Span>, Vec<Span>), +} + +fn calc_unused_spans( + unused_import: &UnusedImport<'_>, + use_tree: &ast::UseTree, + use_tree_id: ast::NodeId, +) -> UnusedSpanResult { + // The full span is the whole item's span if this current tree is not nested inside another + // This tells rustfix to remove the whole item if all the imports are unused + let full_span = if unused_import.use_tree.span == use_tree.span { + unused_import.item_span + } else { + use_tree.span + }; + match use_tree.kind { + ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => { + if unused_import.unused.contains(&use_tree_id) { + UnusedSpanResult::FlatUnused(use_tree.span, full_span) + } else { + UnusedSpanResult::Used + } + } + ast::UseTreeKind::Nested(ref nested) => { + if nested.is_empty() { + return UnusedSpanResult::FlatUnused(use_tree.span, full_span); + } + + let mut unused_spans = Vec::new(); + let mut to_remove = Vec::new(); + let mut all_nested_unused = true; + let mut previous_unused = false; + for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() { + let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) { + UnusedSpanResult::Used => { + all_nested_unused = false; + None + } + UnusedSpanResult::FlatUnused(span, remove) => { + unused_spans.push(span); + Some(remove) + } + UnusedSpanResult::NestedFullUnused(mut spans, remove) => { + unused_spans.append(&mut spans); + Some(remove) + } + UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => { + all_nested_unused = false; + unused_spans.append(&mut spans); + to_remove.append(&mut to_remove_extra); + None + } + }; + if let Some(remove) = remove { + let remove_span = if nested.len() == 1 { + remove + } else if pos == nested.len() - 1 || !all_nested_unused { + // Delete everything from the end of the last import, to delete the + // previous comma + nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span) + } else { + // Delete everything until the next import, to delete the trailing commas + use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo()) + }; + + // Try to collapse adjacent spans into a single one. This prevents all cases of + // overlapping removals, which are not supported by rustfix + if previous_unused && !to_remove.is_empty() { + let previous = to_remove.pop().unwrap(); + to_remove.push(previous.to(remove_span)); + } else { + to_remove.push(remove_span); + } + } + previous_unused = remove.is_some(); + } + if unused_spans.is_empty() { + UnusedSpanResult::Used + } else if all_nested_unused { + UnusedSpanResult::NestedFullUnused(unused_spans, full_span) + } else { + UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove) + } + } + } +} + +impl Resolver<'_> { + pub(crate) fn check_unused(&mut self, krate: &ast::Crate) { + for import in self.potentially_unused_imports.iter() { + match import.kind { + _ if import.used.get() + || import.vis.get().is_public() + || import.span.is_dummy() => + { + if let ImportKind::MacroUse = import.kind { + if !import.span.is_dummy() { + self.lint_buffer.buffer_lint( + MACRO_USE_EXTERN_CRATE, + import.id, + import.span, + "deprecated `#[macro_use]` attribute used to \ + import macros should be replaced at use sites \ + with a `use` item to import the macro \ + instead", + ); + } + } + } + ImportKind::ExternCrate { .. } => { + let def_id = self.local_def_id(import.id); + self.maybe_unused_extern_crates.push((def_id, import.span)); + } + ImportKind::MacroUse => { + let msg = "unused `#[macro_use]` import"; + self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); + } + _ => {} + } + } + + let mut visitor = UnusedImportCheckVisitor { + r: self, + unused_imports: Default::default(), + base_use_tree: None, + base_id: ast::DUMMY_NODE_ID, + item_span: DUMMY_SP, + }; + visit::walk_crate(&mut visitor, krate); + + for unused in visitor.unused_imports.values() { + let mut fixes = Vec::new(); + let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) { + UnusedSpanResult::Used => continue, + UnusedSpanResult::FlatUnused(span, remove) => { + fixes.push((remove, String::new())); + vec![span] + } + UnusedSpanResult::NestedFullUnused(spans, remove) => { + fixes.push((remove, String::new())); + spans + } + UnusedSpanResult::NestedPartialUnused(spans, remove) => { + for fix in &remove { + fixes.push((*fix, String::new())); + } + spans + } + }; + + let len = spans.len(); + spans.sort(); + let ms = MultiSpan::from_spans(spans.clone()); + let mut span_snippets = spans + .iter() + .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) { + Ok(s) => Some(format!("`{}`", s)), + _ => None, + }) + .collect::<Vec<String>>(); + span_snippets.sort(); + let msg = format!( + "unused import{}{}", + pluralize!(len), + if !span_snippets.is_empty() { + format!(": {}", span_snippets.join(", ")) + } else { + String::new() + } + ); + + let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span { + "remove the whole `use` item" + } else if spans.len() > 1 { + "remove the unused imports" + } else { + "remove the unused import" + }; + + // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]` + // attribute; however, if not, suggest adding the attribute. There is no way to + // retrieve attributes here because we do not have a `TyCtxt` yet. + let test_module_span = if visitor.r.session.opts.test { + None + } else { + let parent_module = visitor.r.get_nearest_non_block_module( + visitor.r.local_def_id(unused.use_tree_id).to_def_id(), + ); + match module_to_string(parent_module) { + Some(module) + if module == "test" + || module == "tests" + || module.starts_with("test_") + || module.starts_with("tests_") + || module.ends_with("_test") + || module.ends_with("_tests") => + { + Some(parent_module.span) + } + _ => None, + } + }; + + visitor.r.lint_buffer.buffer_lint_with_diagnostic( + UNUSED_IMPORTS, + unused.use_tree_id, + ms, + &msg, + BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes, test_module_span), + ); + } + } +} diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs new file mode 100644 index 000000000..66641fb2c --- /dev/null +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -0,0 +1,354 @@ +use crate::{ImplTraitContext, Resolver}; +use rustc_ast::visit::{self, FnKind}; +use rustc_ast::walk_list; +use rustc_ast::*; +use rustc_expand::expand::AstFragment; +use rustc_hir::def_id::LocalDefId; +use rustc_hir::definitions::*; +use rustc_span::hygiene::LocalExpnId; +use rustc_span::symbol::sym; +use rustc_span::Span; +use tracing::debug; + +pub(crate) fn collect_definitions( + resolver: &mut Resolver<'_>, + fragment: &AstFragment, + expansion: LocalExpnId, +) { + let (parent_def, impl_trait_context) = resolver.invocation_parents[&expansion]; + fragment.visit_with(&mut DefCollector { resolver, parent_def, expansion, impl_trait_context }); +} + +/// Creates `DefId`s for nodes in the AST. +struct DefCollector<'a, 'b> { + resolver: &'a mut Resolver<'b>, + parent_def: LocalDefId, + impl_trait_context: ImplTraitContext, + expansion: LocalExpnId, +} + +impl<'a, 'b> DefCollector<'a, 'b> { + fn create_def(&mut self, node_id: NodeId, data: DefPathData, span: Span) -> LocalDefId { + let parent_def = self.parent_def; + debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def); + self.resolver.create_def( + parent_def, + node_id, + data, + self.expansion.to_expn_id(), + span.with_parent(None), + ) + } + + fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) { + let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def); + f(self); + self.parent_def = orig_parent_def; + } + + fn with_impl_trait<F: FnOnce(&mut Self)>( + &mut self, + impl_trait_context: ImplTraitContext, + f: F, + ) { + let orig_itc = std::mem::replace(&mut self.impl_trait_context, impl_trait_context); + f(self); + self.impl_trait_context = orig_itc; + } + + fn collect_field(&mut self, field: &'a FieldDef, index: Option<usize>) { + let index = |this: &Self| { + index.unwrap_or_else(|| { + let node_id = NodeId::placeholder_from_expn_id(this.expansion); + this.resolver.placeholder_field_indices[&node_id] + }) + }; + + if field.is_placeholder { + let old_index = self.resolver.placeholder_field_indices.insert(field.id, index(self)); + assert!(old_index.is_none(), "placeholder field index is reset for a node ID"); + self.visit_macro_invoc(field.id); + } else { + let name = field.ident.map_or_else(|| sym::integer(index(self)), |ident| ident.name); + let def = self.create_def(field.id, DefPathData::ValueNs(name), field.span); + self.with_parent(def, |this| visit::walk_field_def(this, field)); + } + } + + fn visit_macro_invoc(&mut self, id: NodeId) { + let id = id.placeholder_to_expn_id(); + let old_parent = + self.resolver.invocation_parents.insert(id, (self.parent_def, self.impl_trait_context)); + assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation"); + } +} + +impl<'a, 'b> visit::Visitor<'a> for DefCollector<'a, 'b> { + fn visit_item(&mut self, i: &'a Item) { + debug!("visit_item: {:?}", i); + + // Pick the def data. This need not be unique, but the more + // information we encapsulate into, the better + let def_data = match &i.kind { + ItemKind::Impl { .. } => DefPathData::Impl, + ItemKind::ForeignMod(..) => DefPathData::ForeignMod, + ItemKind::Mod(..) + | ItemKind::Trait(..) + | ItemKind::TraitAlias(..) + | ItemKind::Enum(..) + | ItemKind::Struct(..) + | ItemKind::Union(..) + | ItemKind::ExternCrate(..) + | ItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name), + ItemKind::Static(..) | ItemKind::Const(..) | ItemKind::Fn(..) => { + DefPathData::ValueNs(i.ident.name) + } + ItemKind::MacroDef(..) => DefPathData::MacroNs(i.ident.name), + ItemKind::MacCall(..) => { + visit::walk_item(self, i); + return self.visit_macro_invoc(i.id); + } + ItemKind::GlobalAsm(..) => DefPathData::GlobalAsm, + ItemKind::Use(..) => { + return visit::walk_item(self, i); + } + }; + let def = self.create_def(i.id, def_data, i.span); + + self.with_parent(def, |this| { + this.with_impl_trait(ImplTraitContext::Existential, |this| { + match i.kind { + ItemKind::Struct(ref struct_def, _) | ItemKind::Union(ref struct_def, _) => { + // If this is a unit or tuple-like struct, register the constructor. + if let Some(ctor_hir_id) = struct_def.ctor_id() { + this.create_def(ctor_hir_id, DefPathData::Ctor, i.span); + } + } + _ => {} + } + visit::walk_item(this, i); + }) + }); + } + + fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) { + if let FnKind::Fn(_, _, sig, _, generics, body) = fn_kind { + if let Async::Yes { closure_id, return_impl_trait_id, .. } = sig.header.asyncness { + self.visit_generics(generics); + + let return_impl_trait_id = + self.create_def(return_impl_trait_id, DefPathData::ImplTrait, span); + + // For async functions, we need to create their inner defs inside of a + // closure to match their desugared representation. Besides that, + // we must mirror everything that `visit::walk_fn` below does. + self.visit_fn_header(&sig.header); + for param in &sig.decl.inputs { + self.visit_param(param); + } + self.with_parent(return_impl_trait_id, |this| { + this.visit_fn_ret_ty(&sig.decl.output) + }); + let closure_def = self.create_def(closure_id, DefPathData::ClosureExpr, span); + self.with_parent(closure_def, |this| walk_list!(this, visit_block, body)); + return; + } + } + + visit::walk_fn(self, fn_kind, span); + } + + fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) { + self.create_def(id, DefPathData::Use, use_tree.span); + match use_tree.kind { + UseTreeKind::Simple(_, id1, id2) => { + self.create_def(id1, DefPathData::Use, use_tree.prefix.span); + self.create_def(id2, DefPathData::Use, use_tree.prefix.span); + } + UseTreeKind::Glob => (), + UseTreeKind::Nested(..) => {} + } + visit::walk_use_tree(self, use_tree, id); + } + + fn visit_foreign_item(&mut self, foreign_item: &'a ForeignItem) { + if let ForeignItemKind::MacCall(_) = foreign_item.kind { + return self.visit_macro_invoc(foreign_item.id); + } + + let def = self.create_def( + foreign_item.id, + DefPathData::ValueNs(foreign_item.ident.name), + foreign_item.span, + ); + + self.with_parent(def, |this| { + visit::walk_foreign_item(this, foreign_item); + }); + } + + fn visit_variant(&mut self, v: &'a Variant) { + if v.is_placeholder { + return self.visit_macro_invoc(v.id); + } + let def = self.create_def(v.id, DefPathData::TypeNs(v.ident.name), v.span); + self.with_parent(def, |this| { + if let Some(ctor_hir_id) = v.data.ctor_id() { + this.create_def(ctor_hir_id, DefPathData::Ctor, v.span); + } + visit::walk_variant(this, v) + }); + } + + fn visit_variant_data(&mut self, data: &'a VariantData) { + // The assumption here is that non-`cfg` macro expansion cannot change field indices. + // It currently holds because only inert attributes are accepted on fields, + // and every such attribute expands into a single field after it's resolved. + for (index, field) in data.fields().iter().enumerate() { + self.collect_field(field, Some(index)); + } + } + + fn visit_generic_param(&mut self, param: &'a GenericParam) { + if param.is_placeholder { + self.visit_macro_invoc(param.id); + return; + } + let name = param.ident.name; + let def_path_data = match param.kind { + GenericParamKind::Lifetime { .. } => DefPathData::LifetimeNs(name), + GenericParamKind::Type { .. } => DefPathData::TypeNs(name), + GenericParamKind::Const { .. } => DefPathData::ValueNs(name), + }; + self.create_def(param.id, def_path_data, param.ident.span); + + // impl-Trait can happen inside generic parameters, like + // ``` + // fn foo<U: Iterator<Item = impl Clone>>() {} + // ``` + // + // In that case, the impl-trait is lowered as an additional generic parameter. + self.with_impl_trait(ImplTraitContext::Universal(self.parent_def), |this| { + visit::walk_generic_param(this, param) + }); + } + + fn visit_assoc_item(&mut self, i: &'a AssocItem, ctxt: visit::AssocCtxt) { + let def_data = match &i.kind { + AssocItemKind::Fn(..) | AssocItemKind::Const(..) => DefPathData::ValueNs(i.ident.name), + AssocItemKind::TyAlias(..) => DefPathData::TypeNs(i.ident.name), + AssocItemKind::MacCall(..) => return self.visit_macro_invoc(i.id), + }; + + let def = self.create_def(i.id, def_data, i.span); + self.with_parent(def, |this| visit::walk_assoc_item(this, i, ctxt)); + } + + fn visit_pat(&mut self, pat: &'a Pat) { + match pat.kind { + PatKind::MacCall(..) => self.visit_macro_invoc(pat.id), + _ => visit::walk_pat(self, pat), + } + } + + fn visit_anon_const(&mut self, constant: &'a AnonConst) { + let def = self.create_def(constant.id, DefPathData::AnonConst, constant.value.span); + self.with_parent(def, |this| visit::walk_anon_const(this, constant)); + } + + fn visit_expr(&mut self, expr: &'a Expr) { + let parent_def = match expr.kind { + ExprKind::MacCall(..) => return self.visit_macro_invoc(expr.id), + ExprKind::Closure(_, _, asyncness, ..) => { + // Async closures desugar to closures inside of closures, so + // we must create two defs. + let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span); + match asyncness { + Async::Yes { closure_id, .. } => { + self.create_def(closure_id, DefPathData::ClosureExpr, expr.span) + } + Async::No => closure_def, + } + } + ExprKind::Async(_, async_id, _) => { + self.create_def(async_id, DefPathData::ClosureExpr, expr.span) + } + _ => self.parent_def, + }; + + self.with_parent(parent_def, |this| visit::walk_expr(this, expr)); + } + + fn visit_ty(&mut self, ty: &'a Ty) { + match ty.kind { + TyKind::MacCall(..) => self.visit_macro_invoc(ty.id), + TyKind::ImplTrait(node_id, _) => { + let parent_def = match self.impl_trait_context { + ImplTraitContext::Universal(item_def) => self.resolver.create_def( + item_def, + node_id, + DefPathData::ImplTrait, + self.expansion.to_expn_id(), + ty.span, + ), + ImplTraitContext::Existential => { + self.create_def(node_id, DefPathData::ImplTrait, ty.span) + } + }; + self.with_parent(parent_def, |this| visit::walk_ty(this, ty)) + } + _ => visit::walk_ty(self, ty), + } + } + + fn visit_stmt(&mut self, stmt: &'a Stmt) { + match stmt.kind { + StmtKind::MacCall(..) => self.visit_macro_invoc(stmt.id), + _ => visit::walk_stmt(self, stmt), + } + } + + fn visit_arm(&mut self, arm: &'a Arm) { + if arm.is_placeholder { self.visit_macro_invoc(arm.id) } else { visit::walk_arm(self, arm) } + } + + fn visit_expr_field(&mut self, f: &'a ExprField) { + if f.is_placeholder { + self.visit_macro_invoc(f.id) + } else { + visit::walk_expr_field(self, f) + } + } + + fn visit_pat_field(&mut self, fp: &'a PatField) { + if fp.is_placeholder { + self.visit_macro_invoc(fp.id) + } else { + visit::walk_pat_field(self, fp) + } + } + + fn visit_param(&mut self, p: &'a Param) { + if p.is_placeholder { + self.visit_macro_invoc(p.id) + } else { + self.with_impl_trait(ImplTraitContext::Universal(self.parent_def), |this| { + visit::walk_param(this, p) + }) + } + } + + // This method is called only when we are visiting an individual field + // after expanding an attribute on it. + fn visit_field_def(&mut self, field: &'a FieldDef) { + self.collect_field(field, None); + } + + fn visit_crate(&mut self, krate: &'a Crate) { + if krate.is_placeholder { + self.visit_macro_invoc(krate.id) + } else { + visit::walk_crate(self, krate) + } + } +} diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs new file mode 100644 index 000000000..8839fb1a1 --- /dev/null +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -0,0 +1,2714 @@ +use std::ptr; + +use rustc_ast::ptr::P; +use rustc_ast::visit::{self, Visitor}; +use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID}; +use rustc_ast_pretty::pprust; +use rustc_data_structures::fx::FxHashSet; +use rustc_errors::struct_span_err; +use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan}; +use rustc_feature::BUILTIN_ATTRIBUTES; +use rustc_hir::def::Namespace::{self, *}; +use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS}; +use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::PrimTy; +use rustc_index::vec::IndexVec; +use rustc_middle::bug; +use rustc_middle::ty::DefIdTree; +use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE; +use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS; +use rustc_session::lint::BuiltinLintDiagnostics; +use rustc_session::Session; +use rustc_span::edition::Edition; +use rustc_span::hygiene::MacroKind; +use rustc_span::lev_distance::find_best_match_for_name; +use rustc_span::source_map::SourceMap; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::{BytePos, Span}; +use tracing::debug; + +use crate::imports::{Import, ImportKind, ImportResolver}; +use crate::late::{PatternSource, Rib}; +use crate::path_names_to_string; +use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize}; +use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot}; +use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError}; +use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet}; +use crate::{Segment, UseError}; + +#[cfg(test)] +mod tests; + +type Res = def::Res<ast::NodeId>; + +/// A vector of spans and replacements, a message and applicability. +pub(crate) type Suggestion = (Vec<(Span, String)>, String, Applicability); + +/// Potential candidate for an undeclared or out-of-scope label - contains the ident of a +/// similarly named label and whether or not it is reachable. +pub(crate) type LabelSuggestion = (Ident, bool); + +pub(crate) enum SuggestionTarget { + /// The target has a similar name as the name used by the programmer (probably a typo) + SimilarlyNamed, + /// The target is the only valid item that can be used in the corresponding context + SingleItem, +} + +pub(crate) struct TypoSuggestion { + pub candidate: Symbol, + pub res: Res, + pub target: SuggestionTarget, +} + +impl TypoSuggestion { + pub(crate) fn typo_from_res(candidate: Symbol, res: Res) -> TypoSuggestion { + Self { candidate, res, target: SuggestionTarget::SimilarlyNamed } + } + pub(crate) fn single_item_from_res(candidate: Symbol, res: Res) -> TypoSuggestion { + Self { candidate, res, target: SuggestionTarget::SingleItem } + } +} + +/// A free importable items suggested in case of resolution failure. +pub(crate) struct ImportSuggestion { + pub did: Option<DefId>, + pub descr: &'static str, + pub path: Path, + pub accessible: bool, + /// An extra note that should be issued if this item is suggested + pub note: Option<String>, +} + +/// Adjust the impl span so that just the `impl` keyword is taken by removing +/// everything after `<` (`"impl<T> Iterator for A<T> {}" -> "impl"`) and +/// everything after the first whitespace (`"impl Iterator for A" -> "impl"`). +/// +/// *Attention*: the method used is very fragile since it essentially duplicates the work of the +/// parser. If you need to use this function or something similar, please consider updating the +/// `source_map` functions and this function to something more robust. +fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span { + let impl_span = sm.span_until_char(impl_span, '<'); + sm.span_until_whitespace(impl_span) +} + +impl<'a> Resolver<'a> { + pub(crate) fn report_errors(&mut self, krate: &Crate) { + self.report_with_use_injections(krate); + + for &(span_use, span_def) in &self.macro_expanded_macro_export_errors { + let msg = "macro-expanded `macro_export` macros from the current crate \ + cannot be referred to by absolute paths"; + self.lint_buffer.buffer_lint_with_diagnostic( + MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, + CRATE_NODE_ID, + span_use, + msg, + BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def), + ); + } + + for ambiguity_error in &self.ambiguity_errors { + self.report_ambiguity_error(ambiguity_error); + } + + let mut reported_spans = FxHashSet::default(); + for error in &self.privacy_errors { + if reported_spans.insert(error.dedup_span) { + self.report_privacy_error(error); + } + } + } + + fn report_with_use_injections(&mut self, krate: &Crate) { + for UseError { mut err, candidates, def_id, instead, suggestion, path } in + self.use_injections.drain(..) + { + let (span, found_use) = if let Some(def_id) = def_id.as_local() { + UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]) + } else { + (None, FoundUse::No) + }; + if !candidates.is_empty() { + show_candidates( + &self.session, + &self.source_span, + &mut err, + span, + &candidates, + if instead { Instead::Yes } else { Instead::No }, + found_use, + IsPattern::No, + path, + ); + } else if let Some((span, msg, sugg, appl)) = suggestion { + err.span_suggestion(span, msg, sugg, appl); + } + err.emit(); + } + } + + pub(crate) fn report_conflict<'b>( + &mut self, + parent: Module<'_>, + ident: Ident, + ns: Namespace, + new_binding: &NameBinding<'b>, + old_binding: &NameBinding<'b>, + ) { + // Error on the second of two conflicting names + if old_binding.span.lo() > new_binding.span.lo() { + return self.report_conflict(parent, ident, ns, old_binding, new_binding); + } + + let container = match parent.kind { + ModuleKind::Def(kind, _, _) => kind.descr(parent.def_id()), + ModuleKind::Block => "block", + }; + + let old_noun = match old_binding.is_import() { + true => "import", + false => "definition", + }; + + let new_participle = match new_binding.is_import() { + true => "imported", + false => "defined", + }; + + let (name, span) = + (ident.name, self.session.source_map().guess_head_span(new_binding.span)); + + if let Some(s) = self.name_already_seen.get(&name) { + if s == &span { + return; + } + } + + let old_kind = match (ns, old_binding.module()) { + (ValueNS, _) => "value", + (MacroNS, _) => "macro", + (TypeNS, _) if old_binding.is_extern_crate() => "extern crate", + (TypeNS, Some(module)) if module.is_normal() => "module", + (TypeNS, Some(module)) if module.is_trait() => "trait", + (TypeNS, _) => "type", + }; + + let msg = format!("the name `{}` is defined multiple times", name); + + let mut err = match (old_binding.is_extern_crate(), new_binding.is_extern_crate()) { + (true, true) => struct_span_err!(self.session, span, E0259, "{}", msg), + (true, _) | (_, true) => match new_binding.is_import() && old_binding.is_import() { + true => struct_span_err!(self.session, span, E0254, "{}", msg), + false => struct_span_err!(self.session, span, E0260, "{}", msg), + }, + _ => match (old_binding.is_import(), new_binding.is_import()) { + (false, false) => struct_span_err!(self.session, span, E0428, "{}", msg), + (true, true) => struct_span_err!(self.session, span, E0252, "{}", msg), + _ => struct_span_err!(self.session, span, E0255, "{}", msg), + }, + }; + + err.note(&format!( + "`{}` must be defined only once in the {} namespace of this {}", + name, + ns.descr(), + container + )); + + err.span_label(span, format!("`{}` re{} here", name, new_participle)); + err.span_label( + self.session.source_map().guess_head_span(old_binding.span), + format!("previous {} of the {} `{}` here", old_noun, old_kind, name), + ); + + // See https://github.com/rust-lang/rust/issues/32354 + use NameBindingKind::Import; + let import = match (&new_binding.kind, &old_binding.kind) { + // If there are two imports where one or both have attributes then prefer removing the + // import without attributes. + (Import { import: new, .. }, Import { import: old, .. }) + if { + !new_binding.span.is_dummy() + && !old_binding.span.is_dummy() + && (new.has_attributes || old.has_attributes) + } => + { + if old.has_attributes { + Some((new, new_binding.span, true)) + } else { + Some((old, old_binding.span, true)) + } + } + // Otherwise prioritize the new binding. + (Import { import, .. }, other) if !new_binding.span.is_dummy() => { + Some((import, new_binding.span, other.is_import())) + } + (other, Import { import, .. }) if !old_binding.span.is_dummy() => { + Some((import, old_binding.span, other.is_import())) + } + _ => None, + }; + + // Check if the target of the use for both bindings is the same. + let duplicate = new_binding.res().opt_def_id() == old_binding.res().opt_def_id(); + let has_dummy_span = new_binding.span.is_dummy() || old_binding.span.is_dummy(); + let from_item = + self.extern_prelude.get(&ident).map_or(true, |entry| entry.introduced_by_item); + // Only suggest removing an import if both bindings are to the same def, if both spans + // aren't dummy spans. Further, if both bindings are imports, then the ident must have + // been introduced by an item. + let should_remove_import = duplicate + && !has_dummy_span + && ((new_binding.is_extern_crate() || old_binding.is_extern_crate()) || from_item); + + match import { + Some((import, span, true)) if should_remove_import && import.is_nested() => { + self.add_suggestion_for_duplicate_nested_use(&mut err, import, span) + } + Some((import, _, true)) if should_remove_import && !import.is_glob() => { + // Simple case - remove the entire import. Due to the above match arm, this can + // only be a single use so just remove it entirely. + err.tool_only_span_suggestion( + import.use_span_with_attributes, + "remove unnecessary import", + "", + Applicability::MaybeIncorrect, + ); + } + Some((import, span, _)) => { + self.add_suggestion_for_rename_of_use(&mut err, name, import, span) + } + _ => {} + } + + err.emit(); + self.name_already_seen.insert(name, span); + } + + /// This function adds a suggestion to change the binding name of a new import that conflicts + /// with an existing import. + /// + /// ```text,ignore (diagnostic) + /// help: you can use `as` to change the binding name of the import + /// | + /// LL | use foo::bar as other_bar; + /// | ^^^^^^^^^^^^^^^^^^^^^ + /// ``` + fn add_suggestion_for_rename_of_use( + &self, + err: &mut Diagnostic, + name: Symbol, + import: &Import<'_>, + binding_span: Span, + ) { + let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { + format!("Other{}", name) + } else { + format!("other_{}", name) + }; + + let mut suggestion = None; + match import.kind { + ImportKind::Single { type_ns_only: true, .. } => { + suggestion = Some(format!("self as {}", suggested_name)) + } + ImportKind::Single { source, .. } => { + if let Some(pos) = + source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize) + { + if let Ok(snippet) = self.session.source_map().span_to_snippet(binding_span) { + if pos <= snippet.len() { + suggestion = Some(format!( + "{} as {}{}", + &snippet[..pos], + suggested_name, + if snippet.ends_with(';') { ";" } else { "" } + )) + } + } + } + } + ImportKind::ExternCrate { source, target } => { + suggestion = Some(format!( + "extern crate {} as {};", + source.unwrap_or(target.name), + suggested_name, + )) + } + _ => unreachable!(), + } + + let rename_msg = "you can use `as` to change the binding name of the import"; + if let Some(suggestion) = suggestion { + err.span_suggestion( + binding_span, + rename_msg, + suggestion, + Applicability::MaybeIncorrect, + ); + } else { + err.span_label(binding_span, rename_msg); + } + } + + /// This function adds a suggestion to remove an unnecessary binding from an import that is + /// nested. In the following example, this function will be invoked to remove the `a` binding + /// in the second use statement: + /// + /// ```ignore (diagnostic) + /// use issue_52891::a; + /// use issue_52891::{d, a, e}; + /// ``` + /// + /// The following suggestion will be added: + /// + /// ```ignore (diagnostic) + /// use issue_52891::{d, a, e}; + /// ^-- help: remove unnecessary import + /// ``` + /// + /// If the nested use contains only one import then the suggestion will remove the entire + /// line. + /// + /// It is expected that the provided import is nested - this isn't checked by the + /// function. If this invariant is not upheld, this function's behaviour will be unexpected + /// as characters expected by span manipulations won't be present. + fn add_suggestion_for_duplicate_nested_use( + &self, + err: &mut Diagnostic, + import: &Import<'_>, + binding_span: Span, + ) { + assert!(import.is_nested()); + let message = "remove unnecessary import"; + + // Two examples will be used to illustrate the span manipulations we're doing: + // + // - Given `use issue_52891::{d, a, e};` where `a` is a duplicate then `binding_span` is + // `a` and `import.use_span` is `issue_52891::{d, a, e};`. + // - Given `use issue_52891::{d, e, a};` where `a` is a duplicate then `binding_span` is + // `a` and `import.use_span` is `issue_52891::{d, e, a};`. + + let (found_closing_brace, span) = + find_span_of_binding_until_next_binding(self.session, binding_span, import.use_span); + + // If there was a closing brace then identify the span to remove any trailing commas from + // previous imports. + if found_closing_brace { + if let Some(span) = extend_span_to_previous_binding(self.session, span) { + err.tool_only_span_suggestion(span, message, "", Applicability::MaybeIncorrect); + } else { + // Remove the entire line if we cannot extend the span back, this indicates an + // `issue_52891::{self}` case. + err.span_suggestion( + import.use_span_with_attributes, + message, + "", + Applicability::MaybeIncorrect, + ); + } + + return; + } + + err.span_suggestion(span, message, "", Applicability::MachineApplicable); + } + + pub(crate) fn lint_if_path_starts_with_module( + &mut self, + finalize: Option<Finalize>, + path: &[Segment], + second_binding: Option<&NameBinding<'_>>, + ) { + let Some(Finalize { node_id, root_span, .. }) = finalize else { + return; + }; + + let first_name = match path.get(0) { + // In the 2018 edition this lint is a hard error, so nothing to do + Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name, + _ => return, + }; + + // We're only interested in `use` paths which should start with + // `{{root}}` currently. + if first_name != kw::PathRoot { + return; + } + + match path.get(1) { + // If this import looks like `crate::...` it's already good + Some(Segment { ident, .. }) if ident.name == kw::Crate => return, + // Otherwise go below to see if it's an extern crate + Some(_) => {} + // If the path has length one (and it's `PathRoot` most likely) + // then we don't know whether we're gonna be importing a crate or an + // item in our crate. Defer this lint to elsewhere + None => return, + } + + // If the first element of our path was actually resolved to an + // `ExternCrate` (also used for `crate::...`) then no need to issue a + // warning, this looks all good! + if let Some(binding) = second_binding { + if let NameBindingKind::Import { import, .. } = binding.kind { + // Careful: we still want to rewrite paths from renamed extern crates. + if let ImportKind::ExternCrate { source: None, .. } = import.kind { + return; + } + } + } + + let diag = BuiltinLintDiagnostics::AbsPathWithModule(root_span); + self.lint_buffer.buffer_lint_with_diagnostic( + ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, + node_id, + root_span, + "absolute paths must start with `self`, `super`, \ + `crate`, or an external crate name in the 2018 edition", + diag, + ); + } + + pub(crate) fn add_module_candidates( + &mut self, + module: Module<'a>, + names: &mut Vec<TypoSuggestion>, + filter_fn: &impl Fn(Res) -> bool, + ) { + for (key, resolution) in self.resolutions(module).borrow().iter() { + if let Some(binding) = resolution.borrow().binding { + let res = binding.res(); + if filter_fn(res) { + names.push(TypoSuggestion::typo_from_res(key.ident.name, res)); + } + } + } + } + + /// Combines an error with provided span and emits it. + /// + /// This takes the error provided, combines it with the span and any additional spans inside the + /// error and emits it. + pub(crate) fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) { + self.into_struct_error(span, resolution_error).emit(); + } + + pub(crate) fn into_struct_error( + &mut self, + span: Span, + resolution_error: ResolutionError<'a>, + ) -> DiagnosticBuilder<'_, ErrorGuaranteed> { + match resolution_error { + ResolutionError::GenericParamsFromOuterFunction(outer_res, has_generic_params) => { + let mut err = struct_span_err!( + self.session, + span, + E0401, + "can't use generic parameters from outer function", + ); + err.span_label(span, "use of generic parameter from outer function"); + + let sm = self.session.source_map(); + match outer_res { + Res::SelfTy { trait_: maybe_trait_defid, alias_to: maybe_impl_defid } => { + if let Some(impl_span) = + maybe_impl_defid.and_then(|(def_id, _)| self.opt_span(def_id)) + { + err.span_label( + reduce_impl_span_to_impl_keyword(sm, impl_span), + "`Self` type implicitly declared here, by this `impl`", + ); + } + match (maybe_trait_defid, maybe_impl_defid) { + (Some(_), None) => { + err.span_label(span, "can't use `Self` here"); + } + (_, Some(_)) => { + err.span_label(span, "use a type here instead"); + } + (None, None) => bug!("`impl` without trait nor type?"), + } + return err; + } + Res::Def(DefKind::TyParam, def_id) => { + if let Some(span) = self.opt_span(def_id) { + err.span_label(span, "type parameter from outer function"); + } + } + Res::Def(DefKind::ConstParam, def_id) => { + if let Some(span) = self.opt_span(def_id) { + err.span_label(span, "const parameter from outer function"); + } + } + _ => { + bug!( + "GenericParamsFromOuterFunction should only be used with Res::SelfTy, \ + DefKind::TyParam or DefKind::ConstParam" + ); + } + } + + if has_generic_params == HasGenericParams::Yes { + // Try to retrieve the span of the function signature and generate a new + // message with a local type or const parameter. + let sugg_msg = "try using a local generic parameter instead"; + if let Some((sugg_span, snippet)) = sm.generate_local_type_param_snippet(span) { + // Suggest the modification to the user + err.span_suggestion( + sugg_span, + sugg_msg, + snippet, + Applicability::MachineApplicable, + ); + } else if let Some(sp) = sm.generate_fn_name_span(span) { + err.span_label( + sp, + "try adding a local generic parameter in this method instead", + ); + } else { + err.help("try using a local generic parameter instead"); + } + } + + err + } + ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => { + let mut err = struct_span_err!( + self.session, + span, + E0403, + "the name `{}` is already used for a generic \ + parameter in this item's generic parameters", + name, + ); + err.span_label(span, "already used"); + err.span_label(first_use_span, format!("first use of `{}`", name)); + err + } + ResolutionError::MethodNotMemberOfTrait(method, trait_, candidate) => { + let mut err = struct_span_err!( + self.session, + span, + E0407, + "method `{}` is not a member of trait `{}`", + method, + trait_ + ); + err.span_label(span, format!("not a member of trait `{}`", trait_)); + if let Some(candidate) = candidate { + err.span_suggestion( + method.span, + "there is an associated function with a similar name", + candidate.to_ident_string(), + Applicability::MaybeIncorrect, + ); + } + err + } + ResolutionError::TypeNotMemberOfTrait(type_, trait_, candidate) => { + let mut err = struct_span_err!( + self.session, + span, + E0437, + "type `{}` is not a member of trait `{}`", + type_, + trait_ + ); + err.span_label(span, format!("not a member of trait `{}`", trait_)); + if let Some(candidate) = candidate { + err.span_suggestion( + type_.span, + "there is an associated type with a similar name", + candidate.to_ident_string(), + Applicability::MaybeIncorrect, + ); + } + err + } + ResolutionError::ConstNotMemberOfTrait(const_, trait_, candidate) => { + let mut err = struct_span_err!( + self.session, + span, + E0438, + "const `{}` is not a member of trait `{}`", + const_, + trait_ + ); + err.span_label(span, format!("not a member of trait `{}`", trait_)); + if let Some(candidate) = candidate { + err.span_suggestion( + const_.span, + "there is an associated constant with a similar name", + candidate.to_ident_string(), + Applicability::MaybeIncorrect, + ); + } + err + } + ResolutionError::VariableNotBoundInPattern(binding_error, parent_scope) => { + let BindingError { name, target, origin, could_be_path } = binding_error; + + let target_sp = target.iter().copied().collect::<Vec<_>>(); + let origin_sp = origin.iter().copied().collect::<Vec<_>>(); + + let msp = MultiSpan::from_spans(target_sp.clone()); + let mut err = struct_span_err!( + self.session, + msp, + E0408, + "variable `{}` is not bound in all patterns", + name, + ); + for sp in target_sp { + err.span_label(sp, format!("pattern doesn't bind `{}`", name)); + } + for sp in origin_sp { + err.span_label(sp, "variable not in all patterns"); + } + if could_be_path { + let import_suggestions = self.lookup_import_candidates( + Ident::with_dummy_span(name), + Namespace::ValueNS, + &parent_scope, + &|res: Res| match res { + Res::Def( + DefKind::Ctor(CtorOf::Variant, CtorKind::Const) + | DefKind::Ctor(CtorOf::Struct, CtorKind::Const) + | DefKind::Const + | DefKind::AssocConst, + _, + ) => true, + _ => false, + }, + ); + + if import_suggestions.is_empty() { + let help_msg = format!( + "if you meant to match on a variant or a `const` item, consider \ + making the path in the pattern qualified: `path::to::ModOrType::{}`", + name, + ); + err.span_help(span, &help_msg); + } + show_candidates( + &self.session, + &self.source_span, + &mut err, + Some(span), + &import_suggestions, + Instead::No, + FoundUse::Yes, + IsPattern::Yes, + vec![], + ); + } + err + } + ResolutionError::VariableBoundWithDifferentMode(variable_name, first_binding_span) => { + let mut err = struct_span_err!( + self.session, + span, + E0409, + "variable `{}` is bound inconsistently across alternatives separated by `|`", + variable_name + ); + err.span_label(span, "bound in different ways"); + err.span_label(first_binding_span, "first binding"); + err + } + ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => { + let mut err = struct_span_err!( + self.session, + span, + E0415, + "identifier `{}` is bound more than once in this parameter list", + identifier + ); + err.span_label(span, "used as parameter more than once"); + err + } + ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => { + let mut err = struct_span_err!( + self.session, + span, + E0416, + "identifier `{}` is bound more than once in the same pattern", + identifier + ); + err.span_label(span, "used in a pattern more than once"); + err + } + ResolutionError::UndeclaredLabel { name, suggestion } => { + let mut err = struct_span_err!( + self.session, + span, + E0426, + "use of undeclared label `{}`", + name + ); + + err.span_label(span, format!("undeclared label `{}`", name)); + + match suggestion { + // A reachable label with a similar name exists. + Some((ident, true)) => { + err.span_label(ident.span, "a label with a similar name is reachable"); + err.span_suggestion( + span, + "try using similarly named label", + ident.name, + Applicability::MaybeIncorrect, + ); + } + // An unreachable label with a similar name exists. + Some((ident, false)) => { + err.span_label( + ident.span, + "a label with a similar name exists but is unreachable", + ); + } + // No similarly-named labels exist. + None => (), + } + + err + } + ResolutionError::SelfImportsOnlyAllowedWithin { root, span_with_rename } => { + let mut err = struct_span_err!( + self.session, + span, + E0429, + "{}", + "`self` imports are only allowed within a { } list" + ); + + // None of the suggestions below would help with a case like `use self`. + if !root { + // use foo::bar::self -> foo::bar + // use foo::bar::self as abc -> foo::bar as abc + err.span_suggestion( + span, + "consider importing the module directly", + "", + Applicability::MachineApplicable, + ); + + // use foo::bar::self -> foo::bar::{self} + // use foo::bar::self as abc -> foo::bar::{self as abc} + let braces = vec![ + (span_with_rename.shrink_to_lo(), "{".to_string()), + (span_with_rename.shrink_to_hi(), "}".to_string()), + ]; + err.multipart_suggestion( + "alternatively, use the multi-path `use` syntax to import `self`", + braces, + Applicability::MachineApplicable, + ); + } + err + } + ResolutionError::SelfImportCanOnlyAppearOnceInTheList => { + let mut err = struct_span_err!( + self.session, + span, + E0430, + "`self` import can only appear once in an import list" + ); + err.span_label(span, "can only appear once in an import list"); + err + } + ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => { + let mut err = struct_span_err!( + self.session, + span, + E0431, + "`self` import can only appear in an import list with \ + a non-empty prefix" + ); + err.span_label(span, "can only appear in an import list with a non-empty prefix"); + err + } + ResolutionError::FailedToResolve { label, suggestion } => { + let mut err = + struct_span_err!(self.session, span, E0433, "failed to resolve: {}", &label); + err.span_label(span, label); + + if let Some((suggestions, msg, applicability)) = suggestion { + if suggestions.is_empty() { + err.help(&msg); + return err; + } + err.multipart_suggestion(&msg, suggestions, applicability); + } + + err + } + ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => { + let mut err = struct_span_err!( + self.session, + span, + E0434, + "{}", + "can't capture dynamic environment in a fn item" + ); + err.help("use the `|| { ... }` closure form instead"); + err + } + ResolutionError::AttemptToUseNonConstantValueInConstant(ident, sugg, current) => { + let mut err = struct_span_err!( + self.session, + span, + E0435, + "attempt to use a non-constant value in a constant" + ); + // let foo =... + // ^^^ given this Span + // ------- get this Span to have an applicable suggestion + + // edit: + // only do this if the const and usage of the non-constant value are on the same line + // the further the two are apart, the higher the chance of the suggestion being wrong + + let sp = self + .session + .source_map() + .span_extend_to_prev_str(ident.span, current, true, false); + + match sp { + Some(sp) if !self.session.source_map().is_multiline(sp) => { + let sp = sp.with_lo(BytePos(sp.lo().0 - (current.len() as u32))); + err.span_suggestion( + sp, + &format!("consider using `{}` instead of `{}`", sugg, current), + format!("{} {}", sugg, ident), + Applicability::MaybeIncorrect, + ); + err.span_label(span, "non-constant value"); + } + _ => { + err.span_label(ident.span, &format!("this would need to be a `{}`", sugg)); + } + } + + err + } + ResolutionError::BindingShadowsSomethingUnacceptable { + shadowing_binding, + name, + participle, + article, + shadowed_binding, + shadowed_binding_span, + } => { + let shadowed_binding_descr = shadowed_binding.descr(); + let mut err = struct_span_err!( + self.session, + span, + E0530, + "{}s cannot shadow {}s", + shadowing_binding.descr(), + shadowed_binding_descr, + ); + err.span_label( + span, + format!("cannot be named the same as {} {}", article, shadowed_binding_descr), + ); + match (shadowing_binding, shadowed_binding) { + ( + PatternSource::Match, + Res::Def(DefKind::Ctor(CtorOf::Variant | CtorOf::Struct, CtorKind::Fn), _), + ) => { + err.span_suggestion( + span, + "try specify the pattern arguments", + format!("{}(..)", name), + Applicability::Unspecified, + ); + } + _ => (), + } + let msg = + format!("the {} `{}` is {} here", shadowed_binding_descr, name, participle); + err.span_label(shadowed_binding_span, msg); + err + } + ResolutionError::ForwardDeclaredGenericParam => { + let mut err = struct_span_err!( + self.session, + span, + E0128, + "generic parameters with a default cannot use \ + forward declared identifiers" + ); + err.span_label(span, "defaulted generic parameters cannot be forward declared"); + err + } + ResolutionError::ParamInTyOfConstParam(name) => { + let mut err = struct_span_err!( + self.session, + span, + E0770, + "the type of const parameters must not depend on other generic parameters" + ); + err.span_label( + span, + format!("the type must not depend on the parameter `{}`", name), + ); + err + } + ResolutionError::ParamInNonTrivialAnonConst { name, is_type } => { + let mut err = self.session.struct_span_err( + span, + "generic parameters may not be used in const operations", + ); + err.span_label(span, &format!("cannot perform const operation using `{}`", name)); + + if is_type { + err.note("type parameters may not be used in const expressions"); + } else { + err.help(&format!( + "const parameters may only be used as standalone arguments, i.e. `{}`", + name + )); + } + + if self.session.is_nightly_build() { + err.help( + "use `#![feature(generic_const_exprs)]` to allow generic const expressions", + ); + } + + err + } + ResolutionError::SelfInGenericParamDefault => { + let mut err = struct_span_err!( + self.session, + span, + E0735, + "generic parameters cannot use `Self` in their defaults" + ); + err.span_label(span, "`Self` in generic parameter default"); + err + } + ResolutionError::UnreachableLabel { name, definition_span, suggestion } => { + let mut err = struct_span_err!( + self.session, + span, + E0767, + "use of unreachable label `{}`", + name, + ); + + err.span_label(definition_span, "unreachable label defined here"); + err.span_label(span, format!("unreachable label `{}`", name)); + err.note( + "labels are unreachable through functions, closures, async blocks and modules", + ); + + match suggestion { + // A reachable label with a similar name exists. + Some((ident, true)) => { + err.span_label(ident.span, "a label with a similar name is reachable"); + err.span_suggestion( + span, + "try using similarly named label", + ident.name, + Applicability::MaybeIncorrect, + ); + } + // An unreachable label with a similar name exists. + Some((ident, false)) => { + err.span_label( + ident.span, + "a label with a similar name exists but is also unreachable", + ); + } + // No similarly-named labels exist. + None => (), + } + + err + } + ResolutionError::TraitImplMismatch { + name, + kind, + code, + trait_item_span, + trait_path, + } => { + let mut err = self.session.struct_span_err_with_code( + span, + &format!( + "item `{}` is an associated {}, which doesn't match its trait `{}`", + name, kind, trait_path, + ), + code, + ); + err.span_label(span, "does not match trait"); + err.span_label(trait_item_span, "item in trait"); + err + } + ResolutionError::InvalidAsmSym => { + let mut err = self.session.struct_span_err(span, "invalid `sym` operand"); + err.span_label(span, "is a local variable"); + err.help("`sym` operands must refer to either a function or a static"); + err + } + } + } + + pub(crate) fn report_vis_error( + &mut self, + vis_resolution_error: VisResolutionError<'_>, + ) -> ErrorGuaranteed { + match vis_resolution_error { + VisResolutionError::Relative2018(span, path) => { + let mut err = self.session.struct_span_err( + span, + "relative paths are not supported in visibilities in 2018 edition or later", + ); + err.span_suggestion( + path.span, + "try", + format!("crate::{}", pprust::path_to_string(&path)), + Applicability::MaybeIncorrect, + ); + err + } + VisResolutionError::AncestorOnly(span) => struct_span_err!( + self.session, + span, + E0742, + "visibilities can only be restricted to ancestor modules" + ), + VisResolutionError::FailedToResolve(span, label, suggestion) => { + self.into_struct_error(span, ResolutionError::FailedToResolve { label, suggestion }) + } + VisResolutionError::ExpectedFound(span, path_str, res) => { + let mut err = struct_span_err!( + self.session, + span, + E0577, + "expected module, found {} `{}`", + res.descr(), + path_str + ); + err.span_label(span, "not a module"); + err + } + VisResolutionError::Indeterminate(span) => struct_span_err!( + self.session, + span, + E0578, + "cannot determine resolution for the visibility" + ), + VisResolutionError::ModuleOnly(span) => { + self.session.struct_span_err(span, "visibility must resolve to a module") + } + } + .emit() + } + + /// Lookup typo candidate in scope for a macro or import. + fn early_lookup_typo_candidate( + &mut self, + scope_set: ScopeSet<'a>, + parent_scope: &ParentScope<'a>, + ident: Ident, + filter_fn: &impl Fn(Res) -> bool, + ) -> Option<TypoSuggestion> { + let mut suggestions = Vec::new(); + let ctxt = ident.span.ctxt(); + self.visit_scopes(scope_set, parent_scope, ctxt, |this, scope, use_prelude, _| { + match scope { + Scope::DeriveHelpers(expn_id) => { + let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper); + if filter_fn(res) { + suggestions.extend( + this.helper_attrs + .get(&expn_id) + .into_iter() + .flatten() + .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)), + ); + } + } + Scope::DeriveHelpersCompat => { + let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat); + if filter_fn(res) { + for derive in parent_scope.derives { + let parent_scope = &ParentScope { derives: &[], ..*parent_scope }; + if let Ok((Some(ext), _)) = this.resolve_macro_path( + derive, + Some(MacroKind::Derive), + parent_scope, + false, + false, + ) { + suggestions.extend( + ext.helper_attrs + .iter() + .map(|name| TypoSuggestion::typo_from_res(*name, res)), + ); + } + } + } + } + Scope::MacroRules(macro_rules_scope) => { + if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() { + let res = macro_rules_binding.binding.res(); + if filter_fn(res) { + suggestions.push(TypoSuggestion::typo_from_res( + macro_rules_binding.ident.name, + res, + )) + } + } + } + Scope::CrateRoot => { + let root_ident = Ident::new(kw::PathRoot, ident.span); + let root_module = this.resolve_crate_root(root_ident); + this.add_module_candidates(root_module, &mut suggestions, filter_fn); + } + Scope::Module(module, _) => { + this.add_module_candidates(module, &mut suggestions, filter_fn); + } + Scope::RegisteredAttrs => { + let res = Res::NonMacroAttr(NonMacroAttrKind::Registered); + if filter_fn(res) { + suggestions.extend( + this.registered_attrs + .iter() + .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)), + ); + } + } + Scope::MacroUsePrelude => { + suggestions.extend(this.macro_use_prelude.iter().filter_map( + |(name, binding)| { + let res = binding.res(); + filter_fn(res).then_some(TypoSuggestion::typo_from_res(*name, res)) + }, + )); + } + Scope::BuiltinAttrs => { + let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(kw::Empty)); + if filter_fn(res) { + suggestions.extend( + BUILTIN_ATTRIBUTES + .iter() + .map(|attr| TypoSuggestion::typo_from_res(attr.name, res)), + ); + } + } + Scope::ExternPrelude => { + suggestions.extend(this.extern_prelude.iter().filter_map(|(ident, _)| { + let res = Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()); + filter_fn(res).then_some(TypoSuggestion::typo_from_res(ident.name, res)) + })); + } + Scope::ToolPrelude => { + let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); + suggestions.extend( + this.registered_tools + .iter() + .map(|ident| TypoSuggestion::typo_from_res(ident.name, res)), + ); + } + Scope::StdLibPrelude => { + if let Some(prelude) = this.prelude { + let mut tmp_suggestions = Vec::new(); + this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn); + suggestions.extend( + tmp_suggestions + .into_iter() + .filter(|s| use_prelude || this.is_builtin_macro(s.res)), + ); + } + } + Scope::BuiltinTypes => { + suggestions.extend(PrimTy::ALL.iter().filter_map(|prim_ty| { + let res = Res::PrimTy(*prim_ty); + filter_fn(res).then_some(TypoSuggestion::typo_from_res(prim_ty.name(), res)) + })) + } + } + + None::<()> + }); + + // Make sure error reporting is deterministic. + suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap()); + + match find_best_match_for_name( + &suggestions.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(), + ident.name, + None, + ) { + Some(found) if found != ident.name => { + suggestions.into_iter().find(|suggestion| suggestion.candidate == found) + } + _ => None, + } + } + + fn lookup_import_candidates_from_module<FilterFn>( + &mut self, + lookup_ident: Ident, + namespace: Namespace, + parent_scope: &ParentScope<'a>, + start_module: Module<'a>, + crate_name: Ident, + filter_fn: FilterFn, + ) -> Vec<ImportSuggestion> + where + FilterFn: Fn(Res) -> bool, + { + let mut candidates = Vec::new(); + let mut seen_modules = FxHashSet::default(); + let mut worklist = vec![(start_module, Vec::<ast::PathSegment>::new(), true)]; + let mut worklist_via_import = vec![]; + + while let Some((in_module, path_segments, accessible)) = match worklist.pop() { + None => worklist_via_import.pop(), + Some(x) => Some(x), + } { + let in_module_is_extern = !in_module.def_id().is_local(); + // We have to visit module children in deterministic order to avoid + // instabilities in reported imports (#43552). + in_module.for_each_child(self, |this, ident, ns, name_binding| { + // avoid non-importable candidates + if !name_binding.is_importable() { + return; + } + + let child_accessible = + accessible && this.is_accessible_from(name_binding.vis, parent_scope.module); + + // do not venture inside inaccessible items of other crates + if in_module_is_extern && !child_accessible { + return; + } + + let via_import = name_binding.is_import() && !name_binding.is_extern_crate(); + + // There is an assumption elsewhere that paths of variants are in the enum's + // declaration and not imported. With this assumption, the variant component is + // chopped and the rest of the path is assumed to be the enum's own path. For + // errors where a variant is used as the type instead of the enum, this causes + // funny looking invalid suggestions, i.e `foo` instead of `foo::MyEnum`. + if via_import && name_binding.is_possibly_imported_variant() { + return; + } + + // #90113: Do not count an inaccessible reexported item as a candidate. + if let NameBindingKind::Import { binding, .. } = name_binding.kind { + if this.is_accessible_from(binding.vis, parent_scope.module) + && !this.is_accessible_from(name_binding.vis, parent_scope.module) + { + return; + } + } + + // collect results based on the filter function + // avoid suggesting anything from the same module in which we are resolving + // avoid suggesting anything with a hygienic name + if ident.name == lookup_ident.name + && ns == namespace + && !ptr::eq(in_module, parent_scope.module) + && !ident.span.normalize_to_macros_2_0().from_expansion() + { + let res = name_binding.res(); + if filter_fn(res) { + // create the path + let mut segms = path_segments.clone(); + if lookup_ident.span.rust_2018() { + // crate-local absolute paths start with `crate::` in edition 2018 + // FIXME: may also be stabilized for Rust 2015 (Issues #45477, #44660) + segms.insert(0, ast::PathSegment::from_ident(crate_name)); + } + + segms.push(ast::PathSegment::from_ident(ident)); + let path = Path { span: name_binding.span, segments: segms, tokens: None }; + let did = match res { + Res::Def(DefKind::Ctor(..), did) => this.opt_parent(did), + _ => res.opt_def_id(), + }; + + if child_accessible { + // Remove invisible match if exists + if let Some(idx) = candidates + .iter() + .position(|v: &ImportSuggestion| v.did == did && !v.accessible) + { + candidates.remove(idx); + } + } + + if candidates.iter().all(|v: &ImportSuggestion| v.did != did) { + // See if we're recommending TryFrom, TryInto, or FromIterator and add + // a note about editions + let note = if let Some(did) = did { + let requires_note = !did.is_local() + && this.cstore().item_attrs_untracked(did, this.session).any( + |attr| { + if attr.has_name(sym::rustc_diagnostic_item) { + [sym::TryInto, sym::TryFrom, sym::FromIterator] + .map(|x| Some(x)) + .contains(&attr.value_str()) + } else { + false + } + }, + ); + + requires_note.then(|| { + format!( + "'{}' is included in the prelude starting in Edition 2021", + path_names_to_string(&path) + ) + }) + } else { + None + }; + + candidates.push(ImportSuggestion { + did, + descr: res.descr(), + path, + accessible: child_accessible, + note, + }); + } + } + } + + // collect submodules to explore + if let Some(module) = name_binding.module() { + // form the path + let mut path_segments = path_segments.clone(); + path_segments.push(ast::PathSegment::from_ident(ident)); + + let is_extern_crate_that_also_appears_in_prelude = + name_binding.is_extern_crate() && lookup_ident.span.rust_2018(); + + if !is_extern_crate_that_also_appears_in_prelude { + // add the module to the lookup + if seen_modules.insert(module.def_id()) { + if via_import { &mut worklist_via_import } else { &mut worklist } + .push((module, path_segments, child_accessible)); + } + } + } + }) + } + + // If only some candidates are accessible, take just them + if !candidates.iter().all(|v: &ImportSuggestion| !v.accessible) { + candidates = candidates.into_iter().filter(|x| x.accessible).collect(); + } + + candidates + } + + /// When name resolution fails, this method can be used to look up candidate + /// entities with the expected name. It allows filtering them using the + /// supplied predicate (which should be used to only accept the types of + /// definitions expected, e.g., traits). The lookup spans across all crates. + /// + /// N.B., the method does not look into imports, but this is not a problem, + /// since we report the definitions (thus, the de-aliased imports). + pub(crate) fn lookup_import_candidates<FilterFn>( + &mut self, + lookup_ident: Ident, + namespace: Namespace, + parent_scope: &ParentScope<'a>, + filter_fn: FilterFn, + ) -> Vec<ImportSuggestion> + where + FilterFn: Fn(Res) -> bool, + { + let mut suggestions = self.lookup_import_candidates_from_module( + lookup_ident, + namespace, + parent_scope, + self.graph_root, + Ident::with_dummy_span(kw::Crate), + &filter_fn, + ); + + if lookup_ident.span.rust_2018() { + let extern_prelude_names = self.extern_prelude.clone(); + for (ident, _) in extern_prelude_names.into_iter() { + if ident.span.from_expansion() { + // Idents are adjusted to the root context before being + // resolved in the extern prelude, so reporting this to the + // user is no help. This skips the injected + // `extern crate std` in the 2018 edition, which would + // otherwise cause duplicate suggestions. + continue; + } + if let Some(crate_id) = self.crate_loader.maybe_process_path_extern(ident.name) { + let crate_root = self.expect_module(crate_id.as_def_id()); + suggestions.extend(self.lookup_import_candidates_from_module( + lookup_ident, + namespace, + parent_scope, + crate_root, + ident, + &filter_fn, + )); + } + } + } + + suggestions + } + + pub(crate) fn unresolved_macro_suggestions( + &mut self, + err: &mut Diagnostic, + macro_kind: MacroKind, + parent_scope: &ParentScope<'a>, + ident: Ident, + ) { + let is_expected = &|res: Res| res.macro_kind() == Some(macro_kind); + let suggestion = self.early_lookup_typo_candidate( + ScopeSet::Macro(macro_kind), + parent_scope, + ident, + is_expected, + ); + self.add_typo_suggestion(err, suggestion, ident.span); + + let import_suggestions = + self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, is_expected); + show_candidates( + &self.session, + &self.source_span, + err, + None, + &import_suggestions, + Instead::No, + FoundUse::Yes, + IsPattern::No, + vec![], + ); + + if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) { + let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident); + err.span_note(ident.span, &msg); + return; + } + if self.macro_names.contains(&ident.normalize_to_macros_2_0()) { + err.help("have you added the `#[macro_use]` on the module/import?"); + return; + } + if ident.name == kw::Default + && let ModuleKind::Def(DefKind::Enum, def_id, _) = parent_scope.module.kind + && let Some(span) = self.opt_span(def_id) + { + let source_map = self.session.source_map(); + let head_span = source_map.guess_head_span(span); + if let Ok(head) = source_map.span_to_snippet(head_span) { + err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect); + } else { + err.span_help( + head_span, + "consider adding `#[derive(Default)]` to this enum", + ); + } + } + for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] { + if let Ok(binding) = self.early_resolve_ident_in_lexical_scope( + ident, + ScopeSet::All(ns, false), + &parent_scope, + None, + false, + None, + ) { + let desc = match binding.res() { + Res::Def(DefKind::Macro(MacroKind::Bang), _) => { + "a function-like macro".to_string() + } + Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => { + format!("an attribute: `#[{}]`", ident) + } + Res::Def(DefKind::Macro(MacroKind::Derive), _) => { + format!("a derive macro: `#[derive({})]`", ident) + } + Res::ToolMod => { + // Don't confuse the user with tool modules. + continue; + } + Res::Def(DefKind::Trait, _) if macro_kind == MacroKind::Derive => { + "only a trait, without a derive macro".to_string() + } + res => format!( + "{} {}, not {} {}", + res.article(), + res.descr(), + macro_kind.article(), + macro_kind.descr_expected(), + ), + }; + if let crate::NameBindingKind::Import { import, .. } = binding.kind { + if !import.span.is_dummy() { + err.span_note( + import.span, + &format!("`{}` is imported here, but it is {}", ident, desc), + ); + // Silence the 'unused import' warning we might get, + // since this diagnostic already covers that import. + self.record_use(ident, binding, false); + return; + } + } + err.note(&format!("`{}` is in scope, but it is {}", ident, desc)); + return; + } + } + } + + pub(crate) fn add_typo_suggestion( + &self, + err: &mut Diagnostic, + suggestion: Option<TypoSuggestion>, + span: Span, + ) -> bool { + let suggestion = match suggestion { + None => return false, + // We shouldn't suggest underscore. + Some(suggestion) if suggestion.candidate == kw::Underscore => return false, + Some(suggestion) => suggestion, + }; + let def_span = suggestion.res.opt_def_id().and_then(|def_id| match def_id.krate { + LOCAL_CRATE => self.opt_span(def_id), + _ => Some(self.cstore().get_span_untracked(def_id, self.session)), + }); + if let Some(def_span) = def_span { + if span.overlaps(def_span) { + // Don't suggest typo suggestion for itself like in the following: + // error[E0423]: expected function, tuple struct or tuple variant, found struct `X` + // --> $DIR/issue-64792-bad-unicode-ctor.rs:3:14 + // | + // LL | struct X {} + // | ----------- `X` defined here + // LL | + // LL | const Y: X = X("ö"); + // | -------------^^^^^^- similarly named constant `Y` defined here + // | + // help: use struct literal syntax instead + // | + // LL | const Y: X = X {}; + // | ^^^^ + // help: a constant with a similar name exists + // | + // LL | const Y: X = Y("ö"); + // | ^ + return false; + } + let prefix = match suggestion.target { + SuggestionTarget::SimilarlyNamed => "similarly named ", + SuggestionTarget::SingleItem => "", + }; + + err.span_label( + self.session.source_map().guess_head_span(def_span), + &format!( + "{}{} `{}` defined here", + prefix, + suggestion.res.descr(), + suggestion.candidate, + ), + ); + } + let msg = match suggestion.target { + SuggestionTarget::SimilarlyNamed => format!( + "{} {} with a similar name exists", + suggestion.res.article(), + suggestion.res.descr() + ), + SuggestionTarget::SingleItem => { + format!("maybe you meant this {}", suggestion.res.descr()) + } + }; + err.span_suggestion(span, &msg, suggestion.candidate, Applicability::MaybeIncorrect); + true + } + + fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String { + let res = b.res(); + if b.span.is_dummy() || !self.session.source_map().is_span_accessible(b.span) { + // These already contain the "built-in" prefix or look bad with it. + let add_built_in = + !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod); + let (built_in, from) = if from_prelude { + ("", " from prelude") + } else if b.is_extern_crate() + && !b.is_import() + && self.session.opts.externs.get(ident.as_str()).is_some() + { + ("", " passed with `--extern`") + } else if add_built_in { + (" built-in", "") + } else { + ("", "") + }; + + let a = if built_in.is_empty() { res.article() } else { "a" }; + format!("{a}{built_in} {thing}{from}", thing = res.descr()) + } else { + let introduced = if b.is_import() { "imported" } else { "defined" }; + format!("the {thing} {introduced} here", thing = res.descr()) + } + } + + fn report_ambiguity_error(&self, ambiguity_error: &AmbiguityError<'_>) { + let AmbiguityError { kind, ident, b1, b2, misc1, misc2 } = *ambiguity_error; + let (b1, b2, misc1, misc2, swapped) = if b2.span.is_dummy() && !b1.span.is_dummy() { + // We have to print the span-less alternative first, otherwise formatting looks bad. + (b2, b1, misc2, misc1, true) + } else { + (b1, b2, misc1, misc2, false) + }; + + let mut err = struct_span_err!(self.session, ident.span, E0659, "`{ident}` is ambiguous"); + err.span_label(ident.span, "ambiguous name"); + err.note(&format!("ambiguous because of {}", kind.descr())); + + let mut could_refer_to = |b: &NameBinding<'_>, misc: AmbiguityErrorMisc, also: &str| { + let what = self.binding_description(b, ident, misc == AmbiguityErrorMisc::FromPrelude); + let note_msg = format!("`{ident}` could{also} refer to {what}"); + + let thing = b.res().descr(); + let mut help_msgs = Vec::new(); + if b.is_glob_import() + && (kind == AmbiguityKind::GlobVsGlob + || kind == AmbiguityKind::GlobVsExpanded + || kind == AmbiguityKind::GlobVsOuter && swapped != also.is_empty()) + { + help_msgs.push(format!( + "consider adding an explicit import of `{ident}` to disambiguate" + )) + } + if b.is_extern_crate() && ident.span.rust_2018() { + help_msgs.push(format!("use `::{ident}` to refer to this {thing} unambiguously")) + } + if misc == AmbiguityErrorMisc::SuggestCrate { + help_msgs + .push(format!("use `crate::{ident}` to refer to this {thing} unambiguously")) + } else if misc == AmbiguityErrorMisc::SuggestSelf { + help_msgs + .push(format!("use `self::{ident}` to refer to this {thing} unambiguously")) + } + + err.span_note(b.span, ¬e_msg); + for (i, help_msg) in help_msgs.iter().enumerate() { + let or = if i == 0 { "" } else { "or " }; + err.help(&format!("{}{}", or, help_msg)); + } + }; + + could_refer_to(b1, misc1, ""); + could_refer_to(b2, misc2, " also"); + err.emit(); + } + + /// If the binding refers to a tuple struct constructor with fields, + /// returns the span of its fields. + fn ctor_fields_span(&self, binding: &NameBinding<'_>) -> Option<Span> { + if let NameBindingKind::Res( + Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), ctor_def_id), + _, + ) = binding.kind + { + let def_id = self.parent(ctor_def_id); + let fields = self.field_names.get(&def_id)?; + return fields.iter().map(|name| name.span).reduce(Span::to); // None for `struct Foo()` + } + None + } + + fn report_privacy_error(&self, privacy_error: &PrivacyError<'_>) { + let PrivacyError { ident, binding, .. } = *privacy_error; + + let res = binding.res(); + let ctor_fields_span = self.ctor_fields_span(binding); + let plain_descr = res.descr().to_string(); + let nonimport_descr = + if ctor_fields_span.is_some() { plain_descr + " constructor" } else { plain_descr }; + let import_descr = nonimport_descr.clone() + " import"; + let get_descr = + |b: &NameBinding<'_>| if b.is_import() { &import_descr } else { &nonimport_descr }; + + // Print the primary message. + let descr = get_descr(binding); + let mut err = + struct_span_err!(self.session, ident.span, E0603, "{} `{}` is private", descr, ident); + err.span_label(ident.span, &format!("private {}", descr)); + if let Some(span) = ctor_fields_span { + err.span_label(span, "a constructor is private if any of the fields is private"); + } + + // Print the whole import chain to make it easier to see what happens. + let first_binding = binding; + let mut next_binding = Some(binding); + let mut next_ident = ident; + while let Some(binding) = next_binding { + let name = next_ident; + next_binding = match binding.kind { + _ if res == Res::Err => None, + NameBindingKind::Import { binding, import, .. } => match import.kind { + _ if binding.span.is_dummy() => None, + ImportKind::Single { source, .. } => { + next_ident = source; + Some(binding) + } + ImportKind::Glob { .. } | ImportKind::MacroUse => Some(binding), + ImportKind::ExternCrate { .. } => None, + }, + _ => None, + }; + + let first = ptr::eq(binding, first_binding); + let msg = format!( + "{and_refers_to}the {item} `{name}`{which} is defined here{dots}", + and_refers_to = if first { "" } else { "...and refers to " }, + item = get_descr(binding), + which = if first { "" } else { " which" }, + dots = if next_binding.is_some() { "..." } else { "" }, + ); + let def_span = self.session.source_map().guess_head_span(binding.span); + let mut note_span = MultiSpan::from_span(def_span); + if !first && binding.vis.is_public() { + note_span.push_span_label(def_span, "consider importing it directly"); + } + err.span_note(note_span, &msg); + } + + err.emit(); + } + + pub(crate) fn find_similarly_named_module_or_crate( + &mut self, + ident: Symbol, + current_module: &Module<'a>, + ) -> Option<Symbol> { + let mut candidates = self + .extern_prelude + .iter() + .map(|(ident, _)| ident.name) + .chain( + self.module_map + .iter() + .filter(|(_, module)| { + current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module) + }) + .flat_map(|(_, module)| module.kind.name()), + ) + .filter(|c| !c.to_string().is_empty()) + .collect::<Vec<_>>(); + candidates.sort(); + candidates.dedup(); + match find_best_match_for_name(&candidates, ident, None) { + Some(sugg) if sugg == ident => None, + sugg => sugg, + } + } + + pub(crate) fn report_path_resolution_error( + &mut self, + path: &[Segment], + opt_ns: Option<Namespace>, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + ribs: Option<&PerNS<Vec<Rib<'a>>>>, + ignore_binding: Option<&'a NameBinding<'a>>, + module: Option<ModuleOrUniformRoot<'a>>, + i: usize, + ident: Ident, + ) -> (String, Option<Suggestion>) { + let is_last = i == path.len() - 1; + let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; + let module_res = match module { + Some(ModuleOrUniformRoot::Module(module)) => module.res(), + _ => None, + }; + if module_res == self.graph_root.res() { + let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _)); + let mut candidates = self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod); + candidates + .sort_by_cached_key(|c| (c.path.segments.len(), pprust::path_to_string(&c.path))); + if let Some(candidate) = candidates.get(0) { + ( + String::from("unresolved import"), + Some(( + vec![(ident.span, pprust::path_to_string(&candidate.path))], + String::from("a similar path exists"), + Applicability::MaybeIncorrect, + )), + ) + } else if self.session.edition() == Edition::Edition2015 { + ( + format!("maybe a missing crate `{ident}`?"), + Some(( + vec![], + format!( + "consider adding `extern crate {ident}` to use the `{ident}` crate" + ), + Applicability::MaybeIncorrect, + )), + ) + } else { + (format!("could not find `{ident}` in the crate root"), None) + } + } else if i > 0 { + let parent = path[i - 1].ident.name; + let parent = match parent { + // ::foo is mounted at the crate root for 2015, and is the extern + // prelude for 2018+ + kw::PathRoot if self.session.edition() > Edition::Edition2015 => { + "the list of imported crates".to_owned() + } + kw::PathRoot | kw::Crate => "the crate root".to_owned(), + _ => format!("`{parent}`"), + }; + + let mut msg = format!("could not find `{}` in {}", ident, parent); + if ns == TypeNS || ns == ValueNS { + let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; + let binding = if let Some(module) = module { + self.resolve_ident_in_module( + module, + ident, + ns_to_try, + parent_scope, + None, + ignore_binding, + ).ok() + } else if let Some(ribs) = ribs + && let Some(TypeNS | ValueNS) = opt_ns + { + match self.resolve_ident_in_lexical_scope( + ident, + ns_to_try, + parent_scope, + None, + &ribs[ns_to_try], + ignore_binding, + ) { + // we found a locally-imported or available item/module + Some(LexicalScopeBinding::Item(binding)) => Some(binding), + _ => None, + } + } else { + let scopes = ScopeSet::All(ns_to_try, opt_ns.is_none()); + self.early_resolve_ident_in_lexical_scope( + ident, + scopes, + parent_scope, + None, + false, + ignore_binding, + ).ok() + }; + if let Some(binding) = binding { + let mut found = |what| { + msg = format!( + "expected {}, found {} `{}` in {}", + ns.descr(), + what, + ident, + parent + ) + }; + if binding.module().is_some() { + found("module") + } else { + match binding.res() { + Res::Def(kind, id) => found(kind.descr(id)), + _ => found(ns_to_try.descr()), + } + } + }; + } + (msg, None) + } else if ident.name == kw::SelfUpper { + ("`Self` is only available in impls, traits, and type definitions".to_string(), None) + } else if ident.name.as_str().chars().next().map_or(false, |c| c.is_ascii_uppercase()) { + // Check whether the name refers to an item in the value namespace. + let binding = if let Some(ribs) = ribs { + self.resolve_ident_in_lexical_scope( + ident, + ValueNS, + parent_scope, + None, + &ribs[ValueNS], + ignore_binding, + ) + } else { + None + }; + let match_span = match binding { + // Name matches a local variable. For example: + // ``` + // fn f() { + // let Foo: &str = ""; + // println!("{}", Foo::Bar); // Name refers to local + // // variable `Foo`. + // } + // ``` + Some(LexicalScopeBinding::Res(Res::Local(id))) => { + Some(*self.pat_span_map.get(&id).unwrap()) + } + // Name matches item from a local name binding + // created by `use` declaration. For example: + // ``` + // pub Foo: &str = ""; + // + // mod submod { + // use super::Foo; + // println!("{}", Foo::Bar); // Name refers to local + // // binding `Foo`. + // } + // ``` + Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span), + _ => None, + }; + let suggestion = if let Some(span) = match_span { + Some(( + vec![(span, String::from(""))], + format!("`{}` is defined here, but is not a type", ident), + Applicability::MaybeIncorrect, + )) + } else { + None + }; + + (format!("use of undeclared type `{}`", ident), suggestion) + } else { + let suggestion = if ident.name == sym::alloc { + Some(( + vec![], + String::from("add `extern crate alloc` to use the `alloc` crate"), + Applicability::MaybeIncorrect, + )) + } else { + self.find_similarly_named_module_or_crate(ident.name, &parent_scope.module).map( + |sugg| { + ( + vec![(ident.span, sugg.to_string())], + String::from("there is a crate or module with a similar name"), + Applicability::MaybeIncorrect, + ) + }, + ) + }; + (format!("use of undeclared crate or module `{}`", ident), suggestion) + } + } +} + +impl<'a, 'b> ImportResolver<'a, 'b> { + /// Adds suggestions for a path that cannot be resolved. + pub(crate) fn make_path_suggestion( + &mut self, + span: Span, + mut path: Vec<Segment>, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec<Segment>, Option<String>)> { + debug!("make_path_suggestion: span={:?} path={:?}", span, path); + + match (path.get(0), path.get(1)) { + // `{{root}}::ident::...` on both editions. + // On 2015 `{{root}}` is usually added implicitly. + (Some(fst), Some(snd)) + if fst.ident.name == kw::PathRoot && !snd.ident.is_path_segment_keyword() => {} + // `ident::...` on 2018. + (Some(fst), _) + if fst.ident.span.rust_2018() && !fst.ident.is_path_segment_keyword() => + { + // Insert a placeholder that's later replaced by `self`/`super`/etc. + path.insert(0, Segment::from_ident(Ident::empty())); + } + _ => return None, + } + + self.make_missing_self_suggestion(path.clone(), parent_scope) + .or_else(|| self.make_missing_crate_suggestion(path.clone(), parent_scope)) + .or_else(|| self.make_missing_super_suggestion(path.clone(), parent_scope)) + .or_else(|| self.make_external_crate_suggestion(path, parent_scope)) + } + + /// Suggest a missing `self::` if that resolves to an correct module. + /// + /// ```text + /// | + /// LL | use foo::Bar; + /// | ^^^ did you mean `self::foo`? + /// ``` + fn make_missing_self_suggestion( + &mut self, + mut path: Vec<Segment>, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec<Segment>, Option<String>)> { + // Replace first ident with `self` and check if that is valid. + path[0].ident.name = kw::SelfLower; + let result = self.r.maybe_resolve_path(&path, None, parent_scope); + debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result); + if let PathResult::Module(..) = result { Some((path, None)) } else { None } + } + + /// Suggests a missing `crate::` if that resolves to an correct module. + /// + /// ```text + /// | + /// LL | use foo::Bar; + /// | ^^^ did you mean `crate::foo`? + /// ``` + fn make_missing_crate_suggestion( + &mut self, + mut path: Vec<Segment>, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec<Segment>, Option<String>)> { + // Replace first ident with `crate` and check if that is valid. + path[0].ident.name = kw::Crate; + let result = self.r.maybe_resolve_path(&path, None, parent_scope); + debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result); + if let PathResult::Module(..) = result { + Some(( + path, + Some( + "`use` statements changed in Rust 2018; read more at \ + <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-\ + clarity.html>" + .to_string(), + ), + )) + } else { + None + } + } + + /// Suggests a missing `super::` if that resolves to an correct module. + /// + /// ```text + /// | + /// LL | use foo::Bar; + /// | ^^^ did you mean `super::foo`? + /// ``` + fn make_missing_super_suggestion( + &mut self, + mut path: Vec<Segment>, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec<Segment>, Option<String>)> { + // Replace first ident with `crate` and check if that is valid. + path[0].ident.name = kw::Super; + let result = self.r.maybe_resolve_path(&path, None, parent_scope); + debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result); + if let PathResult::Module(..) = result { Some((path, None)) } else { None } + } + + /// Suggests a missing external crate name if that resolves to an correct module. + /// + /// ```text + /// | + /// LL | use foobar::Baz; + /// | ^^^^^^ did you mean `baz::foobar`? + /// ``` + /// + /// Used when importing a submodule of an external crate but missing that crate's + /// name as the first part of path. + fn make_external_crate_suggestion( + &mut self, + mut path: Vec<Segment>, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec<Segment>, Option<String>)> { + if path[1].ident.span.rust_2015() { + return None; + } + + // Sort extern crate names in *reverse* order to get + // 1) some consistent ordering for emitted diagnostics, and + // 2) `std` suggestions before `core` suggestions. + let mut extern_crate_names = + self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>(); + extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap()); + + for name in extern_crate_names.into_iter() { + // Replace first ident with a crate name and check if that is valid. + path[0].ident.name = name; + let result = self.r.maybe_resolve_path(&path, None, parent_scope); + debug!( + "make_external_crate_suggestion: name={:?} path={:?} result={:?}", + name, path, result + ); + if let PathResult::Module(..) = result { + return Some((path, None)); + } + } + + None + } + + /// Suggests importing a macro from the root of the crate rather than a module within + /// the crate. + /// + /// ```text + /// help: a macro with this name exists at the root of the crate + /// | + /// LL | use issue_59764::makro; + /// | ^^^^^^^^^^^^^^^^^^ + /// | + /// = note: this could be because a macro annotated with `#[macro_export]` will be exported + /// at the root of the crate instead of the module where it is defined + /// ``` + pub(crate) fn check_for_module_export_macro( + &mut self, + import: &'b Import<'b>, + module: ModuleOrUniformRoot<'b>, + ident: Ident, + ) -> Option<(Option<Suggestion>, Option<String>)> { + let ModuleOrUniformRoot::Module(mut crate_module) = module else { + return None; + }; + + while let Some(parent) = crate_module.parent { + crate_module = parent; + } + + if ModuleOrUniformRoot::same_def(ModuleOrUniformRoot::Module(crate_module), module) { + // Don't make a suggestion if the import was already from the root of the + // crate. + return None; + } + + let resolutions = self.r.resolutions(crate_module).borrow(); + let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?; + let binding = resolution.borrow().binding()?; + if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() { + let module_name = crate_module.kind.name().unwrap(); + let import_snippet = match import.kind { + ImportKind::Single { source, target, .. } if source != target => { + format!("{} as {}", source, target) + } + _ => format!("{}", ident), + }; + + let mut corrections: Vec<(Span, String)> = Vec::new(); + if !import.is_nested() { + // Assume this is the easy case of `use issue_59764::foo::makro;` and just remove + // intermediate segments. + corrections.push((import.span, format!("{}::{}", module_name, import_snippet))); + } else { + // Find the binding span (and any trailing commas and spaces). + // ie. `use a::b::{c, d, e};` + // ^^^ + let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding( + self.r.session, + import.span, + import.use_span, + ); + debug!( + "check_for_module_export_macro: found_closing_brace={:?} binding_span={:?}", + found_closing_brace, binding_span + ); + + let mut removal_span = binding_span; + if found_closing_brace { + // If the binding span ended with a closing brace, as in the below example: + // ie. `use a::b::{c, d};` + // ^ + // Then expand the span of characters to remove to include the previous + // binding's trailing comma. + // ie. `use a::b::{c, d};` + // ^^^ + if let Some(previous_span) = + extend_span_to_previous_binding(self.r.session, binding_span) + { + debug!("check_for_module_export_macro: previous_span={:?}", previous_span); + removal_span = removal_span.with_lo(previous_span.lo()); + } + } + debug!("check_for_module_export_macro: removal_span={:?}", removal_span); + + // Remove the `removal_span`. + corrections.push((removal_span, "".to_string())); + + // Find the span after the crate name and if it has nested imports immediately + // after the crate name already. + // ie. `use a::b::{c, d};` + // ^^^^^^^^^ + // or `use a::{b, c, d}};` + // ^^^^^^^^^^^ + let (has_nested, after_crate_name) = find_span_immediately_after_crate_name( + self.r.session, + module_name, + import.use_span, + ); + debug!( + "check_for_module_export_macro: has_nested={:?} after_crate_name={:?}", + has_nested, after_crate_name + ); + + let source_map = self.r.session.source_map(); + + // Add the import to the start, with a `{` if required. + let start_point = source_map.start_point(after_crate_name); + if let Ok(start_snippet) = source_map.span_to_snippet(start_point) { + corrections.push(( + start_point, + if has_nested { + // In this case, `start_snippet` must equal '{'. + format!("{}{}, ", start_snippet, import_snippet) + } else { + // In this case, add a `{`, then the moved import, then whatever + // was there before. + format!("{{{}, {}", import_snippet, start_snippet) + }, + )); + } + + // Add a `};` to the end if nested, matching the `{` added at the start. + if !has_nested { + corrections.push((source_map.end_point(after_crate_name), "};".to_string())); + } + } + + let suggestion = Some(( + corrections, + String::from("a macro with this name exists at the root of the crate"), + Applicability::MaybeIncorrect, + )); + Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \ + at the root of the crate instead of the module where it is defined" + .to_string()))) + } else { + None + } + } +} + +/// Given a `binding_span` of a binding within a use statement: +/// +/// ```ignore (illustrative) +/// use foo::{a, b, c}; +/// // ^ +/// ``` +/// +/// then return the span until the next binding or the end of the statement: +/// +/// ```ignore (illustrative) +/// use foo::{a, b, c}; +/// // ^^^ +/// ``` +fn find_span_of_binding_until_next_binding( + sess: &Session, + binding_span: Span, + use_span: Span, +) -> (bool, Span) { + let source_map = sess.source_map(); + + // Find the span of everything after the binding. + // ie. `a, e};` or `a};` + let binding_until_end = binding_span.with_hi(use_span.hi()); + + // Find everything after the binding but not including the binding. + // ie. `, e};` or `};` + let after_binding_until_end = binding_until_end.with_lo(binding_span.hi()); + + // Keep characters in the span until we encounter something that isn't a comma or + // whitespace. + // ie. `, ` or ``. + // + // Also note whether a closing brace character was encountered. If there + // was, then later go backwards to remove any trailing commas that are left. + let mut found_closing_brace = false; + let after_binding_until_next_binding = + source_map.span_take_while(after_binding_until_end, |&ch| { + if ch == '}' { + found_closing_brace = true; + } + ch == ' ' || ch == ',' + }); + + // Combine the two spans. + // ie. `a, ` or `a`. + // + // Removing these would leave `issue_52891::{d, e};` or `issue_52891::{d, e, };` + let span = binding_span.with_hi(after_binding_until_next_binding.hi()); + + (found_closing_brace, span) +} + +/// Given a `binding_span`, return the span through to the comma or opening brace of the previous +/// binding. +/// +/// ```ignore (illustrative) +/// use foo::a::{a, b, c}; +/// // ^^--- binding span +/// // | +/// // returned span +/// +/// use foo::{a, b, c}; +/// // --- binding span +/// ``` +fn extend_span_to_previous_binding(sess: &Session, binding_span: Span) -> Option<Span> { + let source_map = sess.source_map(); + + // `prev_source` will contain all of the source that came before the span. + // Then split based on a command and take the first (ie. closest to our span) + // snippet. In the example, this is a space. + let prev_source = source_map.span_to_prev_source(binding_span).ok()?; + + let prev_comma = prev_source.rsplit(',').collect::<Vec<_>>(); + let prev_starting_brace = prev_source.rsplit('{').collect::<Vec<_>>(); + if prev_comma.len() <= 1 || prev_starting_brace.len() <= 1 { + return None; + } + + let prev_comma = prev_comma.first().unwrap(); + let prev_starting_brace = prev_starting_brace.first().unwrap(); + + // If the amount of source code before the comma is greater than + // the amount of source code before the starting brace then we've only + // got one item in the nested item (eg. `issue_52891::{self}`). + if prev_comma.len() > prev_starting_brace.len() { + return None; + } + + Some(binding_span.with_lo(BytePos( + // Take away the number of bytes for the characters we've found and an + // extra for the comma. + binding_span.lo().0 - (prev_comma.as_bytes().len() as u32) - 1, + ))) +} + +/// Given a `use_span` of a binding within a use statement, returns the highlighted span and if +/// it is a nested use tree. +/// +/// ```ignore (illustrative) +/// use foo::a::{b, c}; +/// // ^^^^^^^^^^ -- false +/// +/// use foo::{a, b, c}; +/// // ^^^^^^^^^^ -- true +/// +/// use foo::{a, b::{c, d}}; +/// // ^^^^^^^^^^^^^^^ -- true +/// ``` +fn find_span_immediately_after_crate_name( + sess: &Session, + module_name: Symbol, + use_span: Span, +) -> (bool, Span) { + debug!( + "find_span_immediately_after_crate_name: module_name={:?} use_span={:?}", + module_name, use_span + ); + let source_map = sess.source_map(); + + // Using `use issue_59764::foo::{baz, makro};` as an example throughout.. + let mut num_colons = 0; + // Find second colon.. `use issue_59764:` + let until_second_colon = source_map.span_take_while(use_span, |c| { + if *c == ':' { + num_colons += 1; + } + !matches!(c, ':' if num_colons == 2) + }); + // Find everything after the second colon.. `foo::{baz, makro};` + let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1)); + + let mut found_a_non_whitespace_character = false; + // Find the first non-whitespace character in `from_second_colon`.. `f` + let after_second_colon = source_map.span_take_while(from_second_colon, |c| { + if found_a_non_whitespace_character { + return false; + } + if !c.is_whitespace() { + found_a_non_whitespace_character = true; + } + true + }); + + // Find the first `{` in from_second_colon.. `foo::{` + let next_left_bracket = source_map.span_through_char(from_second_colon, '{'); + + (next_left_bracket == after_second_colon, from_second_colon) +} + +/// A suggestion has already been emitted, change the wording slightly to clarify that both are +/// independent options. +enum Instead { + Yes, + No, +} + +/// Whether an existing place with an `use` item was found. +enum FoundUse { + Yes, + No, +} + +/// Whether a binding is part of a pattern or an expression. Used for diagnostics. +enum IsPattern { + /// The binding is part of a pattern + Yes, + /// The binding is part of an expression + No, +} + +/// When an entity with a given name is not available in scope, we search for +/// entities with that name in all crates. This method allows outputting the +/// results of this search in a programmer-friendly way +fn show_candidates( + session: &Session, + source_span: &IndexVec<LocalDefId, Span>, + err: &mut Diagnostic, + // This is `None` if all placement locations are inside expansions + use_placement_span: Option<Span>, + candidates: &[ImportSuggestion], + instead: Instead, + found_use: FoundUse, + is_pattern: IsPattern, + path: Vec<Segment>, +) { + if candidates.is_empty() { + return; + } + + let mut accessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> = + Vec::new(); + let mut inaccessible_path_strings: Vec<(String, &str, Option<DefId>, &Option<String>)> = + Vec::new(); + + candidates.iter().for_each(|c| { + (if c.accessible { &mut accessible_path_strings } else { &mut inaccessible_path_strings }) + .push((path_names_to_string(&c.path), c.descr, c.did, &c.note)) + }); + + // we want consistent results across executions, but candidates are produced + // by iterating through a hash map, so make sure they are ordered: + for path_strings in [&mut accessible_path_strings, &mut inaccessible_path_strings] { + path_strings.sort_by(|a, b| a.0.cmp(&b.0)); + let core_path_strings = + path_strings.drain_filter(|p| p.0.starts_with("core::")).collect::<Vec<_>>(); + path_strings.extend(core_path_strings); + path_strings.dedup_by(|a, b| a.0 == b.0); + } + + if !accessible_path_strings.is_empty() { + let (determiner, kind, name) = if accessible_path_strings.len() == 1 { + ("this", accessible_path_strings[0].1, format!(" `{}`", accessible_path_strings[0].0)) + } else { + ("one of these", "items", String::new()) + }; + + let instead = if let Instead::Yes = instead { " instead" } else { "" }; + let mut msg = if let IsPattern::Yes = is_pattern { + format!( + "if you meant to match on {}{}{}, use the full path in the pattern", + kind, instead, name + ) + } else { + format!("consider importing {} {}{}", determiner, kind, instead) + }; + + for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) { + err.note(note); + } + + if let (IsPattern::Yes, Some(span)) = (is_pattern, use_placement_span) { + err.span_suggestions( + span, + &msg, + accessible_path_strings.into_iter().map(|a| a.0), + Applicability::MaybeIncorrect, + ); + } else if let Some(span) = use_placement_span { + for candidate in &mut accessible_path_strings { + // produce an additional newline to separate the new use statement + // from the directly following item. + let additional_newline = if let FoundUse::Yes = found_use { "" } else { "\n" }; + candidate.0 = format!("use {};\n{}", &candidate.0, additional_newline); + } + + err.span_suggestions( + span, + &msg, + accessible_path_strings.into_iter().map(|a| a.0), + Applicability::MaybeIncorrect, + ); + if let [first, .., last] = &path[..] { + err.span_suggestion_verbose( + first.ident.span.until(last.ident.span), + &format!("if you import `{}`, refer to it directly", last.ident), + "", + Applicability::Unspecified, + ); + } + } else { + msg.push(':'); + + for candidate in accessible_path_strings { + msg.push('\n'); + msg.push_str(&candidate.0); + } + + err.note(&msg); + } + } else { + assert!(!inaccessible_path_strings.is_empty()); + + let prefix = + if let IsPattern::Yes = is_pattern { "you might have meant to match on " } else { "" }; + if inaccessible_path_strings.len() == 1 { + let (name, descr, def_id, note) = &inaccessible_path_strings[0]; + let msg = format!( + "{}{} `{}`{} exists but is inaccessible", + prefix, + descr, + name, + if let IsPattern::Yes = is_pattern { ", which" } else { "" } + ); + + if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) { + let span = source_span[local_def_id]; + let span = session.source_map().guess_head_span(span); + let mut multi_span = MultiSpan::from_span(span); + multi_span.push_span_label(span, "not accessible"); + err.span_note(multi_span, &msg); + } else { + err.note(&msg); + } + if let Some(note) = (*note).as_deref() { + err.note(note); + } + } else { + let (_, descr_first, _, _) = &inaccessible_path_strings[0]; + let descr = if inaccessible_path_strings + .iter() + .skip(1) + .all(|(_, descr, _, _)| descr == descr_first) + { + descr_first + } else { + "item" + }; + let plural_descr = + if descr.ends_with('s') { format!("{}es", descr) } else { format!("{}s", descr) }; + + let mut msg = format!("{}these {} exist but are inaccessible", prefix, plural_descr); + let mut has_colon = false; + + let mut spans = Vec::new(); + for (name, _, def_id, _) in &inaccessible_path_strings { + if let Some(local_def_id) = def_id.and_then(|did| did.as_local()) { + let span = source_span[local_def_id]; + let span = session.source_map().guess_head_span(span); + spans.push((name, span)); + } else { + if !has_colon { + msg.push(':'); + has_colon = true; + } + msg.push('\n'); + msg.push_str(name); + } + } + + let mut multi_span = MultiSpan::from_spans(spans.iter().map(|(_, sp)| *sp).collect()); + for (name, span) in spans { + multi_span.push_span_label(span, format!("`{}`: not accessible", name)); + } + + for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) { + err.note(note); + } + + err.span_note(multi_span, &msg); + } + } +} + +#[derive(Debug)] +struct UsePlacementFinder { + target_module: NodeId, + first_legal_span: Option<Span>, + first_use_span: Option<Span>, +} + +impl UsePlacementFinder { + fn check(krate: &Crate, target_module: NodeId) -> (Option<Span>, FoundUse) { + let mut finder = + UsePlacementFinder { target_module, first_legal_span: None, first_use_span: None }; + finder.visit_crate(krate); + if let Some(use_span) = finder.first_use_span { + (Some(use_span), FoundUse::Yes) + } else { + (finder.first_legal_span, FoundUse::No) + } + } +} + +impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder { + fn visit_crate(&mut self, c: &Crate) { + if self.target_module == CRATE_NODE_ID { + let inject = c.spans.inject_use_span; + if is_span_suitable_for_use_injection(inject) { + self.first_legal_span = Some(inject); + } + self.first_use_span = search_for_any_use_in_items(&c.items); + return; + } else { + visit::walk_crate(self, c); + } + } + + fn visit_item(&mut self, item: &'tcx ast::Item) { + if self.target_module == item.id { + if let ItemKind::Mod(_, ModKind::Loaded(items, _inline, mod_spans)) = &item.kind { + let inject = mod_spans.inject_use_span; + if is_span_suitable_for_use_injection(inject) { + self.first_legal_span = Some(inject); + } + self.first_use_span = search_for_any_use_in_items(items); + return; + } + } else { + visit::walk_item(self, item); + } + } +} + +fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> { + for item in items { + if let ItemKind::Use(..) = item.kind { + if is_span_suitable_for_use_injection(item.span) { + return Some(item.span.shrink_to_lo()); + } + } + } + return None; +} + +fn is_span_suitable_for_use_injection(s: Span) -> bool { + // don't suggest placing a use before the prelude + // import or other generated ones + !s.from_expansion() +} + +/// Convert the given number into the corresponding ordinal +pub(crate) fn ordinalize(v: usize) -> String { + let suffix = match ((11..=13).contains(&(v % 100)), v % 10) { + (false, 1) => "st", + (false, 2) => "nd", + (false, 3) => "rd", + _ => "th", + }; + format!("{v}{suffix}") +} diff --git a/compiler/rustc_resolve/src/diagnostics/tests.rs b/compiler/rustc_resolve/src/diagnostics/tests.rs new file mode 100644 index 000000000..2aa6cc61e --- /dev/null +++ b/compiler/rustc_resolve/src/diagnostics/tests.rs @@ -0,0 +1,40 @@ +use super::ordinalize; + +#[test] +fn test_ordinalize() { + assert_eq!(ordinalize(1), "1st"); + assert_eq!(ordinalize(2), "2nd"); + assert_eq!(ordinalize(3), "3rd"); + assert_eq!(ordinalize(4), "4th"); + assert_eq!(ordinalize(5), "5th"); + // ... + assert_eq!(ordinalize(10), "10th"); + assert_eq!(ordinalize(11), "11th"); + assert_eq!(ordinalize(12), "12th"); + assert_eq!(ordinalize(13), "13th"); + assert_eq!(ordinalize(14), "14th"); + // ... + assert_eq!(ordinalize(20), "20th"); + assert_eq!(ordinalize(21), "21st"); + assert_eq!(ordinalize(22), "22nd"); + assert_eq!(ordinalize(23), "23rd"); + assert_eq!(ordinalize(24), "24th"); + // ... + assert_eq!(ordinalize(30), "30th"); + assert_eq!(ordinalize(31), "31st"); + assert_eq!(ordinalize(32), "32nd"); + assert_eq!(ordinalize(33), "33rd"); + assert_eq!(ordinalize(34), "34th"); + // ... + assert_eq!(ordinalize(7010), "7010th"); + assert_eq!(ordinalize(7011), "7011th"); + assert_eq!(ordinalize(7012), "7012th"); + assert_eq!(ordinalize(7013), "7013th"); + assert_eq!(ordinalize(7014), "7014th"); + // ... + assert_eq!(ordinalize(7020), "7020th"); + assert_eq!(ordinalize(7021), "7021st"); + assert_eq!(ordinalize(7022), "7022nd"); + assert_eq!(ordinalize(7023), "7023rd"); + assert_eq!(ordinalize(7024), "7024th"); +} diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs new file mode 100644 index 000000000..6e6782881 --- /dev/null +++ b/compiler/rustc_resolve/src/ident.rs @@ -0,0 +1,1556 @@ +use rustc_ast::{self as ast, NodeId}; +use rustc_feature::is_builtin_attr_name; +use rustc_hir::def::{DefKind, Namespace, NonMacroAttrKind, PartialRes, PerNS}; +use rustc_hir::PrimTy; +use rustc_middle::bug; +use rustc_middle::ty; +use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK; +use rustc_session::lint::BuiltinLintDiagnostics; +use rustc_span::edition::Edition; +use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext}; +use rustc_span::symbol::{kw, Ident}; +use rustc_span::{Span, DUMMY_SP}; + +use std::ptr; + +use crate::late::{ConstantItemKind, HasGenericParams, PathSource, Rib, RibKind}; +use crate::macros::{sub_namespace_match, MacroRulesScope}; +use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, Determinacy, Finalize}; +use crate::{ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot}; +use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res}; +use crate::{ResolutionError, Resolver, Scope, ScopeSet, Segment, ToNameBinding, Weak}; + +use Determinacy::*; +use Namespace::*; +use RibKind::*; + +impl<'a> Resolver<'a> { + /// A generic scope visitor. + /// Visits scopes in order to resolve some identifier in them or perform other actions. + /// If the callback returns `Some` result, we stop visiting scopes and return it. + pub(crate) fn visit_scopes<T>( + &mut self, + scope_set: ScopeSet<'a>, + parent_scope: &ParentScope<'a>, + ctxt: SyntaxContext, + mut visitor: impl FnMut( + &mut Self, + Scope<'a>, + /*use_prelude*/ bool, + SyntaxContext, + ) -> Option<T>, + ) -> Option<T> { + // General principles: + // 1. Not controlled (user-defined) names should have higher priority than controlled names + // built into the language or standard library. This way we can add new names into the + // language or standard library without breaking user code. + // 2. "Closed set" below means new names cannot appear after the current resolution attempt. + // Places to search (in order of decreasing priority): + // (Type NS) + // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet + // (open set, not controlled). + // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents + // (open, not controlled). + // 3. Extern prelude (open, the open part is from macro expansions, not controlled). + // 4. Tool modules (closed, controlled right now, but not in the future). + // 5. Standard library prelude (de-facto closed, controlled). + // 6. Language prelude (closed, controlled). + // (Value NS) + // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet + // (open set, not controlled). + // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents + // (open, not controlled). + // 3. Standard library prelude (de-facto closed, controlled). + // (Macro NS) + // 1-3. Derive helpers (open, not controlled). All ambiguities with other names + // are currently reported as errors. They should be higher in priority than preludes + // and probably even names in modules according to the "general principles" above. They + // also should be subject to restricted shadowing because are effectively produced by + // 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 `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 + // ambiguities with `macro_rules`. + // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled). + // 4a. User-defined prelude from macro-use + // (open, the open part is from macro expansions, not controlled). + // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled). + // 4c. Standard library prelude (de-facto closed, controlled). + // 6. Language prelude: builtin attributes (closed, controlled). + + let rust_2015 = ctxt.edition() == Edition::Edition2015; + let (ns, macro_kind, is_absolute_path) = match scope_set { + ScopeSet::All(ns, _) => (ns, None, false), + ScopeSet::AbsolutePath(ns) => (ns, None, true), + ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), + ScopeSet::Late(ns, ..) => (ns, None, false), + }; + let module = match scope_set { + // Start with the specified module. + ScopeSet::Late(_, module, _) => module, + // Jump out of trait or enum modules, they do not act as scopes. + _ => parent_scope.module.nearest_item_scope(), + }; + let mut scope = match ns { + _ if is_absolute_path => Scope::CrateRoot, + TypeNS | ValueNS => Scope::Module(module, None), + MacroNS => Scope::DeriveHelpers(parent_scope.expansion), + }; + let mut ctxt = ctxt.normalize_to_macros_2_0(); + let mut use_prelude = !module.no_implicit_prelude; + + loop { + let visit = match scope { + // Derive helpers are not in scope when resolving derives in the same container. + Scope::DeriveHelpers(expn_id) => { + !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive)) + } + Scope::DeriveHelpersCompat => true, + Scope::MacroRules(macro_rules_scope) => { + // Use "path compression" on `macro_rules` scope chains. This is an optimization + // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`. + // As another consequence of this optimization visitors never observe invocation + // scopes for macros that were already expanded. + while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() { + if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) { + macro_rules_scope.set(next_scope.get()); + } else { + break; + } + } + true + } + Scope::CrateRoot => true, + Scope::Module(..) => true, + Scope::RegisteredAttrs => use_prelude, + Scope::MacroUsePrelude => use_prelude || rust_2015, + Scope::BuiltinAttrs => true, + Scope::ExternPrelude => use_prelude || is_absolute_path, + Scope::ToolPrelude => use_prelude, + Scope::StdLibPrelude => use_prelude || ns == MacroNS, + Scope::BuiltinTypes => true, + }; + + if visit { + if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) { + return break_result; + } + } + + scope = match scope { + Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat, + Scope::DeriveHelpers(expn_id) => { + // Derive helpers are not visible to code generated by bang or derive macros. + let expn_data = expn_id.expn_data(); + match expn_data.kind { + ExpnKind::Root + | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => { + Scope::DeriveHelpersCompat + } + _ => Scope::DeriveHelpers(expn_data.parent.expect_local()), + } + } + Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), + Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { + MacroRulesScope::Binding(binding) => { + Scope::MacroRules(binding.parent_macro_rules_scope) + } + MacroRulesScope::Invocation(invoc_id) => { + Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules) + } + MacroRulesScope::Empty => Scope::Module(module, None), + }, + Scope::CrateRoot => match ns { + TypeNS => { + ctxt.adjust(ExpnId::root()); + Scope::ExternPrelude + } + ValueNS | MacroNS => break, + }, + Scope::Module(module, prev_lint_id) => { + use_prelude = !module.no_implicit_prelude; + let derive_fallback_lint_id = match scope_set { + ScopeSet::Late(.., lint_id) => lint_id, + _ => None, + }; + match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) { + Some((parent_module, lint_id)) => { + Scope::Module(parent_module, lint_id.or(prev_lint_id)) + } + None => { + ctxt.adjust(ExpnId::root()); + match ns { + TypeNS => Scope::ExternPrelude, + ValueNS => Scope::StdLibPrelude, + MacroNS => Scope::RegisteredAttrs, + } + } + } + } + Scope::RegisteredAttrs => Scope::MacroUsePrelude, + Scope::MacroUsePrelude => Scope::StdLibPrelude, + Scope::BuiltinAttrs => break, // nowhere else to search + Scope::ExternPrelude if is_absolute_path => break, + Scope::ExternPrelude => Scope::ToolPrelude, + Scope::ToolPrelude => Scope::StdLibPrelude, + Scope::StdLibPrelude => match ns { + TypeNS => Scope::BuiltinTypes, + ValueNS => break, // nowhere else to search + MacroNS => Scope::BuiltinAttrs, + }, + Scope::BuiltinTypes => break, // nowhere else to search + }; + } + + None + } + + fn hygienic_lexical_parent( + &mut self, + module: Module<'a>, + ctxt: &mut SyntaxContext, + derive_fallback_lint_id: Option<NodeId>, + ) -> Option<(Module<'a>, Option<NodeId>)> { + if !module.expansion.outer_expn_is_descendant_of(*ctxt) { + return Some((self.expn_def_scope(ctxt.remove_mark()), None)); + } + + if let ModuleKind::Block = module.kind { + return Some((module.parent.unwrap().nearest_item_scope(), None)); + } + + // We need to support the next case under a deprecation warning + // ``` + // struct MyStruct; + // ---- begin: this comes from a proc macro derive + // mod implementation_details { + // // Note that `MyStruct` is not in scope here. + // impl SomeTrait for MyStruct { ... } + // } + // ---- end + // ``` + // So we have to fall back to the module's parent during lexical resolution in this case. + if derive_fallback_lint_id.is_some() { + if let Some(parent) = module.parent { + // Inner module is inside the macro, parent module is outside of the macro. + if module.expansion != parent.expansion + && module.expansion.is_descendant_of(parent.expansion) + { + // The macro is a proc macro derive + if let Some(def_id) = module.expansion.expn_data().macro_def_id { + let ext = self.get_macro_by_def_id(def_id).ext; + if ext.builtin_name.is_none() + && ext.macro_kind() == MacroKind::Derive + && parent.expansion.outer_expn_is_descendant_of(*ctxt) + { + return Some((parent, derive_fallback_lint_id)); + } + } + } + } + } + + None + } + + /// This resolves the identifier `ident` in the namespace `ns` in the current lexical scope. + /// More specifically, we proceed up the hierarchy of scopes and return the binding for + /// `ident` in the first scope that defines it (or None if no scopes define it). + /// + /// A block's items are above its local variables in the scope hierarchy, regardless of where + /// the items are defined in the block. For example, + /// ```rust + /// fn f() { + /// g(); // Since there are no local variables in scope yet, this resolves to the item. + /// let g = || {}; + /// fn g() {} + /// g(); // This resolves to the local variable `g` since it shadows the item. + /// } + /// ``` + /// + /// Invariant: This must only be called during main resolution, not during + /// import resolution. + #[tracing::instrument(level = "debug", skip(self, ribs))] + pub(crate) fn resolve_ident_in_lexical_scope( + &mut self, + mut ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ribs: &[Rib<'a>], + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Option<LexicalScopeBinding<'a>> { + assert!(ns == TypeNS || ns == ValueNS); + let orig_ident = ident; + if ident.name == kw::Empty { + return Some(LexicalScopeBinding::Res(Res::Err)); + } + 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 normalized_span = ident.span.normalize_to_macros_2_0(); + (normalized_span, normalized_span) + } else { + (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) + }; + ident.span = general_span; + let normalized_ident = Ident { span: normalized_span, ..ident }; + + // Walk backwards up the ribs in scope. + let mut module = self.graph_root; + 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 + // (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((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident) + { + // The ident resolves to a type parameter or local variable. + return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( + i, + rib_ident, + *res, + finalize.map(|finalize| finalize.path_span), + *original_rib_ident_def, + ribs, + ))); + } + + module = match ribs[i].kind { + ModuleRibKind(module) => module, + MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { + // If an invocation of this macro created `ident`, give up on `ident` + // and switch to `ident`'s source from the macro definition. + ident.span.remove_mark(); + continue; + } + _ => continue, + }; + + match module.kind { + ModuleKind::Block => {} // We can see through blocks + _ => break, + } + + let item = self.resolve_ident_in_module_unadjusted( + ModuleOrUniformRoot::Module(module), + ident, + ns, + parent_scope, + finalize, + ignore_binding, + ); + if let Ok(binding) = item { + // The ident resolves to an item. + return Some(LexicalScopeBinding::Item(binding)); + } + } + self.early_resolve_ident_in_lexical_scope( + orig_ident, + ScopeSet::Late(ns, module, finalize.map(|finalize| finalize.node_id)), + parent_scope, + finalize, + finalize.is_some(), + ignore_binding, + ) + .ok() + .map(LexicalScopeBinding::Item) + } + + /// Resolve an identifier in lexical scope. + /// This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during + /// expansion and import resolution (perhaps they can be merged in the future). + /// The function is used for resolving initial segments of macro paths (e.g., `foo` in + /// `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition. + #[tracing::instrument(level = "debug", skip(self, scope_set))] + pub(crate) fn early_resolve_ident_in_lexical_scope( + &mut self, + orig_ident: Ident, + scope_set: ScopeSet<'a>, + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + force: bool, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Result<&'a NameBinding<'a>, Determinacy> { + bitflags::bitflags! { + struct Flags: u8 { + const MACRO_RULES = 1 << 0; + const MODULE = 1 << 1; + const MISC_SUGGEST_CRATE = 1 << 2; + const MISC_SUGGEST_SELF = 1 << 3; + const MISC_FROM_PRELUDE = 1 << 4; + } + } + + assert!(force || !finalize.is_some()); // `finalize` implies `force` + + // Make sure `self`, `super` etc produce an error when passed to here. + if orig_ident.is_path_segment_keyword() { + return Err(Determinacy::Determined); + } + + let (ns, macro_kind, is_import) = match scope_set { + ScopeSet::All(ns, is_import) => (ns, None, is_import), + ScopeSet::AbsolutePath(ns) => (ns, None, false), + ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), + ScopeSet::Late(ns, ..) => (ns, None, false), + }; + + // This is *the* result, resolution from the scope closest to the resolved identifier. + // However, sometimes this result is "weak" because it comes from a glob import or + // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g. + // mod m { ... } // solution in outer scope + // { + // use prefix::*; // imports another `m` - innermost solution + // // weak, cannot shadow the outer `m`, need to report ambiguity error + // m::mac!(); + // } + // So we have to save the innermost solution and continue searching in outer scopes + // to detect potential ambiguities. + let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None; + let mut determinacy = Determinacy::Determined; + + // Go through all the scopes and try to resolve the name. + let break_result = self.visit_scopes( + scope_set, + parent_scope, + orig_ident.span.ctxt(), + |this, scope, use_prelude, ctxt| { + let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt)); + let ok = |res, span, arenas| { + Ok(( + (res, ty::Visibility::Public, span, LocalExpnId::ROOT) + .to_name_binding(arenas), + Flags::empty(), + )) + }; + let result = match scope { + Scope::DeriveHelpers(expn_id) => { + if let Some(attr) = this + .helper_attrs + .get(&expn_id) + .and_then(|attrs| attrs.iter().rfind(|i| ident == **i)) + { + let binding = ( + Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper), + ty::Visibility::Public, + attr.span, + expn_id, + ) + .to_name_binding(this.arenas); + Ok((binding, Flags::empty())) + } else { + Err(Determinacy::Determined) + } + } + Scope::DeriveHelpersCompat => { + let mut result = Err(Determinacy::Determined); + for derive in parent_scope.derives { + let parent_scope = &ParentScope { derives: &[], ..*parent_scope }; + match this.resolve_macro_path( + derive, + Some(MacroKind::Derive), + parent_scope, + true, + force, + ) { + Ok((Some(ext), _)) => { + if ext.helper_attrs.contains(&ident.name) { + result = ok( + Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat), + derive.span, + this.arenas, + ); + break; + } + } + Ok(_) | Err(Determinacy::Determined) => {} + Err(Determinacy::Undetermined) => { + result = Err(Determinacy::Undetermined) + } + } + } + result + } + Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { + MacroRulesScope::Binding(macro_rules_binding) + if ident == macro_rules_binding.ident => + { + Ok((macro_rules_binding.binding, Flags::MACRO_RULES)) + } + MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined), + _ => Err(Determinacy::Determined), + }, + Scope::CrateRoot => { + let root_ident = Ident::new(kw::PathRoot, ident.span); + let root_module = this.resolve_crate_root(root_ident); + let binding = this.resolve_ident_in_module_ext( + ModuleOrUniformRoot::Module(root_module), + ident, + ns, + parent_scope, + finalize, + ignore_binding, + ); + match binding { + Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)), + Err((Determinacy::Undetermined, Weak::No)) => { + return Some(Err(Determinacy::determined(force))); + } + Err((Determinacy::Undetermined, Weak::Yes)) => { + Err(Determinacy::Undetermined) + } + Err((Determinacy::Determined, _)) => Err(Determinacy::Determined), + } + } + Scope::Module(module, derive_fallback_lint_id) => { + let adjusted_parent_scope = &ParentScope { module, ..*parent_scope }; + let binding = this.resolve_ident_in_module_unadjusted_ext( + ModuleOrUniformRoot::Module(module), + ident, + ns, + adjusted_parent_scope, + !matches!(scope_set, ScopeSet::Late(..)), + finalize, + ignore_binding, + ); + match binding { + Ok(binding) => { + if let Some(lint_id) = derive_fallback_lint_id { + this.lint_buffer.buffer_lint_with_diagnostic( + PROC_MACRO_DERIVE_RESOLUTION_FALLBACK, + lint_id, + orig_ident.span, + &format!( + "cannot find {} `{}` in this scope", + ns.descr(), + ident + ), + BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback( + orig_ident.span, + ), + ); + } + let misc_flags = if ptr::eq(module, this.graph_root) { + Flags::MISC_SUGGEST_CRATE + } else if module.is_normal() { + Flags::MISC_SUGGEST_SELF + } else { + Flags::empty() + }; + Ok((binding, Flags::MODULE | misc_flags)) + } + Err((Determinacy::Undetermined, Weak::No)) => { + return Some(Err(Determinacy::determined(force))); + } + Err((Determinacy::Undetermined, Weak::Yes)) => { + Err(Determinacy::Undetermined) + } + Err((Determinacy::Determined, _)) => Err(Determinacy::Determined), + } + } + Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() { + Some(ident) => ok( + Res::NonMacroAttr(NonMacroAttrKind::Registered), + ident.span, + this.arenas, + ), + None => Err(Determinacy::Determined), + }, + Scope::MacroUsePrelude => { + match this.macro_use_prelude.get(&ident.name).cloned() { + Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)), + None => Err(Determinacy::determined( + this.graph_root.unexpanded_invocations.borrow().is_empty(), + )), + } + } + Scope::BuiltinAttrs => { + if is_builtin_attr_name(ident.name) { + ok( + Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)), + DUMMY_SP, + this.arenas, + ) + } else { + Err(Determinacy::Determined) + } + } + Scope::ExternPrelude => { + match this.extern_prelude_get(ident, finalize.is_some()) { + Some(binding) => Ok((binding, Flags::empty())), + None => Err(Determinacy::determined( + this.graph_root.unexpanded_invocations.borrow().is_empty(), + )), + } + } + Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() { + Some(ident) => ok(Res::ToolMod, ident.span, this.arenas), + None => Err(Determinacy::Determined), + }, + Scope::StdLibPrelude => { + let mut result = Err(Determinacy::Determined); + if let Some(prelude) = this.prelude { + if let Ok(binding) = this.resolve_ident_in_module_unadjusted( + ModuleOrUniformRoot::Module(prelude), + ident, + ns, + parent_scope, + None, + ignore_binding, + ) { + if use_prelude || this.is_builtin_macro(binding.res()) { + result = Ok((binding, Flags::MISC_FROM_PRELUDE)); + } + } + } + result + } + Scope::BuiltinTypes => match PrimTy::from_name(ident.name) { + Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas), + None => Err(Determinacy::Determined), + }, + }; + + match result { + Ok((binding, flags)) + if sub_namespace_match(binding.macro_kind(), macro_kind) => + { + if finalize.is_none() || matches!(scope_set, ScopeSet::Late(..)) { + return Some(Ok(binding)); + } + + if let Some((innermost_binding, innermost_flags)) = innermost_result { + // Found another solution, if the first one was "weak", report an error. + let (res, innermost_res) = (binding.res(), innermost_binding.res()); + if res != innermost_res { + let is_builtin = |res| { + matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..))) + }; + let derive_helper = + Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper); + let derive_helper_compat = + Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat); + + let ambiguity_error_kind = if is_import { + Some(AmbiguityKind::Import) + } else if is_builtin(innermost_res) || is_builtin(res) { + Some(AmbiguityKind::BuiltinAttr) + } else if innermost_res == derive_helper_compat + || res == derive_helper_compat && innermost_res != derive_helper + { + Some(AmbiguityKind::DeriveHelper) + } else if innermost_flags.contains(Flags::MACRO_RULES) + && flags.contains(Flags::MODULE) + && !this.disambiguate_macro_rules_vs_modularized( + innermost_binding, + binding, + ) + || flags.contains(Flags::MACRO_RULES) + && innermost_flags.contains(Flags::MODULE) + && !this.disambiguate_macro_rules_vs_modularized( + binding, + innermost_binding, + ) + { + Some(AmbiguityKind::MacroRulesVsModularized) + } else if innermost_binding.is_glob_import() { + Some(AmbiguityKind::GlobVsOuter) + } else if innermost_binding + .may_appear_after(parent_scope.expansion, binding) + { + Some(AmbiguityKind::MoreExpandedVsOuter) + } else { + None + }; + if let Some(kind) = ambiguity_error_kind { + let misc = |f: Flags| { + if f.contains(Flags::MISC_SUGGEST_CRATE) { + AmbiguityErrorMisc::SuggestCrate + } else if f.contains(Flags::MISC_SUGGEST_SELF) { + AmbiguityErrorMisc::SuggestSelf + } else if f.contains(Flags::MISC_FROM_PRELUDE) { + AmbiguityErrorMisc::FromPrelude + } else { + AmbiguityErrorMisc::None + } + }; + this.ambiguity_errors.push(AmbiguityError { + kind, + ident: orig_ident, + b1: innermost_binding, + b2: binding, + misc1: misc(innermost_flags), + misc2: misc(flags), + }); + return Some(Ok(innermost_binding)); + } + } + } else { + // Found the first solution. + innermost_result = Some((binding, flags)); + } + } + Ok(..) | Err(Determinacy::Determined) => {} + Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined, + } + + None + }, + ); + + if let Some(break_result) = break_result { + return break_result; + } + + // The first found solution was the only one, return it. + if let Some((binding, _)) = innermost_result { + return Ok(binding); + } + + Err(Determinacy::determined(determinacy == Determinacy::Determined || force)) + } + + #[tracing::instrument(level = "debug", skip(self))] + pub(crate) fn maybe_resolve_ident_in_module( + &mut self, + module: ModuleOrUniformRoot<'a>, + ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + ) -> Result<&'a NameBinding<'a>, Determinacy> { + self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, None, None) + .map_err(|(determinacy, _)| determinacy) + } + + #[tracing::instrument(level = "debug", skip(self))] + pub(crate) fn resolve_ident_in_module( + &mut self, + module: ModuleOrUniformRoot<'a>, + ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Result<&'a NameBinding<'a>, Determinacy> { + self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, finalize, ignore_binding) + .map_err(|(determinacy, _)| determinacy) + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_ident_in_module_ext( + &mut self, + module: ModuleOrUniformRoot<'a>, + mut ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { + let tmp_parent_scope; + let mut adjusted_parent_scope = parent_scope; + match module { + ModuleOrUniformRoot::Module(m) => { + if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { + tmp_parent_scope = + ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; + adjusted_parent_scope = &tmp_parent_scope; + } + } + ModuleOrUniformRoot::ExternPrelude => { + ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); + } + ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { + // No adjustments + } + } + self.resolve_ident_in_module_unadjusted_ext( + module, + ident, + ns, + adjusted_parent_scope, + false, + finalize, + ignore_binding, + ) + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_ident_in_module_unadjusted( + &mut self, + module: ModuleOrUniformRoot<'a>, + ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Result<&'a NameBinding<'a>, Determinacy> { + self.resolve_ident_in_module_unadjusted_ext( + module, + ident, + ns, + parent_scope, + false, + finalize, + ignore_binding, + ) + .map_err(|(determinacy, _)| determinacy) + } + + /// Attempts to resolve `ident` in namespaces `ns` of `module`. + /// Invariant: if `finalize` is `Some`, expansion and import resolution must be complete. + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_ident_in_module_unadjusted_ext( + &mut self, + module: ModuleOrUniformRoot<'a>, + ident: Ident, + ns: Namespace, + parent_scope: &ParentScope<'a>, + restricted_shadowing: bool, + finalize: Option<Finalize>, + // This binding should be ignored during in-module resolution, so that we don't get + // "self-confirming" import resolutions during import validation and checking. + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { + let module = match module { + ModuleOrUniformRoot::Module(module) => module, + ModuleOrUniformRoot::CrateRootAndExternPrelude => { + assert!(!restricted_shadowing); + let binding = self.early_resolve_ident_in_lexical_scope( + ident, + ScopeSet::AbsolutePath(ns), + parent_scope, + finalize, + finalize.is_some(), + ignore_binding, + ); + return binding.map_err(|determinacy| (determinacy, Weak::No)); + } + ModuleOrUniformRoot::ExternPrelude => { + assert!(!restricted_shadowing); + return if ns != TypeNS { + Err((Determined, Weak::No)) + } else if let Some(binding) = self.extern_prelude_get(ident, finalize.is_some()) { + Ok(binding) + } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() { + // Macro-expanded `extern crate` items can add names to extern prelude. + Err((Undetermined, Weak::No)) + } else { + Err((Determined, Weak::No)) + }; + } + ModuleOrUniformRoot::CurrentScope => { + assert!(!restricted_shadowing); + if ns == TypeNS { + if ident.name == kw::Crate || ident.name == kw::DollarCrate { + let module = self.resolve_crate_root(ident); + let binding = + (module, ty::Visibility::Public, module.span, LocalExpnId::ROOT) + .to_name_binding(self.arenas); + return Ok(binding); + } else if ident.name == kw::Super || ident.name == kw::SelfLower { + // FIXME: Implement these with renaming requirements so that e.g. + // `use super;` doesn't work, but `use super as name;` does. + // Fall through here to get an error from `early_resolve_...`. + } + } + + let scopes = ScopeSet::All(ns, true); + let binding = self.early_resolve_ident_in_lexical_scope( + ident, + scopes, + parent_scope, + finalize, + finalize.is_some(), + ignore_binding, + ); + return binding.map_err(|determinacy| (determinacy, Weak::No)); + } + }; + + let key = self.new_key(ident, ns); + let resolution = + self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports. + + if let Some(Finalize { path_span, report_private, .. }) = finalize { + // If the primary binding is unusable, search further and return the shadowed glob + // binding if it exists. What we really want here is having two separate scopes in + // a module - one for non-globs and one for globs, but until that's done use this + // hack to avoid inconsistent resolution ICEs during import validation. + let binding = [resolution.binding, resolution.shadowed_glob] + .into_iter() + .filter_map(|binding| match (binding, ignore_binding) { + (Some(binding), Some(ignored)) if ptr::eq(binding, ignored) => None, + _ => binding, + }) + .next(); + let Some(binding) = binding else { + return Err((Determined, Weak::No)); + }; + + if !self.is_accessible_from(binding.vis, parent_scope.module) { + if report_private { + self.privacy_errors.push(PrivacyError { + ident, + binding, + dedup_span: path_span, + }); + } else { + return Err((Determined, Weak::No)); + } + } + + // Forbid expanded shadowing to avoid time travel. + if let Some(shadowed_glob) = resolution.shadowed_glob + && restricted_shadowing + && binding.expansion != LocalExpnId::ROOT + && binding.res() != shadowed_glob.res() + { + self.ambiguity_errors.push(AmbiguityError { + kind: AmbiguityKind::GlobVsExpanded, + ident, + b1: binding, + b2: shadowed_glob, + misc1: AmbiguityErrorMisc::None, + misc2: AmbiguityErrorMisc::None, + }); + } + + if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT { + if let NameBindingKind::Res(_, true) = binding.kind { + self.macro_expanded_macro_export_errors.insert((path_span, binding.span)); + } + } + + self.record_use(ident, binding, restricted_shadowing); + return Ok(binding); + } + + let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| { + if let Some(ignored) = ignore_binding && ptr::eq(binding, ignored) { + return Err((Determined, Weak::No)); + } + let usable = this.is_accessible_from(binding.vis, parent_scope.module); + if usable { Ok(binding) } else { Err((Determined, Weak::No)) } + }; + + // Items and single imports are not shadowable, if we have one, then it's determined. + if let Some(binding) = resolution.binding { + if !binding.is_glob_import() { + return check_usable(self, binding); + } + } + + // --- From now on we either have a glob resolution or no resolution. --- + + // Check if one of single imports can still define the name, + // if it can then our result is not determined and can be invalidated. + for single_import in &resolution.single_imports { + if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) { + continue; + } + let Some(module) = single_import.imported_module.get() else { + return Err((Undetermined, Weak::No)); + }; + let ImportKind::Single { source: ident, .. } = single_import.kind else { + unreachable!(); + }; + match self.resolve_ident_in_module( + module, + ident, + ns, + &single_import.parent_scope, + None, + ignore_binding, + ) { + Err(Determined) => continue, + Ok(binding) + if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) => + { + continue; + } + Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)), + } + } + + // So we have a resolution that's from a glob import. This resolution is determined + // if it cannot be shadowed by some new item/import expanded from a macro. + // This happens either if there are no unexpanded macros, or expanded names cannot + // shadow globs (that happens in macro namespace or with restricted shadowing). + // + // Additionally, any macro in any module can plant names in the root module if it creates + // `macro_export` macros, so the root module effectively has unresolved invocations if any + // module has unresolved invocations. + // However, it causes resolution/expansion to stuck too often (#53144), so, to make + // progress, we have to ignore those potential unresolved invocations from other modules + // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted + // shadowing is enabled, see `macro_expanded_macro_export_errors`). + let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty(); + if let Some(binding) = resolution.binding { + if !unexpanded_macros || ns == MacroNS || restricted_shadowing { + return check_usable(self, binding); + } else { + return Err((Undetermined, Weak::No)); + } + } + + // --- From now on we have no resolution. --- + + // Now we are in situation when new item/import can appear only from a glob or a macro + // expansion. With restricted shadowing names from globs and macro expansions cannot + // shadow names from outer scopes, so we can freely fallback from module search to search + // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer + // scopes we return `Undetermined` with `Weak::Yes`. + + // Check if one of unexpanded macros can still define the name, + // if it can then our "no resolution" result is not determined and can be invalidated. + if unexpanded_macros { + return Err((Undetermined, Weak::Yes)); + } + + // Check if one of glob imports can still define the name, + // if it can then our "no resolution" result is not determined and can be invalidated. + for glob_import in module.globs.borrow().iter() { + if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) { + continue; + } + let module = match glob_import.imported_module.get() { + Some(ModuleOrUniformRoot::Module(module)) => module, + Some(_) => continue, + None => return Err((Undetermined, Weak::Yes)), + }; + let tmp_parent_scope; + 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 = + ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; + adjusted_parent_scope = &tmp_parent_scope; + } + Some(None) => {} + None => continue, + }; + let result = self.resolve_ident_in_module_unadjusted( + ModuleOrUniformRoot::Module(module), + ident, + ns, + adjusted_parent_scope, + None, + ignore_binding, + ); + + match result { + Err(Determined) => continue, + Ok(binding) + if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) => + { + continue; + } + Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)), + } + } + + // No resolution and no one else can define the name - determinate error. + Err((Determined, Weak::No)) + } + + /// Validate a local resolution (from ribs). + #[tracing::instrument(level = "debug", skip(self, all_ribs))] + fn validate_res_from_ribs( + &mut self, + rib_index: usize, + rib_ident: Ident, + mut res: Res, + finalize: Option<Span>, + original_rib_ident_def: Ident, + all_ribs: &[Rib<'a>], + ) -> Res { + const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation"; + debug!("validate_res_from_ribs({:?})", res); + let ribs = &all_ribs[rib_index + 1..]; + + // An invalid forward use of a generic parameter from a previous default. + if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind { + if let Some(span) = finalize { + let res_error = if rib_ident.name == kw::SelfUpper { + ResolutionError::SelfInGenericParamDefault + } else { + ResolutionError::ForwardDeclaredGenericParam + }; + self.report_error(span, res_error); + } + assert_eq!(res, Res::Err); + return Res::Err; + } + + match res { + Res::Local(_) => { + use ResolutionError::*; + let mut res_err = None; + + for rib in ribs { + match rib.kind { + NormalRibKind + | ClosureOrAsyncRibKind + | ModuleRibKind(..) + | MacroDefinition(..) + | ForwardGenericParamBanRibKind => { + // Nothing to do. Continue. + } + ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => { + // This was an attempt to access an upvar inside a + // named function item. This is not allowed, so we + // report an error. + if let Some(span) = finalize { + // We don't immediately trigger a resolve error, because + // we want certain other resolution errors (namely those + // emitted for `ConstantItemRibKind` below) to take + // precedence. + res_err = Some((span, CannotCaptureDynamicEnvironmentInFnItem)); + } + } + ConstantItemRibKind(_, item) => { + // Still doesn't deal with upvars + if let Some(span) = finalize { + let (span, resolution_error) = + if let Some((ident, constant_item_kind)) = item { + let kind_str = match constant_item_kind { + ConstantItemKind::Const => "const", + ConstantItemKind::Static => "static", + }; + ( + span, + AttemptToUseNonConstantValueInConstant( + ident, "let", kind_str, + ), + ) + } else { + ( + rib_ident.span, + AttemptToUseNonConstantValueInConstant( + original_rib_ident_def, + "const", + "let", + ), + ) + }; + self.report_error(span, resolution_error); + } + return Res::Err; + } + ConstParamTyRibKind => { + if let Some(span) = finalize { + self.report_error(span, ParamInTyOfConstParam(rib_ident.name)); + } + return Res::Err; + } + InlineAsmSymRibKind => { + if let Some(span) = finalize { + self.report_error(span, InvalidAsmSym); + } + return Res::Err; + } + } + } + if let Some((span, res_err)) = res_err { + self.report_error(span, res_err); + return Res::Err; + } + } + Res::Def(DefKind::TyParam, _) | Res::SelfTy { .. } => { + for rib in ribs { + let has_generic_params: HasGenericParams = match rib.kind { + NormalRibKind + | ClosureOrAsyncRibKind + | AssocItemRibKind + | ModuleRibKind(..) + | MacroDefinition(..) + | InlineAsmSymRibKind + | ForwardGenericParamBanRibKind => { + // Nothing to do. Continue. + continue; + } + + ConstantItemRibKind(trivial, _) => { + let features = self.session.features_untracked(); + // HACK(min_const_generics): We currently only allow `N` or `{ N }`. + if !(trivial == HasGenericParams::Yes || features.generic_const_exprs) { + // HACK(min_const_generics): If we encounter `Self` in an anonymous constant + // we can't easily tell if it's generic at this stage, so we instead remember + // this and then enforce the self type to be concrete later on. + if let Res::SelfTy { trait_, alias_to: Some((def, _)) } = res { + res = Res::SelfTy { trait_, alias_to: Some((def, true)) } + } else { + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::ParamInNonTrivialAnonConst { + name: rib_ident.name, + is_type: true, + }, + ); + self.session.delay_span_bug(span, CG_BUG_STR); + } + + return Res::Err; + } + } + + continue; + } + + // This was an attempt to use a type parameter outside its scope. + ItemRibKind(has_generic_params) => has_generic_params, + FnItemRibKind => HasGenericParams::Yes, + ConstParamTyRibKind => { + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::ParamInTyOfConstParam(rib_ident.name), + ); + } + return Res::Err; + } + }; + + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::GenericParamsFromOuterFunction( + res, + has_generic_params, + ), + ); + } + return Res::Err; + } + } + Res::Def(DefKind::ConstParam, _) => { + let mut ribs = ribs.iter().peekable(); + if let Some(Rib { kind: FnItemRibKind, .. }) = ribs.peek() { + // When declaring const parameters inside function signatures, the first rib + // is always a `FnItemRibKind`. In this case, we can skip it, to avoid it + // (spuriously) conflicting with the const param. + ribs.next(); + } + + for rib in ribs { + let has_generic_params = match rib.kind { + NormalRibKind + | ClosureOrAsyncRibKind + | AssocItemRibKind + | ModuleRibKind(..) + | MacroDefinition(..) + | InlineAsmSymRibKind + | ForwardGenericParamBanRibKind => continue, + + ConstantItemRibKind(trivial, _) => { + let features = self.session.features_untracked(); + // HACK(min_const_generics): We currently only allow `N` or `{ N }`. + if !(trivial == HasGenericParams::Yes || features.generic_const_exprs) { + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::ParamInNonTrivialAnonConst { + name: rib_ident.name, + is_type: false, + }, + ); + self.session.delay_span_bug(span, CG_BUG_STR); + } + + return Res::Err; + } + + continue; + } + + ItemRibKind(has_generic_params) => has_generic_params, + FnItemRibKind => HasGenericParams::Yes, + ConstParamTyRibKind => { + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::ParamInTyOfConstParam(rib_ident.name), + ); + } + return Res::Err; + } + }; + + // This was an attempt to use a const parameter outside its scope. + if let Some(span) = finalize { + self.report_error( + span, + ResolutionError::GenericParamsFromOuterFunction( + res, + has_generic_params, + ), + ); + } + return Res::Err; + } + } + _ => {} + } + res + } + + #[tracing::instrument(level = "debug", skip(self))] + pub(crate) fn maybe_resolve_path( + &mut self, + path: &[Segment], + opt_ns: Option<Namespace>, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + ) -> PathResult<'a> { + self.resolve_path_with_ribs(path, opt_ns, parent_scope, None, None, None) + } + + #[tracing::instrument(level = "debug", skip(self))] + pub(crate) fn resolve_path( + &mut self, + path: &[Segment], + opt_ns: Option<Namespace>, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> PathResult<'a> { + self.resolve_path_with_ribs(path, opt_ns, parent_scope, finalize, None, ignore_binding) + } + + pub(crate) fn resolve_path_with_ribs( + &mut self, + path: &[Segment], + opt_ns: Option<Namespace>, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + finalize: Option<Finalize>, + ribs: Option<&PerNS<Vec<Rib<'a>>>>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> PathResult<'a> { + debug!("resolve_path(path={:?}, opt_ns={:?}, finalize={:?})", path, opt_ns, finalize); + + let mut module = None; + let mut allow_super = true; + let mut second_binding = None; + + for (i, &Segment { ident, id, .. }) in path.iter().enumerate() { + debug!("resolve_path ident {} {:?} {:?}", i, ident, id); + let record_segment_res = |this: &mut Self, res| { + if finalize.is_some() { + if let Some(id) = id { + if !this.partial_res_map.contains_key(&id) { + assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); + this.record_partial_res(id, PartialRes::new(res)); + } + } + } + }; + + let is_last = i == path.len() - 1; + let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; + let name = ident.name; + + allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super); + + if ns == TypeNS { + if allow_super && name == kw::Super { + 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 { + Some(ModuleOrUniformRoot::Module(module)) => Some(module), + _ => None, + }, + }; + if let Some(self_module) = self_module { + if let Some(parent) = self_module.parent { + module = Some(ModuleOrUniformRoot::Module( + self.resolve_self(&mut ctxt, parent), + )); + continue; + } + } + return PathResult::failed(ident.span, false, finalize.is_some(), || { + ("there are too many leading `super` keywords".to_string(), None) + }); + } + if i == 0 { + if name == kw::SelfLower { + let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); + module = Some(ModuleOrUniformRoot::Module( + self.resolve_self(&mut ctxt, parent_scope.module), + )); + continue; + } + if name == kw::PathRoot && ident.span.rust_2018() { + module = Some(ModuleOrUniformRoot::ExternPrelude); + continue; + } + if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { + // `::a::b` from 2015 macro on 2018 global edition + module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); + continue; + } + if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { + // `::a::b`, `crate::a::b` or `$crate::a::b` + module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident))); + continue; + } + } + } + + // Report special messages for path segment keywords in wrong positions. + if ident.is_path_segment_keyword() && i != 0 { + return PathResult::failed(ident.span, false, finalize.is_some(), || { + let name_str = if name == kw::PathRoot { + "crate root".to_string() + } else { + format!("`{}`", name) + }; + let label = if i == 1 && path[0].ident.name == kw::PathRoot { + format!("global paths cannot start with {}", name_str) + } else { + format!("{} in paths can only be used in start position", name_str) + }; + (label, None) + }); + } + + enum FindBindingResult<'a> { + Binding(Result<&'a NameBinding<'a>, Determinacy>), + Res(Res), + } + let find_binding_in_ns = |this: &mut Self, ns| { + let binding = if let Some(module) = module { + this.resolve_ident_in_module( + module, + ident, + ns, + parent_scope, + finalize, + ignore_binding, + ) + } else if let Some(ribs) = ribs + && let Some(TypeNS | ValueNS) = opt_ns + { + match this.resolve_ident_in_lexical_scope( + ident, + ns, + parent_scope, + finalize, + &ribs[ns], + ignore_binding, + ) { + // we found a locally-imported or available item/module + Some(LexicalScopeBinding::Item(binding)) => Ok(binding), + // we found a local variable or type param + Some(LexicalScopeBinding::Res(res)) => return FindBindingResult::Res(res), + _ => Err(Determinacy::determined(finalize.is_some())), + } + } else { + let scopes = ScopeSet::All(ns, opt_ns.is_none()); + this.early_resolve_ident_in_lexical_scope( + ident, + scopes, + parent_scope, + finalize, + finalize.is_some(), + ignore_binding, + ) + }; + FindBindingResult::Binding(binding) + }; + let binding = match find_binding_in_ns(self, ns) { + FindBindingResult::Res(res) => { + record_segment_res(self, res); + return PathResult::NonModule(PartialRes::with_unresolved_segments( + res, + path.len() - 1, + )); + } + FindBindingResult::Binding(binding) => binding, + }; + match binding { + Ok(binding) => { + if i == 1 { + second_binding = Some(binding); + } + let res = binding.res(); + let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res); + if let Some(next_module) = binding.module() { + module = Some(ModuleOrUniformRoot::Module(next_module)); + record_segment_res(self, res); + } else if res == Res::ToolMod && i + 1 != path.len() { + if binding.is_import() { + self.session + .struct_span_err( + ident.span, + "cannot use a tool module through an import", + ) + .span_note(binding.span, "the tool module imported here") + .emit(); + } + let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); + return PathResult::NonModule(PartialRes::new(res)); + } else if res == Res::Err { + return PathResult::NonModule(PartialRes::new(Res::Err)); + } else if opt_ns.is_some() && (is_last || maybe_assoc) { + self.lint_if_path_starts_with_module(finalize, path, second_binding); + record_segment_res(self, res); + return PathResult::NonModule(PartialRes::with_unresolved_segments( + res, + path.len() - i - 1, + )); + } else { + return PathResult::failed(ident.span, is_last, finalize.is_some(), || { + let label = format!( + "`{ident}` is {} {}, not a module", + res.article(), + res.descr() + ); + (label, None) + }); + } + } + Err(Undetermined) => return PathResult::Indeterminate, + Err(Determined) => { + if let Some(ModuleOrUniformRoot::Module(module)) = module { + if opt_ns.is_some() && !module.is_normal() { + return PathResult::NonModule(PartialRes::with_unresolved_segments( + module.res().unwrap(), + path.len() - i, + )); + } + } + + return PathResult::failed(ident.span, is_last, finalize.is_some(), || { + self.report_path_resolution_error( + path, + opt_ns, + parent_scope, + ribs, + ignore_binding, + module, + i, + ident, + ) + }); + } + } + } + + self.lint_if_path_starts_with_module(finalize, path, second_binding); + + PathResult::Module(match module { + Some(module) => module, + None if path.is_empty() => ModuleOrUniformRoot::CurrentScope, + _ => bug!("resolve_path: non-empty path `{:?}` has no module", path), + }) + } +} diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs new file mode 100644 index 000000000..b89273990 --- /dev/null +++ b/compiler/rustc_resolve/src/imports.rs @@ -0,0 +1,1151 @@ +//! A bunch of methods and structures more or less related to resolving imports. + +use crate::diagnostics::Suggestion; +use crate::Determinacy::{self, *}; +use crate::Namespace::{MacroNS, TypeNS}; +use crate::{module_to_string, names_to_string}; +use crate::{AmbiguityKind, BindingKey, ModuleKind, ResolutionError, Resolver, Segment}; +use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet}; +use crate::{NameBinding, NameBindingKind, PathResult}; + +use rustc_ast::NodeId; +use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::intern::Interned; +use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan}; +use rustc_hir::def::{self, DefKind, PartialRes}; +use rustc_middle::metadata::ModChild; +use rustc_middle::span_bug; +use rustc_middle::ty; +use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS}; +use rustc_session::lint::BuiltinLintDiagnostics; +use rustc_span::hygiene::LocalExpnId; +use rustc_span::lev_distance::find_best_match_for_name; +use rustc_span::symbol::{kw, Ident, Symbol}; +use rustc_span::Span; + +use tracing::*; + +use std::cell::Cell; +use std::{mem, ptr}; + +type Res = def::Res<NodeId>; + +/// Contains data for specific kinds of imports. +#[derive(Clone, Debug)] +pub enum ImportKind<'a> { + Single { + /// `source` in `use prefix::source as target`. + source: Ident, + /// `target` in `use prefix::source as target`. + target: Ident, + /// Bindings to which `source` refers to. + source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>, + /// Bindings introduced by `target`. + target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>, + /// `true` for `...::{self [as target]}` imports, `false` otherwise. + type_ns_only: bool, + /// Did this import result from a nested import? ie. `use foo::{bar, baz};` + nested: bool, + /// Additional `NodeId`s allocated to a `ast::UseTree` for automatically generated `use` statement + /// (eg. implicit struct constructors) + additional_ids: (NodeId, NodeId), + }, + Glob { + is_prelude: bool, + max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export. + // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors. + }, + ExternCrate { + source: Option<Symbol>, + target: Ident, + }, + MacroUse, +} + +/// One import. +#[derive(Debug, Clone)] +pub(crate) struct Import<'a> { + pub kind: ImportKind<'a>, + + /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`. + /// + /// In the case where the `Import` was expanded from a "nested" use tree, + /// this id is the ID of the leaf tree. For example: + /// + /// ```ignore (pacify the merciless tidy) + /// use foo::bar::{a, b} + /// ``` + /// + /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree` + /// for `a` in this field. + pub id: NodeId, + + /// The `id` of the "root" use-kind -- this is always the same as + /// `id` except in the case of "nested" use trees, in which case + /// it will be the `id` of the root use tree. e.g., in the example + /// from `id`, this would be the ID of the `use foo::bar` + /// `UseTree` node. + pub root_id: NodeId, + + /// Span of the entire use statement. + pub use_span: Span, + + /// Span of the entire use statement with attributes. + pub use_span_with_attributes: Span, + + /// Did the use statement have any attributes? + pub has_attributes: bool, + + /// Span of this use tree. + pub span: Span, + + /// Span of the *root* use tree (see `root_id`). + pub root_span: Span, + + pub parent_scope: ParentScope<'a>, + pub module_path: Vec<Segment>, + /// The resolution of `module_path`. + pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>, + pub vis: Cell<ty::Visibility>, + pub used: Cell<bool>, +} + +impl<'a> Import<'a> { + pub fn is_glob(&self) -> bool { + matches!(self.kind, ImportKind::Glob { .. }) + } + + pub fn is_nested(&self) -> bool { + match self.kind { + ImportKind::Single { nested, .. } => nested, + _ => false, + } + } +} + +/// Records information about the resolution of a name in a namespace of a module. +#[derive(Clone, Default, Debug)] +pub(crate) struct NameResolution<'a> { + /// Single imports that may define the name in the namespace. + /// Imports are arena-allocated, so it's ok to use pointers as keys. + pub single_imports: FxHashSet<Interned<'a, Import<'a>>>, + /// The least shadowable known binding for this name, or None if there are no known bindings. + pub binding: Option<&'a NameBinding<'a>>, + pub shadowed_glob: Option<&'a NameBinding<'a>>, +} + +impl<'a> NameResolution<'a> { + // Returns the binding for the name if it is known or None if it not known. + pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> { + self.binding.and_then(|binding| { + if !binding.is_glob_import() || self.single_imports.is_empty() { + Some(binding) + } else { + None + } + }) + } + + pub(crate) fn add_single_import(&mut self, import: &'a Import<'a>) { + self.single_imports.insert(Interned::new_unchecked(import)); + } +} + +// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;` +// are permitted for backward-compatibility under a deprecation lint. +fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool { + match (&import.kind, &binding.kind) { + ( + ImportKind::Single { .. }, + NameBindingKind::Import { + import: Import { kind: ImportKind::ExternCrate { .. }, .. }, + .. + }, + ) => import.vis.get().is_public(), + _ => false, + } +} + +impl<'a> Resolver<'a> { + // Given a binding and an import that resolves to it, + // return the corresponding binding defined by the import. + pub(crate) fn import( + &self, + binding: &'a NameBinding<'a>, + import: &'a Import<'a>, + ) -> &'a NameBinding<'a> { + let vis = if binding.vis.is_at_least(import.vis.get(), self) + || pub_use_of_private_extern_crate_hack(import, binding) + { + import.vis.get() + } else { + binding.vis + }; + + if let ImportKind::Glob { ref max_vis, .. } = import.kind { + if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) { + max_vis.set(vis) + } + } + + self.arenas.alloc_name_binding(NameBinding { + kind: NameBindingKind::Import { binding, import, used: Cell::new(false) }, + ambiguity: None, + span: import.span, + vis, + expansion: import.parent_scope.expansion, + }) + } + + // Define the name or return the existing binding if there is a collision. + pub(crate) fn try_define( + &mut self, + module: Module<'a>, + key: BindingKey, + binding: &'a NameBinding<'a>, + ) -> Result<(), &'a NameBinding<'a>> { + let res = binding.res(); + self.check_reserved_macro_name(key.ident, res); + self.set_binding_parent_module(binding, module); + self.update_resolution(module, key, |this, resolution| { + if let Some(old_binding) = resolution.binding { + if res == Res::Err { + // Do not override real bindings with `Res::Err`s from error recovery. + return Ok(()); + } + match (old_binding.is_glob_import(), binding.is_glob_import()) { + (true, true) => { + if res != old_binding.res() { + resolution.binding = Some(this.ambiguity( + AmbiguityKind::GlobVsGlob, + old_binding, + binding, + )); + } else if !old_binding.vis.is_at_least(binding.vis, &*this) { + // We are glob-importing the same item but with greater visibility. + resolution.binding = Some(binding); + } + } + (old_glob @ true, false) | (old_glob @ false, true) => { + let (glob_binding, nonglob_binding) = + if old_glob { (old_binding, binding) } else { (binding, old_binding) }; + if glob_binding.res() != nonglob_binding.res() + && key.ns == MacroNS + && nonglob_binding.expansion != LocalExpnId::ROOT + { + resolution.binding = Some(this.ambiguity( + AmbiguityKind::GlobVsExpanded, + nonglob_binding, + glob_binding, + )); + } else { + resolution.binding = Some(nonglob_binding); + } + resolution.shadowed_glob = Some(glob_binding); + } + (false, false) => { + return Err(old_binding); + } + } + } else { + resolution.binding = Some(binding); + } + + Ok(()) + }) + } + + fn ambiguity( + &self, + kind: AmbiguityKind, + primary_binding: &'a NameBinding<'a>, + secondary_binding: &'a NameBinding<'a>, + ) -> &'a NameBinding<'a> { + self.arenas.alloc_name_binding(NameBinding { + ambiguity: Some((secondary_binding, kind)), + ..primary_binding.clone() + }) + } + + // Use `f` to mutate the resolution of the name in the module. + // If the resolution becomes a success, define it in the module's glob importers. + fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T + where + F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T, + { + // Ensure that `resolution` isn't borrowed when defining in the module's glob importers, + // during which the resolution might end up getting re-defined via a glob cycle. + let (binding, t) = { + let resolution = &mut *self.resolution(module, key).borrow_mut(); + let old_binding = resolution.binding(); + + let t = f(self, resolution); + + match resolution.binding() { + _ if old_binding.is_some() => return t, + None => return t, + Some(binding) => match old_binding { + Some(old_binding) if ptr::eq(old_binding, binding) => return t, + _ => (binding, t), + }, + } + }; + + // Define `binding` in `module`s glob importers. + for import in module.glob_importers.borrow_mut().iter() { + let mut ident = key.ident; + let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) { + Some(Some(def)) => self.expn_def_scope(def), + Some(None) => import.parent_scope.module, + None => continue, + }; + if self.is_accessible_from(binding.vis, scope) { + let imported_binding = self.import(binding, import); + let key = BindingKey { ident, ..key }; + let _ = self.try_define(import.parent_scope.module, key, imported_binding); + } + } + + t + } + + // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed resolution, + // also mark such failed imports as used to avoid duplicate diagnostics. + fn import_dummy_binding(&mut self, import: &'a Import<'a>) { + if let ImportKind::Single { target, ref target_bindings, .. } = import.kind { + if target_bindings.iter().any(|binding| binding.get().is_some()) { + return; // Has resolution, do not create the dummy binding + } + let dummy_binding = self.dummy_binding; + let dummy_binding = self.import(dummy_binding, import); + self.per_ns(|this, ns| { + let key = this.new_key(target, ns); + let _ = this.try_define(import.parent_scope.module, key, dummy_binding); + }); + self.record_use(target, dummy_binding, false); + } else if import.imported_module.get().is_none() { + import.used.set(true); + self.used_imports.insert(import.id); + } + } +} + +/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved +/// import errors within the same use tree into a single diagnostic. +#[derive(Debug, Clone)] +struct UnresolvedImportError { + span: Span, + label: Option<String>, + note: Option<String>, + suggestion: Option<Suggestion>, +} + +pub struct ImportResolver<'a, 'b> { + pub r: &'a mut Resolver<'b>, +} + +impl<'a, 'b> ImportResolver<'a, 'b> { + // Import resolution + // + // This is a fixed-point algorithm. We resolve imports until our efforts + // are stymied by an unresolved import; then we bail out of the current + // module and continue. We terminate successfully once no more imports + // remain or unsuccessfully when no forward progress in resolving imports + // is made. + + /// Resolves all imports for the crate. This method performs the fixed- + /// point iteration. + pub fn resolve_imports(&mut self) { + let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1; + while self.r.indeterminate_imports.len() < prev_num_indeterminates { + prev_num_indeterminates = self.r.indeterminate_imports.len(); + for import in mem::take(&mut self.r.indeterminate_imports) { + match self.resolve_import(&import) { + true => self.r.determined_imports.push(import), + false => self.r.indeterminate_imports.push(import), + } + } + } + } + + pub fn finalize_imports(&mut self) { + for module in self.r.arenas.local_modules().iter() { + self.finalize_resolutions_in(module); + } + + let mut seen_spans = FxHashSet::default(); + let mut errors = vec![]; + let mut prev_root_id: NodeId = NodeId::from_u32(0); + let determined_imports = mem::take(&mut self.r.determined_imports); + let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports); + + for (is_indeterminate, import) in determined_imports + .into_iter() + .map(|i| (false, i)) + .chain(indeterminate_imports.into_iter().map(|i| (true, i))) + { + let unresolved_import_error = self.finalize_import(import); + + // If this import is unresolved then create a dummy import + // resolution for it so that later resolve stages won't complain. + self.r.import_dummy_binding(import); + + if let Some(err) = unresolved_import_error { + if let ImportKind::Single { source, ref source_bindings, .. } = import.kind { + if source.name == kw::SelfLower { + // Silence `unresolved import` error if E0429 is already emitted + if let Err(Determined) = source_bindings.value_ns.get() { + continue; + } + } + } + + if prev_root_id.as_u32() != 0 + && prev_root_id.as_u32() != import.root_id.as_u32() + && !errors.is_empty() + { + // In the case of a new import line, throw a diagnostic message + // for the previous line. + self.throw_unresolved_import_error(errors, None); + errors = vec![]; + } + if seen_spans.insert(err.span) { + let path = import_path_to_string( + &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(), + &import.kind, + err.span, + ); + errors.push((path, err)); + prev_root_id = import.root_id; + } + } else if is_indeterminate { + let path = import_path_to_string( + &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(), + &import.kind, + import.span, + ); + let err = UnresolvedImportError { + span: import.span, + label: None, + note: None, + suggestion: None, + }; + if path.contains("::") { + errors.push((path, err)) + } + } + } + + if !errors.is_empty() { + self.throw_unresolved_import_error(errors, None); + } + } + + fn throw_unresolved_import_error( + &self, + errors: Vec<(String, UnresolvedImportError)>, + span: Option<MultiSpan>, + ) { + /// Upper limit on the number of `span_label` messages. + const MAX_LABEL_COUNT: usize = 10; + + let (span, msg) = if errors.is_empty() { + (span.unwrap(), "unresolved import".to_string()) + } else { + let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect()); + + let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>(); + + let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),); + + (span, msg) + }; + + let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg); + + if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() { + diag.note(note); + } + + for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) { + if let Some(label) = err.label { + diag.span_label(err.span, label); + } + + if let Some((suggestions, msg, applicability)) = err.suggestion { + if suggestions.is_empty() { + diag.help(&msg); + continue; + } + diag.multipart_suggestion(&msg, suggestions, applicability); + } + } + + diag.emit(); + } + + /// Attempts to resolve the given import, returning true if its resolution is determined. + /// If successful, the resolved bindings are written into the module. + fn resolve_import(&mut self, import: &'b Import<'b>) -> bool { + debug!( + "(resolving import for module) resolving import `{}::...` in `{}`", + Segment::names_to_string(&import.module_path), + module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()), + ); + + let module = if let Some(module) = import.imported_module.get() { + module + } else { + // For better failure detection, pretend that the import will + // not define any names while resolving its module path. + let orig_vis = import.vis.replace(ty::Visibility::Invisible); + let path_res = + self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope); + import.vis.set(orig_vis); + + match path_res { + PathResult::Module(module) => module, + PathResult::Indeterminate => return false, + PathResult::NonModule(..) | PathResult::Failed { .. } => return true, + } + }; + + import.imported_module.set(Some(module)); + let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind { + ImportKind::Single { + source, + target, + ref source_bindings, + ref target_bindings, + type_ns_only, + .. + } => (source, target, source_bindings, target_bindings, type_ns_only), + ImportKind::Glob { .. } => { + self.resolve_glob_import(import); + return true; + } + _ => unreachable!(), + }; + + let mut indeterminate = false; + self.r.per_ns(|this, ns| { + if !type_ns_only || ns == TypeNS { + if let Err(Undetermined) = source_bindings[ns].get() { + // For better failure detection, pretend that the import will + // not define any names while resolving its module path. + let orig_vis = import.vis.replace(ty::Visibility::Invisible); + let binding = this.resolve_ident_in_module( + module, + source, + ns, + &import.parent_scope, + None, + None, + ); + import.vis.set(orig_vis); + source_bindings[ns].set(binding); + } else { + return; + }; + + let parent = import.parent_scope.module; + match source_bindings[ns].get() { + Err(Undetermined) => indeterminate = true, + // Don't update the resolution, because it was never added. + Err(Determined) if target.name == kw::Underscore => {} + Ok(binding) if binding.is_importable() => { + let imported_binding = this.import(binding, import); + target_bindings[ns].set(Some(imported_binding)); + this.define(parent, target, ns, imported_binding); + } + source_binding @ (Ok(..) | Err(Determined)) => { + if source_binding.is_ok() { + let msg = format!("`{}` is not directly importable", target); + struct_span_err!(this.session, import.span, E0253, "{}", &msg) + .span_label(import.span, "cannot be imported directly") + .emit(); + } + let key = this.new_key(target, ns); + this.update_resolution(parent, key, |_, resolution| { + resolution.single_imports.remove(&Interned::new_unchecked(import)); + }); + } + } + } + }); + + !indeterminate + } + + /// Performs final import resolution, consistency checks and error reporting. + /// + /// Optionally returns an unresolved import error. This error is buffered and used to + /// consolidate multiple unresolved import errors into a single diagnostic. + fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> { + let orig_vis = import.vis.replace(ty::Visibility::Invisible); + let ignore_binding = match &import.kind { + ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(), + _ => None, + }; + let prev_ambiguity_errors_len = self.r.ambiguity_errors.len(); + let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span); + let path_res = self.r.resolve_path( + &import.module_path, + None, + &import.parent_scope, + Some(finalize), + ignore_binding, + ); + let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len; + import.vis.set(orig_vis); + let module = match path_res { + PathResult::Module(module) => { + // Consistency checks, analogous to `finalize_macro_resolutions`. + if let Some(initial_module) = import.imported_module.get() { + if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity { + span_bug!(import.span, "inconsistent resolution for an import"); + } + } else if self.r.privacy_errors.is_empty() { + let msg = "cannot determine resolution for the import"; + let msg_note = "import resolution is stuck, try simplifying other imports"; + self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); + } + + module + } + PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { + if no_ambiguity { + assert!(import.imported_module.get().is_none()); + self.r + .report_error(span, ResolutionError::FailedToResolve { label, suggestion }); + } + return None; + } + PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => { + if no_ambiguity { + assert!(import.imported_module.get().is_none()); + let err = match self.make_path_suggestion( + span, + import.module_path.clone(), + &import.parent_scope, + ) { + Some((suggestion, note)) => UnresolvedImportError { + span, + label: None, + note, + suggestion: Some(( + vec![(span, Segment::names_to_string(&suggestion))], + String::from("a similar path exists"), + Applicability::MaybeIncorrect, + )), + }, + None => UnresolvedImportError { + span, + label: Some(label), + note: None, + suggestion, + }, + }; + return Some(err); + } + return None; + } + PathResult::NonModule(_) => { + if no_ambiguity { + assert!(import.imported_module.get().is_none()); + } + // The error was already reported earlier. + return None; + } + PathResult::Indeterminate => unreachable!(), + }; + + let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind { + ImportKind::Single { + source, + target, + ref source_bindings, + ref target_bindings, + type_ns_only, + .. + } => (source, target, source_bindings, target_bindings, type_ns_only), + ImportKind::Glob { is_prelude, ref max_vis } => { + if import.module_path.len() <= 1 { + // HACK(eddyb) `lint_if_path_starts_with_module` needs at least + // 2 segments, so the `resolve_path` above won't trigger it. + let mut full_path = import.module_path.clone(); + full_path.push(Segment::from_ident(Ident::empty())); + self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None); + } + + if let ModuleOrUniformRoot::Module(module) = module { + if ptr::eq(module, import.parent_scope.module) { + // Importing a module into itself is not allowed. + return Some(UnresolvedImportError { + span: import.span, + label: Some(String::from("cannot glob-import a module into itself")), + note: None, + suggestion: None, + }); + } + } + if !is_prelude && + max_vis.get() != ty::Visibility::Invisible && // Allow empty globs. + !max_vis.get().is_at_least(import.vis.get(), &*self.r) + { + let msg = "glob import doesn't reexport anything because no candidate is public enough"; + self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); + } + return None; + } + _ => unreachable!(), + }; + + let mut all_ns_err = true; + self.r.per_ns(|this, ns| { + if !type_ns_only || ns == TypeNS { + let orig_vis = import.vis.replace(ty::Visibility::Invisible); + let binding = this.resolve_ident_in_module( + module, + ident, + ns, + &import.parent_scope, + Some(Finalize { report_private: false, ..finalize }), + target_bindings[ns].get(), + ); + import.vis.set(orig_vis); + + match binding { + Ok(binding) => { + // Consistency checks, analogous to `finalize_macro_resolutions`. + let initial_res = source_bindings[ns].get().map(|initial_binding| { + all_ns_err = false; + if let Some(target_binding) = target_bindings[ns].get() { + if target.name == kw::Underscore + && initial_binding.is_extern_crate() + && !initial_binding.is_import() + { + this.record_use( + ident, + target_binding, + import.module_path.is_empty(), + ); + } + } + initial_binding.res() + }); + let res = binding.res(); + if let Ok(initial_res) = initial_res { + if res != initial_res && this.ambiguity_errors.is_empty() { + span_bug!(import.span, "inconsistent resolution for an import"); + } + } else if res != Res::Err + && this.ambiguity_errors.is_empty() + && this.privacy_errors.is_empty() + { + let msg = "cannot determine resolution for the import"; + let msg_note = + "import resolution is stuck, try simplifying other imports"; + this.session.struct_span_err(import.span, msg).note(msg_note).emit(); + } + } + Err(..) => { + // FIXME: This assert may fire if public glob is later shadowed by a private + // single import (see test `issue-55884-2.rs`). In theory single imports should + // always block globs, even if they are not yet resolved, so that this kind of + // self-inconsistent resolution never happens. + // Re-enable the assert when the issue is fixed. + // assert!(result[ns].get().is_err()); + } + } + } + }); + + if all_ns_err { + let mut all_ns_failed = true; + self.r.per_ns(|this, ns| { + if !type_ns_only || ns == TypeNS { + let binding = this.resolve_ident_in_module( + module, + ident, + ns, + &import.parent_scope, + Some(finalize), + None, + ); + if binding.is_ok() { + all_ns_failed = false; + } + } + }); + + return if all_ns_failed { + let resolutions = match module { + ModuleOrUniformRoot::Module(module) => { + Some(self.r.resolutions(module).borrow()) + } + _ => None, + }; + let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter()); + let names = resolutions + .filter_map(|(BindingKey { ident: i, .. }, resolution)| { + if *i == ident { + return None; + } // Never suggest the same name + match *resolution.borrow() { + NameResolution { binding: Some(name_binding), .. } => { + match name_binding.kind { + NameBindingKind::Import { binding, .. } => { + match binding.kind { + // Never suggest the name that has binding error + // i.e., the name that cannot be previously resolved + NameBindingKind::Res(Res::Err, _) => None, + _ => Some(i.name), + } + } + _ => Some(i.name), + } + } + NameResolution { ref single_imports, .. } + if single_imports.is_empty() => + { + None + } + _ => Some(i.name), + } + }) + .collect::<Vec<Symbol>>(); + + let lev_suggestion = + find_best_match_for_name(&names, ident.name, None).map(|suggestion| { + ( + vec![(ident.span, suggestion.to_string())], + String::from("a similar name exists in the module"), + Applicability::MaybeIncorrect, + ) + }); + + let (suggestion, note) = + match self.check_for_module_export_macro(import, module, ident) { + Some((suggestion, note)) => (suggestion.or(lev_suggestion), note), + _ => (lev_suggestion, None), + }; + + let label = match module { + ModuleOrUniformRoot::Module(module) => { + let module_str = module_to_string(module); + if let Some(module_str) = module_str { + format!("no `{}` in `{}`", ident, module_str) + } else { + format!("no `{}` in the root", ident) + } + } + _ => { + if !ident.is_path_segment_keyword() { + format!("no external crate `{}`", ident) + } else { + // HACK(eddyb) this shows up for `self` & `super`, which + // should work instead - for now keep the same error message. + format!("no `{}` in the root", ident) + } + } + }; + + Some(UnresolvedImportError { + span: import.span, + label: Some(label), + note, + suggestion, + }) + } else { + // `resolve_ident_in_module` reported a privacy error. + None + }; + } + + let mut reexport_error = None; + let mut any_successful_reexport = false; + let mut crate_private_reexport = false; + self.r.per_ns(|this, ns| { + if let Ok(binding) = source_bindings[ns].get() { + let vis = import.vis.get(); + if !binding.vis.is_at_least(vis, &*this) { + reexport_error = Some((ns, binding)); + if let ty::Visibility::Restricted(binding_def_id) = binding.vis { + if binding_def_id.is_top_level_module() { + crate_private_reexport = true; + } + } + } else { + any_successful_reexport = true; + } + } + }); + + // All namespaces must be re-exported with extra visibility for an error to occur. + if !any_successful_reexport { + let (ns, binding) = reexport_error.unwrap(); + if pub_use_of_private_extern_crate_hack(import, binding) { + let msg = format!( + "extern crate `{}` is private, and cannot be \ + re-exported (error E0365), consider declaring with \ + `pub`", + ident + ); + self.r.lint_buffer.buffer_lint( + PUB_USE_OF_PRIVATE_EXTERN_CRATE, + import.id, + import.span, + &msg, + ); + } else { + let error_msg = if crate_private_reexport { + format!( + "`{}` is only public within the crate, and cannot be re-exported outside", + ident + ) + } else { + format!("`{}` is private, and cannot be re-exported", ident) + }; + + if ns == TypeNS { + let label_msg = if crate_private_reexport { + format!("re-export of crate public `{}`", ident) + } else { + format!("re-export of private `{}`", ident) + }; + + struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg) + .span_label(import.span, label_msg) + .note(&format!("consider declaring type or module `{}` with `pub`", ident)) + .emit(); + } else { + let mut err = + struct_span_err!(self.r.session, import.span, E0364, "{error_msg}"); + match binding.kind { + NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id), _) + // exclude decl_macro + if self.r.get_macro_by_def_id(def_id).macro_rules => + { + err.span_help( + binding.span, + "consider adding a `#[macro_export]` to the macro in the imported module", + ); + } + _ => { + err.span_note( + import.span, + &format!( + "consider marking `{ident}` as `pub` in the imported module" + ), + ); + } + } + err.emit(); + } + } + } + + if import.module_path.len() <= 1 { + // HACK(eddyb) `lint_if_path_starts_with_module` needs at least + // 2 segments, so the `resolve_path` above won't trigger it. + let mut full_path = import.module_path.clone(); + full_path.push(Segment::from_ident(ident)); + self.r.per_ns(|this, ns| { + if let Ok(binding) = source_bindings[ns].get() { + this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding)); + } + }); + } + + // Record what this import resolves to for later uses in documentation, + // this may resolve to either a value or a type, but for documentation + // purposes it's good enough to just favor one over the other. + self.r.per_ns(|this, ns| { + if let Ok(binding) = source_bindings[ns].get() { + this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res()); + } + }); + + self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target); + + debug!("(resolving single import) successfully resolved import"); + None + } + + fn check_for_redundant_imports( + &mut self, + ident: Ident, + import: &'b Import<'b>, + source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>, + target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>, + target: Ident, + ) { + // Skip if the import was produced by a macro. + if import.parent_scope.expansion != LocalExpnId::ROOT { + return; + } + + // Skip if we are inside a named module (in contrast to an anonymous + // module defined by a block). + if let ModuleKind::Def(..) = import.parent_scope.module.kind { + return; + } + + let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None }; + + let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None }; + + self.r.per_ns(|this, ns| { + if let Ok(binding) = source_bindings[ns].get() { + if binding.res() == Res::Err { + return; + } + + match this.early_resolve_ident_in_lexical_scope( + target, + ScopeSet::All(ns, false), + &import.parent_scope, + None, + false, + target_bindings[ns].get(), + ) { + Ok(other_binding) => { + is_redundant[ns] = Some( + binding.res() == other_binding.res() && !other_binding.is_ambiguity(), + ); + redundant_span[ns] = Some((other_binding.span, other_binding.is_import())); + } + Err(_) => is_redundant[ns] = Some(false), + } + } + }); + + if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant) + { + let mut redundant_spans: Vec<_> = redundant_span.present_items().collect(); + redundant_spans.sort(); + redundant_spans.dedup(); + self.r.lint_buffer.buffer_lint_with_diagnostic( + UNUSED_IMPORTS, + import.id, + import.span, + &format!("the item `{}` is imported redundantly", ident), + BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident), + ); + } + } + + fn resolve_glob_import(&mut self, import: &'b Import<'b>) { + let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else { + self.r.session.span_err(import.span, "cannot glob-import all possible crates"); + return; + }; + + if module.is_trait() { + self.r.session.span_err(import.span, "items in traits are not importable"); + return; + } else if ptr::eq(module, import.parent_scope.module) { + return; + } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind { + self.r.prelude = Some(module); + return; + } + + // Add to module's glob_importers + module.glob_importers.borrow_mut().push(import); + + // Ensure that `resolutions` isn't borrowed during `try_define`, + // since it might get updated via a glob cycle. + let bindings = self + .r + .resolutions(module) + .borrow() + .iter() + .filter_map(|(key, resolution)| { + resolution.borrow().binding().map(|binding| (*key, binding)) + }) + .collect::<Vec<_>>(); + for (mut key, binding) in bindings { + let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) { + Some(Some(def)) => self.r.expn_def_scope(def), + Some(None) => import.parent_scope.module, + None => continue, + }; + if self.r.is_accessible_from(binding.vis, scope) { + let imported_binding = self.r.import(binding, import); + let _ = self.r.try_define(import.parent_scope.module, key, imported_binding); + } + } + + // Record the destination of this import + self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap())); + } + + // Miscellaneous post-processing, including recording re-exports, + // reporting conflicts, and reporting unresolved imports. + fn finalize_resolutions_in(&mut self, module: Module<'b>) { + // Since import resolution is finished, globs will not define any more names. + *module.globs.borrow_mut() = Vec::new(); + + if let Some(def_id) = module.opt_def_id() { + let mut reexports = Vec::new(); + + module.for_each_child(self.r, |_, ident, _, binding| { + // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules` + // into the crate root to actual `NameBindingKind::Import`. + if binding.is_import() + || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true)) + { + let res = binding.res().expect_non_local(); + // Ambiguous imports are treated as errors at this point and are + // not exposed to other crates (see #36837 for more details). + if res != def::Res::Err && !binding.is_ambiguity() { + reexports.push(ModChild { + ident, + res, + vis: binding.vis, + span: binding.span, + macro_rules: false, + }); + } + } + }); + + if !reexports.is_empty() { + // Call to `expect_local` should be fine because current + // code is only called for local modules. + self.r.reexport_map.insert(def_id.expect_local(), reexports); + } + } + } +} + +fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String { + let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot); + let global = !names.is_empty() && names[0].name == kw::PathRoot; + if let Some(pos) = pos { + let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] }; + names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()) + } else { + let names = if global { &names[1..] } else { names }; + if names.is_empty() { + import_kind_to_string(import_kind) + } else { + format!( + "{}::{}", + names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()), + import_kind_to_string(import_kind), + ) + } + } +} + +fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String { + match import_kind { + ImportKind::Single { source, .. } => source.to_string(), + ImportKind::Glob { .. } => "*".to_string(), + ImportKind::ExternCrate { .. } => "<extern crate>".to_string(), + ImportKind::MacroUse => "#[macro_use]".to_string(), + } +} diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs new file mode 100644 index 000000000..dea3eaecd --- /dev/null +++ b/compiler/rustc_resolve/src/late.rs @@ -0,0 +1,3984 @@ +// ignore-tidy-filelength +//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros. +//! It runs when the crate is fully expanded and its module structure is fully built. +//! So it just walks through the crate and resolves all the expressions, types, etc. +//! +//! If you wonder why there's no `early.rs`, that's because it's split into three files - +//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`. + +use RibKind::*; + +use crate::{path_names_to_string, BindingError, Finalize, LexicalScopeBinding}; +use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult}; +use crate::{ResolutionError, Resolver, Segment, UseError}; + +use rustc_ast::ptr::P; +use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; +use rustc_ast::*; +use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; +use rustc_errors::DiagnosticId; +use rustc_hir::def::Namespace::{self, *}; +use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS}; +use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_hir::{PrimTy, TraitCandidate}; +use rustc_middle::middle::resolve_lifetime::Set1; +use rustc_middle::ty::DefIdTree; +use rustc_middle::{bug, span_bug}; +use rustc_session::lint; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::{BytePos, Span}; +use smallvec::{smallvec, SmallVec}; + +use rustc_span::source_map::{respan, Spanned}; +use std::collections::{hash_map::Entry, BTreeSet}; +use std::mem::{replace, take}; +use tracing::debug; + +mod diagnostics; +pub(crate) mod lifetimes; + +type Res = def::Res<NodeId>; + +type IdentMap<T> = FxHashMap<Ident, T>; + +/// Map from the name in a pattern to its binding mode. +type BindingMap = IdentMap<BindingInfo>; + +use diagnostics::{ + ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind, +}; + +#[derive(Copy, Clone, Debug)] +struct BindingInfo { + span: Span, + binding_mode: BindingMode, +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum PatternSource { + Match, + Let, + For, + FnParam, +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum IsRepeatExpr { + No, + Yes, +} + +impl PatternSource { + pub fn descr(self) -> &'static str { + match self { + PatternSource::Match => "match binding", + PatternSource::Let => "let binding", + PatternSource::For => "for binding", + PatternSource::FnParam => "function parameter", + } + } +} + +/// Denotes whether the context for the set of already bound bindings is a `Product` +/// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`. +/// See those functions for more information. +#[derive(PartialEq)] +enum PatBoundCtx { + /// A product pattern context, e.g., `Variant(a, b)`. + Product, + /// An or-pattern context, e.g., `p_0 | ... | p_n`. + Or, +} + +/// Does this the item (from the item rib scope) allow generic parameters? +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub(crate) enum HasGenericParams { + Yes, + No, +} + +impl HasGenericParams { + fn force_yes_if(self, b: bool) -> Self { + if b { Self::Yes } else { self } + } +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub(crate) enum ConstantItemKind { + Const, + Static, +} + +/// The rib kind restricts certain accesses, +/// e.g. to a `Res::Local` of an outer item. +#[derive(Copy, Clone, Debug)] +pub(crate) enum RibKind<'a> { + /// No restriction needs to be applied. + NormalRibKind, + + /// We passed through an impl or trait and are now in one of its + /// methods or associated types. Allow references to ty params that impl or trait + /// binds. Disallow any other upvars (including other ty params that are + /// upvars). + AssocItemRibKind, + + /// We passed through a closure. Disallow labels. + ClosureOrAsyncRibKind, + + /// We passed through a function definition. Disallow upvars. + /// Permit only those const parameters that are specified in the function's generics. + FnItemRibKind, + + /// We passed through an item scope. Disallow upvars. + ItemRibKind(HasGenericParams), + + /// We're in a constant item. Can't refer to dynamic stuff. + /// + /// The item may reference generic parameters in trivial constant expressions. + /// All other constants aren't allowed to use generic params at all. + ConstantItemRibKind(HasGenericParams, Option<(Ident, ConstantItemKind)>), + + /// We passed through a module. + ModuleRibKind(Module<'a>), + + /// We passed through a `macro_rules!` statement + MacroDefinition(DefId), + + /// All bindings in this rib are generic parameters that can't be used + /// from the default of a generic parameter because they're not declared + /// before said generic parameter. Also see the `visit_generics` override. + ForwardGenericParamBanRibKind, + + /// We are inside of the type of a const parameter. Can't refer to any + /// parameters. + ConstParamTyRibKind, + + /// We are inside a `sym` inline assembly operand. Can only refer to + /// globals. + InlineAsmSymRibKind, +} + +impl RibKind<'_> { + /// Whether this rib kind contains generic parameters, as opposed to local + /// variables. + pub(crate) fn contains_params(&self) -> bool { + match self { + NormalRibKind + | ClosureOrAsyncRibKind + | FnItemRibKind + | ConstantItemRibKind(..) + | ModuleRibKind(_) + | MacroDefinition(_) + | ConstParamTyRibKind + | InlineAsmSymRibKind => false, + AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true, + } + } + + /// This rib forbids referring to labels defined in upwards ribs. + fn is_label_barrier(self) -> bool { + match self { + NormalRibKind | MacroDefinition(..) => false, + + AssocItemRibKind + | ClosureOrAsyncRibKind + | FnItemRibKind + | ItemRibKind(..) + | ConstantItemRibKind(..) + | ModuleRibKind(..) + | ForwardGenericParamBanRibKind + | ConstParamTyRibKind + | InlineAsmSymRibKind => true, + } + } +} + +/// A single local scope. +/// +/// A rib represents a scope names can live in. Note that these appear in many places, not just +/// around braces. At any place where the list of accessible names (of the given namespace) +/// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a +/// stack. This may be, for example, a `let` statement (because it introduces variables), a macro, +/// etc. +/// +/// Different [rib kinds](enum@RibKind) are transparent for different names. +/// +/// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When +/// resolving, the name is looked up from inside out. +#[derive(Debug)] +pub(crate) struct Rib<'a, R = Res> { + pub bindings: IdentMap<R>, + pub kind: RibKind<'a>, +} + +impl<'a, R> Rib<'a, R> { + fn new(kind: RibKind<'a>) -> Rib<'a, R> { + Rib { bindings: Default::default(), kind } + } +} + +#[derive(Clone, Copy, Debug)] +enum LifetimeUseSet { + One { use_span: Span, use_ctxt: visit::LifetimeCtxt }, + Many, +} + +#[derive(Copy, Clone, Debug)] +enum LifetimeRibKind { + /// This rib acts as a barrier to forbid reference to lifetimes of a parent item. + Item, + + /// This rib declares generic parameters. + Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind }, + + /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const + /// generics. We are disallowing this until we can decide on how we want to handle non-'static + /// lifetimes in const generics. See issue #74052 for discussion. + ConstGeneric, + + /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`. + /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by + /// `body_id` is an anonymous constant and `lifetime_ref` is non-static. + AnonConst, + + /// Create a new anonymous lifetime parameter and reference it. + /// + /// If `report_in_path`, report an error when encountering lifetime elision in a path: + /// ```compile_fail + /// struct Foo<'a> { x: &'a () } + /// async fn foo(x: Foo) {} + /// ``` + /// + /// Note: the error should not trigger when the elided lifetime is in a pattern or + /// expression-position path: + /// ``` + /// struct Foo<'a> { x: &'a () } + /// async fn foo(Foo { x: _ }: Foo<'_>) {} + /// ``` + AnonymousCreateParameter { binder: NodeId, report_in_path: bool }, + + /// Give a hard error when either `&` or `'_` is written. Used to + /// rule out things like `where T: Foo<'_>`. Does not imply an + /// error on default object bounds (e.g., `Box<dyn Foo>`). + AnonymousReportError, + + /// Replace all anonymous lifetimes by provided lifetime. + Elided(LifetimeRes), + + /// Signal we cannot find which should be the anonymous lifetime. + ElisionFailure, +} + +#[derive(Copy, Clone, Debug)] +enum LifetimeBinderKind { + BareFnType, + PolyTrait, + WhereBound, + Item, + Function, + Closure, + ImplBlock, +} + +impl LifetimeBinderKind { + fn descr(self) -> &'static str { + use LifetimeBinderKind::*; + match self { + BareFnType => "type", + PolyTrait => "bound", + WhereBound => "bound", + Item => "item", + ImplBlock => "impl block", + Function => "function", + Closure => "closure", + } + } +} + +#[derive(Debug)] +struct LifetimeRib { + kind: LifetimeRibKind, + // We need to preserve insertion order for async fns. + bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>, +} + +impl LifetimeRib { + fn new(kind: LifetimeRibKind) -> LifetimeRib { + LifetimeRib { bindings: Default::default(), kind } + } +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub(crate) enum AliasPossibility { + No, + Maybe, +} + +#[derive(Copy, Clone, Debug)] +pub(crate) enum PathSource<'a> { + // Type paths `Path`. + Type, + // Trait paths in bounds or impls. + Trait(AliasPossibility), + // Expression paths `path`, with optional parent context. + Expr(Option<&'a Expr>), + // Paths in path patterns `Path`. + Pat, + // Paths in struct expressions and patterns `Path { .. }`. + Struct, + // Paths in tuple struct patterns `Path(..)`. + TupleStruct(Span, &'a [Span]), + // `m::A::B` in `<T as m::A>::B::C`. + TraitItem(Namespace), +} + +impl<'a> PathSource<'a> { + fn namespace(self) -> Namespace { + match self { + PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS, + PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS, + PathSource::TraitItem(ns) => ns, + } + } + + fn defer_to_typeck(self) -> bool { + match self { + PathSource::Type + | PathSource::Expr(..) + | PathSource::Pat + | PathSource::Struct + | PathSource::TupleStruct(..) => true, + PathSource::Trait(_) | PathSource::TraitItem(..) => false, + } + } + + fn descr_expected(self) -> &'static str { + match &self { + PathSource::Type => "type", + PathSource::Trait(_) => "trait", + PathSource::Pat => "unit struct, unit variant or constant", + PathSource::Struct => "struct, variant or union type", + PathSource::TupleStruct(..) => "tuple struct or tuple variant", + PathSource::TraitItem(ns) => match ns { + TypeNS => "associated type", + ValueNS => "method or associated constant", + MacroNS => bug!("associated macro"), + }, + PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) { + // "function" here means "anything callable" rather than `DefKind::Fn`, + // this is not precise but usually more helpful than just "value". + Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind { + // the case of `::some_crate()` + ExprKind::Path(_, path) + if path.segments.len() == 2 + && path.segments[0].ident.name == kw::PathRoot => + { + "external crate" + } + ExprKind::Path(_, path) => { + let mut msg = "function"; + if let Some(segment) = path.segments.iter().last() { + if let Some(c) = segment.ident.to_string().chars().next() { + if c.is_uppercase() { + msg = "function, tuple struct or tuple variant"; + } + } + } + msg + } + _ => "function", + }, + _ => "value", + }, + } + } + + fn is_call(self) -> bool { + matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. }))) + } + + pub(crate) fn is_expected(self, res: Res) -> bool { + match self { + PathSource::Type => matches!( + res, + Res::Def( + DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::Trait + | DefKind::TraitAlias + | DefKind::TyAlias + | DefKind::AssocTy + | DefKind::TyParam + | DefKind::OpaqueTy + | DefKind::ForeignTy, + _, + ) | Res::PrimTy(..) + | Res::SelfTy { .. } + ), + PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)), + PathSource::Trait(AliasPossibility::Maybe) => { + matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) + } + PathSource::Expr(..) => matches!( + res, + Res::Def( + DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) + | DefKind::Const + | DefKind::Static(_) + | DefKind::Fn + | DefKind::AssocFn + | DefKind::AssocConst + | DefKind::ConstParam, + _, + ) | Res::Local(..) + | Res::SelfCtor(..) + ), + PathSource::Pat => { + res.expected_in_unit_struct_pat() + || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _)) + } + PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(), + PathSource::Struct => matches!( + res, + Res::Def( + DefKind::Struct + | DefKind::Union + | DefKind::Variant + | DefKind::TyAlias + | DefKind::AssocTy, + _, + ) | Res::SelfTy { .. } + ), + PathSource::TraitItem(ns) => match res { + Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, + Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, + _ => false, + }, + } + } + + fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId { + use rustc_errors::error_code; + match (self, has_unexpected_resolution) { + (PathSource::Trait(_), true) => error_code!(E0404), + (PathSource::Trait(_), false) => error_code!(E0405), + (PathSource::Type, true) => error_code!(E0573), + (PathSource::Type, false) => error_code!(E0412), + (PathSource::Struct, true) => error_code!(E0574), + (PathSource::Struct, false) => error_code!(E0422), + (PathSource::Expr(..), true) => error_code!(E0423), + (PathSource::Expr(..), false) => error_code!(E0425), + (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532), + (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531), + (PathSource::TraitItem(..), true) => error_code!(E0575), + (PathSource::TraitItem(..), false) => error_code!(E0576), + } + } +} + +#[derive(Default)] +struct DiagnosticMetadata<'ast> { + /// The current trait's associated items' ident, used for diagnostic suggestions. + current_trait_assoc_items: Option<&'ast [P<AssocItem>]>, + + /// The current self type if inside an impl (used for better errors). + current_self_type: Option<Ty>, + + /// The current self item if inside an ADT (used for better errors). + current_self_item: Option<NodeId>, + + /// The current trait (used to suggest). + current_item: Option<&'ast Item>, + + /// When processing generics and encountering a type not found, suggest introducing a type + /// param. + currently_processing_generics: bool, + + /// The current enclosing (non-closure) function (used for better errors). + current_function: Option<(FnKind<'ast>, Span)>, + + /// A list of labels as of yet unused. Labels will be removed from this map when + /// they are used (in a `break` or `continue` statement) + unused_labels: FxHashMap<NodeId, Span>, + + /// Only used for better errors on `fn(): fn()`. + current_type_ascription: Vec<Span>, + + /// Only used for better errors on `let x = { foo: bar };`. + /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only + /// needed for cases where this parses as a correct type ascription. + current_block_could_be_bare_struct_literal: Option<Span>, + + /// Only used for better errors on `let <pat>: <expr, not type>;`. + current_let_binding: Option<(Span, Option<Span>, Option<Span>)>, + + /// Used to detect possible `if let` written without `let` and to provide structured suggestion. + in_if_condition: Option<&'ast Expr>, + + /// If we are currently in a trait object definition. Used to point at the bounds when + /// encountering a struct or enum. + current_trait_object: Option<&'ast [ast::GenericBound]>, + + /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`. + current_where_predicate: Option<&'ast WherePredicate>, + + current_type_path: Option<&'ast Ty>, + + /// The current impl items (used to suggest). + current_impl_items: Option<&'ast [P<AssocItem>]>, + + /// When processing impl trait + currently_processing_impl_trait: Option<(TraitRef, Ty)>, + + /// Accumulate the errors due to missed lifetime elision, + /// and report them all at once for each function. + current_elision_failures: Vec<MissingLifetime>, +} + +struct LateResolutionVisitor<'a, 'b, 'ast> { + r: &'b mut Resolver<'a>, + + /// The module that represents the current item scope. + parent_scope: ParentScope<'a>, + + /// The current set of local scopes for types and values. + /// FIXME #4948: Reuse ribs to avoid allocation. + ribs: PerNS<Vec<Rib<'a>>>, + + /// The current set of local scopes, for labels. + label_ribs: Vec<Rib<'a, NodeId>>, + + /// The current set of local scopes for lifetimes. + lifetime_ribs: Vec<LifetimeRib>, + + /// We are looking for lifetimes in an elision context. + /// The set contains all the resolutions that we encountered so far. + /// They will be used to determine the correct lifetime for the fn return type. + /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named + /// lifetimes. + lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>, + + /// The trait that the current context can refer to. + current_trait_ref: Option<(Module<'a>, TraitRef)>, + + /// Fields used to add information to diagnostic errors. + diagnostic_metadata: Box<DiagnosticMetadata<'ast>>, + + /// State used to know whether to ignore resolution errors for function bodies. + /// + /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items. + /// In most cases this will be `None`, in which case errors will always be reported. + /// If it is `true`, then it will be updated when entering a nested function or trait body. + in_func_body: bool, + + /// Count the number of places a lifetime is used. + lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>, +} + +/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes. +impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> { + fn visit_attribute(&mut self, _: &'ast Attribute) { + // We do not want to resolve expressions that appear in attributes, + // as they do not correspond to actual code. + } + fn visit_item(&mut self, item: &'ast Item) { + let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item)); + // Always report errors in items we just entered. + let old_ignore = replace(&mut self.in_func_body, false); + self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item)); + self.in_func_body = old_ignore; + self.diagnostic_metadata.current_item = prev; + } + fn visit_arm(&mut self, arm: &'ast Arm) { + self.resolve_arm(arm); + } + fn visit_block(&mut self, block: &'ast Block) { + self.resolve_block(block); + } + fn visit_anon_const(&mut self, constant: &'ast AnonConst) { + // We deal with repeat expressions explicitly in `resolve_expr`. + self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| { + this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| { + this.resolve_anon_const(constant, IsRepeatExpr::No); + }) + }) + } + fn visit_expr(&mut self, expr: &'ast Expr) { + self.resolve_expr(expr, None); + } + fn visit_local(&mut self, local: &'ast Local) { + let local_spans = match local.pat.kind { + // We check for this to avoid tuple struct fields. + PatKind::Wild => None, + _ => Some(( + local.pat.span, + local.ty.as_ref().map(|ty| ty.span), + local.kind.init().map(|init| init.span), + )), + }; + let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans); + self.resolve_local(local); + self.diagnostic_metadata.current_let_binding = original; + } + fn visit_ty(&mut self, ty: &'ast Ty) { + let prev = self.diagnostic_metadata.current_trait_object; + let prev_ty = self.diagnostic_metadata.current_type_path; + match ty.kind { + TyKind::Rptr(None, _) => { + // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with + // NodeId `ty.id`. + // This span will be used in case of elision failure. + let span = self.r.session.source_map().next_point(ty.span.shrink_to_lo()); + self.resolve_elided_lifetime(ty.id, span); + visit::walk_ty(self, ty); + } + TyKind::Path(ref qself, ref path) => { + self.diagnostic_metadata.current_type_path = Some(ty); + self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type); + + // Check whether we should interpret this as a bare trait object. + if qself.is_none() + && let Some(partial_res) = self.r.partial_res_map.get(&ty.id) + && partial_res.unresolved_segments() == 0 + && let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = partial_res.base_res() + { + // This path is actually a bare trait object. In case of a bare `Fn`-trait + // object with anonymous lifetimes, we need this rib to correctly place the + // synthetic lifetimes. + let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo()); + self.with_generic_param_rib( + &[], + NormalRibKind, + LifetimeRibKind::Generics { + binder: ty.id, + kind: LifetimeBinderKind::PolyTrait, + span, + }, + |this| this.visit_path(&path, ty.id), + ); + } else { + visit::walk_ty(self, ty) + } + } + TyKind::ImplicitSelf => { + let self_ty = Ident::with_dummy_span(kw::SelfUpper); + let res = self + .resolve_ident_in_lexical_scope( + self_ty, + TypeNS, + Some(Finalize::new(ty.id, ty.span)), + None, + ) + .map_or(Res::Err, |d| d.res()); + self.r.record_partial_res(ty.id, PartialRes::new(res)); + visit::walk_ty(self, ty) + } + TyKind::ImplTrait(..) => { + let candidates = self.lifetime_elision_candidates.take(); + visit::walk_ty(self, ty); + self.lifetime_elision_candidates = candidates; + } + TyKind::TraitObject(ref bounds, ..) => { + self.diagnostic_metadata.current_trait_object = Some(&bounds[..]); + visit::walk_ty(self, ty) + } + TyKind::BareFn(ref bare_fn) => { + let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo()); + self.with_generic_param_rib( + &bare_fn.generic_params, + NormalRibKind, + LifetimeRibKind::Generics { + binder: ty.id, + kind: LifetimeBinderKind::BareFnType, + span, + }, + |this| { + this.visit_generic_params(&bare_fn.generic_params, false); + this.with_lifetime_rib( + LifetimeRibKind::AnonymousCreateParameter { + binder: ty.id, + report_in_path: false, + }, + |this| { + this.resolve_fn_signature( + ty.id, + false, + // We don't need to deal with patterns in parameters, because + // they are not possible for foreign or bodiless functions. + bare_fn + .decl + .inputs + .iter() + .map(|Param { ty, .. }| (None, &**ty)), + &bare_fn.decl.output, + ) + }, + ); + }, + ) + } + _ => visit::walk_ty(self, ty), + } + self.diagnostic_metadata.current_trait_object = prev; + self.diagnostic_metadata.current_type_path = prev_ty; + } + fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, _: &'ast TraitBoundModifier) { + let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo()); + self.with_generic_param_rib( + &tref.bound_generic_params, + NormalRibKind, + LifetimeRibKind::Generics { + binder: tref.trait_ref.ref_id, + kind: LifetimeBinderKind::PolyTrait, + span, + }, + |this| { + this.visit_generic_params(&tref.bound_generic_params, false); + this.smart_resolve_path( + tref.trait_ref.ref_id, + None, + &tref.trait_ref.path, + PathSource::Trait(AliasPossibility::Maybe), + ); + this.visit_trait_ref(&tref.trait_ref); + }, + ); + } + fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) { + match foreign_item.kind { + ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => { + self.with_lifetime_rib(LifetimeRibKind::Item, |this| { + this.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: foreign_item.id, + kind: LifetimeBinderKind::Item, + span: generics.span, + }, + |this| visit::walk_foreign_item(this, foreign_item), + ) + }); + } + ForeignItemKind::Fn(box Fn { ref generics, .. }) => { + self.with_lifetime_rib(LifetimeRibKind::Item, |this| { + this.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: foreign_item.id, + kind: LifetimeBinderKind::Function, + span: generics.span, + }, + |this| visit::walk_foreign_item(this, foreign_item), + ) + }); + } + ForeignItemKind::Static(..) => { + self.with_item_rib(|this| { + visit::walk_foreign_item(this, foreign_item); + }); + } + ForeignItemKind::MacCall(..) => { + panic!("unexpanded macro in resolve!") + } + } + } + fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) { + let rib_kind = match fn_kind { + // Bail if the function is foreign, and thus cannot validly have + // a body, or if there's no body for some other reason. + FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _) + | FnKind::Fn(_, _, sig, _, generics, None) => { + self.visit_fn_header(&sig.header); + self.visit_generics(generics); + self.with_lifetime_rib( + LifetimeRibKind::AnonymousCreateParameter { + binder: fn_id, + report_in_path: false, + }, + |this| { + this.resolve_fn_signature( + fn_id, + sig.decl.has_self(), + sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), + &sig.decl.output, + ) + }, + ); + return; + } + FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind, + FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind, + FnKind::Closure(..) => ClosureOrAsyncRibKind, + }; + let previous_value = self.diagnostic_metadata.current_function; + if matches!(fn_kind, FnKind::Fn(..)) { + self.diagnostic_metadata.current_function = Some((fn_kind, sp)); + } + debug!("(resolving function) entering function"); + + // Create a value rib for the function. + self.with_rib(ValueNS, rib_kind, |this| { + // Create a label rib for the function. + this.with_label_rib(FnItemRibKind, |this| { + match fn_kind { + FnKind::Fn(_, _, sig, _, generics, body) => { + this.visit_generics(generics); + + let declaration = &sig.decl; + let async_node_id = sig.header.asyncness.opt_return_id(); + + this.with_lifetime_rib( + LifetimeRibKind::AnonymousCreateParameter { + binder: fn_id, + report_in_path: async_node_id.is_some(), + }, + |this| { + this.resolve_fn_signature( + fn_id, + declaration.has_self(), + declaration + .inputs + .iter() + .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)), + &declaration.output, + ) + }, + ); + + // Construct the list of in-scope lifetime parameters for async lowering. + // We include all lifetime parameters, either named or "Fresh". + // The order of those parameters does not matter, as long as it is + // deterministic. + if let Some(async_node_id) = async_node_id { + let mut extra_lifetime_params = this + .r + .extra_lifetime_params_map + .get(&fn_id) + .cloned() + .unwrap_or_default(); + for rib in this.lifetime_ribs.iter().rev() { + extra_lifetime_params.extend( + rib.bindings + .iter() + .map(|(&ident, &(node_id, res))| (ident, node_id, res)), + ); + match rib.kind { + LifetimeRibKind::Item => break, + LifetimeRibKind::AnonymousCreateParameter { + binder, .. + } => { + if let Some(earlier_fresh) = + this.r.extra_lifetime_params_map.get(&binder) + { + extra_lifetime_params.extend(earlier_fresh); + } + } + _ => {} + } + } + this.r + .extra_lifetime_params_map + .insert(async_node_id, extra_lifetime_params); + } + + if let Some(body) = body { + // Ignore errors in function bodies if this is rustdoc + // Be sure not to set this until the function signature has been resolved. + let previous_state = replace(&mut this.in_func_body, true); + // Resolve the function body, potentially inside the body of an async closure + this.with_lifetime_rib( + LifetimeRibKind::Elided(LifetimeRes::Infer), + |this| this.visit_block(body), + ); + + debug!("(resolving function) leaving function"); + this.in_func_body = previous_state; + } + } + FnKind::Closure(binder, declaration, body) => { + this.visit_closure_binder(binder); + + this.with_lifetime_rib( + match binder { + // We do not have any explicit generic lifetime parameter. + ClosureBinder::NotPresent => { + LifetimeRibKind::AnonymousCreateParameter { + binder: fn_id, + report_in_path: false, + } + } + ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError, + }, + // Add each argument to the rib. + |this| this.resolve_params(&declaration.inputs), + ); + this.with_lifetime_rib( + match binder { + ClosureBinder::NotPresent => { + LifetimeRibKind::Elided(LifetimeRes::Infer) + } + ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError, + }, + |this| visit::walk_fn_ret_ty(this, &declaration.output), + ); + + // Ignore errors in function bodies if this is rustdoc + // Be sure not to set this until the function signature has been resolved. + let previous_state = replace(&mut this.in_func_body, true); + // Resolve the function body, potentially inside the body of an async closure + this.with_lifetime_rib( + LifetimeRibKind::Elided(LifetimeRes::Infer), + |this| this.visit_expr(body), + ); + + debug!("(resolving function) leaving function"); + this.in_func_body = previous_state; + } + } + }) + }); + self.diagnostic_metadata.current_function = previous_value; + } + fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) { + self.resolve_lifetime(lifetime, use_ctxt) + } + + fn visit_generics(&mut self, generics: &'ast Generics) { + self.visit_generic_params( + &generics.params, + self.diagnostic_metadata.current_self_item.is_some(), + ); + for p in &generics.where_clause.predicates { + self.visit_where_predicate(p); + } + } + + fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) { + match b { + ClosureBinder::NotPresent => {} + ClosureBinder::For { generic_params, .. } => { + self.visit_generic_params( + &generic_params, + self.diagnostic_metadata.current_self_item.is_some(), + ); + } + } + } + + fn visit_generic_arg(&mut self, arg: &'ast GenericArg) { + debug!("visit_generic_arg({:?})", arg); + let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true); + match arg { + GenericArg::Type(ref ty) => { + // We parse const arguments as path types as we cannot distinguish them during + // parsing. We try to resolve that ambiguity by attempting resolution the type + // namespace first, and if that fails we try again in the value namespace. If + // resolution in the value namespace succeeds, we have an generic const argument on + // our hands. + if let TyKind::Path(ref qself, ref path) = ty.kind { + // We cannot disambiguate multi-segment paths right now as that requires type + // checking. + if path.segments.len() == 1 && path.segments[0].args.is_none() { + let mut check_ns = |ns| { + self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns) + .is_some() + }; + if !check_ns(TypeNS) && check_ns(ValueNS) { + // This must be equivalent to `visit_anon_const`, but we cannot call it + // directly due to visitor lifetimes so we have to copy-paste some code. + // + // Note that we might not be inside of an repeat expression here, + // but considering that `IsRepeatExpr` is only relevant for + // non-trivial constants this is doesn't matter. + self.with_constant_rib( + IsRepeatExpr::No, + HasGenericParams::Yes, + None, + |this| { + this.smart_resolve_path( + ty.id, + qself.as_ref(), + path, + PathSource::Expr(None), + ); + + if let Some(ref qself) = *qself { + this.visit_ty(&qself.ty); + } + this.visit_path(path, ty.id); + }, + ); + + self.diagnostic_metadata.currently_processing_generics = prev; + return; + } + } + } + + self.visit_ty(ty); + } + GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg), + GenericArg::Const(ct) => self.visit_anon_const(ct), + } + self.diagnostic_metadata.currently_processing_generics = prev; + } + + fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) { + self.visit_ident(constraint.ident); + if let Some(ref gen_args) = constraint.gen_args { + // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided. + self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { + this.visit_generic_args(gen_args.span(), gen_args) + }); + } + match constraint.kind { + AssocConstraintKind::Equality { ref term } => match term { + Term::Ty(ty) => self.visit_ty(ty), + Term::Const(c) => self.visit_anon_const(c), + }, + AssocConstraintKind::Bound { ref bounds } => { + walk_list!(self, visit_param_bound, bounds, BoundKind::Bound); + } + } + } + + fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) { + if let Some(ref args) = path_segment.args { + match &**args { + GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, path_span, args), + GenericArgs::Parenthesized(p_args) => { + // Probe the lifetime ribs to know how to behave. + for rib in self.lifetime_ribs.iter().rev() { + match rib.kind { + // We are inside a `PolyTraitRef`. The lifetimes are + // to be intoduced in that (maybe implicit) `for<>` binder. + LifetimeRibKind::Generics { + binder, + kind: LifetimeBinderKind::PolyTrait, + .. + } => { + self.with_lifetime_rib( + LifetimeRibKind::AnonymousCreateParameter { + binder, + report_in_path: false, + }, + |this| { + this.resolve_fn_signature( + binder, + false, + p_args.inputs.iter().map(|ty| (None, &**ty)), + &p_args.output, + ) + }, + ); + break; + } + // We have nowhere to introduce generics. Code is malformed, + // so use regular lifetime resolution to avoid spurious errors. + LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => { + visit::walk_generic_args(self, path_span, args); + break; + } + LifetimeRibKind::AnonymousCreateParameter { .. } + | LifetimeRibKind::AnonymousReportError + | LifetimeRibKind::Elided(_) + | LifetimeRibKind::ElisionFailure + | LifetimeRibKind::AnonConst + | LifetimeRibKind::ConstGeneric => {} + } + } + } + } + } + } + + fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { + debug!("visit_where_predicate {:?}", p); + let previous_value = + replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p)); + self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { + if let WherePredicate::BoundPredicate(WhereBoundPredicate { + ref bounded_ty, + ref bounds, + ref bound_generic_params, + span: predicate_span, + .. + }) = p + { + let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo()); + this.with_generic_param_rib( + &bound_generic_params, + NormalRibKind, + LifetimeRibKind::Generics { + binder: bounded_ty.id, + kind: LifetimeBinderKind::WhereBound, + span, + }, + |this| { + this.visit_generic_params(&bound_generic_params, false); + this.visit_ty(bounded_ty); + for bound in bounds { + this.visit_param_bound(bound, BoundKind::Bound) + } + }, + ); + } else { + visit::walk_where_predicate(this, p); + } + }); + self.diagnostic_metadata.current_where_predicate = previous_value; + } + + fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) { + for (op, _) in &asm.operands { + match op { + InlineAsmOperand::In { expr, .. } + | InlineAsmOperand::Out { expr: Some(expr), .. } + | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr), + InlineAsmOperand::Out { expr: None, .. } => {} + InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => { + self.visit_expr(in_expr); + if let Some(out_expr) = out_expr { + self.visit_expr(out_expr); + } + } + InlineAsmOperand::Const { anon_const, .. } => { + // Although this is `DefKind::AnonConst`, it is allowed to reference outer + // generic parameters like an inline const. + self.resolve_inline_const(anon_const); + } + InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym), + } + } + } + + fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) { + // This is similar to the code for AnonConst. + self.with_rib(ValueNS, InlineAsmSymRibKind, |this| { + this.with_rib(TypeNS, InlineAsmSymRibKind, |this| { + this.with_label_rib(InlineAsmSymRibKind, |this| { + this.smart_resolve_path( + sym.id, + sym.qself.as_ref(), + &sym.path, + PathSource::Expr(None), + ); + visit::walk_inline_asm_sym(this, sym); + }); + }) + }); + } +} + +impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { + fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> { + // During late resolution we only track the module component of the parent scope, + // although it may be useful to track other components as well for diagnostics. + let graph_root = resolver.graph_root; + let parent_scope = ParentScope::module(graph_root, resolver); + let start_rib_kind = ModuleRibKind(graph_root); + LateResolutionVisitor { + r: resolver, + parent_scope, + ribs: PerNS { + value_ns: vec![Rib::new(start_rib_kind)], + type_ns: vec![Rib::new(start_rib_kind)], + macro_ns: vec![Rib::new(start_rib_kind)], + }, + label_ribs: Vec::new(), + lifetime_ribs: Vec::new(), + lifetime_elision_candidates: None, + current_trait_ref: None, + diagnostic_metadata: Box::new(DiagnosticMetadata::default()), + // errors at module scope should always be reported + in_func_body: false, + lifetime_uses: Default::default(), + } + } + + fn maybe_resolve_ident_in_lexical_scope( + &mut self, + ident: Ident, + ns: Namespace, + ) -> Option<LexicalScopeBinding<'a>> { + self.r.resolve_ident_in_lexical_scope( + ident, + ns, + &self.parent_scope, + None, + &self.ribs[ns], + None, + ) + } + + fn resolve_ident_in_lexical_scope( + &mut self, + ident: Ident, + ns: Namespace, + finalize: Option<Finalize>, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Option<LexicalScopeBinding<'a>> { + self.r.resolve_ident_in_lexical_scope( + ident, + ns, + &self.parent_scope, + finalize, + &self.ribs[ns], + ignore_binding, + ) + } + + fn resolve_path( + &mut self, + path: &[Segment], + opt_ns: Option<Namespace>, // `None` indicates a module path in import + finalize: Option<Finalize>, + ) -> PathResult<'a> { + self.r.resolve_path_with_ribs( + path, + opt_ns, + &self.parent_scope, + finalize, + Some(&self.ribs), + None, + ) + } + + // AST resolution + // + // We maintain a list of value ribs and type ribs. + // + // Simultaneously, we keep track of the current position in the module + // graph in the `parent_scope.module` pointer. When we go to resolve a name in + // the value or type namespaces, we first look through all the ribs and + // then query the module graph. When we resolve a name in the module + // namespace, we can skip all the ribs (since nested modules are not + // allowed within blocks in Rust) and jump straight to the current module + // graph node. + // + // Named implementations are handled separately. When we find a method + // call, we consult the module node to find all of the implementations in + // scope. This information is lazily cached in the module node. We then + // generate a fake "implementation scope" containing all the + // implementations thus found, for compatibility with old resolve pass. + + /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`). + fn with_rib<T>( + &mut self, + ns: Namespace, + kind: RibKind<'a>, + work: impl FnOnce(&mut Self) -> T, + ) -> T { + self.ribs[ns].push(Rib::new(kind)); + let ret = work(self); + self.ribs[ns].pop(); + ret + } + + fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { + if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) { + // Move down in the graph. + let orig_module = replace(&mut self.parent_scope.module, module); + self.with_rib(ValueNS, ModuleRibKind(module), |this| { + this.with_rib(TypeNS, ModuleRibKind(module), |this| { + let ret = f(this); + this.parent_scope.module = orig_module; + ret + }) + }) + } else { + f(self) + } + } + + fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) { + // For type parameter defaults, we have to ban access + // to following type parameters, as the InternalSubsts can only + // provide previous type parameters as they're built. We + // put all the parameters on the ban list and then remove + // them one by one as they are processed and become available. + let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind); + let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind); + for param in params.iter() { + match param.kind { + GenericParamKind::Type { .. } => { + forward_ty_ban_rib + .bindings + .insert(Ident::with_dummy_span(param.ident.name), Res::Err); + } + GenericParamKind::Const { .. } => { + forward_const_ban_rib + .bindings + .insert(Ident::with_dummy_span(param.ident.name), Res::Err); + } + GenericParamKind::Lifetime => {} + } + } + + // rust-lang/rust#61631: The type `Self` is essentially + // another type parameter. For ADTs, we consider it + // well-defined only after all of the ADT type parameters have + // been provided. Therefore, we do not allow use of `Self` + // anywhere in ADT type parameter defaults. + // + // (We however cannot ban `Self` for defaults on *all* generic + // lists; e.g. trait generics can usefully refer to `Self`, + // such as in the case of `trait Add<Rhs = Self>`.) + if add_self_upper { + // (`Some` if + only if we are in ADT's generics.) + forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err); + } + + self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { + for param in params { + match param.kind { + GenericParamKind::Lifetime => { + for bound in ¶m.bounds { + this.visit_param_bound(bound, BoundKind::Bound); + } + } + GenericParamKind::Type { ref default } => { + for bound in ¶m.bounds { + this.visit_param_bound(bound, BoundKind::Bound); + } + + if let Some(ref ty) = default { + this.ribs[TypeNS].push(forward_ty_ban_rib); + this.ribs[ValueNS].push(forward_const_ban_rib); + this.visit_ty(ty); + forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap(); + forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap(); + } + + // Allow all following defaults to refer to this type parameter. + forward_ty_ban_rib + .bindings + .remove(&Ident::with_dummy_span(param.ident.name)); + } + GenericParamKind::Const { ref ty, kw_span: _, ref default } => { + // Const parameters can't have param bounds. + assert!(param.bounds.is_empty()); + + this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind)); + this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind)); + this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| { + this.visit_ty(ty) + }); + this.ribs[TypeNS].pop().unwrap(); + this.ribs[ValueNS].pop().unwrap(); + + if let Some(ref expr) = default { + this.ribs[TypeNS].push(forward_ty_ban_rib); + this.ribs[ValueNS].push(forward_const_ban_rib); + this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| { + this.resolve_anon_const(expr, IsRepeatExpr::No) + }); + forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap(); + forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap(); + } + + // Allow all following defaults to refer to this const parameter. + forward_const_ban_rib + .bindings + .remove(&Ident::with_dummy_span(param.ident.name)); + } + } + } + }) + } + + #[tracing::instrument(level = "debug", skip(self, work))] + fn with_lifetime_rib<T>( + &mut self, + kind: LifetimeRibKind, + work: impl FnOnce(&mut Self) -> T, + ) -> T { + self.lifetime_ribs.push(LifetimeRib::new(kind)); + let outer_elision_candidates = self.lifetime_elision_candidates.take(); + let ret = work(self); + self.lifetime_elision_candidates = outer_elision_candidates; + self.lifetime_ribs.pop(); + ret + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) { + let ident = lifetime.ident; + + if ident.name == kw::StaticLifetime { + self.record_lifetime_res( + lifetime.id, + LifetimeRes::Static, + LifetimeElisionCandidate::Named, + ); + return; + } + + if ident.name == kw::UnderscoreLifetime { + return self.resolve_anonymous_lifetime(lifetime, false); + } + + let mut indices = (0..self.lifetime_ribs.len()).rev(); + for i in &mut indices { + let rib = &self.lifetime_ribs[i]; + let normalized_ident = ident.normalize_to_macros_2_0(); + if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) { + self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named); + + if let LifetimeRes::Param { param, .. } = res { + match self.lifetime_uses.entry(param) { + Entry::Vacant(v) => { + debug!("First use of {:?} at {:?}", res, ident.span); + let use_set = self + .lifetime_ribs + .iter() + .rev() + .find_map(|rib| match rib.kind { + // Do not suggest eliding a lifetime where an anonymous + // lifetime would be illegal. + LifetimeRibKind::Item + | LifetimeRibKind::AnonymousReportError + | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many), + // An anonymous lifetime is legal here, go ahead. + LifetimeRibKind::AnonymousCreateParameter { .. } => { + Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt }) + } + // Only report if eliding the lifetime would have the same + // semantics. + LifetimeRibKind::Elided(r) => Some(if res == r { + LifetimeUseSet::One { use_span: ident.span, use_ctxt } + } else { + LifetimeUseSet::Many + }), + LifetimeRibKind::Generics { .. } + | LifetimeRibKind::ConstGeneric + | LifetimeRibKind::AnonConst => None, + }) + .unwrap_or(LifetimeUseSet::Many); + debug!(?use_ctxt, ?use_set); + v.insert(use_set); + } + Entry::Occupied(mut o) => { + debug!("Many uses of {:?} at {:?}", res, ident.span); + *o.get_mut() = LifetimeUseSet::Many; + } + } + } + return; + } + + match rib.kind { + LifetimeRibKind::Item => break, + LifetimeRibKind::ConstGeneric => { + self.emit_non_static_lt_in_const_generic_error(lifetime); + self.record_lifetime_res( + lifetime.id, + LifetimeRes::Error, + LifetimeElisionCandidate::Ignore, + ); + return; + } + LifetimeRibKind::AnonConst => { + self.maybe_emit_forbidden_non_static_lifetime_error(lifetime); + self.record_lifetime_res( + lifetime.id, + LifetimeRes::Error, + LifetimeElisionCandidate::Ignore, + ); + return; + } + _ => {} + } + } + + let mut outer_res = None; + for i in indices { + let rib = &self.lifetime_ribs[i]; + let normalized_ident = ident.normalize_to_macros_2_0(); + if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) { + outer_res = Some(outer); + break; + } + } + + self.emit_undeclared_lifetime_error(lifetime, outer_res); + self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named); + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) { + debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime); + + let missing_lifetime = MissingLifetime { + id: lifetime.id, + span: lifetime.ident.span, + kind: if elided { + MissingLifetimeKind::Ampersand + } else { + MissingLifetimeKind::Underscore + }, + count: 1, + }; + let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime); + for i in (0..self.lifetime_ribs.len()).rev() { + let rib = &mut self.lifetime_ribs[i]; + debug!(?rib.kind); + match rib.kind { + LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { + let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder); + self.record_lifetime_res(lifetime.id, res, elision_candidate); + return; + } + LifetimeRibKind::AnonymousReportError => { + let (msg, note) = if elided { + ( + "`&` without an explicit lifetime name cannot be used here", + "explicit lifetime name needed here", + ) + } else { + ("`'_` cannot be used here", "`'_` is a reserved lifetime name") + }; + rustc_errors::struct_span_err!( + self.r.session, + lifetime.ident.span, + E0637, + "{}", + msg, + ) + .span_label(lifetime.ident.span, note) + .emit(); + + self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate); + return; + } + LifetimeRibKind::Elided(res) => { + self.record_lifetime_res(lifetime.id, res, elision_candidate); + return; + } + LifetimeRibKind::ElisionFailure => { + self.diagnostic_metadata.current_elision_failures.push(missing_lifetime); + self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate); + return; + } + LifetimeRibKind::Item => break, + LifetimeRibKind::Generics { .. } + | LifetimeRibKind::ConstGeneric + | LifetimeRibKind::AnonConst => {} + } + } + self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate); + self.report_missing_lifetime_specifiers(vec![missing_lifetime], None); + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) { + let id = self.r.next_node_id(); + let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) }; + + self.record_lifetime_res( + anchor_id, + LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) }, + LifetimeElisionCandidate::Ignore, + ); + self.resolve_anonymous_lifetime(<, true); + } + + #[tracing::instrument(level = "debug", skip(self))] + fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes { + debug_assert_eq!(ident.name, kw::UnderscoreLifetime); + debug!(?ident.span); + + // Leave the responsibility to create the `LocalDefId` to lowering. + let param = self.r.next_node_id(); + let res = LifetimeRes::Fresh { param, binder }; + + // Record the created lifetime parameter so lowering can pick it up and add it to HIR. + self.r + .extra_lifetime_params_map + .entry(binder) + .or_insert_with(Vec::new) + .push((ident, param, res)); + res + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_elided_lifetimes_in_path( + &mut self, + path_id: NodeId, + partial_res: PartialRes, + path: &[Segment], + source: PathSource<'_>, + path_span: Span, + ) { + let proj_start = path.len() - partial_res.unresolved_segments(); + for (i, segment) in path.iter().enumerate() { + if segment.has_lifetime_args { + continue; + } + let Some(segment_id) = segment.id else { + continue; + }; + + // Figure out if this is a type/trait segment, + // which may need lifetime elision performed. + let type_def_id = match partial_res.base_res() { + Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id), + Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id), + Res::Def(DefKind::Struct, def_id) + | Res::Def(DefKind::Union, def_id) + | Res::Def(DefKind::Enum, def_id) + | Res::Def(DefKind::TyAlias, def_id) + | Res::Def(DefKind::Trait, def_id) + if i + 1 == proj_start => + { + def_id + } + _ => continue, + }; + + let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id); + if expected_lifetimes == 0 { + continue; + } + + let node_ids = self.r.next_node_ids(expected_lifetimes); + self.record_lifetime_res( + segment_id, + LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end }, + LifetimeElisionCandidate::Ignore, + ); + + let inferred = match source { + PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false, + PathSource::Expr(..) + | PathSource::Pat + | PathSource::Struct + | PathSource::TupleStruct(..) => true, + }; + if inferred { + // Do not create a parameter for patterns and expressions: type checking can infer + // the appropriate lifetime for us. + for id in node_ids { + self.record_lifetime_res( + id, + LifetimeRes::Infer, + LifetimeElisionCandidate::Named, + ); + } + continue; + } + + let elided_lifetime_span = if segment.has_generic_args { + // If there are brackets, but not generic arguments, then use the opening bracket + segment.args_span.with_hi(segment.args_span.lo() + BytePos(1)) + } else { + // If there are no brackets, use the identifier span. + // HACK: we use find_ancestor_inside to properly suggest elided spans in paths + // originating from macros, since the segment's span might be from a macro arg. + segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span) + }; + let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span); + + let missing_lifetime = MissingLifetime { + id: node_ids.start, + span: elided_lifetime_span, + kind: if segment.has_generic_args { + MissingLifetimeKind::Comma + } else { + MissingLifetimeKind::Brackets + }, + count: expected_lifetimes, + }; + let mut should_lint = true; + for rib in self.lifetime_ribs.iter().rev() { + match rib.kind { + // In create-parameter mode we error here because we don't want to support + // deprecated impl elision in new features like impl elision and `async fn`, + // both of which work using the `CreateParameter` mode: + // + // impl Foo for std::cell::Ref<u32> // note lack of '_ + // async fn foo(_: std::cell::Ref<u32>) { ... } + LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => { + let sess = self.r.session; + let mut err = rustc_errors::struct_span_err!( + sess, + path_span, + E0726, + "implicit elided lifetime not allowed here" + ); + rustc_errors::add_elided_lifetime_in_path_suggestion( + sess.source_map(), + &mut err, + expected_lifetimes, + path_span, + !segment.has_generic_args, + elided_lifetime_span, + ); + err.note("assuming a `'static` lifetime..."); + err.emit(); + should_lint = false; + + for id in node_ids { + self.record_lifetime_res( + id, + LifetimeRes::Error, + LifetimeElisionCandidate::Named, + ); + } + break; + } + // Do not create a parameter for patterns and expressions. + LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { + // Group all suggestions into the first record. + let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime); + for id in node_ids { + let res = self.create_fresh_lifetime(id, ident, binder); + self.record_lifetime_res( + id, + res, + replace(&mut candidate, LifetimeElisionCandidate::Named), + ); + } + break; + } + LifetimeRibKind::Elided(res) => { + let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime); + for id in node_ids { + self.record_lifetime_res( + id, + res, + replace(&mut candidate, LifetimeElisionCandidate::Ignore), + ); + } + break; + } + LifetimeRibKind::ElisionFailure => { + self.diagnostic_metadata.current_elision_failures.push(missing_lifetime); + for id in node_ids { + self.record_lifetime_res( + id, + LifetimeRes::Error, + LifetimeElisionCandidate::Ignore, + ); + } + break; + } + // `LifetimeRes::Error`, which would usually be used in the case of + // `ReportError`, is unsuitable here, as we don't emit an error yet. Instead, + // we simply resolve to an implicit lifetime, which will be checked later, at + // which point a suitable error will be emitted. + LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => { + for id in node_ids { + self.record_lifetime_res( + id, + LifetimeRes::Error, + LifetimeElisionCandidate::Ignore, + ); + } + self.report_missing_lifetime_specifiers(vec![missing_lifetime], None); + break; + } + LifetimeRibKind::Generics { .. } + | LifetimeRibKind::ConstGeneric + | LifetimeRibKind::AnonConst => {} + } + } + + if should_lint { + self.r.lint_buffer.buffer_lint_with_diagnostic( + lint::builtin::ELIDED_LIFETIMES_IN_PATHS, + segment_id, + elided_lifetime_span, + "hidden lifetime parameters in types are deprecated", + lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths( + expected_lifetimes, + path_span, + !segment.has_generic_args, + elided_lifetime_span, + ), + ); + } + } + } + + #[tracing::instrument(level = "debug", skip(self))] + fn record_lifetime_res( + &mut self, + id: NodeId, + res: LifetimeRes, + candidate: LifetimeElisionCandidate, + ) { + if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { + panic!( + "lifetime {:?} resolved multiple times ({:?} before, {:?} now)", + id, prev_res, res + ) + } + match res { + LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => { + if let Some(ref mut candidates) = self.lifetime_elision_candidates { + candidates.insert(res, candidate); + } + } + LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {} + } + } + + #[tracing::instrument(level = "debug", skip(self))] + fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) { + if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) { + panic!( + "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)", + id, prev_res, res + ) + } + } + + /// Perform resolution of a function signature, accounting for lifetime elision. + #[tracing::instrument(level = "debug", skip(self, inputs))] + fn resolve_fn_signature( + &mut self, + fn_id: NodeId, + has_self: bool, + inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone, + output_ty: &'ast FnRetTy, + ) { + // Add each argument to the rib. + let elision_lifetime = self.resolve_fn_params(has_self, inputs); + debug!(?elision_lifetime); + + let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures); + let output_rib = if let Ok(res) = elision_lifetime.as_ref() { + LifetimeRibKind::Elided(*res) + } else { + LifetimeRibKind::ElisionFailure + }; + self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty)); + let elision_failures = + replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures); + if !elision_failures.is_empty() { + let Err(failure_info) = elision_lifetime else { bug!() }; + self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info)); + } + } + + /// Resolve inside function parameters and parameter types. + /// Returns the lifetime for elision in fn return type, + /// or diagnostic information in case of elision failure. + fn resolve_fn_params( + &mut self, + has_self: bool, + inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>, + ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> { + let outer_candidates = + replace(&mut self.lifetime_elision_candidates, Some(Default::default())); + + let mut elision_lifetime = None; + let mut lifetime_count = 0; + let mut parameter_info = Vec::new(); + + let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; + for (index, (pat, ty)) in inputs.enumerate() { + debug!(?pat, ?ty); + if let Some(pat) = pat { + self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); + } + self.visit_ty(ty); + + if let Some(ref candidates) = self.lifetime_elision_candidates { + let new_count = candidates.len(); + let local_count = new_count - lifetime_count; + if local_count != 0 { + parameter_info.push(ElisionFnParameter { + index, + ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind { + Some(ident) + } else { + None + }, + lifetime_count: local_count, + span: ty.span, + }); + } + lifetime_count = new_count; + } + + // Handle `self` specially. + if index == 0 && has_self { + let self_lifetime = self.find_lifetime_for_self(ty); + if let Set1::One(lifetime) = self_lifetime { + elision_lifetime = Some(lifetime); + self.lifetime_elision_candidates = None; + } else { + self.lifetime_elision_candidates = Some(Default::default()); + lifetime_count = 0; + } + } + debug!("(resolving function / closure) recorded parameter"); + } + + let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates); + debug!(?all_candidates); + + if let Some(res) = elision_lifetime { + return Ok(res); + } + + // We do not have a `self` candidate, look at the full list. + let all_candidates = all_candidates.unwrap(); + if all_candidates.len() == 1 { + Ok(*all_candidates.first().unwrap().0) + } else { + let all_candidates = all_candidates + .into_iter() + .filter_map(|(_, candidate)| match candidate { + LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None, + LifetimeElisionCandidate::Missing(missing) => Some(missing), + }) + .collect(); + Err((all_candidates, parameter_info)) + } + } + + /// List all the lifetimes that appear in the provided type. + fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> { + struct SelfVisitor<'r, 'a> { + r: &'r Resolver<'a>, + impl_self: Option<Res>, + lifetime: Set1<LifetimeRes>, + } + + impl SelfVisitor<'_, '_> { + // Look for `self: &'a Self` - also desugared from `&'a self`, + // and if that matches, use it for elision and return early. + fn is_self_ty(&self, ty: &Ty) -> bool { + match ty.kind { + TyKind::ImplicitSelf => true, + TyKind::Path(None, _) => { + let path_res = self.r.partial_res_map[&ty.id].base_res(); + if let Res::SelfTy { .. } = path_res { + return true; + } + Some(path_res) == self.impl_self + } + _ => false, + } + } + } + + impl<'a> Visitor<'a> for SelfVisitor<'_, '_> { + fn visit_ty(&mut self, ty: &'a Ty) { + trace!("SelfVisitor considering ty={:?}", ty); + if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) { + let lt_id = if let Some(lt) = lt { + lt.id + } else { + let res = self.r.lifetimes_res_map[&ty.id]; + let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() }; + start + }; + let lt_res = self.r.lifetimes_res_map[<_id]; + trace!("SelfVisitor inserting res={:?}", lt_res); + self.lifetime.insert(lt_res); + } + visit::walk_ty(self, ty) + } + } + + let impl_self = self + .diagnostic_metadata + .current_self_type + .as_ref() + .and_then(|ty| { + if let TyKind::Path(None, _) = ty.kind { + self.r.partial_res_map.get(&ty.id) + } else { + None + } + }) + .map(|res| res.base_res()) + .filter(|res| { + // Permit the types that unambiguously always + // result in the same type constructor being used + // (it can't differ between `Self` and `self`). + matches!( + res, + Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_) + ) + }); + let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty }; + visitor.visit_ty(ty); + trace!("SelfVisitor found={:?}", visitor.lifetime); + visitor.lifetime + } + + /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved + /// label and reports an error if the label is not found or is unreachable. + fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> { + let mut suggestion = None; + + for i in (0..self.label_ribs.len()).rev() { + let rib = &self.label_ribs[i]; + + if let MacroDefinition(def) = rib.kind { + // If an invocation of this macro created `ident`, give up on `ident` + // and switch to `ident`'s source from the macro definition. + if def == self.r.macro_def(label.span.ctxt()) { + label.span.remove_mark(); + } + } + + let ident = label.normalize_to_macro_rules(); + if let Some((ident, id)) = rib.bindings.get_key_value(&ident) { + let definition_span = ident.span; + return if self.is_label_valid_from_rib(i) { + Ok((*id, definition_span)) + } else { + Err(ResolutionError::UnreachableLabel { + name: label.name, + definition_span, + suggestion, + }) + }; + } + + // Diagnostics: Check if this rib contains a label with a similar name, keep track of + // the first such label that is encountered. + suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label)); + } + + Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion }) + } + + /// Determine whether or not a label from the `rib_index`th label rib is reachable. + fn is_label_valid_from_rib(&self, rib_index: usize) -> bool { + let ribs = &self.label_ribs[rib_index + 1..]; + + for rib in ribs { + if rib.kind.is_label_barrier() { + return false; + } + } + + true + } + + fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) { + debug!("resolve_adt"); + self.with_current_self_item(item, |this| { + this.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: item.id, + kind: LifetimeBinderKind::Item, + span: generics.span, + }, + |this| { + let item_def_id = this.r.local_def_id(item.id).to_def_id(); + this.with_self_rib( + Res::SelfTy { trait_: None, alias_to: Some((item_def_id, false)) }, + |this| { + visit::walk_item(this, item); + }, + ); + }, + ); + }); + } + + fn future_proof_import(&mut self, use_tree: &UseTree) { + let segments = &use_tree.prefix.segments; + if !segments.is_empty() { + let ident = segments[0].ident; + if ident.is_path_segment_keyword() || ident.span.rust_2015() { + return; + } + + let nss = match use_tree.kind { + UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..], + _ => &[TypeNS], + }; + let report_error = |this: &Self, ns| { + let what = if ns == TypeNS { "type parameters" } else { "local variables" }; + if this.should_report_errs() { + this.r + .session + .span_err(ident.span, &format!("imports cannot refer to {}", what)); + } + }; + + for &ns in nss { + match self.maybe_resolve_ident_in_lexical_scope(ident, ns) { + Some(LexicalScopeBinding::Res(..)) => { + report_error(self, ns); + } + Some(LexicalScopeBinding::Item(binding)) => { + if let Some(LexicalScopeBinding::Res(..)) = + self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding)) + { + report_error(self, ns); + } + } + None => {} + } + } + } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind { + for (use_tree, _) in use_trees { + self.future_proof_import(use_tree); + } + } + } + + fn resolve_item(&mut self, item: &'ast Item) { + let name = item.ident.name; + debug!("(resolving item) resolving {} ({:?})", name, item.kind); + + match item.kind { + ItemKind::TyAlias(box TyAlias { ref generics, .. }) => { + self.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: item.id, + kind: LifetimeBinderKind::Item, + span: generics.span, + }, + |this| visit::walk_item(this, item), + ); + } + + ItemKind::Fn(box Fn { ref generics, .. }) => { + self.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: item.id, + kind: LifetimeBinderKind::Function, + span: generics.span, + }, + |this| visit::walk_item(this, item), + ); + } + + ItemKind::Enum(_, ref generics) + | ItemKind::Struct(_, ref generics) + | ItemKind::Union(_, ref generics) => { + self.resolve_adt(item, generics); + } + + ItemKind::Impl(box Impl { + ref generics, + ref of_trait, + ref self_ty, + items: ref impl_items, + .. + }) => { + self.diagnostic_metadata.current_impl_items = Some(impl_items); + self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items); + self.diagnostic_metadata.current_impl_items = None; + } + + ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => { + // Create a new rib for the trait-wide type parameters. + self.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: item.id, + kind: LifetimeBinderKind::Item, + span: generics.span, + }, + |this| { + let local_def_id = this.r.local_def_id(item.id).to_def_id(); + this.with_self_rib( + Res::SelfTy { trait_: Some(local_def_id), alias_to: None }, + |this| { + this.visit_generics(generics); + walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits); + this.resolve_trait_items(items); + }, + ); + }, + ); + } + + ItemKind::TraitAlias(ref generics, ref bounds) => { + // Create a new rib for the trait-wide type parameters. + self.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + binder: item.id, + kind: LifetimeBinderKind::Item, + span: generics.span, + }, + |this| { + let local_def_id = this.r.local_def_id(item.id).to_def_id(); + this.with_self_rib( + Res::SelfTy { trait_: Some(local_def_id), alias_to: None }, + |this| { + this.visit_generics(generics); + walk_list!(this, visit_param_bound, bounds, BoundKind::Bound); + }, + ); + }, + ); + } + + ItemKind::Mod(..) | ItemKind::ForeignMod(_) => { + self.with_scope(item.id, |this| { + visit::walk_item(this, item); + }); + } + + ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => { + self.with_item_rib(|this| { + this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| { + this.visit_ty(ty); + }); + this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| { + if let Some(expr) = expr { + let constant_item_kind = match item.kind { + ItemKind::Const(..) => ConstantItemKind::Const, + ItemKind::Static(..) => ConstantItemKind::Static, + _ => unreachable!(), + }; + // We already forbid generic params because of the above item rib, + // so it doesn't matter whether this is a trivial constant. + this.with_constant_rib( + IsRepeatExpr::No, + HasGenericParams::Yes, + Some((item.ident, constant_item_kind)), + |this| this.visit_expr(expr), + ); + } + }); + }); + } + + ItemKind::Use(ref use_tree) => { + self.future_proof_import(use_tree); + } + + ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => { + // do nothing, these are just around to be encoded + } + + ItemKind::GlobalAsm(_) => { + visit::walk_item(self, item); + } + + ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"), + } + } + + fn with_generic_param_rib<'c, F>( + &'c mut self, + params: &'c [GenericParam], + kind: RibKind<'a>, + lifetime_kind: LifetimeRibKind, + f: F, + ) where + F: FnOnce(&mut Self), + { + debug!("with_generic_param_rib"); + let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } + = lifetime_kind else { panic!() }; + + let mut function_type_rib = Rib::new(kind); + let mut function_value_rib = Rib::new(kind); + let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind); + let mut seen_bindings = FxHashMap::default(); + // Store all seen lifetimes names from outer scopes. + let mut seen_lifetimes = FxHashSet::default(); + + // We also can't shadow bindings from the parent item + if let AssocItemRibKind = kind { + let mut add_bindings_for_ns = |ns| { + let parent_rib = self.ribs[ns] + .iter() + .rfind(|r| matches!(r.kind, ItemRibKind(_))) + .expect("associated item outside of an item"); + seen_bindings + .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span))); + }; + add_bindings_for_ns(ValueNS); + add_bindings_for_ns(TypeNS); + } + + // Forbid shadowing lifetime bindings + for rib in self.lifetime_ribs.iter().rev() { + seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident)); + if let LifetimeRibKind::Item = rib.kind { + break; + } + } + + for param in params { + let ident = param.ident.normalize_to_macros_2_0(); + debug!("with_generic_param_rib: {}", param.id); + + if let GenericParamKind::Lifetime = param.kind + && let Some(&original) = seen_lifetimes.get(&ident) + { + diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident); + // Record lifetime res, so lowering knows there is something fishy. + self.record_lifetime_param(param.id, LifetimeRes::Error); + continue; + } + + match seen_bindings.entry(ident) { + Entry::Occupied(entry) => { + let span = *entry.get(); + let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span); + self.report_error(param.ident.span, err); + if let GenericParamKind::Lifetime = param.kind { + // Record lifetime res, so lowering knows there is something fishy. + self.record_lifetime_param(param.id, LifetimeRes::Error); + continue; + } + } + Entry::Vacant(entry) => { + entry.insert(param.ident.span); + } + } + + if param.ident.name == kw::UnderscoreLifetime { + rustc_errors::struct_span_err!( + self.r.session, + param.ident.span, + E0637, + "`'_` cannot be used here" + ) + .span_label(param.ident.span, "`'_` is a reserved lifetime name") + .emit(); + // Record lifetime res, so lowering knows there is something fishy. + self.record_lifetime_param(param.id, LifetimeRes::Error); + continue; + } + + if param.ident.name == kw::StaticLifetime { + rustc_errors::struct_span_err!( + self.r.session, + param.ident.span, + E0262, + "invalid lifetime parameter name: `{}`", + param.ident, + ) + .span_label(param.ident.span, "'static is a reserved lifetime name") + .emit(); + // Record lifetime res, so lowering knows there is something fishy. + self.record_lifetime_param(param.id, LifetimeRes::Error); + continue; + } + + let def_id = self.r.local_def_id(param.id); + + // Plain insert (no renaming). + let (rib, def_kind) = match param.kind { + GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam), + GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam), + GenericParamKind::Lifetime => { + let res = LifetimeRes::Param { param: def_id, binder }; + self.record_lifetime_param(param.id, res); + function_lifetime_rib.bindings.insert(ident, (param.id, res)); + continue; + } + }; + + let res = match kind { + ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()), + NormalRibKind => Res::Err, + _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind), + }; + self.r.record_partial_res(param.id, PartialRes::new(res)); + rib.bindings.insert(ident, res); + } + + self.lifetime_ribs.push(function_lifetime_rib); + self.ribs[ValueNS].push(function_value_rib); + self.ribs[TypeNS].push(function_type_rib); + + f(self); + + self.ribs[TypeNS].pop(); + self.ribs[ValueNS].pop(); + let function_lifetime_rib = self.lifetime_ribs.pop().unwrap(); + + // Do not account for the parameters we just bound for function lifetime elision. + if let Some(ref mut candidates) = self.lifetime_elision_candidates { + for (_, res) in function_lifetime_rib.bindings.values() { + candidates.remove(res); + } + } + + if let LifetimeBinderKind::BareFnType + | LifetimeBinderKind::WhereBound + | LifetimeBinderKind::Function + | LifetimeBinderKind::ImplBlock = generics_kind + { + self.maybe_report_lifetime_uses(generics_span, params) + } + } + + fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) { + self.label_ribs.push(Rib::new(kind)); + f(self); + self.label_ribs.pop(); + } + + fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) { + let kind = ItemRibKind(HasGenericParams::No); + self.with_lifetime_rib(LifetimeRibKind::Item, |this| { + this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f)) + }) + } + + // HACK(min_const_generics,const_evaluatable_unchecked): We + // want to keep allowing `[0; std::mem::size_of::<*mut T>()]` + // with a future compat lint for now. We do this by adding an + // additional special case for repeat expressions. + // + // Note that we intentionally still forbid `[0; N + 1]` during + // name resolution so that we don't extend the future + // compat lint to new cases. + #[instrument(level = "debug", skip(self, f))] + fn with_constant_rib( + &mut self, + is_repeat: IsRepeatExpr, + may_use_generics: HasGenericParams, + item: Option<(Ident, ConstantItemKind)>, + f: impl FnOnce(&mut Self), + ) { + self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| { + this.with_rib( + TypeNS, + ConstantItemRibKind( + may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes), + item, + ), + |this| { + this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f); + }, + ) + }); + } + + fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T { + // Handle nested impls (inside fn bodies) + let previous_value = + replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone())); + let result = f(self); + self.diagnostic_metadata.current_self_type = previous_value; + result + } + + fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T { + let previous_value = + replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id)); + let result = f(self); + self.diagnostic_metadata.current_self_item = previous_value; + result + } + + /// When evaluating a `trait` use its associated types' idents for suggestions in E0412. + fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) { + let trait_assoc_items = + replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items)); + + let walk_assoc_item = + |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| { + this.with_generic_param_rib( + &generics.params, + AssocItemRibKind, + LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind }, + |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait), + ); + }; + + for item in trait_items { + match &item.kind { + AssocItemKind::Const(_, ty, default) => { + self.visit_ty(ty); + // Only impose the restrictions of `ConstRibKind` for an + // actual constant expression in a provided default. + if let Some(expr) = default { + // We allow arbitrary const expressions inside of associated consts, + // even if they are potentially not const evaluatable. + // + // Type parameters can already be used and as associated consts are + // not used as part of the type system, this is far less surprising. + self.with_lifetime_rib( + LifetimeRibKind::Elided(LifetimeRes::Infer), + |this| { + this.with_constant_rib( + IsRepeatExpr::No, + HasGenericParams::Yes, + None, + |this| this.visit_expr(expr), + ) + }, + ); + } + } + AssocItemKind::Fn(box Fn { generics, .. }) => { + walk_assoc_item(self, generics, LifetimeBinderKind::Function, item); + } + AssocItemKind::TyAlias(box TyAlias { generics, .. }) => self + .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { + walk_assoc_item(this, generics, LifetimeBinderKind::Item, item) + }), + AssocItemKind::MacCall(_) => { + panic!("unexpanded macro in resolve!") + } + }; + } + + self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items; + } + + /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`). + fn with_optional_trait_ref<T>( + &mut self, + opt_trait_ref: Option<&TraitRef>, + self_type: &'ast Ty, + f: impl FnOnce(&mut Self, Option<DefId>) -> T, + ) -> T { + let mut new_val = None; + let mut new_id = None; + if let Some(trait_ref) = opt_trait_ref { + let path: Vec<_> = Segment::from_path(&trait_ref.path); + self.diagnostic_metadata.currently_processing_impl_trait = + Some((trait_ref.clone(), self_type.clone())); + let res = self.smart_resolve_path_fragment( + None, + &path, + PathSource::Trait(AliasPossibility::No), + Finalize::new(trait_ref.ref_id, trait_ref.path.span), + ); + self.diagnostic_metadata.currently_processing_impl_trait = None; + if let Some(def_id) = res.base_res().opt_def_id() { + new_id = Some(def_id); + new_val = Some((self.r.expect_module(def_id), trait_ref.clone())); + } + } + let original_trait_ref = replace(&mut self.current_trait_ref, new_val); + let result = f(self, new_id); + self.current_trait_ref = original_trait_ref; + result + } + + fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) { + let mut self_type_rib = Rib::new(NormalRibKind); + + // Plain insert (no renaming, since types are not currently hygienic) + self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res); + self.ribs[ns].push(self_type_rib); + f(self); + self.ribs[ns].pop(); + } + + fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) { + self.with_self_rib_ns(TypeNS, self_res, f) + } + + fn resolve_implementation( + &mut self, + generics: &'ast Generics, + opt_trait_reference: &'ast Option<TraitRef>, + self_type: &'ast Ty, + item_id: NodeId, + impl_items: &'ast [P<AssocItem>], + ) { + debug!("resolve_implementation"); + // If applicable, create a rib for the type parameters. + self.with_generic_param_rib( + &generics.params, + ItemRibKind(HasGenericParams::Yes), + LifetimeRibKind::Generics { + span: generics.span, + binder: item_id, + kind: LifetimeBinderKind::ImplBlock, + }, + |this| { + // Dummy self type for better errors if `Self` is used in the trait path. + this.with_self_rib(Res::SelfTy { trait_: None, alias_to: None }, |this| { + this.with_lifetime_rib( + LifetimeRibKind::AnonymousCreateParameter { + binder: item_id, + report_in_path: true + }, + |this| { + // Resolve the trait reference, if necessary. + this.with_optional_trait_ref( + opt_trait_reference.as_ref(), + self_type, + |this, trait_id| { + let item_def_id = this.r.local_def_id(item_id); + + // Register the trait definitions from here. + if let Some(trait_id) = trait_id { + this.r + .trait_impls + .entry(trait_id) + .or_default() + .push(item_def_id); + } + + let item_def_id = item_def_id.to_def_id(); + let res = Res::SelfTy { + trait_: trait_id, + alias_to: Some((item_def_id, false)), + }; + this.with_self_rib(res, |this| { + if let Some(trait_ref) = opt_trait_reference.as_ref() { + // Resolve type arguments in the trait path. + visit::walk_trait_ref(this, trait_ref); + } + // Resolve the self type. + this.visit_ty(self_type); + // Resolve the generic parameters. + this.visit_generics(generics); + + // Resolve the items within the impl. + this.with_current_self_type(self_type, |this| { + this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| { + debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)"); + for item in impl_items { + this.resolve_impl_item(&**item); + } + }); + }); + }); + }, + ) + }, + ); + }); + }, + ); + } + + fn resolve_impl_item(&mut self, item: &'ast AssocItem) { + use crate::ResolutionError::*; + match &item.kind { + AssocItemKind::Const(_, ty, default) => { + debug!("resolve_implementation AssocItemKind::Const"); + // If this is a trait impl, ensure the const + // exists in trait + self.check_trait_item( + item.id, + item.ident, + &item.kind, + ValueNS, + item.span, + |i, s, c| ConstNotMemberOfTrait(i, s, c), + ); + + self.visit_ty(ty); + if let Some(expr) = default { + // We allow arbitrary const expressions inside of associated consts, + // even if they are potentially not const evaluatable. + // + // Type parameters can already be used and as associated consts are + // not used as part of the type system, this is far less surprising. + self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| { + this.with_constant_rib( + IsRepeatExpr::No, + HasGenericParams::Yes, + None, + |this| this.visit_expr(expr), + ) + }); + } + } + AssocItemKind::Fn(box Fn { generics, .. }) => { + debug!("resolve_implementation AssocItemKind::Fn"); + // We also need a new scope for the impl item type parameters. + self.with_generic_param_rib( + &generics.params, + AssocItemRibKind, + LifetimeRibKind::Generics { + binder: item.id, + span: generics.span, + kind: LifetimeBinderKind::Function, + }, + |this| { + // If this is a trait impl, ensure the method + // exists in trait + this.check_trait_item( + item.id, + item.ident, + &item.kind, + ValueNS, + item.span, + |i, s, c| MethodNotMemberOfTrait(i, s, c), + ); + + visit::walk_assoc_item(this, item, AssocCtxt::Impl) + }, + ); + } + AssocItemKind::TyAlias(box TyAlias { generics, .. }) => { + debug!("resolve_implementation AssocItemKind::TyAlias"); + // We also need a new scope for the impl item type parameters. + self.with_generic_param_rib( + &generics.params, + AssocItemRibKind, + LifetimeRibKind::Generics { + binder: item.id, + span: generics.span, + kind: LifetimeBinderKind::Item, + }, + |this| { + this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| { + // If this is a trait impl, ensure the type + // exists in trait + this.check_trait_item( + item.id, + item.ident, + &item.kind, + TypeNS, + item.span, + |i, s, c| TypeNotMemberOfTrait(i, s, c), + ); + + visit::walk_assoc_item(this, item, AssocCtxt::Impl) + }); + }, + ); + } + AssocItemKind::MacCall(_) => { + panic!("unexpanded macro in resolve!") + } + } + } + + fn check_trait_item<F>( + &mut self, + id: NodeId, + mut ident: Ident, + kind: &AssocItemKind, + ns: Namespace, + span: Span, + err: F, + ) where + F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>, + { + // If there is a TraitRef in scope for an impl, then the method must be in the trait. + let Some((module, _)) = &self.current_trait_ref else { return; }; + ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); + let key = self.r.new_key(ident, ns); + let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); + debug!(?binding); + if binding.is_none() { + // We could not find the trait item in the correct namespace. + // Check the other namespace to report an error. + let ns = match ns { + ValueNS => TypeNS, + TypeNS => ValueNS, + _ => ns, + }; + let key = self.r.new_key(ident, ns); + binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); + debug!(?binding); + } + let Some(binding) = binding else { + // We could not find the method: report an error. + let candidate = self.find_similarly_named_assoc_item(ident.name, kind); + let path = &self.current_trait_ref.as_ref().unwrap().1.path; + let path_names = path_names_to_string(path); + self.report_error(span, err(ident, path_names, candidate)); + return; + }; + + let res = binding.res(); + let Res::Def(def_kind, _) = res else { bug!() }; + match (def_kind, kind) { + (DefKind::AssocTy, AssocItemKind::TyAlias(..)) + | (DefKind::AssocFn, AssocItemKind::Fn(..)) + | (DefKind::AssocConst, AssocItemKind::Const(..)) => { + self.r.record_partial_res(id, PartialRes::new(res)); + return; + } + _ => {} + } + + // The method kind does not correspond to what appeared in the trait, report. + let path = &self.current_trait_ref.as_ref().unwrap().1.path; + let (code, kind) = match kind { + AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"), + AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"), + AssocItemKind::TyAlias(..) => (rustc_errors::error_code!(E0325), "type"), + AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"), + }; + let trait_path = path_names_to_string(path); + self.report_error( + span, + ResolutionError::TraitImplMismatch { + name: ident.name, + kind, + code, + trait_path, + trait_item_span: binding.span, + }, + ); + } + + fn resolve_params(&mut self, params: &'ast [Param]) { + let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; + for Param { pat, ty, .. } in params { + self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); + self.visit_ty(ty); + debug!("(resolving function / closure) recorded parameter"); + } + } + + fn resolve_local(&mut self, local: &'ast Local) { + debug!("resolving local ({:?})", local); + // Resolve the type. + walk_list!(self, visit_ty, &local.ty); + + // Resolve the initializer. + if let Some((init, els)) = local.kind.init_else_opt() { + self.visit_expr(init); + + // Resolve the `else` block + if let Some(els) = els { + self.visit_block(els); + } + } + + // Resolve the pattern. + self.resolve_pattern_top(&local.pat, PatternSource::Let); + } + + /// build a map from pattern identifiers to binding-info's. + /// this is done hygienically. This could arise for a macro + /// that expands into an or-pattern where one 'x' was from the + /// user and one 'x' came from the macro. + fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap { + let mut binding_map = FxHashMap::default(); + + pat.walk(&mut |pat| { + match pat.kind { + PatKind::Ident(binding_mode, ident, ref sub_pat) + if sub_pat.is_some() || self.is_base_res_local(pat.id) => + { + binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode }); + } + PatKind::Or(ref ps) => { + // Check the consistency of this or-pattern and + // then add all bindings to the larger map. + for bm in self.check_consistent_bindings(ps) { + binding_map.extend(bm); + } + return false; + } + _ => {} + } + + true + }); + + binding_map + } + + fn is_base_res_local(&self, nid: NodeId) -> bool { + matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..))) + } + + /// Checks that all of the arms in an or-pattern have exactly the + /// same set of bindings, with the same binding modes for each. + fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> { + let mut missing_vars = FxHashMap::default(); + let mut inconsistent_vars = FxHashMap::default(); + + // 1) Compute the binding maps of all arms. + let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>(); + + // 2) Record any missing bindings or binding mode inconsistencies. + for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) { + // Check against all arms except for the same pattern which is always self-consistent. + let inners = pats + .iter() + .enumerate() + .filter(|(_, pat)| pat.id != pat_outer.id) + .flat_map(|(idx, _)| maps[idx].iter()) + .map(|(key, binding)| (key.name, map_outer.get(&key), binding)); + + for (name, info, &binding_inner) in inners { + match info { + None => { + // The inner binding is missing in the outer. + let binding_error = + missing_vars.entry(name).or_insert_with(|| BindingError { + name, + origin: BTreeSet::new(), + target: BTreeSet::new(), + could_be_path: name.as_str().starts_with(char::is_uppercase), + }); + binding_error.origin.insert(binding_inner.span); + binding_error.target.insert(pat_outer.span); + } + Some(binding_outer) => { + if binding_outer.binding_mode != binding_inner.binding_mode { + // The binding modes in the outer and inner bindings differ. + inconsistent_vars + .entry(name) + .or_insert((binding_inner.span, binding_outer.span)); + } + } + } + } + } + + // 3) Report all missing variables we found. + let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>(); + missing_vars.sort_by_key(|&(sym, ref _err)| sym); + + for (name, mut v) in missing_vars.into_iter() { + if inconsistent_vars.contains_key(&name) { + v.could_be_path = false; + } + self.report_error( + *v.origin.iter().next().unwrap(), + ResolutionError::VariableNotBoundInPattern(v, self.parent_scope), + ); + } + + // 4) Report all inconsistencies in binding modes we found. + let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>(); + inconsistent_vars.sort(); + for (name, v) in inconsistent_vars { + self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1)); + } + + // 5) Finally bubble up all the binding maps. + maps + } + + /// Check the consistency of the outermost or-patterns. + fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) { + pat.walk(&mut |pat| match pat.kind { + PatKind::Or(ref ps) => { + self.check_consistent_bindings(ps); + false + } + _ => true, + }) + } + + fn resolve_arm(&mut self, arm: &'ast Arm) { + self.with_rib(ValueNS, NormalRibKind, |this| { + this.resolve_pattern_top(&arm.pat, PatternSource::Match); + walk_list!(this, visit_expr, &arm.guard); + this.visit_expr(&arm.body); + }); + } + + /// Arising from `source`, resolve a top level pattern. + fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) { + let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; + self.resolve_pattern(pat, pat_src, &mut bindings); + } + + fn resolve_pattern( + &mut self, + pat: &'ast Pat, + pat_src: PatternSource, + bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, + ) { + // We walk the pattern before declaring the pattern's inner bindings, + // so that we avoid resolving a literal expression to a binding defined + // by the pattern. + visit::walk_pat(self, pat); + self.resolve_pattern_inner(pat, pat_src, bindings); + // This has to happen *after* we determine which pat_idents are variants: + self.check_consistent_bindings_top(pat); + } + + /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`. + /// + /// ### `bindings` + /// + /// A stack of sets of bindings accumulated. + /// + /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should + /// be interpreted as re-binding an already bound binding. This results in an error. + /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result + /// in reusing this binding rather than creating a fresh one. + /// + /// When called at the top level, the stack must have a single element + /// with `PatBound::Product`. Otherwise, pushing to the stack happens as + /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs + /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`. + /// When each `p_i` has been dealt with, the top set is merged with its parent. + /// When a whole or-pattern has been dealt with, the thing happens. + /// + /// See the implementation and `fresh_binding` for more details. + fn resolve_pattern_inner( + &mut self, + pat: &Pat, + pat_src: PatternSource, + bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, + ) { + // Visit all direct subpatterns of this pattern. + pat.walk(&mut |pat| { + debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind); + match pat.kind { + PatKind::Ident(bmode, ident, ref sub) => { + // First try to resolve the identifier as some existing entity, + // then fall back to a fresh binding. + let has_sub = sub.is_some(); + let res = self + .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub) + .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings)); + self.r.record_partial_res(pat.id, PartialRes::new(res)); + self.r.record_pat_span(pat.id, pat.span); + } + PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => { + self.smart_resolve_path( + pat.id, + qself.as_ref(), + path, + PathSource::TupleStruct( + pat.span, + self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)), + ), + ); + } + PatKind::Path(ref qself, ref path) => { + self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat); + } + PatKind::Struct(ref qself, ref path, ..) => { + self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct); + } + PatKind::Or(ref ps) => { + // Add a new set of bindings to the stack. `Or` here records that when a + // binding already exists in this set, it should not result in an error because + // `V1(a) | V2(a)` must be allowed and are checked for consistency later. + bindings.push((PatBoundCtx::Or, Default::default())); + for p in ps { + // Now we need to switch back to a product context so that each + // part of the or-pattern internally rejects already bound names. + // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad. + bindings.push((PatBoundCtx::Product, Default::default())); + self.resolve_pattern_inner(p, pat_src, bindings); + // Move up the non-overlapping bindings to the or-pattern. + // Existing bindings just get "merged". + let collected = bindings.pop().unwrap().1; + bindings.last_mut().unwrap().1.extend(collected); + } + // This or-pattern itself can itself be part of a product, + // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`. + // Both cases bind `a` again in a product pattern and must be rejected. + let collected = bindings.pop().unwrap().1; + bindings.last_mut().unwrap().1.extend(collected); + + // Prevent visiting `ps` as we've already done so above. + return false; + } + _ => {} + } + true + }); + } + + fn fresh_binding( + &mut self, + ident: Ident, + pat_id: NodeId, + pat_src: PatternSource, + bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>, + ) -> Res { + // 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.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. + let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product); + // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`. + // This is *required* for consistency which is checked later. + let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or); + + if already_bound_and { + // Overlap in a product pattern somewhere; report an error. + use ResolutionError::*; + let error = match pat_src { + // `fn f(a: u8, a: u8)`: + PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList, + // `Variant(a, a)`: + _ => IdentifierBoundMoreThanOnceInSamePattern, + }; + self.report_error(ident.span, error(ident.name)); + } + + // Record as bound if it's valid: + let ident_valid = ident.name != kw::Empty; + if ident_valid { + bindings.last_mut().unwrap().1.insert(ident); + } + + if already_bound_or { + // `Variant1(a) | Variant2(a)`, ok + // Reuse definition from the first `a`. + self.innermost_rib_bindings(ValueNS)[&ident] + } else { + let res = Res::Local(pat_id); + if ident_valid { + // A completely fresh binding add to the set if it's valid. + self.innermost_rib_bindings(ValueNS).insert(ident, res); + } + res + } + } + + fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> { + &mut self.ribs[ns].last_mut().unwrap().bindings + } + + fn try_resolve_as_non_binding( + &mut self, + pat_src: PatternSource, + bm: BindingMode, + ident: Ident, + has_sub: bool, + ) -> Option<Res> { + // An immutable (no `mut`) by-value (no `ref`) binding pattern without + // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could + // also be interpreted as a path to e.g. a constant, variant, etc. + let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not); + + let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?; + let (res, binding) = match ls_binding { + LexicalScopeBinding::Item(binding) + if is_syntactic_ambiguity && binding.is_ambiguity() => + { + // For ambiguous bindings we don't know all their definitions and cannot check + // whether they can be shadowed by fresh bindings or not, so force an error. + // issues/33118#issuecomment-233962221 (see below) still applies here, + // but we have to ignore it for backward compatibility. + self.r.record_use(ident, binding, false); + return None; + } + LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)), + LexicalScopeBinding::Res(res) => (res, None), + }; + + match res { + Res::SelfCtor(_) // See #70549. + | Res::Def( + DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam, + _, + ) if is_syntactic_ambiguity => { + // Disambiguate in favor of a unit struct/variant or constant pattern. + if let Some(binding) = binding { + self.r.record_use(ident, binding, false); + } + Some(res) + } + Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => { + // This is unambiguously a fresh binding, either syntactically + // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves + // to something unusable as a pattern (e.g., constructor function), + // but we still conservatively report an error, see + // issues/33118#issuecomment-233962221 for one reason why. + let binding = binding.expect("no binding for a ctor or static"); + self.report_error( + ident.span, + ResolutionError::BindingShadowsSomethingUnacceptable { + shadowing_binding: pat_src, + name: ident.name, + participle: if binding.is_import() { "imported" } else { "defined" }, + article: binding.res().article(), + shadowed_binding: binding.res(), + shadowed_binding_span: binding.span, + }, + ); + None + } + Res::Def(DefKind::ConstParam, def_id) => { + // Same as for DefKind::Const above, but here, `binding` is `None`, so we + // have to construct the error differently + self.report_error( + ident.span, + ResolutionError::BindingShadowsSomethingUnacceptable { + shadowing_binding: pat_src, + name: ident.name, + participle: "defined", + article: res.article(), + shadowed_binding: res, + shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"), + } + ); + None + } + Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => { + // These entities are explicitly allowed to be shadowed by fresh bindings. + None + } + Res::SelfCtor(_) => { + // We resolve `Self` in pattern position as an ident sometimes during recovery, + // so delay a bug instead of ICEing. + self.r.session.delay_span_bug( + ident.span, + "unexpected `SelfCtor` in pattern, expected identifier" + ); + None + } + _ => span_bug!( + ident.span, + "unexpected resolution for an identifier in pattern: {:?}", + res, + ), + } + } + + // High-level and context dependent path resolution routine. + // Resolves the path and records the resolution into definition map. + // If resolution fails tries several techniques to find likely + // resolution candidates, suggest imports or other help, and report + // errors in user friendly way. + fn smart_resolve_path( + &mut self, + id: NodeId, + qself: Option<&QSelf>, + path: &Path, + source: PathSource<'ast>, + ) { + self.smart_resolve_path_fragment( + qself, + &Segment::from_path(path), + source, + Finalize::new(id, path.span), + ); + } + + fn smart_resolve_path_fragment( + &mut self, + qself: Option<&QSelf>, + path: &[Segment], + source: PathSource<'ast>, + finalize: Finalize, + ) -> PartialRes { + tracing::debug!( + "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})", + qself, + path, + finalize, + ); + let ns = source.namespace(); + + let Finalize { node_id, path_span, .. } = finalize; + let report_errors = |this: &mut Self, res: Option<Res>| { + if this.should_report_errs() { + let (err, candidates) = + this.smart_resolve_report_errors(path, path_span, source, res); + + let def_id = this.parent_scope.module.nearest_parent_mod(); + let instead = res.is_some(); + let suggestion = + if res.is_none() { this.report_missing_type_error(path) } else { None }; + + this.r.use_injections.push(UseError { + err, + candidates, + def_id, + instead, + suggestion, + path: path.into(), + }); + } + + PartialRes::new(Res::Err) + }; + + // For paths originating from calls (like in `HashMap::new()`), tries + // to enrich the plain `failed to resolve: ...` message with hints + // about possible missing imports. + // + // Similar thing, for types, happens in `report_errors` above. + let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| { + if !source.is_call() { + return Some(parent_err); + } + + // Before we start looking for candidates, we have to get our hands + // on the type user is trying to perform invocation on; basically: + // we're transforming `HashMap::new` into just `HashMap`. + let path = match path.split_last() { + Some((_, path)) if !path.is_empty() => path, + _ => return Some(parent_err), + }; + + let (mut err, candidates) = + this.smart_resolve_report_errors(path, path_span, PathSource::Type, None); + + if candidates.is_empty() { + err.cancel(); + return Some(parent_err); + } + + // There are two different error messages user might receive at + // this point: + // - E0412 cannot find type `{}` in this scope + // - E0433 failed to resolve: use of undeclared type or module `{}` + // + // The first one is emitted for paths in type-position, and the + // latter one - for paths in expression-position. + // + // Thus (since we're in expression-position at this point), not to + // confuse the user, we want to keep the *message* from E0432 (so + // `parent_err`), but we want *hints* from E0412 (so `err`). + // + // And that's what happens below - we're just mixing both messages + // into a single one. + let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node); + + err.message = take(&mut parent_err.message); + err.code = take(&mut parent_err.code); + err.children = take(&mut parent_err.children); + + parent_err.cancel(); + + let def_id = this.parent_scope.module.nearest_parent_mod(); + + if this.should_report_errs() { + this.r.use_injections.push(UseError { + err, + candidates, + def_id, + instead: false, + suggestion: None, + path: path.into(), + }); + } else { + err.cancel(); + } + + // We don't return `Some(parent_err)` here, because the error will + // be already printed as part of the `use` injections + None + }; + + let partial_res = match self.resolve_qpath_anywhere( + qself, + path, + ns, + path_span, + source.defer_to_typeck(), + finalize, + ) { + Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => { + if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err + { + partial_res + } else { + report_errors(self, Some(partial_res.base_res())) + } + } + + Ok(Some(partial_res)) if source.defer_to_typeck() => { + // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B` + // or `<T>::A::B`. If `B` should be resolved in value namespace then + // it needs to be added to the trait map. + if ns == ValueNS { + let item_name = path.last().unwrap().ident; + let traits = self.traits_in_scope(item_name, ns); + self.r.trait_map.insert(node_id, traits); + } + + if PrimTy::from_name(path[0].ident.name).is_some() { + let mut std_path = Vec::with_capacity(1 + path.len()); + + std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std))); + std_path.extend(path); + if let PathResult::Module(_) | PathResult::NonModule(_) = + self.resolve_path(&std_path, Some(ns), None) + { + // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8` + let item_span = + path.iter().last().map_or(path_span, |segment| segment.ident.span); + + self.r.confused_type_with_std_module.insert(item_span, path_span); + self.r.confused_type_with_std_module.insert(path_span, path_span); + } + } + + partial_res + } + + Err(err) => { + if let Some(err) = report_errors_for_call(self, err) { + self.report_error(err.span, err.node); + } + + PartialRes::new(Res::Err) + } + + _ => report_errors(self, None), + }; + + if !matches!(source, PathSource::TraitItem(..)) { + // Avoid recording definition of `A::B` in `<T as A>::B::C`. + self.r.record_partial_res(node_id, partial_res); + self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span); + } + + partial_res + } + + fn self_type_is_available(&mut self) -> bool { + let binding = self + .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS); + if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } + } + + fn self_value_is_available(&mut self, self_span: Span) -> bool { + let ident = Ident::new(kw::SelfLower, self_span); + let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS); + if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false } + } + + /// A wrapper around [`Resolver::report_error`]. + /// + /// This doesn't emit errors for function bodies if this is rustdoc. + fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) { + if self.should_report_errs() { + self.r.report_error(span, resolution_error); + } + } + + #[inline] + /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items. + fn should_report_errs(&self) -> bool { + !(self.r.session.opts.actually_rustdoc && self.in_func_body) + } + + // Resolve in alternative namespaces if resolution in the primary namespace fails. + fn resolve_qpath_anywhere( + &mut self, + qself: Option<&QSelf>, + path: &[Segment], + primary_ns: Namespace, + span: Span, + defer_to_typeck: bool, + finalize: Finalize, + ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> { + let mut fin_res = None; + + for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() { + if i == 0 || ns != primary_ns { + match self.resolve_qpath(qself, path, ns, finalize)? { + Some(partial_res) + if partial_res.unresolved_segments() == 0 || defer_to_typeck => + { + return Ok(Some(partial_res)); + } + partial_res => { + if fin_res.is_none() { + fin_res = partial_res; + } + } + } + } + } + + assert!(primary_ns != MacroNS); + + if qself.is_none() { + let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident); + let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None }; + if let Ok((_, res)) = + self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false) + { + return Ok(Some(PartialRes::new(res))); + } + } + + Ok(fin_res) + } + + /// Handles paths that may refer to associated items. + fn resolve_qpath( + &mut self, + qself: Option<&QSelf>, + path: &[Segment], + ns: Namespace, + finalize: Finalize, + ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> { + debug!( + "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})", + qself, path, ns, finalize, + ); + + if let Some(qself) = qself { + if qself.position == 0 { + // This is a case like `<T>::B`, where there is no + // trait to resolve. In that case, we leave the `B` + // segment to be resolved by type-check. + return Ok(Some(PartialRes::with_unresolved_segments( + Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()), + path.len(), + ))); + } + + // Make sure `A::B` in `<T as A::B>::C` is a trait item. + // + // Currently, `path` names the full item (`A::B::C`, in + // our example). so we extract the prefix of that that is + // the trait (the slice upto and including + // `qself.position`). And then we recursively resolve that, + // but with `qself` set to `None`. + let ns = if qself.position + 1 == path.len() { ns } else { TypeNS }; + let partial_res = self.smart_resolve_path_fragment( + None, + &path[..=qself.position], + PathSource::TraitItem(ns), + Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span), + ); + + // The remaining segments (the `C` in our example) will + // have to be resolved by type-check, since that requires doing + // trait resolution. + return Ok(Some(PartialRes::with_unresolved_segments( + partial_res.base_res(), + partial_res.unresolved_segments() + path.len() - qself.position - 1, + ))); + } + + let result = match self.resolve_path(&path, Some(ns), Some(finalize)) { + PathResult::NonModule(path_res) => path_res, + PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => { + PartialRes::new(module.res().unwrap()) + } + // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we + // don't report an error right away, but try to fallback to a primitive type. + // So, we are still able to successfully resolve something like + // + // use std::u8; // bring module u8 in scope + // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8 + // u8::max_value() // OK, resolves to associated function <u8>::max_value, + // // not to non-existent std::u8::max_value + // } + // + // Such behavior is required for backward compatibility. + // The same fallback is used when `a` resolves to nothing. + PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. } + if (ns == TypeNS || path.len() > 1) + && PrimTy::from_name(path[0].ident.name).is_some() => + { + let prim = PrimTy::from_name(path[0].ident.name).unwrap(); + PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1) + } + PathResult::Module(ModuleOrUniformRoot::Module(module)) => { + PartialRes::new(module.res().unwrap()) + } + PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { + return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion })); + } + PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), + PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), + }; + + if path.len() > 1 + && result.base_res() != Res::Err + && path[0].ident.name != kw::PathRoot + && path[0].ident.name != kw::DollarCrate + { + let unqualified_result = { + match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) { + PathResult::NonModule(path_res) => path_res.base_res(), + PathResult::Module(ModuleOrUniformRoot::Module(module)) => { + module.res().unwrap() + } + _ => return Ok(Some(result)), + } + }; + if result.base_res() == unqualified_result { + let lint = lint::builtin::UNUSED_QUALIFICATIONS; + self.r.lint_buffer.buffer_lint( + lint, + finalize.node_id, + finalize.path_span, + "unnecessary qualification", + ) + } + } + + Ok(Some(result)) + } + + fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) { + if let Some(label) = label { + if label.ident.as_str().as_bytes()[1] != b'_' { + self.diagnostic_metadata.unused_labels.insert(id, label.ident.span); + } + + if let Ok((_, orig_span)) = self.resolve_label(label.ident) { + diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident) + } + + self.with_label_rib(NormalRibKind, |this| { + let ident = label.ident.normalize_to_macro_rules(); + this.label_ribs.last_mut().unwrap().bindings.insert(ident, id); + f(this); + }); + } else { + f(self); + } + } + + fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) { + self.with_resolved_label(label, id, |this| this.visit_block(block)); + } + + fn resolve_block(&mut self, block: &'ast Block) { + debug!("(resolving block) entering block"); + // Move down in the graph, if there's an anonymous module rooted here. + let orig_module = self.parent_scope.module; + let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference + + let mut num_macro_definition_ribs = 0; + if let Some(anonymous_module) = anonymous_module { + debug!("(resolving block) found anonymous module, moving down"); + self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module))); + self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module))); + self.parent_scope.module = anonymous_module; + } else { + self.ribs[ValueNS].push(Rib::new(NormalRibKind)); + } + + let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take(); + if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) = + (block.could_be_bare_literal, &block.stmts[..]) + && let ExprKind::Type(..) = expr.kind + { + self.diagnostic_metadata.current_block_could_be_bare_struct_literal = + Some(block.span); + } + // Descend into the block. + for stmt in &block.stmts { + if let StmtKind::Item(ref item) = stmt.kind + && let ItemKind::MacroDef(..) = item.kind { + num_macro_definition_ribs += 1; + let res = self.r.local_def_id(item.id).to_def_id(); + self.ribs[ValueNS].push(Rib::new(MacroDefinition(res))); + self.label_ribs.push(Rib::new(MacroDefinition(res))); + } + + self.visit_stmt(stmt); + } + self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev; + + // Move back up. + self.parent_scope.module = orig_module; + for _ in 0..num_macro_definition_ribs { + self.ribs[ValueNS].pop(); + self.label_ribs.pop(); + } + self.ribs[ValueNS].pop(); + if anonymous_module.is_some() { + self.ribs[TypeNS].pop(); + } + debug!("(resolving block) leaving block"); + } + + fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) { + debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat); + self.with_constant_rib( + is_repeat, + if constant.value.is_potential_trivial_const_param() { + HasGenericParams::Yes + } else { + HasGenericParams::No + }, + None, + |this| visit::walk_anon_const(this, constant), + ); + } + + fn resolve_inline_const(&mut self, constant: &'ast AnonConst) { + debug!("resolve_anon_const {constant:?}"); + self.with_constant_rib(IsRepeatExpr::No, HasGenericParams::Yes, None, |this| { + visit::walk_anon_const(this, constant); + }); + } + + fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) { + // First, record candidate traits for this expression if it could + // result in the invocation of a method call. + + self.record_candidate_traits_for_expr_if_necessary(expr); + + // Next, resolve the node. + match expr.kind { + ExprKind::Path(ref qself, ref path) => { + self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent)); + visit::walk_expr(self, expr); + } + + ExprKind::Struct(ref se) => { + self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct); + visit::walk_expr(self, expr); + } + + ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => { + match self.resolve_label(label.ident) { + Ok((node_id, _)) => { + // Since this res is a label, it is never read. + self.r.label_res_map.insert(expr.id, node_id); + self.diagnostic_metadata.unused_labels.remove(&node_id); + } + Err(error) => { + self.report_error(label.ident.span, error); + } + } + + // visit `break` argument if any + visit::walk_expr(self, expr); + } + + ExprKind::Break(None, Some(ref e)) => { + // We use this instead of `visit::walk_expr` to keep the parent expr around for + // better diagnostics. + self.resolve_expr(e, Some(&expr)); + } + + ExprKind::Let(ref pat, ref scrutinee, _) => { + self.visit_expr(scrutinee); + self.resolve_pattern_top(pat, PatternSource::Let); + } + + ExprKind::If(ref cond, ref then, ref opt_else) => { + self.with_rib(ValueNS, NormalRibKind, |this| { + let old = this.diagnostic_metadata.in_if_condition.replace(cond); + this.visit_expr(cond); + this.diagnostic_metadata.in_if_condition = old; + this.visit_block(then); + }); + if let Some(expr) = opt_else { + self.visit_expr(expr); + } + } + + ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block), + + ExprKind::While(ref cond, ref block, label) => { + self.with_resolved_label(label, expr.id, |this| { + this.with_rib(ValueNS, NormalRibKind, |this| { + let old = this.diagnostic_metadata.in_if_condition.replace(cond); + this.visit_expr(cond); + this.diagnostic_metadata.in_if_condition = old; + this.visit_block(block); + }) + }); + } + + ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => { + self.visit_expr(iter_expr); + self.with_rib(ValueNS, NormalRibKind, |this| { + this.resolve_pattern_top(pat, PatternSource::For); + this.resolve_labeled_block(label, expr.id, block); + }); + } + + ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block), + + // Equivalent to `visit::walk_expr` + passing some context to children. + ExprKind::Field(ref subexpression, _) => { + self.resolve_expr(subexpression, Some(expr)); + } + ExprKind::MethodCall(ref segment, ref arguments, _) => { + let mut arguments = arguments.iter(); + self.resolve_expr(arguments.next().unwrap(), Some(expr)); + for argument in arguments { + self.resolve_expr(argument, None); + } + self.visit_path_segment(expr.span, segment); + } + + ExprKind::Call(ref callee, ref arguments) => { + self.resolve_expr(callee, Some(expr)); + let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default(); + for (idx, argument) in arguments.iter().enumerate() { + // Constant arguments need to be treated as AnonConst since + // that is how they will be later lowered to HIR. + if const_args.contains(&idx) { + self.with_constant_rib( + IsRepeatExpr::No, + if argument.is_potential_trivial_const_param() { + HasGenericParams::Yes + } else { + HasGenericParams::No + }, + None, + |this| { + this.resolve_expr(argument, None); + }, + ); + } else { + self.resolve_expr(argument, None); + } + } + } + ExprKind::Type(ref type_expr, ref ty) => { + // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in + // type ascription. Here we are trying to retrieve the span of the colon token as + // well, but only if it's written without spaces `expr:Ty` and therefore confusable + // with `expr::Ty`, only in this case it will match the span from + // `type_ascription_path_suggestions`. + self.diagnostic_metadata + .current_type_ascription + .push(type_expr.span.between(ty.span)); + visit::walk_expr(self, expr); + self.diagnostic_metadata.current_type_ascription.pop(); + } + // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to + // resolve the arguments within the proper scopes so that usages of them inside the + // closure are detected as upvars rather than normal closure arg usages. + ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => { + self.with_rib(ValueNS, NormalRibKind, |this| { + this.with_label_rib(ClosureOrAsyncRibKind, |this| { + // Resolve arguments: + this.resolve_params(&fn_decl.inputs); + // No need to resolve return type -- + // the outer closure return type is `FnRetTy::Default`. + + // Now resolve the inner closure + { + // No need to resolve arguments: the inner closure has none. + // Resolve the return type: + visit::walk_fn_ret_ty(this, &fn_decl.output); + // Resolve the body + this.visit_expr(body); + } + }) + }); + } + // For closures, ClosureOrAsyncRibKind is added in visit_fn + ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => { + self.with_generic_param_rib( + &generic_params, + NormalRibKind, + LifetimeRibKind::Generics { + binder: expr.id, + kind: LifetimeBinderKind::Closure, + span, + }, + |this| visit::walk_expr(this, expr), + ); + } + ExprKind::Closure(..) => visit::walk_expr(self, expr), + ExprKind::Async(..) => { + self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr)); + } + ExprKind::Repeat(ref elem, ref ct) => { + self.visit_expr(elem); + self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| { + this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| { + this.resolve_anon_const(ct, IsRepeatExpr::Yes) + }) + }); + } + ExprKind::ConstBlock(ref ct) => { + self.resolve_inline_const(ct); + } + ExprKind::Index(ref elem, ref idx) => { + self.resolve_expr(elem, Some(expr)); + self.visit_expr(idx); + } + _ => { + visit::walk_expr(self, expr); + } + } + } + + fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) { + match expr.kind { + ExprKind::Field(_, ident) => { + // FIXME(#6890): Even though you can't treat a method like a + // field, we need to add any trait methods we find that match + // the field name so that we can do some nice error reporting + // later on in typeck. + let traits = self.traits_in_scope(ident, ValueNS); + self.r.trait_map.insert(expr.id, traits); + } + ExprKind::MethodCall(ref segment, ..) => { + debug!("(recording candidate traits for expr) recording traits for {}", expr.id); + let traits = self.traits_in_scope(segment.ident, ValueNS); + self.r.trait_map.insert(expr.id, traits); + } + _ => { + // Nothing to do. + } + } + } + + fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> { + self.r.traits_in_scope( + self.current_trait_ref.as_ref().map(|(module, _)| *module), + &self.parent_scope, + ident.span.ctxt(), + Some((ident.name, ns)), + ) + } +} + +struct LifetimeCountVisitor<'a, 'b> { + r: &'b mut Resolver<'a>, +} + +/// Walks the whole crate in DFS order, visiting each item, counting the declared number of +/// lifetime generic parameters. +impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> { + fn visit_item(&mut self, item: &'ast Item) { + match &item.kind { + ItemKind::TyAlias(box TyAlias { ref generics, .. }) + | ItemKind::Fn(box Fn { ref generics, .. }) + | ItemKind::Enum(_, ref generics) + | ItemKind::Struct(_, ref generics) + | ItemKind::Union(_, ref generics) + | ItemKind::Impl(box Impl { ref generics, .. }) + | ItemKind::Trait(box Trait { ref generics, .. }) + | ItemKind::TraitAlias(ref generics, _) => { + let def_id = self.r.local_def_id(item.id); + let count = generics + .params + .iter() + .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. })) + .count(); + self.r.item_generics_num_lifetimes.insert(def_id, count); + } + + ItemKind::Mod(..) + | ItemKind::ForeignMod(..) + | ItemKind::Static(..) + | ItemKind::Const(..) + | ItemKind::Use(..) + | ItemKind::ExternCrate(..) + | ItemKind::MacroDef(..) + | ItemKind::GlobalAsm(..) + | ItemKind::MacCall(..) => {} + } + visit::walk_item(self, item) + } +} + +impl<'a> Resolver<'a> { + pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) { + visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate); + let mut late_resolution_visitor = LateResolutionVisitor::new(self); + visit::walk_crate(&mut late_resolution_visitor, krate); + for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() { + self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label"); + } + } +} diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs new file mode 100644 index 000000000..2b1f2b88e --- /dev/null +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -0,0 +1,2369 @@ +use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion}; +use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind}; +use crate::late::{LifetimeBinderKind, LifetimeRes, LifetimeRibKind, LifetimeUseSet}; +use crate::path_names_to_string; +use crate::{Module, ModuleKind, ModuleOrUniformRoot}; +use crate::{PathResult, PathSource, Segment}; + +use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt}; +use rustc_ast::{ + self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind, + NodeId, Path, Ty, TyKind, DUMMY_NODE_ID, +}; +use rustc_ast_pretty::pprust::path_segment_to_string; +use rustc_data_structures::fx::FxHashSet; +use rustc_errors::{ + pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, + MultiSpan, +}; +use rustc_hir as hir; +use rustc_hir::def::Namespace::{self, *}; +use rustc_hir::def::{self, CtorKind, CtorOf, DefKind}; +use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::PrimTy; +use rustc_session::lint; +use rustc_session::parse::feature_err; +use rustc_session::Session; +use rustc_span::edition::Edition; +use rustc_span::hygiene::MacroKind; +use rustc_span::lev_distance::find_best_match_for_name; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::{BytePos, Span}; + +use std::iter; +use std::ops::Deref; + +use tracing::debug; + +type Res = def::Res<ast::NodeId>; + +/// A field or associated item from self type suggested in case of resolution failure. +enum AssocSuggestion { + Field, + MethodWithSelf, + AssocFn, + AssocType, + AssocConst, +} + +impl AssocSuggestion { + fn action(&self) -> &'static str { + match self { + AssocSuggestion::Field => "use the available field", + AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path", + AssocSuggestion::AssocFn => "call the associated function", + AssocSuggestion::AssocConst => "use the associated `const`", + AssocSuggestion::AssocType => "use the associated type", + } + } +} + +fn is_self_type(path: &[Segment], namespace: Namespace) -> bool { + namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper +} + +fn is_self_value(path: &[Segment], namespace: Namespace) -> bool { + namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower +} + +/// Gets the stringified path for an enum from an `ImportSuggestion` for an enum variant. +fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) { + let variant_path = &suggestion.path; + let variant_path_string = path_names_to_string(variant_path); + + let path_len = suggestion.path.segments.len(); + let enum_path = ast::Path { + span: suggestion.path.span, + segments: suggestion.path.segments[0..path_len - 1].to_vec(), + tokens: None, + }; + let enum_path_string = path_names_to_string(&enum_path); + + (variant_path_string, enum_path_string) +} + +/// Description of an elided lifetime. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub(super) struct MissingLifetime { + /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors. + pub id: NodeId, + /// Where to suggest adding the lifetime. + pub span: Span, + /// How the lifetime was introduced, to have the correct space and comma. + pub kind: MissingLifetimeKind, + /// Number of elided lifetimes, used for elision in path. + pub count: usize, +} + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub(super) enum MissingLifetimeKind { + /// An explicit `'_`. + Underscore, + /// An elided lifetime `&' ty`. + Ampersand, + /// An elided lifetime in brackets with written brackets. + Comma, + /// An elided lifetime with elided brackets. + Brackets, +} + +/// Description of the lifetimes appearing in a function parameter. +/// This is used to provide a literal explanation to the elision failure. +#[derive(Clone, Debug)] +pub(super) struct ElisionFnParameter { + /// The index of the argument in the original definition. + pub index: usize, + /// The name of the argument if it's a simple ident. + pub ident: Option<Ident>, + /// The number of lifetimes in the parameter. + pub lifetime_count: usize, + /// The span of the parameter. + pub span: Span, +} + +/// Description of lifetimes that appear as candidates for elision. +/// This is used to suggest introducing an explicit lifetime. +#[derive(Debug)] +pub(super) enum LifetimeElisionCandidate { + /// This is not a real lifetime. + Ignore, + /// There is a named lifetime, we won't suggest anything. + Named, + Missing(MissingLifetime), +} + +impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { + fn def_span(&self, def_id: DefId) -> Option<Span> { + match def_id.krate { + LOCAL_CRATE => self.r.opt_span(def_id), + _ => Some(self.r.cstore().get_span_untracked(def_id, self.r.session)), + } + } + + /// Handles error reporting for `smart_resolve_path_fragment` function. + /// Creates base error and amends it with one short label and possibly some longer helps/notes. + pub(crate) fn smart_resolve_report_errors( + &mut self, + path: &[Segment], + span: Span, + source: PathSource<'_>, + res: Option<Res>, + ) -> (DiagnosticBuilder<'a, ErrorGuaranteed>, Vec<ImportSuggestion>) { + let ident_span = path.last().map_or(span, |ident| ident.ident.span); + let ns = source.namespace(); + let is_expected = &|res| source.is_expected(res); + let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _)); + + debug!(?res, ?source); + + // Make the base error. + struct BaseError<'a> { + msg: String, + fallback_label: String, + span: Span, + could_be_expr: bool, + suggestion: Option<(Span, &'a str, String)>, + } + let mut expected = source.descr_expected(); + let path_str = Segment::names_to_string(path); + let item_str = path.last().unwrap().ident; + let base_error = if let Some(res) = res { + BaseError { + msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str), + fallback_label: format!("not a {expected}"), + span, + could_be_expr: match res { + Res::Def(DefKind::Fn, _) => { + // Verify whether this is a fn call or an Fn used as a type. + self.r + .session + .source_map() + .span_to_snippet(span) + .map(|snippet| snippet.ends_with(')')) + .unwrap_or(false) + } + Res::Def( + DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst, + _, + ) + | Res::SelfCtor(_) + | Res::PrimTy(_) + | Res::Local(_) => true, + _ => false, + }, + suggestion: None, + } + } else { + let item_span = path.last().unwrap().ident.span; + let (mod_prefix, mod_str, suggestion) = if path.len() == 1 { + debug!(?self.diagnostic_metadata.current_impl_items); + debug!(?self.diagnostic_metadata.current_function); + let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items + && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function + && self.current_trait_ref.is_none() + && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt() + && let Some(item) = items.iter().find(|i| { + if let AssocItemKind::Fn(fn_) = &i.kind + && !fn_.sig.decl.has_self() + && i.ident.name == item_str.name + { + debug!(?item_str.name); + debug!(?fn_.sig.decl.inputs); + return true + } + false + }) + { + Some(( + item_span, + "consider using the associated function", + format!("Self::{}", item.ident) + )) + } else { + None + }; + (String::new(), "this scope".to_string(), suggestion) + } else if path.len() == 2 && path[0].ident.name == kw::PathRoot { + if self.r.session.edition() > Edition::Edition2015 { + // In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude + // which overrides all other expectations of item type + expected = "crate"; + (String::new(), "the list of imported crates".to_string(), None) + } else { + (String::new(), "the crate root".to_string(), None) + } + } else if path.len() == 2 && path[0].ident.name == kw::Crate { + (String::new(), "the crate root".to_string(), None) + } else { + let mod_path = &path[..path.len() - 1]; + let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) { + PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(), + _ => None, + } + .map_or_else(String::new, |res| format!("{} ", res.descr())); + (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None) + }; + BaseError { + msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"), + fallback_label: if path_str == "async" && expected.starts_with("struct") { + "`async` blocks are only allowed in Rust 2018 or later".to_string() + } else { + format!("not found in {mod_str}") + }, + span: item_span, + could_be_expr: false, + suggestion, + } + }; + + let code = source.error_code(res.is_some()); + let mut err = + self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code); + + self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span); + + if let Some(sugg) = base_error.suggestion { + err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect); + } + + if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal { + err.multipart_suggestion( + "you might have meant to write a `struct` literal", + vec![ + (span.shrink_to_lo(), "{ SomeStruct ".to_string()), + (span.shrink_to_hi(), "}".to_string()), + ], + Applicability::HasPlaceholders, + ); + } + match (source, self.diagnostic_metadata.in_if_condition) { + ( + PathSource::Expr(_), + Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }), + ) => { + // Icky heuristic so we don't suggest: + // `if (i + 2) = 2` => `if let (i + 2) = 2` (approximately pattern) + // `if 2 = i` => `if let 2 = i` (lhs needs to contain error span) + if lhs.is_approximately_pattern() && lhs.span.contains(span) { + err.span_suggestion_verbose( + expr_span.shrink_to_lo(), + "you might have meant to use pattern matching", + "let ", + Applicability::MaybeIncorrect, + ); + } + } + _ => {} + } + + let is_assoc_fn = self.self_type_is_available(); + // Emit help message for fake-self from other languages (e.g., `this` in Javascript). + if ["this", "my"].contains(&item_str.as_str()) && is_assoc_fn { + err.span_suggestion_short( + span, + "you might have meant to use `self` here instead", + "self", + Applicability::MaybeIncorrect, + ); + if !self.self_value_is_available(path[0].ident.span) { + if let Some((FnKind::Fn(_, _, sig, ..), fn_span)) = + &self.diagnostic_metadata.current_function + { + let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) { + (param.span.shrink_to_lo(), "&self, ") + } else { + ( + self.r + .session + .source_map() + .span_through_char(*fn_span, '(') + .shrink_to_hi(), + "&self", + ) + }; + err.span_suggestion_verbose( + span, + "if you meant to use `self`, you are also missing a `self` receiver \ + argument", + sugg, + Applicability::MaybeIncorrect, + ); + } + } + } + + self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err); + + // Emit special messages for unresolved `Self` and `self`. + if is_self_type(path, ns) { + err.code(rustc_errors::error_code!(E0411)); + err.span_label( + span, + "`Self` is only available in impls, traits, and type definitions".to_string(), + ); + if let Some(item_kind) = self.diagnostic_metadata.current_item { + err.span_label( + item_kind.ident.span, + format!( + "`Self` not allowed in {} {}", + item_kind.kind.article(), + item_kind.kind.descr() + ), + ); + } + return (err, Vec::new()); + } + if is_self_value(path, ns) { + debug!("smart_resolve_path_fragment: E0424, source={:?}", source); + + err.code(rustc_errors::error_code!(E0424)); + err.span_label(span, match source { + PathSource::Pat => "`self` value is a keyword and may not be bound to variables or shadowed", + _ => "`self` value is a keyword only available in methods with a `self` parameter", + }); + if let Some((fn_kind, span)) = &self.diagnostic_metadata.current_function { + // The current function has a `self' parameter, but we were unable to resolve + // a reference to `self`. This can only happen if the `self` identifier we + // are resolving came from a different hygiene context. + if fn_kind.decl().inputs.get(0).map_or(false, |p| p.is_self()) { + err.span_label(*span, "this function has a `self` parameter, but a macro invocation can only access identifiers it receives from parameters"); + } else { + let doesnt = if is_assoc_fn { + let (span, sugg) = fn_kind + .decl() + .inputs + .get(0) + .map(|p| (p.span.shrink_to_lo(), "&self, ")) + .unwrap_or_else(|| { + // Try to look for the "(" after the function name, if possible. + // This avoids placing the suggestion into the visibility specifier. + let span = fn_kind + .ident() + .map_or(*span, |ident| span.with_lo(ident.span.hi())); + ( + self.r + .session + .source_map() + .span_through_char(span, '(') + .shrink_to_hi(), + "&self", + ) + }); + err.span_suggestion_verbose( + span, + "add a `self` receiver parameter to make the associated `fn` a method", + sugg, + Applicability::MaybeIncorrect, + ); + "doesn't" + } else { + "can't" + }; + if let Some(ident) = fn_kind.ident() { + err.span_label( + ident.span, + &format!("this function {} have a `self` parameter", doesnt), + ); + } + } + } else if let Some(item_kind) = self.diagnostic_metadata.current_item { + err.span_label( + item_kind.ident.span, + format!( + "`self` not allowed in {} {}", + item_kind.kind.article(), + item_kind.kind.descr() + ), + ); + } + return (err, Vec::new()); + } + + // Try to lookup name in more relaxed fashion for better error reporting. + let ident = path.last().unwrap().ident; + let mut candidates = self + .r + .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected) + .into_iter() + .filter(|ImportSuggestion { did, .. }| { + match (did, res.and_then(|res| res.opt_def_id())) { + (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did, + _ => true, + } + }) + .collect::<Vec<_>>(); + let crate_def_id = CRATE_DEF_ID.to_def_id(); + // Try to filter out intrinsics candidates, as long as we have + // some other candidates to suggest. + let intrinsic_candidates: Vec<_> = candidates + .drain_filter(|sugg| { + let path = path_names_to_string(&sugg.path); + path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::") + }) + .collect(); + if candidates.is_empty() { + // Put them back if we have no more candidates to suggest... + candidates.extend(intrinsic_candidates); + } + if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) { + let mut enum_candidates: Vec<_> = self + .r + .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant) + .into_iter() + .map(|suggestion| import_candidate_to_enum_paths(&suggestion)) + .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::")) + .collect(); + if !enum_candidates.is_empty() { + if let (PathSource::Type, Some(span)) = + (source, self.diagnostic_metadata.current_type_ascription.last()) + { + if self + .r + .session + .parse_sess + .type_ascription_path_suggestions + .borrow() + .contains(span) + { + // Already reported this issue on the lhs of the type ascription. + err.delay_as_bug(); + return (err, candidates); + } + } + + enum_candidates.sort(); + + // Contextualize for E0412 "cannot find type", but don't belabor the point + // (that it's a variant) for E0573 "expected type, found variant". + let preamble = if res.is_none() { + let others = match enum_candidates.len() { + 1 => String::new(), + 2 => " and 1 other".to_owned(), + n => format!(" and {} others", n), + }; + format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others) + } else { + String::new() + }; + let msg = format!("{}try using the variant's enum", preamble); + + err.span_suggestions( + span, + &msg, + enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path), + Applicability::MachineApplicable, + ); + } + } + // Try Levenshtein algorithm. + let typo_sugg = self.lookup_typo_candidate(path, ns, is_expected); + if path.len() == 1 && self.self_type_is_available() { + if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) { + let self_is_available = self.self_value_is_available(path[0].ident.span); + match candidate { + AssocSuggestion::Field => { + if self_is_available { + err.span_suggestion( + span, + "you might have meant to use the available field", + format!("self.{path_str}"), + Applicability::MachineApplicable, + ); + } else { + err.span_label(span, "a field by this name exists in `Self`"); + } + } + AssocSuggestion::MethodWithSelf if self_is_available => { + err.span_suggestion( + span, + "you might have meant to call the method", + format!("self.{path_str}"), + Applicability::MachineApplicable, + ); + } + AssocSuggestion::MethodWithSelf + | AssocSuggestion::AssocFn + | AssocSuggestion::AssocConst + | AssocSuggestion::AssocType => { + err.span_suggestion( + span, + &format!("you might have meant to {}", candidate.action()), + format!("Self::{path_str}"), + Applicability::MachineApplicable, + ); + } + } + self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span); + return (err, candidates); + } + + // If the first argument in call is `self` suggest calling a method. + if let Some((call_span, args_span)) = self.call_has_self_arg(source) { + let mut args_snippet = String::new(); + if let Some(args_span) = args_span { + if let Ok(snippet) = self.r.session.source_map().span_to_snippet(args_span) { + args_snippet = snippet; + } + } + + err.span_suggestion( + call_span, + &format!("try calling `{ident}` as a method"), + format!("self.{path_str}({args_snippet})"), + Applicability::MachineApplicable, + ); + return (err, candidates); + } + } + + // Try context-dependent help if relaxed lookup didn't work. + if let Some(res) = res { + if self.smart_resolve_context_dependent_help( + &mut err, + span, + source, + res, + &path_str, + &base_error.fallback_label, + ) { + // We do this to avoid losing a secondary span when we override the main error span. + self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span); + return (err, candidates); + } + } + + let is_macro = + base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none(); + if !self.type_ascription_suggestion(&mut err, base_error.span) { + let mut fallback = false; + if let ( + PathSource::Trait(AliasPossibility::Maybe), + Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)), + false, + ) = (source, res, is_macro) + { + if let Some(bounds @ [_, .., _]) = self.diagnostic_metadata.current_trait_object { + fallback = true; + let spans: Vec<Span> = bounds + .iter() + .map(|bound| bound.span()) + .filter(|&sp| sp != base_error.span) + .collect(); + + let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap(); + // `end_span` is the end of the poly trait ref (Foo + 'baz + Bar><) + let end_span = bounds.iter().map(|bound| bound.span()).last().unwrap(); + // `last_bound_span` is the last bound of the poly trait ref (Foo + >'baz< + Bar) + let last_bound_span = spans.last().cloned().unwrap(); + let mut multi_span: MultiSpan = spans.clone().into(); + for sp in spans { + let msg = if sp == last_bound_span { + format!( + "...because of {these} bound{s}", + these = pluralize!("this", bounds.len() - 1), + s = pluralize!(bounds.len() - 1), + ) + } else { + String::new() + }; + multi_span.push_span_label(sp, msg); + } + multi_span + .push_span_label(base_error.span, "expected this type to be a trait..."); + err.span_help( + multi_span, + "`+` is used to constrain a \"trait object\" type with lifetimes or \ + auto-traits; structs and enums can't be bound in that way", + ); + if bounds.iter().all(|bound| match bound { + ast::GenericBound::Outlives(_) => true, + ast::GenericBound::Trait(tr, _) => tr.span == base_error.span, + }) { + let mut sugg = vec![]; + if base_error.span != start_span { + sugg.push((start_span.until(base_error.span), String::new())); + } + if base_error.span != end_span { + sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new())); + } + + err.multipart_suggestion( + "if you meant to use a type and not a trait here, remove the bounds", + sugg, + Applicability::MaybeIncorrect, + ); + } + } + } + + fallback |= self.restrict_assoc_type_in_where_clause(span, &mut err); + + if !self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span) { + fallback = true; + match self.diagnostic_metadata.current_let_binding { + Some((pat_sp, Some(ty_sp), None)) + if ty_sp.contains(base_error.span) && base_error.could_be_expr => + { + err.span_suggestion_short( + pat_sp.between(ty_sp), + "use `=` if you meant to assign", + " = ", + Applicability::MaybeIncorrect, + ); + } + _ => {} + } + + // If the trait has a single item (which wasn't matched by Levenshtein), suggest it + let suggestion = self.get_single_associated_item(&path, &source, is_expected); + self.r.add_typo_suggestion(&mut err, suggestion, ident_span); + } + if fallback { + // Fallback label. + err.span_label(base_error.span, base_error.fallback_label); + } + } + if let Some(err_code) = &err.code { + if err_code == &rustc_errors::error_code!(E0425) { + for label_rib in &self.label_ribs { + for (label_ident, node_id) in &label_rib.bindings { + if format!("'{}", ident) == label_ident.to_string() { + err.span_label(label_ident.span, "a label with a similar name exists"); + if let PathSource::Expr(Some(Expr { + kind: ExprKind::Break(None, Some(_)), + .. + })) = source + { + err.span_suggestion( + span, + "use the similarly named label", + label_ident.name, + Applicability::MaybeIncorrect, + ); + // Do not lint against unused label when we suggest them. + self.diagnostic_metadata.unused_labels.remove(node_id); + } + } + } + } + } else if err_code == &rustc_errors::error_code!(E0412) { + if let Some(correct) = Self::likely_rust_type(path) { + err.span_suggestion( + span, + "perhaps you intended to use this type", + correct, + Applicability::MaybeIncorrect, + ); + } + } + } + + (err, candidates) + } + + fn detect_assoct_type_constraint_meant_as_path(&self, base_span: Span, err: &mut Diagnostic) { + let Some(ty) = self.diagnostic_metadata.current_type_path else { return; }; + let TyKind::Path(_, path) = &ty.kind else { return; }; + for segment in &path.segments { + let Some(params) = &segment.args else { continue; }; + let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; }; + for param in ¶ms.args { + let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; }; + let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else { + continue; + }; + for bound in bounds { + let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None) + = bound else + { + continue; + }; + if base_span == trait_ref.span { + err.span_suggestion_verbose( + constraint.ident.span.between(trait_ref.span), + "you might have meant to write a path instead of an associated type bound", + "::", + Applicability::MachineApplicable, + ); + } + } + } + } + } + + fn suggest_swapping_misplaced_self_ty_and_trait( + &mut self, + err: &mut Diagnostic, + source: PathSource<'_>, + res: Option<Res>, + span: Span, + ) { + if let Some((trait_ref, self_ty)) = + self.diagnostic_metadata.currently_processing_impl_trait.clone() + && let TyKind::Path(_, self_ty_path) = &self_ty.kind + && let PathResult::Module(ModuleOrUniformRoot::Module(module)) = + self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None) + && let ModuleKind::Def(DefKind::Trait, ..) = module.kind + && trait_ref.path.span == span + && let PathSource::Trait(_) = source + && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res + && let Ok(self_ty_str) = + self.r.session.source_map().span_to_snippet(self_ty.span) + && let Ok(trait_ref_str) = + self.r.session.source_map().span_to_snippet(trait_ref.path.span) + { + err.multipart_suggestion( + "`impl` items mention the trait being implemented first and the type it is being implemented for second", + vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)], + Applicability::MaybeIncorrect, + ); + } + } + + fn get_single_associated_item( + &mut self, + path: &[Segment], + source: &PathSource<'_>, + filter_fn: &impl Fn(Res) -> bool, + ) -> Option<TypoSuggestion> { + if let crate::PathSource::TraitItem(_) = source { + let mod_path = &path[..path.len() - 1]; + if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = + self.resolve_path(mod_path, None, None) + { + let resolutions = self.r.resolutions(module).borrow(); + let targets: Vec<_> = + resolutions + .iter() + .filter_map(|(key, resolution)| { + resolution.borrow().binding.map(|binding| binding.res()).and_then( + |res| if filter_fn(res) { Some((key, res)) } else { None }, + ) + }) + .collect(); + if targets.len() == 1 { + let target = targets[0]; + return Some(TypoSuggestion::single_item_from_res( + target.0.ident.name, + target.1, + )); + } + } + } + None + } + + /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`. + fn restrict_assoc_type_in_where_clause(&mut self, span: Span, err: &mut Diagnostic) -> bool { + // Detect that we are actually in a `where` predicate. + let (bounded_ty, bounds, where_span) = + if let Some(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { + bounded_ty, + bound_generic_params, + bounds, + span, + })) = self.diagnostic_metadata.current_where_predicate + { + if !bound_generic_params.is_empty() { + return false; + } + (bounded_ty, bounds, span) + } else { + return false; + }; + + // Confirm that the target is an associated type. + let (ty, position, path) = if let ast::TyKind::Path( + Some(ast::QSelf { ty, position, .. }), + path, + ) = &bounded_ty.kind + { + // use this to verify that ident is a type param. + let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { + return false; + }; + if !(matches!( + partial_res.base_res(), + hir::def::Res::Def(hir::def::DefKind::AssocTy, _) + ) && partial_res.unresolved_segments() == 0) + { + return false; + } + (ty, position, path) + } else { + return false; + }; + + let peeled_ty = ty.peel_refs(); + if let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind { + // Confirm that the `SelfTy` is a type parameter. + let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else { + return false; + }; + if !(matches!( + partial_res.base_res(), + hir::def::Res::Def(hir::def::DefKind::TyParam, _) + ) && partial_res.unresolved_segments() == 0) + { + return false; + } + if let ( + [ast::PathSegment { ident: constrain_ident, args: None, .. }], + [ast::GenericBound::Trait(poly_trait_ref, ast::TraitBoundModifier::None)], + ) = (&type_param_path.segments[..], &bounds[..]) + { + if let [ast::PathSegment { ident, args: None, .. }] = + &poly_trait_ref.trait_ref.path.segments[..] + { + if ident.span == span { + err.span_suggestion_verbose( + *where_span, + &format!("constrain the associated type to `{}`", ident), + format!( + "{}: {}<{} = {}>", + self.r + .session + .source_map() + .span_to_snippet(ty.span) // Account for `<&'a T as Foo>::Bar`. + .unwrap_or_else(|_| constrain_ident.to_string()), + path.segments[..*position] + .iter() + .map(|segment| path_segment_to_string(segment)) + .collect::<Vec<_>>() + .join("::"), + path.segments[*position..] + .iter() + .map(|segment| path_segment_to_string(segment)) + .collect::<Vec<_>>() + .join("::"), + ident, + ), + Applicability::MaybeIncorrect, + ); + } + return true; + } + } + } + false + } + + /// Check if the source is call expression and the first argument is `self`. If true, + /// return the span of whole call and the span for all arguments expect the first one (`self`). + fn call_has_self_arg(&self, source: PathSource<'_>) -> Option<(Span, Option<Span>)> { + let mut has_self_arg = None; + if let PathSource::Expr(Some(parent)) = source { + match &parent.kind { + ExprKind::Call(_, args) if !args.is_empty() => { + let mut expr_kind = &args[0].kind; + loop { + match expr_kind { + ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => { + if arg_name.segments[0].ident.name == kw::SelfLower { + let call_span = parent.span; + let tail_args_span = if args.len() > 1 { + Some(Span::new( + args[1].span.lo(), + args.last().unwrap().span.hi(), + call_span.ctxt(), + None, + )) + } else { + None + }; + has_self_arg = Some((call_span, tail_args_span)); + } + break; + } + ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind, + _ => break, + } + } + } + _ => (), + } + }; + has_self_arg + } + + fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) { + // HACK(estebank): find a better way to figure out that this was a + // parser issue where a struct literal is being used on an expression + // where a brace being opened means a block is being started. Look + // ahead for the next text to see if `span` is followed by a `{`. + let sm = self.r.session.source_map(); + let mut sp = span; + loop { + sp = sm.next_point(sp); + match sm.span_to_snippet(sp) { + Ok(ref snippet) => { + if snippet.chars().any(|c| !c.is_whitespace()) { + break; + } + } + _ => break, + } + } + let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{"); + // In case this could be a struct literal that needs to be surrounded + // by parentheses, find the appropriate span. + let mut i = 0; + let mut closing_brace = None; + loop { + sp = sm.next_point(sp); + match sm.span_to_snippet(sp) { + Ok(ref snippet) => { + if snippet == "}" { + closing_brace = Some(span.to(sp)); + break; + } + } + _ => break, + } + i += 1; + // The bigger the span, the more likely we're incorrect -- + // bound it to 100 chars long. + if i > 100 { + break; + } + } + (followed_by_brace, closing_brace) + } + + /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment` + /// function. + /// Returns `true` if able to provide context-dependent help. + fn smart_resolve_context_dependent_help( + &mut self, + err: &mut Diagnostic, + span: Span, + source: PathSource<'_>, + res: Res, + path_str: &str, + fallback_label: &str, + ) -> bool { + let ns = source.namespace(); + let is_expected = &|res| source.is_expected(res); + + let path_sep = |err: &mut Diagnostic, expr: &Expr| match expr.kind { + ExprKind::Field(_, ident) => { + err.span_suggestion( + expr.span, + "use the path separator to refer to an item", + format!("{}::{}", path_str, ident), + Applicability::MaybeIncorrect, + ); + true + } + ExprKind::MethodCall(ref segment, ..) => { + let span = expr.span.with_hi(segment.ident.span.hi()); + err.span_suggestion( + span, + "use the path separator to refer to an item", + format!("{}::{}", path_str, segment.ident), + Applicability::MaybeIncorrect, + ); + true + } + _ => false, + }; + + let find_span = |source: &PathSource<'_>, err: &mut Diagnostic| { + match source { + PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. })) + | PathSource::TupleStruct(span, _) => { + // We want the main underline to cover the suggested code as well for + // cleaner output. + err.set_span(*span); + *span + } + _ => span, + } + }; + + let mut bad_struct_syntax_suggestion = |def_id: DefId| { + let (followed_by_brace, closing_brace) = self.followed_by_brace(span); + + match source { + PathSource::Expr(Some( + parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. }, + )) if path_sep(err, &parent) => {} + PathSource::Expr( + None + | Some(Expr { + kind: + ExprKind::Path(..) + | ExprKind::Binary(..) + | ExprKind::Unary(..) + | ExprKind::If(..) + | ExprKind::While(..) + | ExprKind::ForLoop(..) + | ExprKind::Match(..), + .. + }), + ) if followed_by_brace => { + if let Some(sp) = closing_brace { + err.span_label(span, fallback_label); + err.multipart_suggestion( + "surround the struct literal with parentheses", + vec![ + (sp.shrink_to_lo(), "(".to_string()), + (sp.shrink_to_hi(), ")".to_string()), + ], + Applicability::MaybeIncorrect, + ); + } else { + err.span_label( + span, // Note the parentheses surrounding the suggestion below + format!( + "you might want to surround a struct literal with parentheses: \ + `({} {{ /* fields */ }})`?", + path_str + ), + ); + } + } + PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => { + let span = find_span(&source, err); + if let Some(span) = self.def_span(def_id) { + err.span_label(span, &format!("`{}` defined here", path_str)); + } + let (tail, descr, applicability) = match source { + PathSource::Pat | PathSource::TupleStruct(..) => { + ("", "pattern", Applicability::MachineApplicable) + } + _ => (": val", "literal", Applicability::HasPlaceholders), + }; + let (fields, applicability) = match self.r.field_names.get(&def_id) { + Some(fields) => ( + fields + .iter() + .map(|f| format!("{}{}", f.node, tail)) + .collect::<Vec<String>>() + .join(", "), + applicability, + ), + None => ("/* fields */".to_string(), Applicability::HasPlaceholders), + }; + let pad = match self.r.field_names.get(&def_id) { + Some(fields) if fields.is_empty() => "", + _ => " ", + }; + err.span_suggestion( + span, + &format!("use struct {} syntax instead", descr), + format!("{path_str} {{{pad}{fields}{pad}}}"), + applicability, + ); + } + _ => { + err.span_label(span, fallback_label); + } + } + }; + + match (res, source) { + ( + Res::Def(DefKind::Macro(MacroKind::Bang), _), + PathSource::Expr(Some(Expr { + kind: ExprKind::Index(..) | ExprKind::Call(..), .. + })) + | PathSource::Struct, + ) => { + err.span_label(span, fallback_label); + err.span_suggestion_verbose( + span.shrink_to_hi(), + "use `!` to invoke the macro", + "!", + Applicability::MaybeIncorrect, + ); + if path_str == "try" && span.rust_2015() { + err.note("if you want the `try` keyword, you need Rust 2018 or later"); + } + } + (Res::Def(DefKind::Macro(MacroKind::Bang), _), _) => { + err.span_label(span, fallback_label); + } + (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => { + err.span_label(span, "type aliases cannot be used as traits"); + if self.r.session.is_nightly_build() { + let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \ + `type` alias"; + if let Some(span) = self.def_span(def_id) { + if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) { + // The span contains a type alias so we should be able to + // replace `type` with `trait`. + let snip = snip.replacen("type", "trait", 1); + err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect); + } else { + err.span_help(span, msg); + } + } else { + err.help(msg); + } + } + } + (Res::Def(DefKind::Mod, _), PathSource::Expr(Some(parent))) => { + if !path_sep(err, &parent) { + return false; + } + } + ( + Res::Def(DefKind::Enum, def_id), + PathSource::TupleStruct(..) | PathSource::Expr(..), + ) => { + if self + .diagnostic_metadata + .current_type_ascription + .last() + .map(|sp| { + self.r + .session + .parse_sess + .type_ascription_path_suggestions + .borrow() + .contains(&sp) + }) + .unwrap_or(false) + { + err.downgrade_to_delayed_bug(); + // We already suggested changing `:` into `::` during parsing. + return false; + } + + self.suggest_using_enum_variant(err, source, def_id, span); + } + (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => { + let (ctor_def, ctor_vis, fields) = + if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() { + if let PathSource::Expr(Some(parent)) = source { + if let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind { + bad_struct_syntax_suggestion(def_id); + return true; + } + } + struct_ctor + } else { + bad_struct_syntax_suggestion(def_id); + return true; + }; + + let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module); + if !is_expected(ctor_def) || is_accessible { + return true; + } + + let field_spans = match source { + // e.g. `if let Enum::TupleVariant(field1, field2) = _` + PathSource::TupleStruct(_, pattern_spans) => { + err.set_primary_message( + "cannot match against a tuple struct which contains private fields", + ); + + // Use spans of the tuple struct pattern. + Some(Vec::from(pattern_spans)) + } + // e.g. `let _ = Enum::TupleVariant(field1, field2);` + _ if source.is_call() => { + err.set_primary_message( + "cannot initialize a tuple struct which contains private fields", + ); + + // Use spans of the tuple struct definition. + self.r + .field_names + .get(&def_id) + .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>()) + } + _ => None, + }; + + if let Some(spans) = + field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len()) + { + let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans) + .filter(|(vis, _)| { + !self.r.is_accessible_from(**vis, self.parent_scope.module) + }) + .map(|(_, span)| *span) + .collect(); + + if non_visible_spans.len() > 0 { + let mut m: MultiSpan = non_visible_spans.clone().into(); + non_visible_spans + .into_iter() + .for_each(|s| m.push_span_label(s, "private field")); + err.span_note(m, "constructor is not visible here due to private fields"); + } + + return true; + } + + err.span_label(span, "constructor is not visible here due to private fields"); + } + ( + Res::Def( + DefKind::Union | DefKind::Variant | DefKind::Ctor(_, CtorKind::Fictive), + def_id, + ), + _, + ) if ns == ValueNS => { + bad_struct_syntax_suggestion(def_id); + } + (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => { + match source { + PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => { + let span = find_span(&source, err); + if let Some(span) = self.def_span(def_id) { + err.span_label(span, &format!("`{}` defined here", path_str)); + } + err.span_suggestion( + span, + "use this syntax instead", + path_str, + Applicability::MaybeIncorrect, + ); + } + _ => return false, + } + } + (Res::Def(DefKind::Ctor(_, CtorKind::Fn), def_id), _) if ns == ValueNS => { + if let Some(span) = self.def_span(def_id) { + err.span_label(span, &format!("`{}` defined here", path_str)); + } + let fields = self.r.field_names.get(&def_id).map_or_else( + || "/* fields */".to_string(), + |fields| vec!["_"; fields.len()].join(", "), + ); + err.span_suggestion( + span, + "use the tuple variant pattern syntax instead", + format!("{}({})", path_str, fields), + Applicability::HasPlaceholders, + ); + } + (Res::SelfTy { .. }, _) if ns == ValueNS => { + err.span_label(span, fallback_label); + err.note("can't use `Self` as a constructor, you must use the implemented struct"); + } + (Res::Def(DefKind::TyAlias | DefKind::AssocTy, _), _) if ns == ValueNS => { + err.note("can't use a type alias as a constructor"); + } + _ => return false, + } + true + } + + /// Given the target `ident` and `kind`, search for the similarly named associated item + /// in `self.current_trait_ref`. + pub(crate) fn find_similarly_named_assoc_item( + &mut self, + ident: Symbol, + kind: &AssocItemKind, + ) -> Option<Symbol> { + let (module, _) = self.current_trait_ref.as_ref()?; + if ident == kw::Underscore { + // We do nothing for `_`. + return None; + } + + let resolutions = self.r.resolutions(module); + let targets = resolutions + .borrow() + .iter() + .filter_map(|(key, res)| res.borrow().binding.map(|binding| (key, binding.res()))) + .filter(|(_, res)| match (kind, res) { + (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true, + (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true, + (AssocItemKind::TyAlias(..), Res::Def(DefKind::AssocTy, _)) => true, + _ => false, + }) + .map(|(key, _)| key.ident.name) + .collect::<Vec<_>>(); + + find_best_match_for_name(&targets, ident, None) + } + + fn lookup_assoc_candidate<FilterFn>( + &mut self, + ident: Ident, + ns: Namespace, + filter_fn: FilterFn, + ) -> Option<AssocSuggestion> + where + FilterFn: Fn(Res) -> bool, + { + fn extract_node_id(t: &Ty) -> Option<NodeId> { + match t.kind { + TyKind::Path(None, _) => Some(t.id), + TyKind::Rptr(_, ref mut_ty) => extract_node_id(&mut_ty.ty), + // This doesn't handle the remaining `Ty` variants as they are not + // that commonly the self_type, it might be interesting to provide + // support for those in future. + _ => None, + } + } + + // Fields are generally expected in the same contexts as locals. + if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) { + if let Some(node_id) = + self.diagnostic_metadata.current_self_type.as_ref().and_then(extract_node_id) + { + // Look for a field with the same name in the current self_type. + if let Some(resolution) = self.r.partial_res_map.get(&node_id) { + match resolution.base_res() { + Res::Def(DefKind::Struct | DefKind::Union, did) + if resolution.unresolved_segments() == 0 => + { + if let Some(field_names) = self.r.field_names.get(&did) { + if field_names + .iter() + .any(|&field_name| ident.name == field_name.node) + { + return Some(AssocSuggestion::Field); + } + } + } + _ => {} + } + } + } + } + + if let Some(items) = self.diagnostic_metadata.current_trait_assoc_items { + for assoc_item in items { + if assoc_item.ident == ident { + return Some(match &assoc_item.kind { + ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst, + ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => { + AssocSuggestion::MethodWithSelf + } + ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn, + ast::AssocItemKind::TyAlias(..) => AssocSuggestion::AssocType, + ast::AssocItemKind::MacCall(_) => continue, + }); + } + } + } + + // Look for associated items in the current trait. + if let Some((module, _)) = self.current_trait_ref { + if let Ok(binding) = self.r.maybe_resolve_ident_in_module( + ModuleOrUniformRoot::Module(module), + ident, + ns, + &self.parent_scope, + ) { + let res = binding.res(); + if filter_fn(res) { + if self.r.has_self.contains(&res.def_id()) { + return Some(AssocSuggestion::MethodWithSelf); + } else { + match res { + Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn), + Res::Def(DefKind::AssocConst, _) => { + return Some(AssocSuggestion::AssocConst); + } + Res::Def(DefKind::AssocTy, _) => { + return Some(AssocSuggestion::AssocType); + } + _ => {} + } + } + } + } + } + + None + } + + fn lookup_typo_candidate( + &mut self, + path: &[Segment], + ns: Namespace, + filter_fn: &impl Fn(Res) -> bool, + ) -> Option<TypoSuggestion> { + let mut names = Vec::new(); + if path.len() == 1 { + // Search in lexical scope. + // Walk backwards up the ribs in scope and collect candidates. + for rib in self.ribs[ns].iter().rev() { + // Locals and type parameters + for (ident, &res) in &rib.bindings { + if filter_fn(res) { + names.push(TypoSuggestion::typo_from_res(ident.name, res)); + } + } + // Items in scope + if let RibKind::ModuleRibKind(module) = rib.kind { + // Items from this module + self.r.add_module_candidates(module, &mut names, &filter_fn); + + if let ModuleKind::Block = module.kind { + // We can see through blocks + } else { + // Items from the prelude + if !module.no_implicit_prelude { + let extern_prelude = self.r.extern_prelude.clone(); + names.extend(extern_prelude.iter().flat_map(|(ident, _)| { + self.r.crate_loader.maybe_process_path_extern(ident.name).and_then( + |crate_id| { + let crate_mod = + Res::Def(DefKind::Mod, crate_id.as_def_id()); + + if filter_fn(crate_mod) { + Some(TypoSuggestion::typo_from_res( + ident.name, crate_mod, + )) + } else { + None + } + }, + ) + })); + + if let Some(prelude) = self.r.prelude { + self.r.add_module_candidates(prelude, &mut names, &filter_fn); + } + } + break; + } + } + } + // Add primitive types to the mix + if filter_fn(Res::PrimTy(PrimTy::Bool)) { + names.extend(PrimTy::ALL.iter().map(|prim_ty| { + TypoSuggestion::typo_from_res(prim_ty.name(), Res::PrimTy(*prim_ty)) + })) + } + } else { + // Search in module. + let mod_path = &path[..path.len() - 1]; + if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = + self.resolve_path(mod_path, Some(TypeNS), None) + { + self.r.add_module_candidates(module, &mut names, &filter_fn); + } + } + + let name = path[path.len() - 1].ident.name; + // Make sure error reporting is deterministic. + names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap()); + + match find_best_match_for_name( + &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(), + name, + None, + ) { + Some(found) if found != name => { + names.into_iter().find(|suggestion| suggestion.candidate == found) + } + _ => None, + } + } + + // Returns the name of the Rust type approximately corresponding to + // a type name in another programming language. + fn likely_rust_type(path: &[Segment]) -> Option<Symbol> { + let name = path[path.len() - 1].ident.as_str(); + // Common Java types + Some(match name { + "byte" => sym::u8, // In Java, bytes are signed, but in practice one almost always wants unsigned bytes. + "short" => sym::i16, + "Bool" => sym::bool, + "Boolean" => sym::bool, + "boolean" => sym::bool, + "int" => sym::i32, + "long" => sym::i64, + "float" => sym::f32, + "double" => sym::f64, + _ => return None, + }) + } + + /// Only used in a specific case of type ascription suggestions + fn get_colon_suggestion_span(&self, start: Span) -> Span { + let sm = self.r.session.source_map(); + start.to(sm.next_point(start)) + } + + fn type_ascription_suggestion(&self, err: &mut Diagnostic, base_span: Span) -> bool { + let sm = self.r.session.source_map(); + let base_snippet = sm.span_to_snippet(base_span); + if let Some(&sp) = self.diagnostic_metadata.current_type_ascription.last() { + if let Ok(snippet) = sm.span_to_snippet(sp) { + let len = snippet.trim_end().len() as u32; + if snippet.trim() == ":" { + let colon_sp = + sp.with_lo(sp.lo() + BytePos(len - 1)).with_hi(sp.lo() + BytePos(len)); + let mut show_label = true; + if sm.is_multiline(sp) { + err.span_suggestion_short( + colon_sp, + "maybe you meant to write `;` here", + ";", + Applicability::MaybeIncorrect, + ); + } else { + let after_colon_sp = + self.get_colon_suggestion_span(colon_sp.shrink_to_hi()); + if snippet.len() == 1 { + // `foo:bar` + err.span_suggestion( + colon_sp, + "maybe you meant to write a path separator here", + "::", + Applicability::MaybeIncorrect, + ); + show_label = false; + if !self + .r + .session + .parse_sess + .type_ascription_path_suggestions + .borrow_mut() + .insert(colon_sp) + { + err.downgrade_to_delayed_bug(); + } + } + if let Ok(base_snippet) = base_snippet { + let mut sp = after_colon_sp; + for _ in 0..100 { + // Try to find an assignment + sp = sm.next_point(sp); + let snippet = sm.span_to_snippet(sp.to(sm.next_point(sp))); + match snippet { + Ok(ref x) if x.as_str() == "=" => { + err.span_suggestion( + base_span, + "maybe you meant to write an assignment here", + format!("let {}", base_snippet), + Applicability::MaybeIncorrect, + ); + show_label = false; + break; + } + Ok(ref x) if x.as_str() == "\n" => break, + Err(_) => break, + Ok(_) => {} + } + } + } + } + if show_label { + err.span_label( + base_span, + "expecting a type here because of type ascription", + ); + } + return show_label; + } + } + } + false + } + + fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> { + let mut result = None; + let mut seen_modules = FxHashSet::default(); + let mut worklist = vec![(self.r.graph_root, Vec::new())]; + + while let Some((in_module, path_segments)) = worklist.pop() { + // abort if the module is already found + if result.is_some() { + break; + } + + in_module.for_each_child(self.r, |_, ident, _, name_binding| { + // abort if the module is already found or if name_binding is private external + if result.is_some() || !name_binding.vis.is_visible_locally() { + return; + } + if let Some(module) = name_binding.module() { + // form the path + let mut path_segments = path_segments.clone(); + path_segments.push(ast::PathSegment::from_ident(ident)); + let module_def_id = module.def_id(); + if module_def_id == def_id { + let path = + Path { span: name_binding.span, segments: path_segments, tokens: None }; + result = Some(( + module, + ImportSuggestion { + did: Some(def_id), + descr: "module", + path, + accessible: true, + note: None, + }, + )); + } else { + // add the module to the lookup + if seen_modules.insert(module_def_id) { + worklist.push((module, path_segments)); + } + } + } + }); + } + + result + } + + fn collect_enum_ctors(&mut self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> { + self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| { + let mut variants = Vec::new(); + enum_module.for_each_child(self.r, |_, ident, _, name_binding| { + if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() { + let mut segms = enum_import_suggestion.path.segments.clone(); + segms.push(ast::PathSegment::from_ident(ident)); + let path = Path { span: name_binding.span, segments: segms, tokens: None }; + variants.push((path, def_id, kind)); + } + }); + variants + }) + } + + /// Adds a suggestion for using an enum's variant when an enum is used instead. + fn suggest_using_enum_variant( + &mut self, + err: &mut Diagnostic, + source: PathSource<'_>, + def_id: DefId, + span: Span, + ) { + let Some(variants) = self.collect_enum_ctors(def_id) else { + err.note("you might have meant to use one of the enum's variants"); + return; + }; + + let suggest_only_tuple_variants = + matches!(source, PathSource::TupleStruct(..)) || source.is_call(); + if suggest_only_tuple_variants { + // Suggest only tuple variants regardless of whether they have fields and do not + // suggest path with added parentheses. + let suggestable_variants = variants + .iter() + .filter(|(.., kind)| *kind == CtorKind::Fn) + .map(|(variant, ..)| path_names_to_string(variant)) + .collect::<Vec<_>>(); + + let non_suggestable_variant_count = variants.len() - suggestable_variants.len(); + + let source_msg = if source.is_call() { + "to construct" + } else if matches!(source, PathSource::TupleStruct(..)) { + "to match against" + } else { + unreachable!() + }; + + if !suggestable_variants.is_empty() { + let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 { + format!("try {} the enum's variant", source_msg) + } else { + format!("try {} one of the enum's variants", source_msg) + }; + + err.span_suggestions( + span, + &msg, + suggestable_variants.into_iter(), + Applicability::MaybeIncorrect, + ); + } + + // If the enum has no tuple variants.. + if non_suggestable_variant_count == variants.len() { + err.help(&format!("the enum has no tuple variants {}", source_msg)); + } + + // If there are also non-tuple variants.. + if non_suggestable_variant_count == 1 { + err.help(&format!( + "you might have meant {} the enum's non-tuple variant", + source_msg + )); + } else if non_suggestable_variant_count >= 1 { + err.help(&format!( + "you might have meant {} one of the enum's non-tuple variants", + source_msg + )); + } + } else { + let needs_placeholder = |def_id: DefId, kind: CtorKind| { + let has_no_fields = self.r.field_names.get(&def_id).map_or(false, |f| f.is_empty()); + match kind { + CtorKind::Const => false, + CtorKind::Fn | CtorKind::Fictive if has_no_fields => false, + _ => true, + } + }; + + let mut suggestable_variants = variants + .iter() + .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind)) + .map(|(variant, _, kind)| (path_names_to_string(variant), kind)) + .map(|(variant, kind)| match kind { + CtorKind::Const => variant, + CtorKind::Fn => format!("({}())", variant), + CtorKind::Fictive => format!("({} {{}})", variant), + }) + .collect::<Vec<_>>(); + + if !suggestable_variants.is_empty() { + let msg = if suggestable_variants.len() == 1 { + "you might have meant to use the following enum variant" + } else { + "you might have meant to use one of the following enum variants" + }; + + err.span_suggestions( + span, + msg, + suggestable_variants.drain(..), + Applicability::MaybeIncorrect, + ); + } + + let suggestable_variants_with_placeholders = variants + .iter() + .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind)) + .map(|(variant, _, kind)| (path_names_to_string(variant), kind)) + .filter_map(|(variant, kind)| match kind { + CtorKind::Fn => Some(format!("({}(/* fields */))", variant)), + CtorKind::Fictive => Some(format!("({} {{ /* fields */ }})", variant)), + _ => None, + }) + .collect::<Vec<_>>(); + + if !suggestable_variants_with_placeholders.is_empty() { + let msg = match ( + suggestable_variants.is_empty(), + suggestable_variants_with_placeholders.len(), + ) { + (true, 1) => "the following enum variant is available", + (true, _) => "the following enum variants are available", + (false, 1) => "alternatively, the following enum variant is available", + (false, _) => "alternatively, the following enum variants are also available", + }; + + err.span_suggestions( + span, + msg, + suggestable_variants_with_placeholders.into_iter(), + Applicability::HasPlaceholders, + ); + } + }; + + if def_id.is_local() { + if let Some(span) = self.def_span(def_id) { + err.span_note(span, "the enum is defined here"); + } + } + } + + pub(crate) fn report_missing_type_error( + &self, + path: &[Segment], + ) -> Option<(Span, &'static str, String, Applicability)> { + let (ident, span) = match path { + [segment] if !segment.has_generic_args && segment.ident.name != kw::SelfUpper => { + (segment.ident.to_string(), segment.ident.span) + } + _ => return None, + }; + let mut iter = ident.chars().map(|c| c.is_uppercase()); + let single_uppercase_char = + matches!(iter.next(), Some(true)) && matches!(iter.next(), None); + if !self.diagnostic_metadata.currently_processing_generics && !single_uppercase_char { + return None; + } + match (self.diagnostic_metadata.current_item, single_uppercase_char, self.diagnostic_metadata.currently_processing_generics) { + (Some(Item { kind: ItemKind::Fn(..), ident, .. }), _, _) if ident.name == sym::main => { + // Ignore `fn main()` as we don't want to suggest `fn main<T>()` + } + ( + Some(Item { + kind: + kind @ ItemKind::Fn(..) + | kind @ ItemKind::Enum(..) + | kind @ ItemKind::Struct(..) + | kind @ ItemKind::Union(..), + .. + }), + true, _ + ) + // Without the 2nd `true`, we'd suggest `impl <T>` for `impl T` when a type `T` isn't found + | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true) + | (Some(Item { kind, .. }), false, _) => { + // Likely missing type parameter. + if let Some(generics) = kind.generics() { + if span.overlaps(generics.span) { + // Avoid the following: + // error[E0405]: cannot find trait `A` in this scope + // --> $DIR/typo-suggestion-named-underscore.rs:CC:LL + // | + // L | fn foo<T: A>(x: T) {} // Shouldn't suggest underscore + // | ^- help: you might be missing a type parameter: `, A` + // | | + // | not found in this scope + return None; + } + let msg = "you might be missing a type parameter"; + let (span, sugg) = if let [.., param] = &generics.params[..] { + let span = if let [.., bound] = ¶m.bounds[..] { + bound.span() + } else if let GenericParam { + kind: GenericParamKind::Const { ty, kw_span: _, default }, .. + } = param { + default.as_ref().map(|def| def.value.span).unwrap_or(ty.span) + } else { + param.ident.span + }; + (span, format!(", {}", ident)) + } else { + (generics.span, format!("<{}>", ident)) + }; + // Do not suggest if this is coming from macro expansion. + if span.can_be_used_for_suggestions() { + return Some(( + span.shrink_to_hi(), + msg, + sugg, + Applicability::MaybeIncorrect, + )); + } + } + } + _ => {} + } + None + } + + /// Given the target `label`, search the `rib_index`th label rib for similarly named labels, + /// optionally returning the closest match and whether it is reachable. + pub(crate) fn suggestion_for_label_in_rib( + &self, + rib_index: usize, + label: Ident, + ) -> Option<LabelSuggestion> { + // Are ribs from this `rib_index` within scope? + let within_scope = self.is_label_valid_from_rib(rib_index); + + let rib = &self.label_ribs[rib_index]; + let names = rib + .bindings + .iter() + .filter(|(id, _)| id.span.eq_ctxt(label.span)) + .map(|(id, _)| id.name) + .collect::<Vec<Symbol>>(); + + find_best_match_for_name(&names, label.name, None).map(|symbol| { + // Upon finding a similar name, get the ident that it was from - the span + // contained within helps make a useful diagnostic. In addition, determine + // whether this candidate is within scope. + let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap(); + (*ident, within_scope) + }) + } + + pub(crate) fn maybe_report_lifetime_uses( + &mut self, + generics_span: Span, + params: &[ast::GenericParam], + ) { + for (param_index, param) in params.iter().enumerate() { + let GenericParamKind::Lifetime = param.kind else { continue }; + + let def_id = self.r.local_def_id(param.id); + + let use_set = self.lifetime_uses.remove(&def_id); + debug!( + "Use set for {:?}({:?} at {:?}) is {:?}", + def_id, param.ident, param.ident.span, use_set + ); + + let deletion_span = || { + if params.len() == 1 { + // if sole lifetime, remove the entire `<>` brackets + generics_span + } else if param_index == 0 { + // if removing within `<>` brackets, we also want to + // delete a leading or trailing comma as appropriate + param.span().to(params[param_index + 1].span().shrink_to_lo()) + } else { + // if removing within `<>` brackets, we also want to + // delete a leading or trailing comma as appropriate + params[param_index - 1].span().shrink_to_hi().to(param.span()) + } + }; + match use_set { + Some(LifetimeUseSet::Many) => {} + Some(LifetimeUseSet::One { use_span, use_ctxt }) => { + debug!(?param.ident, ?param.ident.span, ?use_span); + + let elidable = matches!(use_ctxt, LifetimeCtxt::Rptr); + + let deletion_span = deletion_span(); + self.r.lint_buffer.buffer_lint_with_diagnostic( + lint::builtin::SINGLE_USE_LIFETIMES, + param.id, + param.ident.span, + &format!("lifetime parameter `{}` only used once", param.ident), + lint::BuiltinLintDiagnostics::SingleUseLifetime { + param_span: param.ident.span, + use_span: Some((use_span, elidable)), + deletion_span, + }, + ); + } + None => { + debug!(?param.ident, ?param.ident.span); + + let deletion_span = deletion_span(); + self.r.lint_buffer.buffer_lint_with_diagnostic( + lint::builtin::UNUSED_LIFETIMES, + param.id, + param.ident.span, + &format!("lifetime parameter `{}` never used", param.ident), + lint::BuiltinLintDiagnostics::SingleUseLifetime { + param_span: param.ident.span, + use_span: None, + deletion_span, + }, + ); + } + } + } + } + + pub(crate) fn emit_undeclared_lifetime_error( + &self, + lifetime_ref: &ast::Lifetime, + outer_lifetime_ref: Option<Ident>, + ) { + debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime); + let mut err = if let Some(outer) = outer_lifetime_ref { + let mut err = struct_span_err!( + self.r.session, + lifetime_ref.ident.span, + E0401, + "can't use generic parameters from outer item", + ); + err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item"); + err.span_label(outer.span, "lifetime parameter from outer item"); + err + } else { + let mut err = struct_span_err!( + self.r.session, + lifetime_ref.ident.span, + E0261, + "use of undeclared lifetime name `{}`", + lifetime_ref.ident + ); + err.span_label(lifetime_ref.ident.span, "undeclared lifetime"); + err + }; + self.suggest_introducing_lifetime( + &mut err, + Some(lifetime_ref.ident.name.as_str()), + |err, _, span, message, suggestion| { + err.span_suggestion(span, message, suggestion, Applicability::MaybeIncorrect); + true + }, + ); + err.emit(); + } + + fn suggest_introducing_lifetime( + &self, + err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>, + name: Option<&str>, + suggest: impl Fn(&mut DiagnosticBuilder<'_, ErrorGuaranteed>, bool, Span, &str, String) -> bool, + ) { + let mut suggest_note = true; + for rib in self.lifetime_ribs.iter().rev() { + let mut should_continue = true; + match rib.kind { + LifetimeRibKind::Generics { binder: _, span, kind } => { + if !span.can_be_used_for_suggestions() && suggest_note && let Some(name) = name { + suggest_note = false; // Avoid displaying the same help multiple times. + err.span_label( + span, + &format!( + "lifetime `{}` is missing in item created through this procedural macro", + name, + ), + ); + continue; + } + + let higher_ranked = matches!( + kind, + LifetimeBinderKind::BareFnType + | LifetimeBinderKind::PolyTrait + | LifetimeBinderKind::WhereBound + ); + let (span, sugg) = if span.is_empty() { + let sugg = format!( + "{}<{}>{}", + if higher_ranked { "for" } else { "" }, + name.unwrap_or("'a"), + if higher_ranked { " " } else { "" }, + ); + (span, sugg) + } else { + let span = + self.r.session.source_map().span_through_char(span, '<').shrink_to_hi(); + let sugg = format!("{}, ", name.unwrap_or("'a")); + (span, sugg) + }; + if higher_ranked { + let message = format!( + "consider making the {} lifetime-generic with a new `{}` lifetime", + kind.descr(), + name.unwrap_or("'a"), + ); + should_continue = suggest(err, true, span, &message, sugg); + err.note_once( + "for more information on higher-ranked polymorphism, visit \ + https://doc.rust-lang.org/nomicon/hrtb.html", + ); + } else if let Some(name) = name { + let message = format!("consider introducing lifetime `{}` here", name); + should_continue = suggest(err, false, span, &message, sugg); + } else { + let message = format!("consider introducing a named lifetime parameter"); + should_continue = suggest(err, false, span, &message, sugg); + } + } + LifetimeRibKind::Item => break, + _ => {} + } + if !should_continue { + break; + } + } + } + + pub(crate) fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) { + struct_span_err!( + self.r.session, + lifetime_ref.ident.span, + E0771, + "use of non-static lifetime `{}` in const generic", + lifetime_ref.ident + ) + .note( + "for more information, see issue #74052 \ + <https://github.com/rust-lang/rust/issues/74052>", + ) + .emit(); + } + + /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`. + /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by + /// `body_id` is an anonymous constant and `lifetime_ref` is non-static. + pub(crate) fn maybe_emit_forbidden_non_static_lifetime_error( + &self, + lifetime_ref: &ast::Lifetime, + ) { + let feature_active = self.r.session.features_untracked().generic_const_exprs; + if !feature_active { + feature_err( + &self.r.session.parse_sess, + sym::generic_const_exprs, + lifetime_ref.ident.span, + "a non-static lifetime is not allowed in a `const`", + ) + .emit(); + } + } + + pub(crate) fn report_missing_lifetime_specifiers( + &mut self, + lifetime_refs: Vec<MissingLifetime>, + function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>, + ) -> ErrorGuaranteed { + let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum(); + let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect(); + + let mut err = struct_span_err!( + self.r.session, + spans, + E0106, + "missing lifetime specifier{}", + pluralize!(num_lifetimes) + ); + self.add_missing_lifetime_specifiers_label( + &mut err, + lifetime_refs, + function_param_lifetimes, + ); + err.emit() + } + + pub(crate) fn add_missing_lifetime_specifiers_label( + &mut self, + err: &mut DiagnosticBuilder<'_, ErrorGuaranteed>, + lifetime_refs: Vec<MissingLifetime>, + function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>, + ) { + for < in &lifetime_refs { + err.span_label( + lt.span, + format!( + "expected {} lifetime parameter{}", + if lt.count == 1 { "named".to_string() } else { lt.count.to_string() }, + pluralize!(lt.count), + ), + ); + } + + let mut in_scope_lifetimes: Vec<_> = self + .lifetime_ribs + .iter() + .rev() + .take_while(|rib| !matches!(rib.kind, LifetimeRibKind::Item)) + .flat_map(|rib| rib.bindings.iter()) + .map(|(&ident, &res)| (ident, res)) + .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime) + .collect(); + debug!(?in_scope_lifetimes); + + debug!(?function_param_lifetimes); + if let Some((param_lifetimes, params)) = &function_param_lifetimes { + let elided_len = param_lifetimes.len(); + let num_params = params.len(); + + let mut m = String::new(); + + for (i, info) in params.iter().enumerate() { + let ElisionFnParameter { ident, index, lifetime_count, span } = *info; + debug_assert_ne!(lifetime_count, 0); + + err.span_label(span, ""); + + if i != 0 { + if i + 1 < num_params { + m.push_str(", "); + } else if num_params == 2 { + m.push_str(" or "); + } else { + m.push_str(", or "); + } + } + + let help_name = if let Some(ident) = ident { + format!("`{}`", ident) + } else { + format!("argument {}", index + 1) + }; + + if lifetime_count == 1 { + m.push_str(&help_name[..]) + } else { + m.push_str(&format!("one of {}'s {} lifetimes", help_name, lifetime_count)[..]) + } + } + + if num_params == 0 { + err.help( + "this function's return type contains a borrowed value, \ + but there is no value for it to be borrowed from", + ); + if in_scope_lifetimes.is_empty() { + in_scope_lifetimes = vec![( + Ident::with_dummy_span(kw::StaticLifetime), + (DUMMY_NODE_ID, LifetimeRes::Static), + )]; + } + } else if elided_len == 0 { + err.help( + "this function's return type contains a borrowed value with \ + an elided lifetime, but the lifetime cannot be derived from \ + the arguments", + ); + if in_scope_lifetimes.is_empty() { + in_scope_lifetimes = vec![( + Ident::with_dummy_span(kw::StaticLifetime), + (DUMMY_NODE_ID, LifetimeRes::Static), + )]; + } + } else if num_params == 1 { + err.help(&format!( + "this function's return type contains a borrowed value, \ + but the signature does not say which {} it is borrowed from", + m + )); + } else { + err.help(&format!( + "this function's return type contains a borrowed value, \ + but the signature does not say whether it is borrowed from {}", + m + )); + } + } + + let existing_name = match &in_scope_lifetimes[..] { + [] => Symbol::intern("'a"), + [(existing, _)] => existing.name, + _ => Symbol::intern("'lifetime"), + }; + + let mut spans_suggs: Vec<_> = Vec::new(); + let build_sugg = |lt: MissingLifetime| match lt.kind { + MissingLifetimeKind::Underscore => { + debug_assert_eq!(lt.count, 1); + (lt.span, existing_name.to_string()) + } + MissingLifetimeKind::Ampersand => { + debug_assert_eq!(lt.count, 1); + (lt.span.shrink_to_hi(), format!("{} ", existing_name)) + } + MissingLifetimeKind::Comma => { + let sugg: String = std::iter::repeat([existing_name.as_str(), ", "]) + .take(lt.count) + .flatten() + .collect(); + (lt.span.shrink_to_hi(), sugg) + } + MissingLifetimeKind::Brackets => { + let sugg: String = std::iter::once("<") + .chain( + std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "), + ) + .chain([">"]) + .collect(); + (lt.span.shrink_to_hi(), sugg) + } + }; + for < in &lifetime_refs { + spans_suggs.push(build_sugg(lt)); + } + debug!(?spans_suggs); + match in_scope_lifetimes.len() { + 0 => { + if let Some((param_lifetimes, _)) = function_param_lifetimes { + for lt in param_lifetimes { + spans_suggs.push(build_sugg(lt)) + } + } + self.suggest_introducing_lifetime( + err, + None, + |err, higher_ranked, span, message, intro_sugg| { + err.multipart_suggestion_verbose( + message, + std::iter::once((span, intro_sugg)) + .chain(spans_suggs.clone()) + .collect(), + Applicability::MaybeIncorrect, + ); + higher_ranked + }, + ); + } + 1 => { + err.multipart_suggestion_verbose( + &format!("consider using the `{}` lifetime", existing_name), + spans_suggs, + Applicability::MaybeIncorrect, + ); + + // Record as using the suggested resolution. + let (_, (_, res)) = in_scope_lifetimes[0]; + for < in &lifetime_refs { + self.r.lifetimes_res_map.insert(lt.id, res); + } + } + _ => { + let lifetime_spans: Vec<_> = + in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect(); + err.span_note(lifetime_spans, "these named lifetimes are available to use"); + + if spans_suggs.len() > 0 { + // This happens when we have `Foo<T>` where we point at the space before `T`, + // but this can be confusing so we give a suggestion with placeholders. + err.multipart_suggestion_verbose( + "consider using one of the available lifetimes here", + spans_suggs, + Applicability::HasPlaceholders, + ); + } + } + } + } +} + +/// Report lifetime/lifetime shadowing as an error. +pub fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) { + let mut err = struct_span_err!( + sess, + shadower.span, + E0496, + "lifetime name `{}` shadows a lifetime name that is already in scope", + orig.name, + ); + err.span_label(orig.span, "first declared here"); + err.span_label(shadower.span, format!("lifetime `{}` already in scope", orig.name)); + err.emit(); +} + +/// Shadowing involving a label is only a warning for historical reasons. +//FIXME: make this a proper lint. +pub fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) { + let name = shadower.name; + let shadower = shadower.span; + let mut err = sess.struct_span_warn( + shadower, + &format!("label name `{}` shadows a label name that is already in scope", name), + ); + err.span_label(orig, "first declared here"); + err.span_label(shadower, format!("label `{}` already in scope", name)); + err.emit(); +} diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs new file mode 100644 index 000000000..94460e33d --- /dev/null +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -0,0 +1,2144 @@ +//! Resolution of early vs late bound lifetimes. +//! +//! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this +//! information, typechecking needs to transform the lifetime parameters into bound lifetimes. +//! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit +//! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file +//! is also responsible for assigning their semantics to implicit lifetimes in trait objects. + +use rustc_ast::walk_list; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_errors::struct_span_err; +use rustc_hir as hir; +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::{DefIdMap, LocalDefId}; +use rustc_hir::intravisit::{self, Visitor}; +use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdMap, LifetimeName, Node}; +use rustc_middle::bug; +use rustc_middle::hir::map::Map; +use rustc_middle::hir::nested_filter; +use rustc_middle::middle::resolve_lifetime::*; +use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; +use rustc_span::def_id::DefId; +use rustc_span::symbol::{sym, Ident}; +use rustc_span::Span; +use std::borrow::Cow; +use std::fmt; +use std::mem::take; + +trait RegionExt { + fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (LocalDefId, Region); + + fn late(index: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region); + + fn id(&self) -> Option<DefId>; + + fn shifted(self, amount: u32) -> Region; + + fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region; + + fn subst<'a, L>(self, params: L, map: &NamedRegionMap) -> Option<Region> + where + L: Iterator<Item = &'a hir::Lifetime>; +} + +impl RegionExt for Region { + fn early(hir_map: Map<'_>, index: &mut u32, param: &GenericParam<'_>) -> (LocalDefId, Region) { + let i = *index; + *index += 1; + let def_id = hir_map.local_def_id(param.hir_id); + debug!("Region::early: index={} def_id={:?}", i, def_id); + (def_id, Region::EarlyBound(i, def_id.to_def_id())) + } + + fn late(idx: u32, hir_map: Map<'_>, param: &GenericParam<'_>) -> (LocalDefId, Region) { + let depth = ty::INNERMOST; + let def_id = hir_map.local_def_id(param.hir_id); + debug!( + "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}", + idx, param, depth, def_id, + ); + (def_id, Region::LateBound(depth, idx, def_id.to_def_id())) + } + + fn id(&self) -> Option<DefId> { + match *self { + Region::Static => None, + + Region::EarlyBound(_, id) | Region::LateBound(_, _, id) | Region::Free(_, id) => { + Some(id) + } + } + } + + fn shifted(self, amount: u32) -> Region { + match self { + Region::LateBound(debruijn, idx, id) => { + Region::LateBound(debruijn.shifted_in(amount), idx, id) + } + _ => self, + } + } + + fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region { + match self { + Region::LateBound(debruijn, index, id) => { + Region::LateBound(debruijn.shifted_out_to_binder(binder), index, id) + } + _ => self, + } + } + + fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region> + where + L: Iterator<Item = &'a hir::Lifetime>, + { + if let Region::EarlyBound(index, _) = self { + params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned()) + } else { + Some(self) + } + } +} + +/// Maps the id of each lifetime reference to the lifetime decl +/// that it corresponds to. +/// +/// FIXME. This struct gets converted to a `ResolveLifetimes` for +/// actual use. It has the same data, but indexed by `LocalDefId`. This +/// is silly. +#[derive(Debug, Default)] +struct NamedRegionMap { + // maps from every use of a named (not anonymous) lifetime to a + // `Region` describing how that region is bound + defs: HirIdMap<Region>, + + // Maps relevant hir items to the bound vars on them. These include: + // - function defs + // - function pointers + // - closures + // - trait refs + // - bound types (like `T` in `for<'a> T<'a>: Foo`) + late_bound_vars: HirIdMap<Vec<ty::BoundVariableKind>>, +} + +pub(crate) struct LifetimeContext<'a, 'tcx> { + pub(crate) tcx: TyCtxt<'tcx>, + map: &'a mut NamedRegionMap, + scope: ScopeRef<'a>, + + /// Indicates that we only care about the definition of a trait. This should + /// be false if the `Item` we are resolving lifetimes for is not a trait or + /// we eventually need lifetimes resolve for trait items. + trait_definition_only: bool, + + /// Cache for cross-crate per-definition object lifetime defaults. + xcrate_object_lifetime_defaults: DefIdMap<Vec<ObjectLifetimeDefault>>, +} + +#[derive(Debug)] +enum Scope<'a> { + /// Declares lifetimes, and each can be early-bound or late-bound. + /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and + /// it should be shifted by the number of `Binder`s in between the + /// declaration `Binder` and the location it's referenced from. + Binder { + /// We use an IndexMap here because we want these lifetimes in order + /// for diagnostics. + lifetimes: FxIndexMap<LocalDefId, Region>, + + /// if we extend this scope with another scope, what is the next index + /// we should use for an early-bound region? + next_early_index: u32, + + /// Whether or not this binder would serve as the parent + /// binder for opaque types introduced within. For example: + /// + /// ```text + /// fn foo<'a>() -> impl for<'b> Trait<Item = impl Trait2<'a>> + /// ``` + /// + /// Here, the opaque types we create for the `impl Trait` + /// and `impl Trait2` references will both have the `foo` item + /// as their parent. When we get to `impl Trait2`, we find + /// that it is nested within the `for<>` binder -- this flag + /// allows us to skip that when looking for the parent binder + /// of the resulting opaque type. + opaque_type_parent: bool, + + scope_type: BinderScopeType, + + /// The late bound vars for a given item are stored by `HirId` to be + /// queried later. However, if we enter an elision scope, we have to + /// later append the elided bound vars to the list and need to know what + /// to append to. + hir_id: hir::HirId, + + s: ScopeRef<'a>, + + /// If this binder comes from a where clause, specify how it was created. + /// This is used to diagnose inaccessible lifetimes in APIT: + /// ```ignore (illustrative) + /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} + /// ``` + where_bound_origin: Option<hir::PredicateOrigin>, + }, + + /// Lifetimes introduced by a fn are scoped to the call-site for that fn, + /// if this is a fn body, otherwise the original definitions are used. + /// Unspecified lifetimes are inferred, unless an elision scope is nested, + /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. + Body { + id: hir::BodyId, + s: ScopeRef<'a>, + }, + + /// A scope which either determines unspecified lifetimes or errors + /// on them (e.g., due to ambiguity). + Elision { + s: ScopeRef<'a>, + }, + + /// Use a specific lifetime (if `Some`) or leave it unset (to be + /// inferred in a function body or potentially error outside one), + /// for the default choice of lifetime in a trait object type. + ObjectLifetimeDefault { + lifetime: Option<Region>, + s: ScopeRef<'a>, + }, + + /// When we have nested trait refs, we concatenate late bound vars for inner + /// trait refs from outer ones. But we also need to include any HRTB + /// lifetimes encountered when identifying the trait that an associated type + /// is declared on. + Supertrait { + lifetimes: Vec<ty::BoundVariableKind>, + s: ScopeRef<'a>, + }, + + TraitRefBoundary { + s: ScopeRef<'a>, + }, + + Root, +} + +#[derive(Copy, Clone, Debug)] +enum BinderScopeType { + /// Any non-concatenating binder scopes. + Normal, + /// Within a syntactic trait ref, there may be multiple poly trait refs that + /// are nested (under the `associated_type_bounds` feature). The binders of + /// the inner poly trait refs are extended from the outer poly trait refs + /// and don't increase the late bound depth. If you had + /// `T: for<'a> Foo<Bar: for<'b> Baz<'a, 'b>>`, then the `for<'b>` scope + /// would be `Concatenating`. This also used in trait refs in where clauses + /// where we have two binders `for<> T: for<> Foo` (I've intentionally left + /// out any lifetimes because they aren't needed to show the two scopes). + /// The inner `for<>` has a scope of `Concatenating`. + Concatenating, +} + +// A helper struct for debugging scopes without printing parent scopes +struct TruncatedScopeDebug<'a>(&'a Scope<'a>); + +impl<'a> fmt::Debug for TruncatedScopeDebug<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Scope::Binder { + lifetimes, + next_early_index, + opaque_type_parent, + scope_type, + hir_id, + where_bound_origin, + s: _, + } => f + .debug_struct("Binder") + .field("lifetimes", lifetimes) + .field("next_early_index", next_early_index) + .field("opaque_type_parent", opaque_type_parent) + .field("scope_type", scope_type) + .field("hir_id", hir_id) + .field("where_bound_origin", where_bound_origin) + .field("s", &"..") + .finish(), + Scope::Body { id, s: _ } => { + f.debug_struct("Body").field("id", id).field("s", &"..").finish() + } + Scope::Elision { s: _ } => f.debug_struct("Elision").field("s", &"..").finish(), + Scope::ObjectLifetimeDefault { lifetime, s: _ } => f + .debug_struct("ObjectLifetimeDefault") + .field("lifetime", lifetime) + .field("s", &"..") + .finish(), + Scope::Supertrait { lifetimes, s: _ } => f + .debug_struct("Supertrait") + .field("lifetimes", lifetimes) + .field("s", &"..") + .finish(), + Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(), + Scope::Root => f.debug_struct("Root").finish(), + } + } +} + +type ScopeRef<'a> = &'a Scope<'a>; + +const ROOT_SCOPE: ScopeRef<'static> = &Scope::Root; + +pub fn provide(providers: &mut ty::query::Providers) { + *providers = ty::query::Providers { + resolve_lifetimes_trait_definition, + resolve_lifetimes, + + named_region_map: |tcx, id| resolve_lifetimes_for(tcx, id).defs.get(&id), + is_late_bound_map, + object_lifetime_defaults: |tcx, id| match tcx.hir().find_by_def_id(id) { + Some(Node::Item(item)) => compute_object_lifetime_defaults(tcx, item), + _ => None, + }, + late_bound_vars_map: |tcx, id| resolve_lifetimes_for(tcx, id).late_bound_vars.get(&id), + + ..*providers + }; +} + +/// Like `resolve_lifetimes`, but does not resolve lifetimes for trait items. +/// Also does not generate any diagnostics. +/// +/// This is ultimately a subset of the `resolve_lifetimes` work. It effectively +/// resolves lifetimes only within the trait "header" -- that is, the trait +/// and supertrait list. In contrast, `resolve_lifetimes` resolves all the +/// lifetimes within the trait and its items. There is room to refactor this, +/// for example to resolve lifetimes for each trait item in separate queries, +/// but it's convenient to do the entire trait at once because the lifetimes +/// from the trait definition are in scope within the trait items as well. +/// +/// The reason for this separate call is to resolve what would otherwise +/// be a cycle. Consider this example: +/// +/// ```ignore UNSOLVED (maybe @jackh726 knows what lifetime parameter to give Sub) +/// trait Base<'a> { +/// type BaseItem; +/// } +/// trait Sub<'b>: for<'a> Base<'a> { +/// type SubItem: Sub<BaseItem = &'b u32>; +/// } +/// ``` +/// +/// When we resolve `Sub` and all its items, we also have to resolve `Sub<BaseItem = &'b u32>`. +/// To figure out the index of `'b`, we have to know about the supertraits +/// of `Sub` so that we can determine that the `for<'a>` will be in scope. +/// (This is because we -- currently at least -- flatten all the late-bound +/// lifetimes into a single binder.) This requires us to resolve the +/// *trait definition* of `Sub`; basically just enough lifetime information +/// to look at the supertraits. +#[tracing::instrument(level = "debug", skip(tcx))] +fn resolve_lifetimes_trait_definition( + tcx: TyCtxt<'_>, + local_def_id: LocalDefId, +) -> ResolveLifetimes { + convert_named_region_map(do_resolve(tcx, local_def_id, true)) +} + +/// Computes the `ResolveLifetimes` map that contains data for an entire `Item`. +/// You should not read the result of this query directly, but rather use +/// `named_region_map`, `is_late_bound_map`, etc. +#[tracing::instrument(level = "debug", skip(tcx))] +fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> ResolveLifetimes { + convert_named_region_map(do_resolve(tcx, local_def_id, false)) +} + +fn do_resolve( + tcx: TyCtxt<'_>, + local_def_id: LocalDefId, + trait_definition_only: bool, +) -> NamedRegionMap { + let item = tcx.hir().expect_item(local_def_id); + let mut named_region_map = + NamedRegionMap { defs: Default::default(), late_bound_vars: Default::default() }; + let mut visitor = LifetimeContext { + tcx, + map: &mut named_region_map, + scope: ROOT_SCOPE, + trait_definition_only, + xcrate_object_lifetime_defaults: Default::default(), + }; + visitor.visit_item(item); + + named_region_map +} + +fn convert_named_region_map(named_region_map: NamedRegionMap) -> ResolveLifetimes { + let mut rl = ResolveLifetimes::default(); + + for (hir_id, v) in named_region_map.defs { + let map = rl.defs.entry(hir_id.owner).or_default(); + map.insert(hir_id.local_id, v); + } + for (hir_id, v) in named_region_map.late_bound_vars { + let map = rl.late_bound_vars.entry(hir_id.owner).or_default(); + map.insert(hir_id.local_id, v); + } + + debug!(?rl.defs); + rl +} + +/// Given `any` owner (structs, traits, trait methods, etc.), does lifetime resolution. +/// There are two important things this does. +/// First, we have to resolve lifetimes for +/// the entire *`Item`* that contains this owner, because that's the largest "scope" +/// where we can have relevant lifetimes. +/// Second, if we are asking for lifetimes in a trait *definition*, we use `resolve_lifetimes_trait_definition` +/// instead of `resolve_lifetimes`, which does not descend into the trait items and does not emit diagnostics. +/// This allows us to avoid cycles. Importantly, if we ask for lifetimes for lifetimes that have an owner +/// other than the trait itself (like the trait methods or associated types), then we just use the regular +/// `resolve_lifetimes`. +fn resolve_lifetimes_for<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ResolveLifetimes { + let item_id = item_for(tcx, def_id); + if item_id == def_id { + let item = tcx.hir().item(hir::ItemId { def_id: item_id }); + match item.kind { + hir::ItemKind::Trait(..) => tcx.resolve_lifetimes_trait_definition(item_id), + _ => tcx.resolve_lifetimes(item_id), + } + } else { + tcx.resolve_lifetimes(item_id) + } +} + +/// Finds the `Item` that contains the given `LocalDefId` +fn item_for(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> LocalDefId { + match tcx.hir().find_by_def_id(local_def_id) { + Some(Node::Item(item)) => { + return item.def_id; + } + _ => {} + } + let item = { + let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id); + let mut parent_iter = tcx.hir().parent_iter(hir_id); + loop { + let node = parent_iter.next().map(|n| n.1); + match node { + Some(hir::Node::Item(item)) => break item.def_id, + Some(hir::Node::Crate(_)) | None => bug!("Called `item_for` on an Item."), + _ => {} + } + } + }; + item +} + +/// In traits, there is an implicit `Self` type parameter which comes before the generics. +/// We have to account for this when computing the index of the other generic parameters. +/// This function returns whether there is such an implicit parameter defined on the given item. +fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool { + matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..)) +} + +fn late_region_as_bound_region<'tcx>(tcx: TyCtxt<'tcx>, region: &Region) -> ty::BoundVariableKind { + match region { + Region::LateBound(_, _, def_id) => { + let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local())); + ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name)) + } + _ => bug!("{:?} is not a late region", region), + } +} + +impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { + /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref. + fn poly_trait_ref_binder_info(&mut self) -> (Vec<ty::BoundVariableKind>, BinderScopeType) { + let mut scope = self.scope; + let mut supertrait_lifetimes = vec![]; + loop { + match scope { + Scope::Body { .. } | Scope::Root => { + break (vec![], BinderScopeType::Normal); + } + + Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => { + scope = s; + } + + Scope::Supertrait { s, lifetimes } => { + supertrait_lifetimes = lifetimes.clone(); + scope = s; + } + + Scope::TraitRefBoundary { .. } => { + // We should only see super trait lifetimes if there is a `Binder` above + assert!(supertrait_lifetimes.is_empty()); + break (vec![], BinderScopeType::Normal); + } + + Scope::Binder { hir_id, .. } => { + // Nested poly trait refs have the binders concatenated + let mut full_binders = + self.map.late_bound_vars.entry(*hir_id).or_default().clone(); + full_binders.extend(supertrait_lifetimes.into_iter()); + break (full_binders, BinderScopeType::Concatenating); + } + } + } + } +} +impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { + type NestedFilter = nested_filter::All; + + fn nested_visit_map(&mut self) -> Self::Map { + self.tcx.hir() + } + + // We want to nest trait/impl items in their parent, but nothing else. + fn visit_nested_item(&mut self, _: hir::ItemId) {} + + fn visit_trait_item_ref(&mut self, ii: &'tcx hir::TraitItemRef) { + if !self.trait_definition_only { + intravisit::walk_trait_item_ref(self, ii) + } + } + + fn visit_nested_body(&mut self, body: hir::BodyId) { + let body = self.tcx.hir().body(body); + self.with(Scope::Body { id: body.id(), s: self.scope }, |this| { + this.visit_body(body); + }); + } + + fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { + if let hir::ExprKind::Closure(hir::Closure { + binder, bound_generic_params, fn_decl, .. + }) = e.kind + { + if let &hir::ClosureBinder::For { span: for_sp, .. } = binder { + fn span_of_infer(ty: &hir::Ty<'_>) -> Option<Span> { + struct V(Option<Span>); + + impl<'v> Visitor<'v> for V { + fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { + match t.kind { + _ if self.0.is_some() => (), + hir::TyKind::Infer => { + self.0 = Some(t.span); + } + _ => intravisit::walk_ty(self, t), + } + } + } + + let mut v = V(None); + v.visit_ty(ty); + v.0 + } + + let infer_in_rt_sp = match fn_decl.output { + hir::FnRetTy::DefaultReturn(sp) => Some(sp), + hir::FnRetTy::Return(ty) => span_of_infer(ty), + }; + + let infer_spans = fn_decl + .inputs + .into_iter() + .filter_map(span_of_infer) + .chain(infer_in_rt_sp) + .collect::<Vec<_>>(); + + if !infer_spans.is_empty() { + self.tcx.sess + .struct_span_err( + infer_spans, + "implicit types in closure signatures are forbidden when `for<...>` is present", + ) + .span_label(for_sp, "`for<...>` is here") + .emit(); + } + } + + let next_early_index = self.next_early_index(); + let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) = + bound_generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + (pair, r) + }) + .unzip(); + + self.map.late_bound_vars.insert(e.hir_id, binders); + let scope = Scope::Binder { + hir_id: e.hir_id, + lifetimes, + s: self.scope, + next_early_index, + opaque_type_parent: false, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + + self.with(scope, |this| { + // a closure has no bounds, so everything + // contained within is scoped within its binder. + intravisit::walk_expr(this, e) + }); + } else { + intravisit::walk_expr(self, e) + } + } + + fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { + match &item.kind { + hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => { + if let Some(of_trait) = of_trait { + self.map.late_bound_vars.insert(of_trait.hir_ref_id, Vec::default()); + } + } + _ => {} + } + match item.kind { + hir::ItemKind::Fn(_, ref generics, _) => { + self.visit_early_late(None, item.hir_id(), generics, |this| { + intravisit::walk_item(this, item); + }); + } + + hir::ItemKind::ExternCrate(_) + | hir::ItemKind::Use(..) + | hir::ItemKind::Macro(..) + | hir::ItemKind::Mod(..) + | hir::ItemKind::ForeignMod { .. } + | hir::ItemKind::GlobalAsm(..) => { + // These sorts of items have no lifetime parameters at all. + intravisit::walk_item(self, item); + } + hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => { + // No lifetime parameters, but implied 'static. + self.with(Scope::Elision { s: self.scope }, |this| { + intravisit::walk_item(this, item) + }); + } + hir::ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => { + // Opaque types are visited when we visit the + // `TyKind::OpaqueDef`, so that they have the lifetimes from + // their parent opaque_ty in scope. + // + // The core idea here is that since OpaqueTys are generated with the impl Trait as + // their owner, we can keep going until we find the Item that owns that. We then + // conservatively add all resolved lifetimes. Otherwise we run into problems in + // cases like `type Foo<'a> = impl Bar<As = impl Baz + 'a>`. + for (_hir_id, node) in + self.tcx.hir().parent_iter(self.tcx.hir().local_def_id_to_hir_id(item.def_id)) + { + match node { + hir::Node::Item(parent_item) => { + let resolved_lifetimes: &ResolveLifetimes = + self.tcx.resolve_lifetimes(item_for(self.tcx, parent_item.def_id)); + // We need to add *all* deps, since opaque tys may want them from *us* + for (&owner, defs) in resolved_lifetimes.defs.iter() { + defs.iter().for_each(|(&local_id, region)| { + self.map.defs.insert(hir::HirId { owner, local_id }, *region); + }); + } + for (&owner, late_bound_vars) in + resolved_lifetimes.late_bound_vars.iter() + { + late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| { + self.map.late_bound_vars.insert( + hir::HirId { owner, local_id }, + late_bound_vars.clone(), + ); + }); + } + break; + } + hir::Node::Crate(_) => bug!("No Item about an OpaqueTy"), + _ => {} + } + } + } + hir::ItemKind::TyAlias(_, ref generics) + | hir::ItemKind::Enum(_, ref generics) + | hir::ItemKind::Struct(_, ref generics) + | hir::ItemKind::Union(_, ref generics) + | hir::ItemKind::Trait(_, _, ref generics, ..) + | hir::ItemKind::TraitAlias(ref generics, ..) + | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => { + // These kinds of items have only early-bound lifetime parameters. + let mut index = if sub_items_have_self_param(&item.kind) { + 1 // Self comes before lifetimes + } else { + 0 + }; + let mut non_lifetime_count = 0; + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); + self.map.late_bound_vars.insert(item.hir_id(), vec![]); + let scope = Scope::Binder { + hir_id: item.hir_id(), + lifetimes, + next_early_index: index + non_lifetime_count, + opaque_type_parent: true, + scope_type: BinderScopeType::Normal, + s: ROOT_SCOPE, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + intravisit::walk_item(this, item); + }); + }); + } + } + } + + fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { + match item.kind { + hir::ForeignItemKind::Fn(_, _, ref generics) => { + self.visit_early_late(None, item.hir_id(), generics, |this| { + intravisit::walk_foreign_item(this, item); + }) + } + hir::ForeignItemKind::Static(..) => { + intravisit::walk_foreign_item(self, item); + } + hir::ForeignItemKind::Type => { + intravisit::walk_foreign_item(self, item); + } + } + } + + #[tracing::instrument(level = "debug", skip(self))] + fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) { + match ty.kind { + hir::TyKind::BareFn(ref c) => { + let next_early_index = self.next_early_index(); + let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) = c + .generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + (pair, r) + }) + .unzip(); + self.map.late_bound_vars.insert(ty.hir_id, binders); + let scope = Scope::Binder { + hir_id: ty.hir_id, + lifetimes, + s: self.scope, + next_early_index, + opaque_type_parent: false, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + // a bare fn has no bounds, so everything + // contained within is scoped within its binder. + intravisit::walk_ty(this, ty); + }); + } + hir::TyKind::TraitObject(bounds, ref lifetime, _) => { + debug!(?bounds, ?lifetime, "TraitObject"); + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + for bound in bounds { + this.visit_poly_trait_ref(bound, hir::TraitBoundModifier::None); + } + }); + match lifetime.name { + LifetimeName::ImplicitObjectLifetimeDefault => { + // If the user does not write *anything*, we + // use the object lifetime defaulting + // rules. So e.g., `Box<dyn Debug>` becomes + // `Box<dyn Debug + 'static>`. + self.resolve_object_lifetime_default(lifetime) + } + LifetimeName::Infer => { + // If the user writes `'_`, we use the *ordinary* elision + // rules. So the `'_` in e.g., `Box<dyn Debug + '_>` will be + // resolved the same as the `'_` in `&'_ Foo`. + // + // cc #48468 + } + LifetimeName::Param(..) | LifetimeName::Static => { + // If the user wrote an explicit name, use that. + self.visit_lifetime(lifetime); + } + LifetimeName::Error => {} + } + } + hir::TyKind::Rptr(ref lifetime_ref, ref mt) => { + self.visit_lifetime(lifetime_ref); + let scope = Scope::ObjectLifetimeDefault { + lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(), + s: self.scope, + }; + self.with(scope, |this| this.visit_ty(&mt.ty)); + } + hir::TyKind::OpaqueDef(item_id, lifetimes) => { + // Resolve the lifetimes in the bounds to the lifetime defs in the generics. + // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to + // `type MyAnonTy<'b> = impl MyTrait<'b>;` + // ^ ^ this gets resolved in the scope of + // the opaque_ty generics + let opaque_ty = self.tcx.hir().item(item_id); + let (generics, bounds) = match opaque_ty.kind { + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias, + .. + }) => { + intravisit::walk_ty(self, ty); + + // Elided lifetimes are not allowed in non-return + // position impl Trait + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + let scope = Scope::Elision { s: this.scope }; + this.with(scope, |this| { + intravisit::walk_item(this, opaque_ty); + }) + }); + + return; + } + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..), + ref generics, + bounds, + .. + }) => (generics, bounds), + ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), + }; + + // Resolve the lifetimes that are applied to the opaque type. + // These are resolved in the current scope. + // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to + // `fn foo<'a>() -> MyAnonTy<'a> { ... }` + // ^ ^this gets resolved in the current scope + for lifetime in lifetimes { + let hir::GenericArg::Lifetime(lifetime) = lifetime else { + continue + }; + self.visit_lifetime(lifetime); + + // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>` + // and ban them. Type variables instantiated inside binders aren't + // well-supported at the moment, so this doesn't work. + // In the future, this should be fixed and this error should be removed. + let def = self.map.defs.get(&lifetime.hir_id).cloned(); + let Some(Region::LateBound(_, _, def_id)) = def else { + continue + }; + let Some(def_id) = def_id.as_local() else { + continue + }; + let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); + // Ensure that the parent of the def is an item, not HRTB + let parent_id = self.tcx.hir().get_parent_node(hir_id); + if !parent_id.is_owner() { + if !self.trait_definition_only { + struct_span_err!( + self.tcx.sess, + lifetime.span, + E0657, + "`impl Trait` can only capture lifetimes \ + bound at the fn or impl level" + ) + .emit(); + } + self.uninsert_lifetime_on_error(lifetime, def.unwrap()); + } + if let hir::Node::Item(hir::Item { + kind: hir::ItemKind::OpaqueTy { .. }, .. + }) = self.tcx.hir().get(parent_id) + { + if !self.trait_definition_only { + let mut err = self.tcx.sess.struct_span_err( + lifetime.span, + "higher kinded lifetime bounds on nested opaque types are not supported yet", + ); + err.span_note(self.tcx.def_span(def_id), "lifetime declared here"); + err.emit(); + } + self.uninsert_lifetime_on_error(lifetime, def.unwrap()); + } + } + + // We want to start our early-bound indices at the end of the parent scope, + // not including any parent `impl Trait`s. + let mut index = self.next_early_index_for_opaque_type(); + debug!(?index); + + let mut lifetimes = FxIndexMap::default(); + let mut non_lifetime_count = 0; + debug!(?generics.params); + for param in generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => { + let (def_id, reg) = Region::early(self.tcx.hir(), &mut index, ¶m); + lifetimes.insert(def_id, reg); + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + } + } + } + let next_early_index = index + non_lifetime_count; + self.map.late_bound_vars.insert(ty.hir_id, vec![]); + + let scope = Scope::Binder { + hir_id: ty.hir_id, + lifetimes, + next_early_index, + s: self.scope, + opaque_type_parent: false, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + this.visit_generics(generics); + for bound in bounds { + this.visit_param_bound(bound); + } + }) + }); + } + _ => intravisit::walk_ty(self, ty), + } + } + + fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { + use self::hir::TraitItemKind::*; + match trait_item.kind { + Fn(_, _) => { + let tcx = self.tcx; + self.visit_early_late( + Some(tcx.hir().get_parent_item(trait_item.hir_id())), + trait_item.hir_id(), + &trait_item.generics, + |this| intravisit::walk_trait_item(this, trait_item), + ); + } + Type(bounds, ref ty) => { + let generics = &trait_item.generics; + let mut index = self.next_early_index(); + debug!("visit_ty: index = {}", index); + let mut non_lifetime_count = 0; + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); + self.map.late_bound_vars.insert(trait_item.hir_id(), vec![]); + let scope = Scope::Binder { + hir_id: trait_item.hir_id(), + lifetimes, + next_early_index: index + non_lifetime_count, + s: self.scope, + opaque_type_parent: true, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + this.visit_generics(generics); + for bound in bounds { + this.visit_param_bound(bound); + } + if let Some(ty) = ty { + this.visit_ty(ty); + } + }) + }); + } + Const(_, _) => { + // Only methods and types support generics. + assert!(trait_item.generics.params.is_empty()); + intravisit::walk_trait_item(self, trait_item); + } + } + } + + fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { + use self::hir::ImplItemKind::*; + match impl_item.kind { + Fn(..) => { + let tcx = self.tcx; + self.visit_early_late( + Some(tcx.hir().get_parent_item(impl_item.hir_id())), + impl_item.hir_id(), + &impl_item.generics, + |this| intravisit::walk_impl_item(this, impl_item), + ); + } + TyAlias(ref ty) => { + let generics = &impl_item.generics; + let mut index = self.next_early_index(); + let mut non_lifetime_count = 0; + debug!("visit_ty: index = {}", index); + let lifetimes: FxIndexMap<LocalDefId, Region> = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); + self.map.late_bound_vars.insert(ty.hir_id, vec![]); + let scope = Scope::Binder { + hir_id: ty.hir_id, + lifetimes, + next_early_index: index + non_lifetime_count, + s: self.scope, + opaque_type_parent: true, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + this.visit_generics(generics); + this.visit_ty(ty); + }) + }); + } + Const(_, _) => { + // Only methods and types support generics. + assert!(impl_item.generics.params.is_empty()); + intravisit::walk_impl_item(self, impl_item); + } + } + } + + #[tracing::instrument(level = "debug", skip(self))] + fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { + match lifetime_ref.name { + hir::LifetimeName::Static => self.insert_lifetime(lifetime_ref, Region::Static), + hir::LifetimeName::Param(param_def_id, _) => { + self.resolve_lifetime_ref(param_def_id, lifetime_ref) + } + // If we've already reported an error, just ignore `lifetime_ref`. + hir::LifetimeName::Error => {} + // Those will be resolved by typechecking. + hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {} + } + } + + fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) { + for (i, segment) in path.segments.iter().enumerate() { + let depth = path.segments.len() - i - 1; + if let Some(ref args) = segment.args { + self.visit_segment_args(path.res, depth, args); + } + } + } + + fn visit_fn( + &mut self, + fk: intravisit::FnKind<'tcx>, + fd: &'tcx hir::FnDecl<'tcx>, + body_id: hir::BodyId, + _: Span, + _: hir::HirId, + ) { + let output = match fd.output { + hir::FnRetTy::DefaultReturn(_) => None, + hir::FnRetTy::Return(ref ty) => Some(&**ty), + }; + self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure)); + intravisit::walk_fn_kind(self, fk); + self.visit_nested_body(body_id) + } + + fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + for param in generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { ref default, .. } => { + if let Some(ref ty) = default { + this.visit_ty(&ty); + } + } + GenericParamKind::Const { ref ty, default } => { + this.visit_ty(&ty); + if let Some(default) = default { + this.visit_body(this.tcx.hir().body(default.body)); + } + } + } + } + for predicate in generics.predicates { + match predicate { + &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { + ref bounded_ty, + bounds, + ref bound_generic_params, + origin, + .. + }) => { + let (lifetimes, binders): (FxIndexMap<LocalDefId, Region>, Vec<_>) = + bound_generic_params + .iter() + .filter(|param| { + matches!(param.kind, GenericParamKind::Lifetime { .. }) + }) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = + Region::late(late_bound_idx as u32, this.tcx.hir(), param); + let r = late_region_as_bound_region(this.tcx, &pair.1); + (pair, r) + }) + .unzip(); + this.map.late_bound_vars.insert(bounded_ty.hir_id, binders.clone()); + let next_early_index = this.next_early_index(); + // Even if there are no lifetimes defined here, we still wrap it in a binder + // scope. If there happens to be a nested poly trait ref (an error), that + // will be `Concatenating` anyways, so we don't have to worry about the depth + // being wrong. + let scope = Scope::Binder { + hir_id: bounded_ty.hir_id, + lifetimes, + s: this.scope, + next_early_index, + opaque_type_parent: false, + scope_type: BinderScopeType::Normal, + where_bound_origin: Some(origin), + }; + this.with(scope, |this| { + this.visit_ty(&bounded_ty); + walk_list!(this, visit_param_bound, bounds); + }) + } + &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { + ref lifetime, + bounds, + .. + }) => { + this.visit_lifetime(lifetime); + walk_list!(this, visit_param_bound, bounds); + + if lifetime.name != hir::LifetimeName::Static { + for bound in bounds { + let hir::GenericBound::Outlives(ref lt) = bound else { + continue; + }; + if lt.name != hir::LifetimeName::Static { + continue; + } + this.insert_lifetime(lt, Region::Static); + this.tcx + .sess + .struct_span_warn( + lifetime.span, + &format!( + "unnecessary lifetime parameter `{}`", + lifetime.name.ident(), + ), + ) + .help(&format!( + "you can use the `'static` lifetime directly, in place of `{}`", + lifetime.name.ident(), + )) + .emit(); + } + } + } + &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { + ref lhs_ty, + ref rhs_ty, + .. + }) => { + this.visit_ty(lhs_ty); + this.visit_ty(rhs_ty); + } + } + } + }) + } + + fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) { + match bound { + hir::GenericBound::LangItemTrait(_, _, hir_id, _) => { + // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go + // through the regular poly trait ref code, so we don't get another + // chance to introduce a binder. For now, I'm keeping the existing logic + // of "if there isn't a Binder scope above us, add one", but I + // imagine there's a better way to go about this. + let (binders, scope_type) = self.poly_trait_ref_binder_info(); + + self.map.late_bound_vars.insert(*hir_id, binders); + let scope = Scope::Binder { + hir_id: *hir_id, + lifetimes: FxIndexMap::default(), + s: self.scope, + next_early_index: self.next_early_index(), + opaque_type_parent: false, + scope_type, + where_bound_origin: None, + }; + self.with(scope, |this| { + intravisit::walk_param_bound(this, bound); + }); + } + _ => intravisit::walk_param_bound(self, bound), + } + } + + fn visit_poly_trait_ref( + &mut self, + trait_ref: &'tcx hir::PolyTraitRef<'tcx>, + _modifier: hir::TraitBoundModifier, + ) { + debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref); + + let next_early_index = self.next_early_index(); + let (mut binders, scope_type) = self.poly_trait_ref_binder_info(); + + let initial_bound_vars = binders.len() as u32; + let mut lifetimes: FxIndexMap<LocalDefId, Region> = FxIndexMap::default(); + let binders_iter = trait_ref + .bound_generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = + Region::late(initial_bound_vars + late_bound_idx as u32, self.tcx.hir(), param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + lifetimes.insert(pair.0, pair.1); + r + }); + binders.extend(binders_iter); + + debug!(?binders); + self.map.late_bound_vars.insert(trait_ref.trait_ref.hir_ref_id, binders); + + // Always introduce a scope here, even if this is in a where clause and + // we introduced the binders around the bounded Ty. In that case, we + // just reuse the concatenation functionality also present in nested trait + // refs. + let scope = Scope::Binder { + hir_id: trait_ref.trait_ref.hir_ref_id, + lifetimes, + s: self.scope, + next_early_index, + opaque_type_parent: false, + scope_type, + where_bound_origin: None, + }; + self.with(scope, |this| { + walk_list!(this, visit_generic_param, trait_ref.bound_generic_params); + this.visit_trait_ref(&trait_ref.trait_ref); + }); + } +} + +fn compute_object_lifetime_defaults<'tcx>( + tcx: TyCtxt<'tcx>, + item: &hir::Item<'_>, +) -> Option<&'tcx [ObjectLifetimeDefault]> { + match item.kind { + hir::ItemKind::Struct(_, ref generics) + | hir::ItemKind::Union(_, ref generics) + | hir::ItemKind::Enum(_, ref generics) + | hir::ItemKind::OpaqueTy(hir::OpaqueTy { + ref generics, + origin: hir::OpaqueTyOrigin::TyAlias, + .. + }) + | hir::ItemKind::TyAlias(_, ref generics) + | hir::ItemKind::Trait(_, _, ref generics, ..) => { + let result = object_lifetime_defaults_for_item(tcx, generics); + + // Debugging aid. + let attrs = tcx.hir().attrs(item.hir_id()); + if tcx.sess.contains_name(attrs, sym::rustc_object_lifetime_default) { + let object_lifetime_default_reprs: String = result + .iter() + .map(|set| match *set { + Set1::Empty => "BaseDefault".into(), + Set1::One(Region::Static) => "'static".into(), + Set1::One(Region::EarlyBound(mut i, _)) => generics + .params + .iter() + .find_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + if i == 0 { + return Some(param.name.ident().to_string().into()); + } + i -= 1; + None + } + _ => None, + }) + .unwrap(), + Set1::One(_) => bug!(), + Set1::Many => "Ambiguous".into(), + }) + .collect::<Vec<Cow<'static, str>>>() + .join(","); + tcx.sess.span_err(item.span, &object_lifetime_default_reprs); + } + + Some(result) + } + _ => None, + } +} + +/// Scan the bounds and where-clauses on parameters to extract bounds +/// of the form `T:'a` so as to determine the `ObjectLifetimeDefault` +/// for each type parameter. +fn object_lifetime_defaults_for_item<'tcx>( + tcx: TyCtxt<'tcx>, + generics: &hir::Generics<'_>, +) -> &'tcx [ObjectLifetimeDefault] { + 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.normalize_to_macros_2_0()); + } + } + } + + let process_param = |param: &hir::GenericParam<'_>| match param.kind { + GenericParamKind::Lifetime { .. } => None, + GenericParamKind::Type { .. } => { + let mut set = Set1::Empty; + + let param_def_id = tcx.hir().local_def_id(param.hir_id); + for predicate in generics.predicates { + // Look for `type: ...` where clauses. + let hir::WherePredicate::BoundPredicate(ref data) = *predicate else { continue }; + + // Ignore `for<'a> type: ...` as they can change what + // lifetimes mean (although we could "just" handle it). + if !data.bound_generic_params.is_empty() { + continue; + } + + let res = match data.bounded_ty.kind { + hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => path.res, + _ => continue, + }; + + if res == Res::Def(DefKind::TyParam, param_def_id.to_def_id()) { + add_bounds(&mut set, &data.bounds); + } + } + + Some(match set { + Set1::Empty => Set1::Empty, + Set1::One(name) => { + if name == hir::LifetimeName::Static { + Set1::One(Region::Static) + } else { + generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + let param_def_id = tcx.hir().local_def_id(param.hir_id); + Some(( + param_def_id, + hir::LifetimeName::Param(param_def_id, param.name), + )) + } + _ => None, + }) + .enumerate() + .find(|&(_, (_, lt_name))| lt_name == name) + .map_or(Set1::Many, |(i, (def_id, _))| { + Set1::One(Region::EarlyBound(i as u32, def_id.to_def_id())) + }) + } + } + Set1::Many => Set1::Many, + }) + } + GenericParamKind::Const { .. } => { + // Generic consts don't impose any constraints. + // + // We still store a dummy value here to allow generic parameters + // in an arbitrary order. + Some(Set1::Empty) + } + }; + + tcx.arena.alloc_from_iter(generics.params.iter().filter_map(process_param)) +} + +impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { + fn with<F>(&mut self, wrap_scope: Scope<'_>, f: F) + where + F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>), + { + let LifetimeContext { tcx, map, .. } = self; + let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults); + let mut this = LifetimeContext { + tcx: *tcx, + map, + scope: &wrap_scope, + trait_definition_only: self.trait_definition_only, + xcrate_object_lifetime_defaults, + }; + let span = tracing::debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope)); + { + let _enter = span.enter(); + f(&mut this); + } + self.xcrate_object_lifetime_defaults = this.xcrate_object_lifetime_defaults; + } + + /// Visits self by adding a scope and handling recursive walk over the contents with `walk`. + /// + /// Handles visiting fns and methods. These are a bit complicated because we must distinguish + /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear + /// within type bounds; those are early bound lifetimes, and the rest are late bound. + /// + /// For example: + /// + /// fn foo<'a,'b,'c,T:Trait<'b>>(...) + /// + /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound + /// lifetimes may be interspersed together. + /// + /// If early bound lifetimes are present, we separate them into their own list (and likewise + /// for late bound). They will be numbered sequentially, starting from the lowest index that is + /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late + /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the + /// ordering is not important there. + fn visit_early_late<F>( + &mut self, + parent_id: Option<LocalDefId>, + hir_id: hir::HirId, + generics: &'tcx hir::Generics<'tcx>, + walk: F, + ) where + F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>), + { + // Find the start of nested early scopes, e.g., in methods. + let mut next_early_index = 0; + if let Some(parent_id) = parent_id { + let parent = self.tcx.hir().expect_item(parent_id); + if sub_items_have_self_param(&parent.kind) { + next_early_index += 1; // Self comes before lifetimes + } + match parent.kind { + hir::ItemKind::Trait(_, _, ref generics, ..) + | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) => { + next_early_index += generics.params.len() as u32; + } + _ => {} + } + } + + let mut non_lifetime_count = 0; + let mut named_late_bound_vars = 0; + let lifetimes: FxIndexMap<LocalDefId, Region> = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.tcx.is_late_bound(param.hir_id) { + let late_bound_idx = named_late_bound_vars; + named_late_bound_vars += 1; + Some(Region::late(late_bound_idx, self.tcx.hir(), param)) + } else { + Some(Region::early(self.tcx.hir(), &mut next_early_index, param)) + } + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); + let next_early_index = next_early_index + non_lifetime_count; + + let binders: Vec<_> = generics + .params + .iter() + .filter(|param| { + matches!(param.kind, GenericParamKind::Lifetime { .. }) + && self.tcx.is_late_bound(param.hir_id) + }) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = Region::late(late_bound_idx as u32, self.tcx.hir(), param); + late_region_as_bound_region(self.tcx, &pair.1) + }) + .collect(); + self.map.late_bound_vars.insert(hir_id, binders); + let scope = Scope::Binder { + hir_id, + lifetimes, + next_early_index, + s: self.scope, + opaque_type_parent: true, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, walk); + } + + fn next_early_index_helper(&self, only_opaque_type_parent: bool) -> u32 { + let mut scope = self.scope; + loop { + match *scope { + Scope::Root => return 0, + + Scope::Binder { next_early_index, opaque_type_parent, .. } + if (!only_opaque_type_parent || opaque_type_parent) => + { + return next_early_index; + } + + Scope::Binder { s, .. } + | Scope::Body { s, .. } + | Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => scope = s, + } + } + } + + /// Returns the next index one would use for an early-bound-region + /// if extending the current scope. + fn next_early_index(&self) -> u32 { + self.next_early_index_helper(true) + } + + /// Returns the next index one would use for an `impl Trait` that + /// is being converted into an opaque type alias `impl Trait`. This will be the + /// next early index from the enclosing item, for the most + /// part. See the `opaque_type_parent` field for more info. + fn next_early_index_for_opaque_type(&self) -> u32 { + self.next_early_index_helper(false) + } + + #[tracing::instrument(level = "debug", skip(self))] + fn resolve_lifetime_ref( + &mut self, + region_def_id: LocalDefId, + lifetime_ref: &'tcx hir::Lifetime, + ) { + // Walk up the scope chain, tracking the number of fn scopes + // that we pass through, until we find a lifetime with the + // given name or we run out of scopes. + // search. + let mut late_depth = 0; + let mut scope = self.scope; + let mut outermost_body = None; + let result = loop { + match *scope { + Scope::Body { id, s } => { + outermost_body = Some(id); + scope = s; + } + + Scope::Root => { + break None; + } + + Scope::Binder { ref lifetimes, scope_type, s, where_bound_origin, .. } => { + if let Some(&def) = lifetimes.get(®ion_def_id) { + break Some(def.shifted(late_depth)); + } + match scope_type { + BinderScopeType::Normal => late_depth += 1, + BinderScopeType::Concatenating => {} + } + // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in + // regular fns. + if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin + && let hir::LifetimeName::Param(_, hir::ParamName::Fresh) = lifetime_ref.name + && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner) + && !self.tcx.features().anonymous_lifetime_in_impl_trait + { + rustc_session::parse::feature_err( + &self.tcx.sess.parse_sess, + sym::anonymous_lifetime_in_impl_trait, + lifetime_ref.span, + "anonymous lifetimes in `impl Trait` are unstable", + ).emit(); + return; + } + scope = s; + } + + Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + }; + + if let Some(mut def) = result { + if let Region::EarlyBound(..) = def { + // Do not free early-bound regions, only late-bound ones. + } else if let Some(body_id) = outermost_body { + let fn_id = self.tcx.hir().body_owner(body_id); + match self.tcx.hir().get(fn_id) { + Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. }) + | Node::TraitItem(&hir::TraitItem { + kind: hir::TraitItemKind::Fn(..), .. + }) + | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => { + let scope = self.tcx.hir().local_def_id(fn_id); + def = Region::Free(scope.to_def_id(), def.id().unwrap()); + } + _ => {} + } + } + + self.insert_lifetime(lifetime_ref, def); + return; + } + + // We may fail to resolve higher-ranked lifetimes that are mentionned by APIT. + // AST-based resolution does not care for impl-trait desugaring, which are the + // responibility of lowering. This may create a mismatch between the resolution + // AST found (`region_def_id`) which points to HRTB, and what HIR allows. + // ``` + // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} + // ``` + // + // In such case, walk back the binders to diagnose it properly. + let mut scope = self.scope; + loop { + match *scope { + Scope::Binder { + where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), .. + } => { + let mut err = self.tcx.sess.struct_span_err( + lifetime_ref.span, + "`impl Trait` can only mention lifetimes bound at the fn or impl level", + ); + err.span_note(self.tcx.def_span(region_def_id), "lifetime declared here"); + err.emit(); + return; + } + Scope::Root => break, + Scope::Binder { s, .. } + | Scope::Body { s, .. } + | Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + } + + self.tcx.sess.delay_span_bug( + lifetime_ref.span, + &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,), + ); + } + + fn visit_segment_args( + &mut self, + res: Res, + depth: usize, + generic_args: &'tcx hir::GenericArgs<'tcx>, + ) { + debug!( + "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})", + res, depth, generic_args, + ); + + if generic_args.parenthesized { + self.visit_fn_like_elision( + generic_args.inputs(), + Some(generic_args.bindings[0].ty()), + false, + ); + return; + } + + for arg in generic_args.args { + if let hir::GenericArg::Lifetime(lt) = arg { + self.visit_lifetime(lt); + } + } + + // Figure out if this is a type/trait segment, + // which requires object lifetime defaults. + let parent_def_id = |this: &mut Self, def_id: DefId| { + let def_key = this.tcx.def_key(def_id); + DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") } + }; + let type_def_id = match res { + Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)), + Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)), + Res::Def( + DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::TyAlias + | DefKind::Trait, + def_id, + ) if depth == 0 => Some(def_id), + _ => None, + }; + + debug!("visit_segment_args: type_def_id={:?}", type_def_id); + + // Compute a vector of defaults, one for each type parameter, + // per the rules given in RFCs 599 and 1156. Example: + // + // ```rust + // struct Foo<'a, T: 'a, U> { } + // ``` + // + // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default + // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound) + // and `dyn Baz` to `dyn Baz + 'static` (because there is no + // such bound). + // + // Therefore, we would compute `object_lifetime_defaults` to a + // vector like `['x, 'static]`. Note that the vector only + // includes type parameters. + let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| { + let in_body = { + let mut scope = self.scope; + loop { + match *scope { + Scope::Root => break false, + + Scope::Body { .. } => break true, + + Scope::Binder { s, .. } + | Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + } + }; + + let map = &self.map; + let set_to_region = |set: &ObjectLifetimeDefault| match *set { + Set1::Empty => { + if in_body { + None + } else { + Some(Region::Static) + } + } + Set1::One(r) => { + let lifetimes = generic_args.args.iter().filter_map(|arg| match arg { + GenericArg::Lifetime(lt) => Some(lt), + _ => None, + }); + r.subst(lifetimes, map) + } + Set1::Many => None, + }; + if let Some(def_id) = def_id.as_local() { + let id = self.tcx.hir().local_def_id_to_hir_id(def_id); + self.tcx + .object_lifetime_defaults(id.owner) + .unwrap() + .iter() + .map(set_to_region) + .collect() + } else { + let tcx = self.tcx; + self.xcrate_object_lifetime_defaults + .entry(def_id) + .or_insert_with(|| { + tcx.generics_of(def_id) + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamDefKind::Type { object_lifetime_default, .. } => { + Some(object_lifetime_default) + } + GenericParamDefKind::Const { .. } => Some(Set1::Empty), + GenericParamDefKind::Lifetime => None, + }) + .collect() + }) + .iter() + .map(set_to_region) + .collect() + } + }); + + debug!("visit_segment_args: object_lifetime_defaults={:?}", object_lifetime_defaults); + + let mut i = 0; + for arg in generic_args.args { + match arg { + GenericArg::Lifetime(_) => {} + GenericArg::Type(ty) => { + if let Some(<) = object_lifetime_defaults.get(i) { + let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope }; + self.with(scope, |this| this.visit_ty(ty)); + } else { + self.visit_ty(ty); + } + i += 1; + } + GenericArg::Const(ct) => { + self.visit_anon_const(&ct.value); + i += 1; + } + GenericArg::Infer(inf) => { + self.visit_id(inf.hir_id); + i += 1; + } + } + } + + // Hack: when resolving the type `XX` in binding like `dyn + // Foo<'b, Item = XX>`, the current object-lifetime default + // would be to examine the trait `Foo` to check whether it has + // a lifetime bound declared on `Item`. e.g., if `Foo` is + // declared like so, then the default object lifetime bound in + // `XX` should be `'b`: + // + // ```rust + // trait Foo<'a> { + // type Item: 'a; + // } + // ``` + // + // but if we just have `type Item;`, then it would be + // `'static`. However, we don't get all of this logic correct. + // + // Instead, we do something hacky: if there are no lifetime parameters + // to the trait, then we simply use a default object lifetime + // bound of `'static`, because there is no other possibility. On the other hand, + // if there ARE lifetime parameters, then we require the user to give an + // explicit bound for now. + // + // This is intended to leave room for us to implement the + // correct behavior in the future. + let has_lifetime_parameter = + generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); + + // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or + // in the trait ref `YY<...>` in `Item: YY<...>`. + for binding in generic_args.bindings { + let scope = Scope::ObjectLifetimeDefault { + lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) }, + s: self.scope, + }; + if let Some(type_def_id) = type_def_id { + let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes( + self.tcx, + type_def_id, + binding.ident, + ); + self.with(scope, |this| { + let scope = Scope::Supertrait { + lifetimes: lifetimes.unwrap_or_default(), + s: this.scope, + }; + this.with(scope, |this| this.visit_assoc_type_binding(binding)); + }); + } else { + self.with(scope, |this| this.visit_assoc_type_binding(binding)); + } + } + } + + /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the + /// associated type name and starting trait. + /// For example, imagine we have + /// ```ignore (illustrative) + /// trait Foo<'a, 'b> { + /// type As; + /// } + /// trait Bar<'b>: for<'a> Foo<'a, 'b> {} + /// trait Bar: for<'b> Bar<'b> {} + /// ``` + /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on + /// the starting trait `Bar`, we would return `Some(['b, 'a])`. + fn supertrait_hrtb_lifetimes( + tcx: TyCtxt<'tcx>, + def_id: DefId, + assoc_name: Ident, + ) -> Option<Vec<ty::BoundVariableKind>> { + let trait_defines_associated_type_named = |trait_def_id: DefId| { + tcx.associated_items(trait_def_id) + .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id) + .is_some() + }; + + use smallvec::{smallvec, SmallVec}; + let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> = + smallvec![(def_id, smallvec![])]; + let mut visited: FxHashSet<DefId> = FxHashSet::default(); + loop { + let Some((def_id, bound_vars)) = stack.pop() else { + break None; + }; + // See issue #83753. If someone writes an associated type on a non-trait, just treat it as + // there being no supertrait HRTBs. + match tcx.def_kind(def_id) { + DefKind::Trait | DefKind::TraitAlias | DefKind::Impl => {} + _ => break None, + } + + if trait_defines_associated_type_named(def_id) { + break Some(bound_vars.into_iter().collect()); + } + let predicates = + tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name))); + let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| { + let bound_predicate = pred.kind(); + match bound_predicate.skip_binder() { + ty::PredicateKind::Trait(data) => { + // The order here needs to match what we would get from `subst_supertrait` + let pred_bound_vars = bound_predicate.bound_vars(); + let mut all_bound_vars = bound_vars.clone(); + all_bound_vars.extend(pred_bound_vars.iter()); + let super_def_id = data.trait_ref.def_id; + Some((super_def_id, all_bound_vars)) + } + _ => None, + } + }); + + let obligations = obligations.filter(|o| visited.insert(o.0)); + stack.extend(obligations); + } + } + + #[tracing::instrument(level = "debug", skip(self))] + fn visit_fn_like_elision( + &mut self, + inputs: &'tcx [hir::Ty<'tcx>], + output: Option<&'tcx hir::Ty<'tcx>>, + in_closure: bool, + ) { + self.with(Scope::Elision { s: self.scope }, |this| { + for input in inputs { + this.visit_ty(input); + } + if !in_closure && let Some(output) = output { + this.visit_ty(output); + } + }); + if in_closure && let Some(output) = output { + self.visit_ty(output); + } + } + + fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) { + debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref); + let mut late_depth = 0; + let mut scope = self.scope; + let lifetime = loop { + match *scope { + Scope::Binder { s, scope_type, .. } => { + match scope_type { + BinderScopeType::Normal => late_depth += 1, + BinderScopeType::Concatenating => {} + } + scope = s; + } + + Scope::Root | Scope::Elision { .. } => break Region::Static, + + Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return, + + Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l, + + Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + }; + self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth)); + } + + #[tracing::instrument(level = "debug", skip(self))] + fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) { + debug!( + node = ?self.tcx.hir().node_to_string(lifetime_ref.hir_id), + span = ?self.tcx.sess.source_map().span_to_diagnostic_string(lifetime_ref.span) + ); + self.map.defs.insert(lifetime_ref.hir_id, def); + } + + /// Sometimes we resolve a lifetime, but later find that it is an + /// error (esp. around impl trait). In that case, we remove the + /// entry into `map.defs` so as not to confuse later code. + fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) { + let old_value = self.map.defs.remove(&lifetime_ref.hir_id); + assert_eq!(old_value, Some(bad_def)); + } +} + +/// Detects late-bound lifetimes and inserts them into +/// `late_bound`. +/// +/// A region declared on a fn is **late-bound** if: +/// - it is constrained by an argument type; +/// - it does not appear in a where-clause. +/// +/// "Constrained" basically means that it appears in any type but +/// not amongst the inputs to a projection. In other words, `<&'a +/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`. +fn is_late_bound_map(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<&FxIndexSet<LocalDefId>> { + let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); + let decl = tcx.hir().fn_decl_by_hir_id(hir_id)?; + let generics = tcx.hir().get_generics(def_id)?; + + let mut late_bound = FxIndexSet::default(); + + let mut constrained_by_input = ConstrainedCollector::default(); + for arg_ty in decl.inputs { + constrained_by_input.visit_ty(arg_ty); + } + + let mut appears_in_output = AllCollector::default(); + intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); + + debug!(?constrained_by_input.regions); + + // Walk the lifetimes that appear in where clauses. + // + // Subtle point: because we disallow nested bindings, we can just + // ignore binders here and scrape up all names we see. + let mut appears_in_where_clause = AllCollector::default(); + appears_in_where_clause.visit_generics(generics); + debug!(?appears_in_where_clause.regions); + + // Late bound regions are those that: + // - appear in the inputs + // - do not appear in the where-clauses + // - are not implicitly captured by `impl Trait` + for param in generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => { /* fall through */ } + + // Neither types nor consts are late-bound. + hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue, + } + + let param_def_id = tcx.hir().local_def_id(param.hir_id); + + // appears in the where clauses? early-bound. + if appears_in_where_clause.regions.contains(¶m_def_id) { + continue; + } + + // does not appear in the inputs, but appears in the return type? early-bound. + if !constrained_by_input.regions.contains(¶m_def_id) + && appears_in_output.regions.contains(¶m_def_id) + { + continue; + } + + debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.hir_id); + + let inserted = late_bound.insert(param_def_id); + assert!(inserted, "visited lifetime {:?} twice", param.hir_id); + } + + debug!(?late_bound); + return Some(tcx.arena.alloc(late_bound)); + + #[derive(Default)] + struct ConstrainedCollector { + regions: FxHashSet<LocalDefId>, + } + + impl<'v> Visitor<'v> for ConstrainedCollector { + fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { + match ty.kind { + hir::TyKind::Path( + hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..), + ) => { + // ignore lifetimes appearing in associated type + // projections, as they are not *constrained* + // (defined above) + } + + hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => { + // consider only the lifetimes on the final + // segment; I am not sure it's even currently + // valid to have them elsewhere, but even if it + // is, those would be potentially inputs to + // projections + if let Some(last_segment) = path.segments.last() { + self.visit_path_segment(path.span, last_segment); + } + } + + _ => { + intravisit::walk_ty(self, ty); + } + } + } + + fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { + if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name { + self.regions.insert(def_id); + } + } + } + + #[derive(Default)] + struct AllCollector { + regions: FxHashSet<LocalDefId>, + } + + impl<'v> Visitor<'v> for AllCollector { + fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { + if let hir::LifetimeName::Param(def_id, _) = lifetime_ref.name { + self.regions.insert(def_id); + } + } + } +} diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs new file mode 100644 index 000000000..62843c651 --- /dev/null +++ b/compiler/rustc_resolve/src/lib.rs @@ -0,0 +1,2089 @@ +//! This crate is responsible for the part of name resolution that doesn't require type checker. +//! +//! Module structure of the crate is built here. +//! Paths in macros, imports, expressions, types, patterns are resolved here. +//! Label and lifetime names are resolved here as well. +//! +//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_typeck`. + +#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] +#![feature(box_patterns)] +#![feature(drain_filter)] +#![feature(if_let_guard)] +#![feature(iter_intersperse)] +#![feature(let_chains)] +#![feature(let_else)] +#![feature(never_type)] +#![recursion_limit = "256"] +#![allow(rustdoc::private_intra_doc_links)] +#![allow(rustc::potential_query_instability)] + +#[macro_use] +extern crate tracing; + +pub use rustc_hir::def::{Namespace, PerNS}; + +use rustc_arena::{DroplessArena, TypedArena}; +use rustc_ast::node_id::NodeMap; +use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID}; +use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_data_structures::intern::Interned; +use rustc_data_structures::sync::Lrc; +use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed}; +use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind}; +use rustc_hir::def::Namespace::*; +use rustc_hir::def::{self, CtorOf, DefKind, LifetimeRes, PartialRes}; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId}; +use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::definitions::{DefPathData, Definitions}; +use rustc_hir::TraitCandidate; +use rustc_index::vec::IndexVec; +use rustc_metadata::creader::{CStore, CrateLoader}; +use rustc_middle::metadata::ModChild; +use rustc_middle::middle::privacy::AccessLevels; +use rustc_middle::span_bug; +use rustc_middle::ty::query::Providers; +use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, ResolverOutputs}; +use rustc_query_system::ich::StableHashingContext; +use rustc_session::cstore::{CrateStore, CrateStoreDyn, MetadataLoaderDyn}; +use rustc_session::lint::LintBuffer; +use rustc_session::Session; +use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}; +use rustc_span::source_map::Spanned; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::{Span, DUMMY_SP}; + +use smallvec::{smallvec, SmallVec}; +use std::cell::{Cell, RefCell}; +use std::collections::BTreeSet; +use std::{cmp, fmt, ptr}; +use tracing::debug; + +use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; +use imports::{Import, ImportKind, ImportResolver, NameResolution}; +use late::{HasGenericParams, PathSource, PatternSource}; +use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; + +use crate::access_levels::AccessLevelsVisitor; + +type Res = def::Res<NodeId>; + +mod access_levels; +mod build_reduced_graph; +mod check_unused; +mod def_collector; +mod diagnostics; +mod ident; +mod imports; +mod late; +mod macros; + +enum Weak { + Yes, + No, +} + +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Determinacy { + Determined, + Undetermined, +} + +impl Determinacy { + fn determined(determined: bool) -> Determinacy { + if determined { Determinacy::Determined } else { Determinacy::Undetermined } + } +} + +/// A specific scope in which a name can be looked up. +/// This enum is currently used only for early resolution (imports and macros), +/// but not for late resolution yet. +#[derive(Clone, Copy)] +enum Scope<'a> { + DeriveHelpers(LocalExpnId), + DeriveHelpersCompat, + MacroRules(MacroRulesScopeRef<'a>), + CrateRoot, + // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK` + // lint if it should be reported. + Module(Module<'a>, Option<NodeId>), + RegisteredAttrs, + MacroUsePrelude, + BuiltinAttrs, + ExternPrelude, + ToolPrelude, + StdLibPrelude, + BuiltinTypes, +} + +/// Names from different contexts may want to visit different subsets of all specific scopes +/// with different restrictions when looking up the resolution. +/// This enum is currently used only for early resolution (imports and macros), +/// but not for late resolution yet. +#[derive(Clone, Copy)] +enum ScopeSet<'a> { + /// All scopes with the given namespace. + All(Namespace, /*is_import*/ bool), + /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros). + AbsolutePath(Namespace), + /// All scopes with macro namespace and the given macro kind restriction. + Macro(MacroKind), + /// All scopes with the given namespace, used for partially performing late resolution. + /// The node id enables lints and is used for reporting them. + Late(Namespace, Module<'a>, Option<NodeId>), +} + +/// Everything you need to know about a name's location to resolve it. +/// Serves as a starting point for the scope visitor. +/// This struct is currently used only for early resolution (imports and macros), +/// but not for late resolution yet. +#[derive(Clone, Copy, Debug)] +pub struct ParentScope<'a> { + pub module: Module<'a>, + expansion: LocalExpnId, + pub macro_rules: MacroRulesScopeRef<'a>, + derives: &'a [ast::Path], +} + +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>, resolver: &Resolver<'a>) -> ParentScope<'a> { + ParentScope { + module, + expansion: LocalExpnId::ROOT, + macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty), + derives: &[], + } + } +} + +#[derive(Copy, Debug, Clone)] +enum ImplTraitContext { + Existential, + Universal(LocalDefId), +} + +#[derive(Eq)] +struct BindingError { + name: Symbol, + origin: BTreeSet<Span>, + target: BTreeSet<Span>, + could_be_path: bool, +} + +impl PartialOrd for BindingError { + fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl PartialEq for BindingError { + fn eq(&self, other: &BindingError) -> bool { + self.name == other.name + } +} + +impl Ord for BindingError { + fn cmp(&self, other: &BindingError) -> cmp::Ordering { + self.name.cmp(&other.name) + } +} + +enum ResolutionError<'a> { + /// Error E0401: can't use type or const parameters from outer function. + GenericParamsFromOuterFunction(Res, HasGenericParams), + /// Error E0403: the name is already used for a type or const parameter in this generic + /// parameter list. + NameAlreadyUsedInParameterList(Symbol, Span), + /// Error E0407: method is not a member of trait. + MethodNotMemberOfTrait(Ident, String, Option<Symbol>), + /// Error E0437: type is not a member of trait. + TypeNotMemberOfTrait(Ident, String, Option<Symbol>), + /// Error E0438: const is not a member of trait. + ConstNotMemberOfTrait(Ident, String, Option<Symbol>), + /// Error E0408: variable `{}` is not bound in all patterns. + VariableNotBoundInPattern(BindingError, ParentScope<'a>), + /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm. + VariableBoundWithDifferentMode(Symbol, Span), + /// Error E0415: identifier is bound more than once in this parameter list. + IdentifierBoundMoreThanOnceInParameterList(Symbol), + /// Error E0416: identifier is bound more than once in the same pattern. + IdentifierBoundMoreThanOnceInSamePattern(Symbol), + /// Error E0426: use of undeclared label. + UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> }, + /// Error E0429: `self` imports are only allowed within a `{ }` list. + SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span }, + /// Error E0430: `self` import can only appear once in the list. + SelfImportCanOnlyAppearOnceInTheList, + /// Error E0431: `self` import can only appear in an import list with a non-empty prefix. + SelfImportOnlyInImportListWithNonEmptyPrefix, + /// Error E0433: failed to resolve. + FailedToResolve { label: String, suggestion: Option<Suggestion> }, + /// Error E0434: can't capture dynamic environment in a fn item. + CannotCaptureDynamicEnvironmentInFnItem, + /// Error E0435: attempt to use a non-constant value in a constant. + AttemptToUseNonConstantValueInConstant( + Ident, + /* suggestion */ &'static str, + /* current */ &'static str, + ), + /// Error E0530: `X` bindings cannot shadow `Y`s. + BindingShadowsSomethingUnacceptable { + shadowing_binding: PatternSource, + name: Symbol, + participle: &'static str, + article: &'static str, + shadowed_binding: Res, + shadowed_binding_span: Span, + }, + /// Error E0128: generic parameters with a default cannot use forward-declared identifiers. + ForwardDeclaredGenericParam, + /// ERROR E0770: the type of const parameters must not depend on other generic parameters. + ParamInTyOfConstParam(Symbol), + /// generic parameters must not be used inside const evaluations. + /// + /// This error is only emitted when using `min_const_generics`. + ParamInNonTrivialAnonConst { name: Symbol, is_type: bool }, + /// Error E0735: generic parameters with a default cannot use `Self` + SelfInGenericParamDefault, + /// Error E0767: use of unreachable label + UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> }, + /// Error E0323, E0324, E0325: mismatch between trait item and impl item. + TraitImplMismatch { + name: Symbol, + kind: &'static str, + trait_path: String, + trait_item_span: Span, + code: rustc_errors::DiagnosticId, + }, + /// Inline asm `sym` operand must refer to a `fn` or `static`. + InvalidAsmSym, +} + +enum VisResolutionError<'a> { + Relative2018(Span, &'a ast::Path), + AncestorOnly(Span), + FailedToResolve(Span, String, Option<Suggestion>), + ExpectedFound(Span, String, Res), + Indeterminate(Span), + ModuleOnly(Span), +} + +/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path +/// segments' which don't have the rest of an AST or HIR `PathSegment`. +#[derive(Clone, Copy, Debug)] +pub struct Segment { + ident: Ident, + id: Option<NodeId>, + /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing + /// nonsensical suggestions. + has_generic_args: bool, + /// Signals whether this `PathSegment` has lifetime arguments. + has_lifetime_args: bool, + args_span: Span, +} + +impl Segment { + fn from_path(path: &Path) -> Vec<Segment> { + path.segments.iter().map(|s| s.into()).collect() + } + + fn from_ident(ident: Ident) -> Segment { + Segment { + ident, + id: None, + has_generic_args: false, + has_lifetime_args: false, + args_span: DUMMY_SP, + } + } + + fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment { + Segment { + ident, + id: Some(id), + has_generic_args: false, + has_lifetime_args: false, + args_span: DUMMY_SP, + } + } + + fn names_to_string(segments: &[Segment]) -> String { + names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) + } +} + +impl<'a> From<&'a ast::PathSegment> for Segment { + fn from(seg: &'a ast::PathSegment) -> Segment { + let has_generic_args = seg.args.is_some(); + let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() { + match args { + GenericArgs::AngleBracketed(args) => { + let found_lifetimes = args + .args + .iter() + .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_)))); + (args.span, found_lifetimes) + } + GenericArgs::Parenthesized(args) => (args.span, true), + } + } else { + (DUMMY_SP, false) + }; + Segment { + ident: seg.ident, + id: Some(seg.id), + has_generic_args, + has_lifetime_args, + args_span, + } + } +} + +/// An intermediate resolution result. +/// +/// This refers to the thing referred by a name. The difference between `Res` and `Item` is that +/// items are visible in their whole block, while `Res`es only from the place they are defined +/// forward. +#[derive(Debug)] +enum LexicalScopeBinding<'a> { + Item(&'a NameBinding<'a>), + Res(Res), +} + +impl<'a> LexicalScopeBinding<'a> { + fn res(self) -> Res { + match self { + LexicalScopeBinding::Item(binding) => binding.res(), + LexicalScopeBinding::Res(res) => res, + } + } +} + +#[derive(Copy, Clone, Debug)] +enum ModuleOrUniformRoot<'a> { + /// Regular module. + Module(Module<'a>), + + /// Virtual module that denotes resolution in crate root with fallback to extern prelude. + CrateRootAndExternPrelude, + + /// Virtual module that denotes resolution in extern prelude. + /// Used for paths starting with `::` on 2018 edition. + ExternPrelude, + + /// Virtual module that denotes resolution in current scope. + /// Used only for resolving single-segment imports. The reason it exists is that import paths + /// are always split into two parts, the first of which should be some kind of module. + CurrentScope, +} + +impl ModuleOrUniformRoot<'_> { + fn same_def(lhs: Self, rhs: Self) -> bool { + match (lhs, rhs) { + (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { + ptr::eq(lhs, rhs) + } + ( + ModuleOrUniformRoot::CrateRootAndExternPrelude, + ModuleOrUniformRoot::CrateRootAndExternPrelude, + ) + | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) + | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true, + _ => false, + } + } +} + +#[derive(Clone, Debug)] +enum PathResult<'a> { + Module(ModuleOrUniformRoot<'a>), + NonModule(PartialRes), + Indeterminate, + Failed { + span: Span, + label: String, + suggestion: Option<Suggestion>, + is_error_from_last_segment: bool, + }, +} + +impl<'a> PathResult<'a> { + fn failed( + span: Span, + is_error_from_last_segment: bool, + finalize: bool, + label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>), + ) -> PathResult<'a> { + let (label, suggestion) = + if finalize { label_and_suggestion() } else { (String::new(), None) }; + PathResult::Failed { span, label, suggestion, is_error_from_last_segment } + } +} + +#[derive(Debug)] +enum ModuleKind { + /// An anonymous module; e.g., just a block. + /// + /// ``` + /// fn main() { + /// fn f() {} // (1) + /// { // This is an anonymous module + /// f(); // This resolves to (2) as we are inside the block. + /// fn f() {} // (2) + /// } + /// f(); // Resolves to (1) + /// } + /// ``` + Block, + /// Any module with a name. + /// + /// This could be: + /// + /// * A normal module – either `mod from_file;` or `mod from_block { }` – + /// or the crate root (which is conceptually a top-level module). + /// Note that the crate root's [name][Self::name] will be [`kw::Empty`]. + /// * A trait or an enum (it implicitly contains associated types, methods and variant + /// constructors). + Def(DefKind, DefId, Symbol), +} + +impl ModuleKind { + /// Get name of the module. + pub fn name(&self) -> Option<Symbol> { + match self { + ModuleKind::Block => None, + ModuleKind::Def(.., name) => Some(*name), + } + } +} + +/// A key that identifies a binding in a given `Module`. +/// +/// Multiple bindings in the same module can have the same key (in a valid +/// program) if all but one of them come from glob imports. +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +struct BindingKey { + /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the + /// identifier. + ident: Ident, + ns: Namespace, + /// 0 if ident is not `_`, otherwise a value that's unique to the specific + /// `_` in the expanded AST that introduced this binding. + disambiguator: u32, +} + +type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>; + +/// One node in the tree of modules. +/// +/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: +/// +/// * `mod` +/// * crate root (aka, top-level anonymous module) +/// * `enum` +/// * `trait` +/// * curly-braced block with statements +/// +/// You can use [`ModuleData::kind`] to determine the kind of module this is. +pub struct ModuleData<'a> { + /// The direct parent module (it may not be a `mod`, however). + parent: Option<Module<'a>>, + /// What kind of module this is, because this may not be a `mod`. + kind: ModuleKind, + + /// Mapping between names and their (possibly in-progress) resolutions in this module. + /// Resolutions in modules from other crates are not populated until accessed. + lazy_resolutions: Resolutions<'a>, + /// True if this is a module from other crate that needs to be populated on access. + populate_on_access: Cell<bool>, + + /// Macro invocations that can expand into items in this module. + unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>, + + /// Whether `#[no_implicit_prelude]` is active. + no_implicit_prelude: bool, + + glob_importers: RefCell<Vec<&'a Import<'a>>>, + globs: RefCell<Vec<&'a Import<'a>>>, + + /// Used to memoize the traits in this module for faster searches through all traits in scope. + traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>, + + /// Span of the module itself. Used for error reporting. + span: Span, + + expansion: ExpnId, +} + +type Module<'a> = &'a ModuleData<'a>; + +impl<'a> ModuleData<'a> { + fn new( + parent: Option<Module<'a>>, + kind: ModuleKind, + expansion: ExpnId, + span: Span, + no_implicit_prelude: bool, + ) -> Self { + let is_foreign = match kind { + ModuleKind::Def(_, def_id, _) => !def_id.is_local(), + ModuleKind::Block => false, + }; + ModuleData { + parent, + kind, + lazy_resolutions: Default::default(), + populate_on_access: Cell::new(is_foreign), + unexpanded_invocations: Default::default(), + no_implicit_prelude, + glob_importers: RefCell::new(Vec::new()), + globs: RefCell::new(Vec::new()), + traits: RefCell::new(None), + span, + expansion, + } + } + + fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F) + where + R: AsMut<Resolver<'a>>, + F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), + { + for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { + if let Some(binding) = name_resolution.borrow().binding { + f(resolver, key.ident, key.ns, binding); + } + } + } + + /// This modifies `self` in place. The traits will be stored in `self.traits`. + fn ensure_traits<R>(&'a self, resolver: &mut R) + where + R: AsMut<Resolver<'a>>, + { + let mut traits = self.traits.borrow_mut(); + if traits.is_none() { + let mut collected_traits = Vec::new(); + self.for_each_child(resolver, |_, name, ns, binding| { + if ns != TypeNS { + return; + } + if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { + collected_traits.push((name, binding)) + } + }); + *traits = Some(collected_traits.into_boxed_slice()); + } + } + + fn res(&self) -> Option<Res> { + match self.kind { + ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), + _ => None, + } + } + + // Public for rustdoc. + pub fn def_id(&self) -> DefId { + self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") + } + + fn opt_def_id(&self) -> Option<DefId> { + match self.kind { + ModuleKind::Def(_, def_id, _) => Some(def_id), + _ => None, + } + } + + // `self` resolves to the first module ancestor that `is_normal`. + fn is_normal(&self) -> bool { + matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) + } + + fn is_trait(&self) -> bool { + matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) + } + + fn nearest_item_scope(&'a self) -> Module<'a> { + match self.kind { + ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { + self.parent.expect("enum or trait module without a parent") + } + _ => self, + } + } + + /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). + /// This may be the crate root. + fn nearest_parent_mod(&self) -> DefId { + match self.kind { + ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, + _ => self.parent.expect("non-root module without parent").nearest_parent_mod(), + } + } + + fn is_ancestor_of(&self, mut other: &Self) -> bool { + while !ptr::eq(self, other) { + if let Some(parent) = other.parent { + other = parent; + } else { + return false; + } + } + true + } +} + +impl<'a> fmt::Debug for ModuleData<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.res()) + } +} + +/// Records a possibly-private value, type, or module definition. +#[derive(Clone, Debug)] +pub struct NameBinding<'a> { + kind: NameBindingKind<'a>, + ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>, + expansion: LocalExpnId, + span: Span, + vis: ty::Visibility, +} + +pub trait ToNameBinding<'a> { + fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>; +} + +impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> { + fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { + self + } +} + +#[derive(Clone, Debug)] +enum NameBindingKind<'a> { + Res(Res, /* is_macro_export */ bool), + Module(Module<'a>), + Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> }, +} + +impl<'a> NameBindingKind<'a> { + /// Is this a name binding of an import? + fn is_import(&self) -> bool { + matches!(*self, NameBindingKind::Import { .. }) + } +} + +struct PrivacyError<'a> { + ident: Ident, + binding: &'a NameBinding<'a>, + dedup_span: Span, +} + +struct UseError<'a> { + err: DiagnosticBuilder<'a, ErrorGuaranteed>, + /// Candidates which user could `use` to access the missing type. + candidates: Vec<ImportSuggestion>, + /// The `DefId` of the module to place the use-statements in. + def_id: DefId, + /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`). + instead: bool, + /// Extra free-form suggestion. + suggestion: Option<(Span, &'static str, String, Applicability)>, + /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling + /// the user to import the item directly. + path: Vec<Segment>, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum AmbiguityKind { + Import, + BuiltinAttr, + DeriveHelper, + MacroRulesVsModularized, + GlobVsOuter, + GlobVsGlob, + GlobVsExpanded, + MoreExpandedVsOuter, +} + +impl AmbiguityKind { + fn descr(self) -> &'static str { + match self { + AmbiguityKind::Import => "multiple potential import sources", + AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute", + AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute", + AmbiguityKind::MacroRulesVsModularized => { + "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module" + } + AmbiguityKind::GlobVsOuter => { + "a conflict between a name from a glob import and an outer scope during import or macro resolution" + } + AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module", + AmbiguityKind::GlobVsExpanded => { + "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution" + } + AmbiguityKind::MoreExpandedVsOuter => { + "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution" + } + } + } +} + +/// Miscellaneous bits of metadata for better ambiguity error reporting. +#[derive(Clone, Copy, PartialEq)] +enum AmbiguityErrorMisc { + SuggestCrate, + SuggestSelf, + FromPrelude, + None, +} + +struct AmbiguityError<'a> { + kind: AmbiguityKind, + ident: Ident, + b1: &'a NameBinding<'a>, + b2: &'a NameBinding<'a>, + misc1: AmbiguityErrorMisc, + misc2: AmbiguityErrorMisc, +} + +impl<'a> NameBinding<'a> { + fn module(&self) -> Option<Module<'a>> { + match self.kind { + NameBindingKind::Module(module) => Some(module), + NameBindingKind::Import { binding, .. } => binding.module(), + _ => None, + } + } + + fn res(&self) -> Res { + match self.kind { + NameBindingKind::Res(res, _) => res, + NameBindingKind::Module(module) => module.res().unwrap(), + NameBindingKind::Import { binding, .. } => binding.res(), + } + } + + fn is_ambiguity(&self) -> bool { + self.ambiguity.is_some() + || match self.kind { + NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), + _ => false, + } + } + + fn is_possibly_imported_variant(&self) -> bool { + match self.kind { + NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), + NameBindingKind::Res( + Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _), + _, + ) => true, + NameBindingKind::Res(..) | NameBindingKind::Module(..) => false, + } + } + + fn is_extern_crate(&self) -> bool { + match self.kind { + NameBindingKind::Import { + import: &Import { kind: ImportKind::ExternCrate { .. }, .. }, + .. + } => true, + NameBindingKind::Module(&ModuleData { + kind: ModuleKind::Def(DefKind::Mod, def_id, _), + .. + }) => def_id.is_crate_root(), + _ => false, + } + } + + fn is_import(&self) -> bool { + matches!(self.kind, NameBindingKind::Import { .. }) + } + + fn is_glob_import(&self) -> bool { + match self.kind { + NameBindingKind::Import { import, .. } => import.is_glob(), + _ => false, + } + } + + fn is_importable(&self) -> bool { + !matches!( + self.res(), + Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) + ) + } + + fn macro_kind(&self) -> Option<MacroKind> { + self.res().macro_kind() + } + + // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` + // at some expansion round `max(invoc, binding)` when they both emerged from macros. + // Then this function returns `true` if `self` may emerge from a macro *after* that + // in some later round and screw up our previously found resolution. + // See more detailed explanation in + // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049 + fn may_appear_after( + &self, + invoc_parent_expansion: LocalExpnId, + binding: &NameBinding<'_>, + ) -> bool { + // self > max(invoc, binding) => !(self <= invoc || self <= binding) + // Expansions are partially ordered, so "may appear after" is an inversion of + // "certainly appears before or simultaneously" and includes unordered cases. + let self_parent_expansion = self.expansion; + let other_parent_expansion = binding.expansion; + let certainly_before_other_or_simultaneously = + other_parent_expansion.is_descendant_of(self_parent_expansion); + let certainly_before_invoc_or_simultaneously = + invoc_parent_expansion.is_descendant_of(self_parent_expansion); + !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously) + } +} + +#[derive(Debug, Default, Clone)] +pub struct ExternPreludeEntry<'a> { + extern_crate_item: Option<&'a NameBinding<'a>>, + pub introduced_by_item: bool, +} + +/// Used for better errors for E0773 +enum BuiltinMacroState { + NotYetSeen(SyntaxExtensionKind), + AlreadySeen(Span), +} + +struct DeriveData { + resolutions: DeriveResolutions, + helper_attrs: Vec<(usize, Ident)>, + has_derive_copy: bool, +} + +#[derive(Clone)] +struct MacroData { + ext: Lrc<SyntaxExtension>, + macro_rules: bool, +} + +/// The main resolver class. +/// +/// This is the visitor that walks the whole crate. +pub struct Resolver<'a> { + session: &'a Session, + + definitions: Definitions, + /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. + expn_that_defined: FxHashMap<LocalDefId, ExpnId>, + /// Reference span for definitions. + source_span: IndexVec<LocalDefId, Span>, + + graph_root: Module<'a>, + + prelude: Option<Module<'a>>, + extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>, + + /// N.B., this is used only for better diagnostics, not name resolution itself. + has_self: FxHashSet<DefId>, + + /// Names of fields of an item `DefId` accessible with dot syntax. + /// Used for hints during error reporting. + field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>, + + /// All imports known to succeed or fail. + determined_imports: Vec<&'a Import<'a>>, + + /// All non-determined imports. + indeterminate_imports: Vec<&'a Import<'a>>, + + // Spans for local variables found during pattern resolution. + // Used for suggestions during error reporting. + pat_span_map: NodeMap<Span>, + + /// Resolutions for nodes that have a single resolution. + partial_res_map: NodeMap<PartialRes>, + /// Resolutions for import nodes, which have multiple resolutions in different namespaces. + import_res_map: NodeMap<PerNS<Option<Res>>>, + /// Resolutions for labels (node IDs of their corresponding blocks or loops). + label_res_map: NodeMap<NodeId>, + /// Resolutions for lifetimes. + lifetimes_res_map: NodeMap<LifetimeRes>, + /// Mapping from generics `def_id`s to TAIT generics `def_id`s. + /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic + /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this + /// field from the original parameter 'a to the new parameter 'a1. + generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>, + /// Lifetime parameters that lowering will have to introduce. + extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>, + + /// `CrateNum` resolutions of `extern crate` items. + extern_crate_map: FxHashMap<LocalDefId, CrateNum>, + reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>, + trait_map: NodeMap<Vec<TraitCandidate>>, + + /// A map from nodes to anonymous modules. + /// Anonymous modules are pseudo-modules that are implicitly created around items + /// contained within blocks. + /// + /// For example, if we have this: + /// + /// fn f() { + /// fn g() { + /// ... + /// } + /// } + /// + /// There will be an anonymous module created around `g` with the ID of the + /// entry block for `f`. + block_map: NodeMap<Module<'a>>, + /// A fake module that contains no definition and no prelude. Used so that + /// some AST passes can generate identifiers that only resolve to local or + /// language items. + empty_module: Module<'a>, + module_map: FxHashMap<DefId, Module<'a>>, + binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>, + underscore_disambiguator: u32, + + /// Maps glob imports to the names of items actually imported. + glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>, + /// Visibilities in "lowered" form, for all entities that have them. + visibilities: FxHashMap<LocalDefId, ty::Visibility>, + has_pub_restricted: bool, + used_imports: FxHashSet<NodeId>, + maybe_unused_trait_imports: FxIndexSet<LocalDefId>, + maybe_unused_extern_crates: Vec<(LocalDefId, Span)>, + + /// Privacy errors are delayed until the end in order to deduplicate them. + privacy_errors: Vec<PrivacyError<'a>>, + /// Ambiguity errors are delayed for deduplication. + ambiguity_errors: Vec<AmbiguityError<'a>>, + /// `use` injections are delayed for better placement and deduplication. + use_injections: Vec<UseError<'a>>, + /// Crate-local macro expanded `macro_export` referred to by a module-relative path. + macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>, + + arenas: &'a ResolverArenas<'a>, + dummy_binding: &'a NameBinding<'a>, + + crate_loader: CrateLoader<'a>, + macro_names: FxHashSet<Ident>, + builtin_macros: FxHashMap<Symbol, BuiltinMacroState>, + /// A small map keeping true kinds of built-in macros that appear to be fn-like on + /// the surface (`macro` items in libcore), but are actually attributes or derives. + builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>, + registered_attrs: FxHashSet<Ident>, + registered_tools: RegisteredTools, + macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>, + macro_map: FxHashMap<DefId, MacroData>, + dummy_ext_bang: Lrc<SyntaxExtension>, + dummy_ext_derive: Lrc<SyntaxExtension>, + non_macro_attr: Lrc<SyntaxExtension>, + local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>, + ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>, + unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>, + unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>, + proc_macro_stubs: FxHashSet<LocalDefId>, + /// Traces collected during macro resolution and validated when it's complete. + single_segment_macro_resolutions: + Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>, + multi_segment_macro_resolutions: + Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>, + builtin_attrs: Vec<(Ident, ParentScope<'a>)>, + /// `derive(Copy)` marks items they are applied to so they are treated specially later. + /// Derive macros cannot modify the item themselves and have to store the markers in the global + /// context, so they attach the markers to derive container IDs using this resolver table. + containers_deriving_copy: FxHashSet<LocalExpnId>, + /// 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<LocalExpnId, ParentScope<'a>>, + /// `macro_rules` scopes *produced* by expanding the macro invocations, + /// include all the `macro_rules` items and other invocations generated by them. + output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>, + /// `macro_rules` scopes produced by `macro_rules` item definitions. + macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>, + /// Helper attributes that are in scope for the given expansion. + helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>, + /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute + /// with the given `ExpnId`. + derive_data: FxHashMap<LocalExpnId, DeriveData>, + + /// Avoid duplicated errors for "name already defined". + name_already_seen: FxHashMap<Symbol, Span>, + + potentially_unused_imports: Vec<&'a Import<'a>>, + + /// Table for mapping struct IDs into struct constructor IDs, + /// it's not used during normal resolution, only for better error reporting. + /// Also includes of list of each fields visibility + struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>, + + /// Features enabled for this crate. + active_features: FxHashSet<Symbol>, + + lint_buffer: LintBuffer, + + next_node_id: NodeId, + + node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>, + def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>, + + /// Indices of unnamed struct or variant fields with unresolved attributes. + placeholder_field_indices: FxHashMap<NodeId, usize>, + /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId` + /// we know what parent node that fragment should be attached to thanks to this table, + /// and how the `impl Trait` fragments were introduced. + invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>, + + /// Some way to know that we are in a *trait* impl in `visit_assoc_item`. + /// FIXME: Replace with a more general AST map (together with some other fields). + trait_impl_items: FxHashSet<LocalDefId>, + + legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>, + /// Amount of lifetime parameters for each item in the crate. + item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>, + + main_def: Option<MainDefinition>, + trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>, + /// A list of proc macro LocalDefIds, written out in the order in which + /// they are declared in the static array generated by proc_macro_harness. + proc_macros: Vec<NodeId>, + confused_type_with_std_module: FxHashMap<Span, Span>, + + access_levels: AccessLevels, +} + +/// Nothing really interesting here; it just provides memory for the rest of the crate. +#[derive(Default)] +pub struct ResolverArenas<'a> { + modules: TypedArena<ModuleData<'a>>, + local_modules: RefCell<Vec<Module<'a>>>, + imports: TypedArena<Import<'a>>, + name_resolutions: TypedArena<RefCell<NameResolution<'a>>>, + ast_paths: TypedArena<ast::Path>, + dropless: DroplessArena, +} + +impl<'a> ResolverArenas<'a> { + fn new_module( + &'a self, + parent: Option<Module<'a>>, + kind: ModuleKind, + expn_id: ExpnId, + span: Span, + no_implicit_prelude: bool, + module_map: &mut FxHashMap<DefId, Module<'a>>, + ) -> Module<'a> { + let module = + self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); + let def_id = module.opt_def_id(); + if def_id.map_or(true, |def_id| def_id.is_local()) { + self.local_modules.borrow_mut().push(module); + } + if let Some(def_id) = def_id { + module_map.insert(def_id, module); + } + module + } + fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> { + self.local_modules.borrow() + } + fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { + self.dropless.alloc(name_binding) + } + fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { + self.imports.alloc(import) + } + fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> { + self.name_resolutions.alloc(Default::default()) + } + fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { + Interned::new_unchecked(self.dropless.alloc(Cell::new(scope))) + } + fn alloc_macro_rules_binding( + &'a self, + binding: MacroRulesBinding<'a>, + ) -> &'a MacroRulesBinding<'a> { + self.dropless.alloc(binding) + } + fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] { + self.ast_paths.alloc_from_iter(paths.iter().cloned()) + } + fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] { + self.dropless.alloc_from_iter(spans) + } +} + +impl<'a> AsMut<Resolver<'a>> for Resolver<'a> { + fn as_mut(&mut self) -> &mut Resolver<'a> { + self + } +} + +impl<'a, 'b> DefIdTree for &'a Resolver<'b> { + #[inline] + fn opt_parent(self, id: DefId) -> Option<DefId> { + match id.as_local() { + Some(id) => self.definitions.def_key(id).parent, + None => self.cstore().def_key(id).parent, + } + .map(|index| DefId { index, ..id }) + } +} + +impl Resolver<'_> { + fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> { + self.node_id_to_def_id.get(&node).copied() + } + + pub fn local_def_id(&self, node: NodeId) -> LocalDefId { + self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) + } + + /// Adds a definition with a parent definition. + fn create_def( + &mut self, + parent: LocalDefId, + node_id: ast::NodeId, + data: DefPathData, + expn_id: ExpnId, + span: Span, + ) -> LocalDefId { + assert!( + !self.node_id_to_def_id.contains_key(&node_id), + "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", + node_id, + data, + self.definitions.def_key(self.node_id_to_def_id[&node_id]), + ); + + let def_id = self.definitions.create_def(parent, data); + + // Create the definition. + if expn_id != ExpnId::root() { + self.expn_that_defined.insert(def_id, expn_id); + } + + // A relative span's parent must be an absolute span. + debug_assert_eq!(span.data_untracked().parent, None); + let _id = self.source_span.push(span); + debug_assert_eq!(_id, def_id); + + // Some things for which we allocate `LocalDefId`s don't correspond to + // anything in the AST, so they don't have a `NodeId`. For these cases + // we don't need a mapping from `NodeId` to `LocalDefId`. + if node_id != ast::DUMMY_NODE_ID { + debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); + self.node_id_to_def_id.insert(node_id, def_id); + } + assert_eq!(self.def_id_to_node_id.push(node_id), def_id); + + def_id + } + + fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { + if let Some(def_id) = def_id.as_local() { + self.item_generics_num_lifetimes[&def_id] + } else { + self.cstore().item_generics_num_lifetimes(def_id, self.session) + } + } +} + +impl<'a> Resolver<'a> { + pub fn new( + session: &'a Session, + krate: &Crate, + crate_name: &str, + metadata_loader: Box<MetadataLoaderDyn>, + arenas: &'a ResolverArenas<'a>, + ) -> Resolver<'a> { + let root_def_id = CRATE_DEF_ID.to_def_id(); + let mut module_map = FxHashMap::default(); + let graph_root = arenas.new_module( + None, + ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), + ExpnId::root(), + krate.spans.inner_span, + session.contains_name(&krate.attrs, sym::no_implicit_prelude), + &mut module_map, + ); + let empty_module = arenas.new_module( + None, + ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), + ExpnId::root(), + DUMMY_SP, + true, + &mut FxHashMap::default(), + ); + + let definitions = Definitions::new(session.local_stable_crate_id()); + + let mut visibilities = FxHashMap::default(); + visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); + + let mut def_id_to_node_id = IndexVec::default(); + assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID); + let mut node_id_to_def_id = FxHashMap::default(); + node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID); + + let mut invocation_parents = FxHashMap::default(); + invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential)); + + let mut source_span = IndexVec::default(); + let _id = source_span.push(krate.spans.inner_span); + debug_assert_eq!(_id, CRATE_DEF_ID); + + let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session + .opts + .externs + .iter() + .filter(|(_, entry)| entry.add_prelude) + .map(|(name, _)| (Ident::from_str(name), Default::default())) + .collect(); + + if !session.contains_name(&krate.attrs, sym::no_core) { + extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); + if !session.contains_name(&krate.attrs, sym::no_std) { + extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); + } + } + + let (registered_attrs, registered_tools) = + macros::registered_attrs_and_tools(session, &krate.attrs); + + let features = session.features_untracked(); + + let mut resolver = Resolver { + session, + + definitions, + expn_that_defined: Default::default(), + source_span, + + // The outermost module has def ID 0; this is not reflected in the + // AST. + graph_root, + prelude: None, + extern_prelude, + + has_self: FxHashSet::default(), + field_names: FxHashMap::default(), + + determined_imports: Vec::new(), + indeterminate_imports: Vec::new(), + + pat_span_map: Default::default(), + partial_res_map: Default::default(), + import_res_map: Default::default(), + label_res_map: Default::default(), + lifetimes_res_map: Default::default(), + generics_def_id_map: Vec::new(), + extra_lifetime_params_map: Default::default(), + extern_crate_map: Default::default(), + reexport_map: FxHashMap::default(), + trait_map: NodeMap::default(), + underscore_disambiguator: 0, + empty_module, + module_map, + block_map: Default::default(), + binding_parent_modules: FxHashMap::default(), + ast_transform_scopes: FxHashMap::default(), + + glob_map: Default::default(), + visibilities, + has_pub_restricted: false, + used_imports: FxHashSet::default(), + maybe_unused_trait_imports: Default::default(), + maybe_unused_extern_crates: Vec::new(), + + privacy_errors: Vec::new(), + ambiguity_errors: Vec::new(), + use_injections: Vec::new(), + macro_expanded_macro_export_errors: BTreeSet::new(), + + arenas, + dummy_binding: arenas.alloc_name_binding(NameBinding { + kind: NameBindingKind::Res(Res::Err, false), + ambiguity: None, + expansion: LocalExpnId::ROOT, + span: DUMMY_SP, + vis: ty::Visibility::Public, + }), + + crate_loader: CrateLoader::new(session, metadata_loader, crate_name), + macro_names: FxHashSet::default(), + builtin_macros: Default::default(), + builtin_macro_kinds: Default::default(), + registered_attrs, + registered_tools, + macro_use_prelude: FxHashMap::default(), + macro_map: FxHashMap::default(), + dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())), + dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), + non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())), + invocation_parent_scopes: Default::default(), + output_macro_rules_scopes: Default::default(), + macro_rules_scopes: Default::default(), + helper_attrs: Default::default(), + derive_data: Default::default(), + local_macro_def_scopes: FxHashMap::default(), + name_already_seen: FxHashMap::default(), + potentially_unused_imports: Vec::new(), + struct_constructors: Default::default(), + unused_macros: Default::default(), + unused_macro_rules: Default::default(), + proc_macro_stubs: Default::default(), + single_segment_macro_resolutions: Default::default(), + multi_segment_macro_resolutions: Default::default(), + builtin_attrs: Default::default(), + containers_deriving_copy: Default::default(), + active_features: features + .declared_lib_features + .iter() + .map(|(feat, ..)| *feat) + .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) + .collect(), + lint_buffer: LintBuffer::default(), + next_node_id: CRATE_NODE_ID, + node_id_to_def_id, + def_id_to_node_id, + placeholder_field_indices: Default::default(), + invocation_parents, + trait_impl_items: Default::default(), + legacy_const_generic_args: Default::default(), + item_generics_num_lifetimes: Default::default(), + main_def: Default::default(), + trait_impls: Default::default(), + proc_macros: Default::default(), + confused_type_with_std_module: Default::default(), + access_levels: Default::default(), + }; + + let root_parent_scope = ParentScope::module(graph_root, &resolver); + resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); + + resolver + } + + fn new_module( + &mut self, + parent: Option<Module<'a>>, + kind: ModuleKind, + expn_id: ExpnId, + span: Span, + no_implicit_prelude: bool, + ) -> Module<'a> { + let module_map = &mut self.module_map; + self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map) + } + + pub fn next_node_id(&mut self) -> NodeId { + let start = self.next_node_id; + let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); + self.next_node_id = ast::NodeId::from_u32(next); + start + } + + pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> { + let start = self.next_node_id; + let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds"); + self.next_node_id = ast::NodeId::from_usize(end); + start..self.next_node_id + } + + pub fn lint_buffer(&mut self) -> &mut LintBuffer { + &mut self.lint_buffer + } + + pub fn arenas() -> ResolverArenas<'a> { + Default::default() + } + + pub fn into_outputs( + self, + ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) { + let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); + let definitions = self.definitions; + let cstore = Box::new(self.crate_loader.into_cstore()); + let source_span = self.source_span; + let expn_that_defined = self.expn_that_defined; + let visibilities = self.visibilities; + let has_pub_restricted = self.has_pub_restricted; + let extern_crate_map = self.extern_crate_map; + let reexport_map = self.reexport_map; + let maybe_unused_trait_imports = self.maybe_unused_trait_imports; + let maybe_unused_extern_crates = self.maybe_unused_extern_crates; + let glob_map = self.glob_map; + let main_def = self.main_def; + let confused_type_with_std_module = self.confused_type_with_std_module; + let access_levels = self.access_levels; + let resolutions = ResolverOutputs { + source_span, + expn_that_defined, + visibilities, + has_pub_restricted, + access_levels, + extern_crate_map, + reexport_map, + glob_map, + maybe_unused_trait_imports, + maybe_unused_extern_crates, + extern_prelude: self + .extern_prelude + .iter() + .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) + .collect(), + main_def, + trait_impls: self.trait_impls, + proc_macros, + confused_type_with_std_module, + registered_tools: self.registered_tools, + }; + let resolutions_lowering = ty::ResolverAstLowering { + legacy_const_generic_args: self.legacy_const_generic_args, + partial_res_map: self.partial_res_map, + import_res_map: self.import_res_map, + label_res_map: self.label_res_map, + lifetimes_res_map: self.lifetimes_res_map, + generics_def_id_map: self.generics_def_id_map, + extra_lifetime_params_map: self.extra_lifetime_params_map, + next_node_id: self.next_node_id, + node_id_to_def_id: self.node_id_to_def_id, + def_id_to_node_id: self.def_id_to_node_id, + trait_map: self.trait_map, + builtin_macro_kinds: self.builtin_macro_kinds, + }; + (definitions, cstore, resolutions, resolutions_lowering) + } + + pub fn clone_outputs( + &self, + ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) { + let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); + let definitions = self.definitions.clone(); + let cstore = Box::new(self.cstore().clone()); + let resolutions = ResolverOutputs { + source_span: self.source_span.clone(), + expn_that_defined: self.expn_that_defined.clone(), + visibilities: self.visibilities.clone(), + has_pub_restricted: self.has_pub_restricted, + extern_crate_map: self.extern_crate_map.clone(), + reexport_map: self.reexport_map.clone(), + glob_map: self.glob_map.clone(), + maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(), + maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(), + extern_prelude: self + .extern_prelude + .iter() + .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) + .collect(), + main_def: self.main_def, + trait_impls: self.trait_impls.clone(), + proc_macros, + confused_type_with_std_module: self.confused_type_with_std_module.clone(), + registered_tools: self.registered_tools.clone(), + access_levels: self.access_levels.clone(), + }; + let resolutions_lowering = ty::ResolverAstLowering { + legacy_const_generic_args: self.legacy_const_generic_args.clone(), + partial_res_map: self.partial_res_map.clone(), + import_res_map: self.import_res_map.clone(), + label_res_map: self.label_res_map.clone(), + lifetimes_res_map: self.lifetimes_res_map.clone(), + generics_def_id_map: self.generics_def_id_map.clone(), + extra_lifetime_params_map: self.extra_lifetime_params_map.clone(), + next_node_id: self.next_node_id.clone(), + node_id_to_def_id: self.node_id_to_def_id.clone(), + def_id_to_node_id: self.def_id_to_node_id.clone(), + trait_map: self.trait_map.clone(), + builtin_macro_kinds: self.builtin_macro_kinds.clone(), + }; + (definitions, cstore, resolutions, resolutions_lowering) + } + + fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { + StableHashingContext::new( + self.session, + &self.definitions, + self.crate_loader.cstore(), + &self.source_span, + ) + } + + pub fn cstore(&self) -> &CStore { + self.crate_loader.cstore() + } + + fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> { + match macro_kind { + MacroKind::Bang => self.dummy_ext_bang.clone(), + MacroKind::Derive => self.dummy_ext_derive.clone(), + MacroKind::Attr => self.non_macro_attr.clone(), + } + } + + /// Runs the function on each namespace. + fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) { + f(self, TypeNS); + f(self, ValueNS); + f(self, MacroNS); + } + + fn is_builtin_macro(&mut self, res: Res) -> bool { + self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some()) + } + + fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { + loop { + match ctxt.outer_expn_data().macro_def_id { + Some(def_id) => return def_id, + None => ctxt.remove_mark(), + }; + } + } + + /// Entry point to crate resolution. + pub fn resolve_crate(&mut self, krate: &Crate) { + self.session.time("resolve_crate", || { + self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports()); + self.session.time("resolve_access_levels", || { + AccessLevelsVisitor::compute_access_levels(self, krate) + }); + self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); + self.session.time("late_resolve_crate", || self.late_resolve_crate(krate)); + self.session.time("resolve_main", || self.resolve_main()); + self.session.time("resolve_check_unused", || self.check_unused(krate)); + self.session.time("resolve_report_errors", || self.report_errors(krate)); + self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate)); + }); + } + + pub fn traits_in_scope( + &mut self, + current_trait: Option<Module<'a>>, + parent_scope: &ParentScope<'a>, + ctxt: SyntaxContext, + assoc_item: Option<(Symbol, Namespace)>, + ) -> Vec<TraitCandidate> { + let mut found_traits = Vec::new(); + + if let Some(module) = current_trait { + if self.trait_may_have_item(Some(module), assoc_item) { + let def_id = module.def_id(); + found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); + } + } + + self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { + match scope { + Scope::Module(module, _) => { + this.traits_in_module(module, assoc_item, &mut found_traits); + } + Scope::StdLibPrelude => { + if let Some(module) = this.prelude { + this.traits_in_module(module, assoc_item, &mut found_traits); + } + } + Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} + _ => unreachable!(), + } + None::<()> + }); + + found_traits + } + + fn traits_in_module( + &mut self, + module: Module<'a>, + assoc_item: Option<(Symbol, Namespace)>, + found_traits: &mut Vec<TraitCandidate>, + ) { + module.ensure_traits(self); + let traits = module.traits.borrow(); + for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { + if self.trait_may_have_item(trait_binding.module(), assoc_item) { + let def_id = trait_binding.res().def_id(); + let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); + found_traits.push(TraitCandidate { def_id, import_ids }); + } + } + } + + // List of traits in scope is pruned on best effort basis. We reject traits not having an + // associated item with the given name and namespace (if specified). This is a conservative + // optimization, proper hygienic type-based resolution of associated items is done in typeck. + // We don't reject trait aliases (`trait_module == None`) because we don't have access to their + // associated items. + fn trait_may_have_item( + &mut self, + trait_module: Option<Module<'a>>, + assoc_item: Option<(Symbol, Namespace)>, + ) -> bool { + match (trait_module, assoc_item) { + (Some(trait_module), Some((name, ns))) => { + self.resolutions(trait_module).borrow().iter().any(|resolution| { + let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; + assoc_ns == ns && assoc_ident.name == name + }) + } + _ => true, + } + } + + fn find_transitive_imports( + &mut self, + mut kind: &NameBindingKind<'_>, + trait_name: Ident, + ) -> SmallVec<[LocalDefId; 1]> { + let mut import_ids = smallvec![]; + while let NameBindingKind::Import { import, binding, .. } = kind { + let id = self.local_def_id(import.id); + self.maybe_unused_trait_imports.insert(id); + self.add_to_glob_map(&import, trait_name); + import_ids.push(id); + kind = &binding.kind; + } + import_ids + } + + fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { + let ident = ident.normalize_to_macros_2_0(); + let disambiguator = if ident.name == kw::Underscore { + self.underscore_disambiguator += 1; + self.underscore_disambiguator + } else { + 0 + }; + BindingKey { ident, ns, disambiguator } + } + + fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { + if module.populate_on_access.get() { + module.populate_on_access.set(false); + self.build_reduced_graph_external(module); + } + &module.lazy_resolutions + } + + fn resolution( + &mut self, + module: Module<'a>, + key: BindingKey, + ) -> &'a RefCell<NameResolution<'a>> { + *self + .resolutions(module) + .borrow_mut() + .entry(key) + .or_insert_with(|| self.arenas.alloc_name_resolution()) + } + + fn record_use( + &mut self, + ident: Ident, + used_binding: &'a NameBinding<'a>, + is_lexical_scope: bool, + ) { + if let Some((b2, kind)) = used_binding.ambiguity { + self.ambiguity_errors.push(AmbiguityError { + kind, + ident, + b1: used_binding, + b2, + misc1: AmbiguityErrorMisc::None, + misc2: AmbiguityErrorMisc::None, + }); + } + if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { + // 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.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; + } + } + } + } + used.set(true); + import.used.set(true); + self.used_imports.insert(import.id); + self.add_to_glob_map(&import, ident); + self.record_use(ident, binding, false); + } + } + + #[inline] + fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { + if import.is_glob() { + let def_id = self.local_def_id(import.id); + self.glob_map.entry(def_id).or_default().insert(ident.name); + } + } + + fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { + debug!("resolve_crate_root({:?})", ident); + let mut ctxt = ident.span.ctxt(); + 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 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.normalize_to_macro_rules(); + debug!( + "resolve_crate_root: marks={:?}", + ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>() + ); + let mut iter = ctxt.marks().into_iter().rev().peekable(); + let mut result = None; + // 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); + iter.next(); + } else { + break; + } + } + debug!( + "resolve_crate_root: found opaque mark {:?} {:?}", + result, + result.map(|r| r.expn_data()) + ); + // 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); + } else { + break; + } + } + debug!( + "resolve_crate_root: found semi-transparent mark {:?} {:?}", + result, + result.map(|r| r.expn_data()) + ); + result + } else { + debug!("resolve_crate_root: not DollarCrate"); + ctxt = ctxt.normalize_to_macros_2_0(); + ctxt.adjust(ExpnId::root()) + }; + let module = match mark { + Some(def) => self.expn_def_scope(def), + None => { + debug!( + "resolve_crate_root({:?}): found no mark (ident.span = {:?})", + ident, ident.span + ); + return self.graph_root; + } + }; + let module = self.expect_module( + module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(), + ); + debug!( + "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", + ident, + module, + module.kind.name(), + ident.span + ); + module + } + + fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { + let mut module = self.expect_module(module.nearest_parent_mod()); + while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { + let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark())); + module = self.expect_module(parent.nearest_parent_mod()); + } + module + } + + fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { + debug!("(recording res) recording {:?} for {}", resolution, node_id); + if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { + panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); + } + } + + fn record_pat_span(&mut self, node: NodeId, span: Span) { + debug!("(recording pat) recording {:?} for {:?}", node, span); + self.pat_span_map.insert(node, span); + } + + fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool { + vis.is_accessible_from(module.nearest_parent_mod(), self) + } + + fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { + if let Some(old_module) = + self.binding_parent_modules.insert(Interned::new_unchecked(binding), module) + { + if !ptr::eq(module, old_module) { + span_bug!(binding.span, "parent module is reset for binding"); + } + } + } + + fn disambiguate_macro_rules_vs_modularized( + &self, + macro_rules: &'a NameBinding<'a>, + modularized: &'a NameBinding<'a>, + ) -> bool { + // 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(&Interned::new_unchecked(macro_rules)), + self.binding_parent_modules.get(&Interned::new_unchecked(modularized)), + ) { + (Some(macro_rules), Some(modularized)) => { + macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() + && modularized.is_ancestor_of(macro_rules) + } + _ => false, + } + } + + fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> { + if ident.is_path_segment_keyword() { + // Make sure `self`, `super` etc produce an error when passed to here. + return None; + } + self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { + if let Some(binding) = entry.extern_crate_item { + if finalize && entry.introduced_by_item { + self.record_use(ident, binding, false); + } + Some(binding) + } else { + let crate_id = if finalize { + let Some(crate_id) = + self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); }; + crate_id + } else { + self.crate_loader.maybe_process_path_extern(ident.name)? + }; + let crate_root = self.expect_module(crate_id.as_def_id()); + Some( + (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT) + .to_name_binding(self.arenas), + ) + } + }) + } + + /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>` + /// isn't something that can be returned because it can't be made to live that long, + /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, + /// just that an error occurred. + pub fn resolve_rustdoc_path( + &mut self, + path_str: &str, + ns: Namespace, + mut parent_scope: ParentScope<'a>, + ) -> Option<Res> { + let mut segments = + Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident)); + if let Some(segment) = segments.first_mut() { + if segment.ident.name == kw::Crate { + // FIXME: `resolve_path` always resolves `crate` to the current crate root, but + // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of + // replacing `crate` with `self` and changing the current module should achieve + // the same effect. + segment.ident.name = kw::SelfLower; + parent_scope.module = + self.expect_module(parent_scope.module.def_id().krate.as_def_id()); + } else if segment.ident.name == kw::Empty { + segment.ident.name = kw::PathRoot; + } + } + + match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) { + PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()), + PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => { + Some(path_res.base_res()) + } + PathResult::Module(ModuleOrUniformRoot::ExternPrelude) + | PathResult::NonModule(..) + | PathResult::Failed { .. } => None, + PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), + } + } + + /// For rustdoc. + /// For local modules returns only reexports, for external modules returns all children. + pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> { + if let Some(def_id) = def_id.as_local() { + self.reexport_map.get(&def_id).cloned().unwrap_or_default() + } else { + self.cstore().module_children_untracked(def_id, self.session) + } + } + + /// For rustdoc. + pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) { + let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item"); + match scope.get() { + MacroRulesScope::Binding(mb) => (scope, mb.binding.res()), + _ => unreachable!(), + } + } + + /// Retrieves the span of the given `DefId` if `DefId` is in the local crate. + #[inline] + pub fn opt_span(&self, def_id: DefId) -> Option<Span> { + def_id.as_local().map(|def_id| self.source_span[def_id]) + } + + /// Checks if an expression refers to a function marked with + /// `#[rustc_legacy_const_generics]` and returns the argument index list + /// from the attribute. + pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> { + if let ExprKind::Path(None, path) = &expr.kind { + // Don't perform legacy const generics rewriting if the path already + // has generic arguments. + if path.segments.last().unwrap().args.is_some() { + return None; + } + + let partial_res = self.partial_res_map.get(&expr.id)?; + if partial_res.unresolved_segments() != 0 { + return None; + } + + if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() { + // We only support cross-crate argument rewriting. Uses + // within the same crate should be updated to use the new + // const generics style. + if def_id.is_local() { + return None; + } + + if let Some(v) = self.legacy_const_generic_args.get(&def_id) { + return v.clone(); + } + + let attr = self + .cstore() + .item_attrs_untracked(def_id, self.session) + .find(|a| a.has_name(sym::rustc_legacy_const_generics))?; + let mut ret = Vec::new(); + for meta in attr.meta_item_list()? { + match meta.literal()?.kind { + LitKind::Int(a, _) => ret.push(a as usize), + _ => panic!("invalid arg index"), + } + } + // Cache the lookup to avoid parsing attributes for an iterm multiple times. + self.legacy_const_generic_args.insert(def_id, Some(ret.clone())); + return Some(ret); + } + } + None + } + + fn resolve_main(&mut self) { + let module = self.graph_root; + let ident = Ident::with_dummy_span(sym::main); + let parent_scope = &ParentScope::module(module, self); + + let Ok(name_binding) = self.maybe_resolve_ident_in_module( + ModuleOrUniformRoot::Module(module), + ident, + ValueNS, + parent_scope, + ) else { + return; + }; + + let res = name_binding.res(); + let is_import = name_binding.is_import(); + let span = name_binding.span; + if let Res::Def(DefKind::Fn, _) = res { + self.record_use(ident, name_binding, false); + } + self.main_def = Some(MainDefinition { res, is_import, span }); + } +} + +fn names_to_string(names: &[Symbol]) -> String { + let mut result = String::new(); + for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { + if i > 0 { + result.push_str("::"); + } + if Ident::with_dummy_span(*name).is_raw_guess() { + result.push_str("r#"); + } + result.push_str(name.as_str()); + } + result +} + +fn path_names_to_string(path: &Path) -> String { + names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>()) +} + +/// A somewhat inefficient routine to obtain the name of a module. +fn module_to_string(module: Module<'_>) -> Option<String> { + let mut names = Vec::new(); + + fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) { + if let ModuleKind::Def(.., name) = module.kind { + if let Some(parent) = module.parent { + names.push(name); + collect_mod(names, parent); + } + } else { + names.push(Symbol::intern("<opaque>")); + collect_mod(names, module.parent.unwrap()); + } + } + collect_mod(&mut names, module); + + if names.is_empty() { + return None; + } + names.reverse(); + Some(names_to_string(&names)) +} + +#[derive(Copy, Clone, Debug)] +struct Finalize { + /// Node ID for linting. + node_id: NodeId, + /// Span of the whole path or some its characteristic fragment. + /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths. + path_span: Span, + /// Span of the path start, suitable for prepending something to to it. + /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths. + root_span: Span, + /// Whether to report privacy errors or silently return "no resolution" for them, + /// similarly to speculative resolution. + report_private: bool, +} + +impl Finalize { + fn new(node_id: NodeId, path_span: Span) -> Finalize { + Finalize::with_root_span(node_id, path_span, path_span) + } + + fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize { + Finalize { node_id, path_span, root_span, report_private: true } + } +} + +pub fn provide(providers: &mut Providers) { + late::lifetimes::provide(providers); +} diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs new file mode 100644 index 000000000..070fb9c72 --- /dev/null +++ b/compiler/rustc_resolve/src/macros.rs @@ -0,0 +1,921 @@ +//! A bunch of methods and structures more or less related to resolving macros and +//! interface provided by `Resolver` to macro expander. + +use crate::imports::ImportResolver; +use crate::Namespace::*; +use crate::{BuiltinMacroState, Determinacy}; +use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet}; +use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment}; +use rustc_ast::{self as ast, Inline, ItemKind, ModKind, NodeId}; +use rustc_ast_pretty::pprust; +use rustc_attr::StabilityLevel; +use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::intern::Interned; +use rustc_data_structures::sync::Lrc; +use rustc_errors::struct_span_err; +use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand}; +use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind}; +use rustc_expand::compile_declarative_macro; +use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion}; +use rustc_hir::def::{self, DefKind, NonMacroAttrKind}; +use rustc_hir::def_id::{CrateNum, LocalDefId}; +use rustc_middle::middle::stability; +use rustc_middle::ty::RegisteredTools; +use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE}; +use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES}; +use rustc_session::lint::BuiltinLintDiagnostics; +use rustc_session::parse::feature_err; +use rustc_session::Session; +use rustc_span::edition::Edition; +use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId}; +use rustc_span::hygiene::{AstPass, MacroKind}; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::{Span, DUMMY_SP}; +use std::cell::Cell; +use std::mem; + +type Res = def::Res<NodeId>; + +/// Binding produced by a `macro_rules` item. +/// Not modularized, can shadow previous `macro_rules` bindings, etc. +#[derive(Debug)] +pub struct MacroRulesBinding<'a> { + pub(crate) binding: &'a NameBinding<'a>, + /// `macro_rules` scope into which the `macro_rules` item was planted. + pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'a>, + pub(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 `macro_rules` scopes too because they +/// can potentially expand into macro definitions. +#[derive(Copy, Clone, Debug)] +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 MacroRulesBinding<'a>), + /// The scope introduced by a macro invocation that can potentially + /// create a `macro_rules!` macro definition. + Invocation(LocalExpnId), +} + +/// `macro_rules!` scopes are always kept by reference and inside a cell. +/// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)` +/// in-place after `invoc_id` gets expanded. +/// This helps to avoid uncontrollable growth of `macro_rules!` scope chains, +/// which usually grow linearly with the number of macro invocations +/// in a module (including derives) and hurt performance. +pub(crate) type MacroRulesScopeRef<'a> = Interned<'a, Cell<MacroRulesScope<'a>>>; + +/// Macro namespace is separated into two sub-namespaces, one for bang macros and +/// one for attribute-like macros (attributes, derives). +/// We ignore resolutions from one sub-namespace when searching names in scope for another. +pub(crate) fn sub_namespace_match( + candidate: Option<MacroKind>, + requirement: Option<MacroKind>, +) -> bool { + #[derive(PartialEq)] + enum SubNS { + Bang, + AttrLike, + } + let sub_ns = |kind| match kind { + MacroKind::Bang => SubNS::Bang, + MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike, + }; + let candidate = candidate.map(sub_ns); + let requirement = requirement.map(sub_ns); + // "No specific sub-namespace" means "matches anything" for both requirements and candidates. + candidate.is_none() || requirement.is_none() || candidate == requirement +} + +// We don't want to format a path using pretty-printing, +// `format!("{}", path)`, because that tries to insert +// line-breaks and is slow. +fn fast_print_path(path: &ast::Path) -> Symbol { + if path.segments.len() == 1 { + path.segments[0].ident.name + } else { + let mut path_str = String::with_capacity(64); + for (i, segment) in path.segments.iter().enumerate() { + if i != 0 { + path_str.push_str("::"); + } + if segment.ident.name != kw::PathRoot { + path_str.push_str(segment.ident.as_str()) + } + } + Symbol::intern(&path_str) + } +} + +/// The code common between processing `#![register_tool]` and `#![register_attr]`. +fn registered_idents( + sess: &Session, + attrs: &[ast::Attribute], + attr_name: Symbol, + descr: &str, +) -> FxHashSet<Ident> { + let mut registered = FxHashSet::default(); + for attr in sess.filter_by_name(attrs, attr_name) { + for nested_meta in attr.meta_item_list().unwrap_or_default() { + match nested_meta.ident() { + Some(ident) => { + if let Some(old_ident) = registered.replace(ident) { + let msg = format!("{} `{}` was already registered", descr, ident); + sess.struct_span_err(ident.span, &msg) + .span_label(old_ident.span, "already registered here") + .emit(); + } + } + None => { + let msg = format!("`{}` only accepts identifiers", attr_name); + let span = nested_meta.span(); + sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit(); + } + } + } + } + registered +} + +pub(crate) fn registered_attrs_and_tools( + sess: &Session, + attrs: &[ast::Attribute], +) -> (FxHashSet<Ident>, FxHashSet<Ident>) { + let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute"); + let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool"); + // We implicitly add `rustfmt` and `clippy` to known tools, + // but it's not an error to register them explicitly. + let predefined_tools = [sym::clippy, sym::rustfmt]; + registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span)); + (registered_attrs, registered_tools) +} + +// Some feature gates for inner attributes are reported as lints for backward compatibility. +fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool { + match &path.segments[..] { + // `#![test]` + [seg] if seg.ident.name == sym::test => return true, + // `#![rustfmt::skip]` on out-of-line modules + [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => { + if let InvocationKind::Attr { item, .. } = &invoc.kind { + if let Annotatable::Item(item) = item { + if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind { + return true; + } + } + } + } + _ => {} + } + false +} + +impl<'a> ResolverExpand for Resolver<'a> { + fn next_node_id(&mut self) -> NodeId { + self.next_node_id() + } + + fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId { + self.invocation_parents[&id].0 + } + + fn resolve_dollar_crates(&mut self) { + hygiene::update_dollar_crate_names(|ctxt| { + let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt)); + match self.resolve_crate_root(ident).kind { + ModuleKind::Def(.., name) if name != kw::Empty => name, + _ => kw::Crate, + } + }); + } + + fn visit_ast_fragment_with_placeholders( + &mut self, + expansion: LocalExpnId, + fragment: &AstFragment, + ) { + // 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_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); + } + + fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) { + if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() { + self.session + .diagnostic() + .bug(&format!("built-in macro `{}` was already registered", name)); + } + } + + // Create a new Expansion with a definition site of the provided module, or + // a fake empty `#[no_implicit_prelude]` module if no module is provided. + fn expansion_for_ast_pass( + &mut self, + call_site: Span, + pass: AstPass, + features: &[Symbol], + parent_module_id: Option<NodeId>, + ) -> LocalExpnId { + let parent_module = + parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id()); + let expn_id = LocalExpnId::fresh( + ExpnData::allow_unstable( + ExpnKind::AstPass(pass), + call_site, + self.session.edition(), + features.into(), + None, + parent_module, + ), + self.create_stable_hashing_context(), + ); + + let parent_scope = + parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id)); + self.ast_transform_scopes.insert(expn_id, parent_scope); + + expn_id + } + + fn resolve_imports(&mut self) { + ImportResolver { r: self }.resolve_imports() + } + + fn resolve_macro_invocation( + &mut self, + invoc: &Invocation, + eager_expansion_root: LocalExpnId, + force: bool, + ) -> Result<Lrc<SyntaxExtension>, Indeterminate> { + let invoc_id = invoc.expansion_data.id; + let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) { + Some(parent_scope) => *parent_scope, + None => { + // If there's no entry in the table, then we are resolving an eagerly expanded + // macro, which should inherit its parent scope from its eager expansion root - + // the macro that requested this eager expansion. + let parent_scope = *self + .invocation_parent_scopes + .get(&eager_expansion_root) + .expect("non-eager expansion without a parent scope"); + self.invocation_parent_scopes.insert(invoc_id, parent_scope); + parent_scope + } + }; + + let (path, kind, inner_attr, derives) = match invoc.kind { + InvocationKind::Attr { ref attr, ref derives, .. } => ( + &attr.get_normal_item().path, + MacroKind::Attr, + attr.style == ast::AttrStyle::Inner, + self.arenas.alloc_ast_paths(derives), + ), + InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]), + InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]), + }; + + // Derives are not included when `invocations` are collected, so we have to add them here. + let parent_scope = &ParentScope { derives, ..parent_scope }; + let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion(); + let node_id = invoc.expansion_data.lint_node_id; + let (ext, res) = self.smart_resolve_macro_path( + path, + kind, + supports_macro_expansion, + inner_attr, + parent_scope, + node_id, + force, + soft_custom_inner_attributes_gate(path, invoc), + )?; + + let span = invoc.span(); + let def_id = res.opt_def_id(); + invoc_id.set_expn_data( + ext.expn_data( + parent_scope.expansion, + span, + fast_print_path(path), + def_id, + def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()), + ), + self.create_stable_hashing_context(), + ); + + Ok(ext) + } + + fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) { + let did = self.local_def_id(id); + self.unused_macro_rules.remove(&(did, rule_i)); + } + + fn check_unused_macros(&mut self) { + for (_, &(node_id, ident)) in self.unused_macros.iter() { + self.lint_buffer.buffer_lint( + UNUSED_MACROS, + node_id, + ident.span, + &format!("unused macro definition: `{}`", ident.name), + ); + } + for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() { + if self.unused_macros.contains_key(&def_id) { + // We already lint the entire macro as unused + continue; + } + let node_id = self.def_id_to_node_id[def_id]; + self.lint_buffer.buffer_lint( + UNUSED_MACRO_RULES, + node_id, + rule_span, + &format!( + "{} rule of macro `{}` is never used", + crate::diagnostics::ordinalize(arm_i + 1), + ident.name + ), + ); + } + } + + fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool { + self.containers_deriving_copy.contains(&expn_id) + } + + fn resolve_derives( + &mut self, + expn_id: LocalExpnId, + force: bool, + derive_paths: &dyn Fn() -> DeriveResolutions, + ) -> Result<(), Indeterminate> { + // Block expansion of the container until we resolve all derives in it. + // This is required for two reasons: + // - Derive helper attributes are in scope for the item to which the `#[derive]` + // is applied, so they have to be produced by the container's expansion rather + // than by individual derives. + // - Derives in the container need to know whether one of them is a built-in `Copy`. + // Temporarily take the data to avoid borrow checker conflicts. + let mut derive_data = mem::take(&mut self.derive_data); + let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData { + resolutions: derive_paths(), + helper_attrs: Vec::new(), + has_derive_copy: false, + }); + let parent_scope = self.invocation_parent_scopes[&expn_id]; + for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() { + if opt_ext.is_none() { + *opt_ext = Some( + match self.resolve_macro_path( + &path, + Some(MacroKind::Derive), + &parent_scope, + true, + force, + ) { + Ok((Some(ext), _)) => { + if !ext.helper_attrs.is_empty() { + let last_seg = path.segments.last().unwrap(); + let span = last_seg.ident.span.normalize_to_macros_2_0(); + entry.helper_attrs.extend( + ext.helper_attrs + .iter() + .map(|name| (i, Ident::new(*name, span))), + ); + } + entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy); + ext + } + Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive), + Err(Determinacy::Undetermined) => { + assert!(self.derive_data.is_empty()); + self.derive_data = derive_data; + return Err(Indeterminate); + } + }, + ); + } + } + // Sort helpers in a stable way independent from the derive resolution order. + entry.helper_attrs.sort_by_key(|(i, _)| *i); + self.helper_attrs + .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect()); + // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive + // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`. + if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) { + self.containers_deriving_copy.insert(expn_id); + } + assert!(self.derive_data.is_empty()); + self.derive_data = derive_data; + Ok(()) + } + + fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> { + self.derive_data.remove(&expn_id).map(|data| data.resolutions) + } + + // The function that implements the resolution logic of `#[cfg_accessible(path)]`. + // Returns true if the path can certainly be resolved in one of three namespaces, + // returns false if the path certainly cannot be resolved in any of the three namespaces. + // Returns `Indeterminate` if we cannot give a certain answer yet. + fn cfg_accessible( + &mut self, + expn_id: LocalExpnId, + path: &ast::Path, + ) -> Result<bool, Indeterminate> { + let span = path.span; + let path = &Segment::from_path(path); + let parent_scope = self.invocation_parent_scopes[&expn_id]; + + let mut indeterminate = false; + for ns in [TypeNS, ValueNS, MacroNS].iter().copied() { + match self.maybe_resolve_path(path, Some(ns), &parent_scope) { + PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true), + PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => { + return Ok(true); + } + PathResult::NonModule(..) | + // HACK(Urgau): This shouldn't be necessary + PathResult::Failed { is_error_from_last_segment: false, .. } => { + self.session + .struct_span_err(span, "not sure whether the path is accessible or not") + .note("the type may have associated items, but we are currently not checking them") + .emit(); + + // If we get a partially resolved NonModule in one namespace, we should get the + // same result in any other namespaces, so we can return early. + return Ok(false); + } + PathResult::Indeterminate => indeterminate = true, + // We can only be sure that a path doesn't exist after having tested all the + // posibilities, only at that time we can return false. + PathResult::Failed { .. } => {} + PathResult::Module(_) => panic!("unexpected path resolution"), + } + } + + if indeterminate { + return Err(Indeterminate); + } + + Ok(false) + } + + fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span { + self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session) + } + + fn declare_proc_macro(&mut self, id: NodeId) { + self.proc_macros.push(id) + } + + fn registered_tools(&self) -> &RegisteredTools { + &self.registered_tools + } +} + +impl<'a> Resolver<'a> { + /// Resolve macro path with error reporting and recovery. + /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions + /// for better error recovery. + fn smart_resolve_macro_path( + &mut self, + path: &ast::Path, + kind: MacroKind, + supports_macro_expansion: SupportsMacroExpansion, + inner_attr: bool, + parent_scope: &ParentScope<'a>, + node_id: NodeId, + force: bool, + soft_custom_inner_attributes_gate: bool, + ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> { + let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force) + { + Ok((Some(ext), res)) => (ext, res), + Ok((None, res)) => (self.dummy_ext(kind), res), + Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err), + Err(Determinacy::Undetermined) => return Err(Indeterminate), + }; + + // Report errors for the resolved macro. + for segment in &path.segments { + if let Some(args) = &segment.args { + self.session.span_err(args.span(), "generic arguments in macro path"); + } + if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") { + self.session.span_err( + segment.ident.span, + "attributes starting with `rustc` are reserved for use by the `rustc` compiler", + ); + } + } + + match res { + Res::Def(DefKind::Macro(_), def_id) => { + if let Some(def_id) = def_id.as_local() { + self.unused_macros.remove(&def_id); + if self.proc_macro_stubs.contains(&def_id) { + self.session.span_err( + path.span, + "can't use a procedural macro from the same crate that defines it", + ); + } + } + } + Res::NonMacroAttr(..) | Res::Err => {} + _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"), + }; + + self.check_stability_and_deprecation(&ext, path, node_id); + + let unexpected_res = if ext.macro_kind() != kind { + Some((kind.article(), kind.descr_expected())) + } else if matches!(res, Res::Def(..)) { + match supports_macro_expansion { + SupportsMacroExpansion::No => Some(("a", "non-macro attribute")), + SupportsMacroExpansion::Yes { supports_inner_attrs } => { + if inner_attr && !supports_inner_attrs { + Some(("a", "non-macro inner attribute")) + } else { + None + } + } + } + } else { + None + }; + if let Some((article, expected)) = unexpected_res { + let path_str = pprust::path_to_string(path); + let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str); + self.session + .struct_span_err(path.span, &msg) + .span_label(path.span, format!("not {} {}", article, expected)) + .emit(); + return Ok((self.dummy_ext(kind), Res::Err)); + } + + // We are trying to avoid reporting this error if other related errors were reported. + if res != Res::Err + && inner_attr + && !self.session.features_untracked().custom_inner_attributes + { + let msg = match res { + Res::Def(..) => "inner macro attributes are unstable", + Res::NonMacroAttr(..) => "custom inner attributes are unstable", + _ => unreachable!(), + }; + if soft_custom_inner_attributes_gate { + self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg); + } else { + feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg) + .emit(); + } + } + + Ok((ext, res)) + } + + pub fn resolve_macro_path( + &mut self, + path: &ast::Path, + kind: Option<MacroKind>, + parent_scope: &ParentScope<'a>, + trace: bool, + force: bool, + ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> { + let path_span = path.span; + let mut path = Segment::from_path(path); + + // Possibly apply the macro helper hack + if kind == Some(MacroKind::Bang) + && path.len() == 1 + && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros + { + let root = Ident::new(kw::DollarCrate, path[0].ident.span); + path.insert(0, Segment::from_ident(root)); + } + + let res = if path.len() > 1 { + let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) { + PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => { + Ok(path_res.base_res()) + } + PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined), + PathResult::NonModule(..) + | PathResult::Indeterminate + | PathResult::Failed { .. } => Err(Determinacy::Determined), + PathResult::Module(..) => unreachable!(), + }; + + if trace { + let kind = kind.expect("macro kind must be specified if tracing is enabled"); + self.multi_segment_macro_resolutions.push(( + path, + path_span, + kind, + *parent_scope, + res.ok(), + )); + } + + self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span); + res + } else { + let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro); + let binding = self.early_resolve_ident_in_lexical_scope( + path[0].ident, + scope_set, + parent_scope, + None, + force, + None, + ); + if let Err(Determinacy::Undetermined) = binding { + return Err(Determinacy::Undetermined); + } + + if trace { + let kind = kind.expect("macro kind must be specified if tracing is enabled"); + self.single_segment_macro_resolutions.push(( + path[0].ident, + kind, + *parent_scope, + binding.ok(), + )); + } + + let res = binding.map(|binding| binding.res()); + self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span); + res + }; + + res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res)) + } + + pub(crate) fn finalize_macro_resolutions(&mut self) { + let check_consistency = |this: &mut Self, + path: &[Segment], + span, + kind: MacroKind, + initial_res: Option<Res>, + res: Res| { + if let Some(initial_res) = initial_res { + if res != initial_res { + // Make sure compilation does not succeed if preferred macro resolution + // has changed after the macro had been expanded. In theory all such + // situations should be reported as errors, so this is a bug. + this.session.delay_span_bug(span, "inconsistent resolution for a macro"); + } + } else { + // It's possible that the macro was unresolved (indeterminate) and silently + // expanded into a dummy fragment for recovery during expansion. + // Now, post-expansion, the resolution may succeed, but we can't change the + // past and need to report an error. + // However, non-speculative `resolve_path` can successfully return private items + // even if speculative `resolve_path` returned nothing previously, so we skip this + // less informative error if the privacy error is reported elsewhere. + if this.privacy_errors.is_empty() { + let msg = format!( + "cannot determine resolution for the {} `{}`", + kind.descr(), + Segment::names_to_string(path) + ); + let msg_note = "import resolution is stuck, try simplifying macro imports"; + this.session.struct_span_err(span, &msg).note(msg_note).emit(); + } + } + }; + + let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions); + for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions { + // FIXME: Path resolution will ICE if segment IDs present. + for seg in &mut path { + seg.id = None; + } + match self.resolve_path( + &path, + Some(MacroNS), + &parent_scope, + Some(Finalize::new(ast::CRATE_NODE_ID, path_span)), + None, + ) { + PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => { + let res = path_res.base_res(); + check_consistency(self, &path, path_span, kind, initial_res, res); + } + path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => { + let (span, label) = if let PathResult::Failed { span, label, .. } = path_res { + (span, label) + } else { + ( + path_span, + format!( + "partially resolved path in {} {}", + kind.article(), + kind.descr() + ), + ) + }; + self.report_error( + span, + ResolutionError::FailedToResolve { label, suggestion: None }, + ); + } + PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), + } + } + + let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions); + for (ident, kind, parent_scope, initial_binding) in macro_resolutions { + match self.early_resolve_ident_in_lexical_scope( + ident, + ScopeSet::Macro(kind), + &parent_scope, + Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)), + true, + None, + ) { + Ok(binding) => { + let initial_res = initial_binding.map(|initial_binding| { + self.record_use(ident, initial_binding, false); + initial_binding.res() + }); + let res = binding.res(); + let seg = Segment::from_ident(ident); + check_consistency(self, &[seg], ident.span, kind, initial_res, res); + if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) { + let node_id = self + .invocation_parents + .get(&parent_scope.expansion) + .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]); + self.lint_buffer.buffer_lint_with_diagnostic( + LEGACY_DERIVE_HELPERS, + node_id, + ident.span, + "derive helper attribute is used before it is introduced", + BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span), + ); + } + } + Err(..) => { + let expected = kind.descr_expected(); + let msg = format!("cannot find {} `{}` in this scope", expected, ident); + let mut err = self.session.struct_span_err(ident.span, &msg); + self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident); + err.emit(); + } + } + } + + let builtin_attrs = mem::take(&mut self.builtin_attrs); + for (ident, parent_scope) in builtin_attrs { + let _ = self.early_resolve_ident_in_lexical_scope( + ident, + ScopeSet::Macro(MacroKind::Attr), + &parent_scope, + Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)), + true, + None, + ); + } + } + + fn check_stability_and_deprecation( + &mut self, + ext: &SyntaxExtension, + path: &ast::Path, + node_id: NodeId, + ) { + let span = path.span; + if let Some(stability) = &ext.stability { + if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level + { + let feature = stability.feature; + + let is_allowed = |feature| { + self.active_features.contains(&feature) || span.allows_unstable(feature) + }; + let allowed_by_implication = + implied_by.map(|feature| is_allowed(feature)).unwrap_or(false); + if !is_allowed(feature) && !allowed_by_implication { + let lint_buffer = &mut self.lint_buffer; + let soft_handler = + |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg); + stability::report_unstable( + self.session, + feature, + reason.to_opt_reason(), + issue, + None, + is_soft, + span, + soft_handler, + ); + } + } + } + if let Some(depr) = &ext.deprecation { + let path = pprust::path_to_string(&path); + let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path); + stability::early_report_deprecation( + &mut self.lint_buffer, + &message, + depr.suggestion, + lint, + span, + node_id, + ); + } + } + + fn prohibit_imported_non_macro_attrs( + &self, + binding: Option<&'a NameBinding<'a>>, + res: Option<Res>, + span: Span, + ) { + if let Some(Res::NonMacroAttr(kind)) = res { + if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) { + let msg = + format!("cannot use {} {} through an import", kind.article(), kind.descr()); + let mut err = self.session.struct_span_err(span, &msg); + if let Some(binding) = binding { + err.span_note(binding.span, &format!("the {} imported here", kind.descr())); + } + err.emit(); + } + } + } + + pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) { + // Reserve some names that are not quite covered by the general check + // performed on `Resolver::builtin_attrs`. + if ident.name == sym::cfg || ident.name == sym::cfg_attr { + let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind()); + if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) { + self.session.span_err( + ident.span, + &format!("name `{}` is reserved in attribute namespace", ident), + ); + } + } + } + + /// Compile the macro into a `SyntaxExtension` and its rule spans. + /// + /// Possibly replace its expander to a pre-defined one for built-in macros. + pub(crate) fn compile_macro( + &mut self, + item: &ast::Item, + edition: Edition, + ) -> (SyntaxExtension, Vec<(usize, Span)>) { + let (mut result, mut rule_spans) = compile_declarative_macro( + &self.session, + self.session.features_untracked(), + item, + edition, + ); + + if let Some(builtin_name) = result.builtin_name { + // The macro was marked with `#[rustc_builtin_macro]`. + if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) { + // The macro is a built-in, replace its expander function + // while still taking everything else from the source code. + // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'. + match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) { + BuiltinMacroState::NotYetSeen(ext) => { + result.kind = ext; + rule_spans = Vec::new(); + if item.id != ast::DUMMY_NODE_ID { + self.builtin_macro_kinds + .insert(self.local_def_id(item.id), result.macro_kind()); + } + } + BuiltinMacroState::AlreadySeen(span) => { + struct_span_err!( + self.session, + item.span, + E0773, + "attempted to define built-in macro more than once" + ) + .span_note(span, "previously defined here") + .emit(); + } + } + } else { + let msg = format!("cannot find a built-in macro with name `{}`", item.ident); + self.session.span_err(item.span, &msg); + } + } + + (result, rule_spans) + } +} |