From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- compiler/rustc_resolve/src/access_levels.rs | 237 ++ compiler/rustc_resolve/src/build_reduced_graph.rs | 1546 ++++++++ compiler/rustc_resolve/src/check_unused.rs | 350 ++ compiler/rustc_resolve/src/def_collector.rs | 354 ++ compiler/rustc_resolve/src/diagnostics.rs | 2714 ++++++++++++++ compiler/rustc_resolve/src/diagnostics/tests.rs | 40 + compiler/rustc_resolve/src/ident.rs | 1556 ++++++++ compiler/rustc_resolve/src/imports.rs | 1151 ++++++ compiler/rustc_resolve/src/late.rs | 3984 +++++++++++++++++++++ compiler/rustc_resolve/src/late/diagnostics.rs | 2369 ++++++++++++ compiler/rustc_resolve/src/late/lifetimes.rs | 2144 +++++++++++ compiler/rustc_resolve/src/lib.rs | 2089 +++++++++++ compiler/rustc_resolve/src/macros.rs | 921 +++++ 13 files changed, 19455 insertions(+) create mode 100644 compiler/rustc_resolve/src/access_levels.rs create mode 100644 compiler/rustc_resolve/src/build_reduced_graph.rs create mode 100644 compiler/rustc_resolve/src/check_unused.rs create mode 100644 compiler/rustc_resolve/src/def_collector.rs create mode 100644 compiler/rustc_resolve/src/diagnostics.rs create mode 100644 compiler/rustc_resolve/src/diagnostics/tests.rs create mode 100644 compiler/rustc_resolve/src/ident.rs create mode 100644 compiler/rustc_resolve/src/imports.rs create mode 100644 compiler/rustc_resolve/src/late.rs create mode 100644 compiler/rustc_resolve/src/late/diagnostics.rs create mode 100644 compiler/rustc_resolve/src/late/lifetimes.rs create mode 100644 compiler/rustc_resolve/src/lib.rs create mode 100644 compiler/rustc_resolve/src/macros.rs (limited to 'compiler/rustc_resolve/src') 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, + 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::>(); + + 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, + ) -> Option { + 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, + ) -> Option { + 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; + +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(&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 + /// (). + 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> { + 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 { + 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> 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> { + 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::>(); + 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>) { + 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, + 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::>(); + 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::>(); + 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, + 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, +} + +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>, + 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), + NestedPartialUnused(Vec, Vec), +} + +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::>(); + 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(&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( + &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) { + 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>() {} + // ``` + // + // 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; + +/// 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, + 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, +} + +/// Adjust the impl span so that just the `impl` keyword is taken by removing +/// everything after `<` (`"impl Iterator for A {}" -> "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, + 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, + 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::>(); + let origin_sp = origin.iter().copied().collect::>(); + + 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 { + 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::>(), + ident.name, + None, + ) { + Some(found) if found != ident.name => { + suggestions.into_iter().find(|suggestion| suggestion.candidate == found) + } + _ => None, + } + } + + fn lookup_import_candidates_from_module( + &mut self, + lookup_ident: Ident, + namespace: Namespace, + parent_scope: &ParentScope<'a>, + start_module: Module<'a>, + crate_name: Ident, + filter_fn: FilterFn, + ) -> Vec + where + FilterFn: Fn(Res) -> bool, + { + let mut candidates = Vec::new(); + let mut seen_modules = FxHashSet::default(); + let mut worklist = vec![(start_module, Vec::::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( + &mut self, + lookup_ident: Ident, + namespace: Namespace, + parent_scope: &ParentScope<'a>, + filter_fn: FilterFn, + ) -> Vec + 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, + 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 { + 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 { + 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::>(); + 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, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + ribs: Option<&PerNS>>>, + ignore_binding: Option<&'a NameBinding<'a>>, + module: Option>, + i: usize, + ident: Ident, + ) -> (String, Option) { + 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, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec, Option)> { + 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, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec, Option)> { + // 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, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec, Option)> { + // 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 \ + " + .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, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec, Option)> { + // 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, + parent_scope: &ParentScope<'b>, + ) -> Option<(Vec, Option)> { + 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::>(); + 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, Option)> { + 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 { + 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::>(); + let prev_starting_brace = prev_source.rsplit('{').collect::>(); + 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, + err: &mut Diagnostic, + // This is `None` if all placement locations are inside expansions + use_placement_span: Option, + candidates: &[ImportSuggestion], + instead: Instead, + found_use: FoundUse, + is_pattern: IsPattern, + path: Vec, +) { + if candidates.is_empty() { + return; + } + + let mut accessible_path_strings: Vec<(String, &str, Option, &Option)> = + Vec::new(); + let mut inaccessible_path_strings: Vec<(String, &str, Option, &Option)> = + 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::>(); + 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, + first_use_span: Option, +} + +impl UsePlacementFinder { + fn check(krate: &Crate, target_module: NodeId) -> (Option, 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]) -> Option { + 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( + &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, + ) -> Option { + // 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, + ) -> Option<(Module<'a>, Option)> { + 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, + ribs: &[Rib<'a>], + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Option> { + 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, + 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, + 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, + 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, + 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, + // 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, + 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, // `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, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + finalize: Option, + 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, // `None` indicates a module path in import + parent_scope: &ParentScope<'a>, + finalize: Option, + ribs: Option<&PerNS>>>, + 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; + +/// 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, Determinacy>>>, + /// Bindings introduced by `target`. + target_bindings: PerNS>>>, + /// `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, // 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, + 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, + /// The resolution of `module_path`. + pub imported_module: Cell>>, + pub vis: Cell, + pub used: Cell, +} + +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>>, + /// 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(&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, + note: Option, + suggestion: Option, +} + +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::>(), + &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::>(), + &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, + ) { + /// 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::>(); + + 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 { + 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::>(); + + 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, Determinacy>>>, + target_bindings: &PerNS>>>, + 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::>(); + 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::>()) + } 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::>()), + 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 { .. } => "".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; + +type IdentMap = FxHashMap; + +/// Map from the name in a pattern to its binding mode. +type BindingMap = IdentMap; + +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, + 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`). + 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, +} + +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 `::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]>, + + /// The current self type if inside an impl (used for better errors). + current_self_type: Option, + + /// The current self item if inside an ADT (used for better errors). + current_self_item: Option, + + /// 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, + + /// Only used for better errors on `fn(): fn()`. + current_type_ascription: Vec, + + /// 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, + + /// Only used for better errors on `let : ;`. + current_let_binding: Option<(Span, Option, Option)>, + + /// 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 ::Baz: String`, suggest `where T: Bar`. + 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]>, + + /// 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, +} + +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>>, + + /// The current set of local scopes, for labels. + label_ribs: Vec>, + + /// The current set of local scopes for lifetimes. + lifetime_ribs: Vec, + + /// 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>, + + /// 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>, + + /// 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, +} + +/// 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> { + 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, + ignore_binding: Option<&'a NameBinding<'a>>, + ) -> Option> { + 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, // `None` indicates a module path in import + finalize: Option, + ) -> 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( + &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(&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`.) + 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( + &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 // note lack of '_ + // async fn foo(_: std::cell::Ref) { ... } + 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, &'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, &'ast Ty)>, + ) -> Result, Vec)> { + 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 { + struct SelfVisitor<'r, 'a> { + r: &'r Resolver<'a>, + impl_self: Option, + lifetime: Set1, + } + + 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(&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(&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]) { + 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( + &mut self, + opt_trait_ref: Option<&TraitRef>, + self_type: &'ast Ty, + f: impl FnOnce(&mut Self, Option) -> 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, + self_type: &'ast Ty, + item_id: NodeId, + impl_items: &'ast [P], + ) { + 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( + &mut self, + id: NodeId, + mut ident: Ident, + kind: &AssocItemKind, + ns: Namespace, + span: Span, + err: F, + ) where + F: FnOnce(Ident, String, Option) -> 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]) -> Vec { + 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::>(); + + // 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::>(); + 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::>(); + 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); 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); 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); 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 { + &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 { + // 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| { + 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>| { + 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 `::A::B` + // or `::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 `::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, Spanned>> { + 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, Spanned>> { + 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 `::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 `::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 ::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