1//! This crate is responsible for the part of name resolution that doesn't require type checker.2//!3//! Module structure of the crate is built here.4//! Paths in macros, imports, expressions, types, patterns are resolved here.5//! Label and lifetime names are resolved here as well.6//!7//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.89// tidy-alphabetical-start10#![allow(internal_features)]11#![feature(arbitrary_self_types)]12#![feature(const_default)]13#![feature(const_trait_impl)]14#![feature(control_flow_into_value)]15#![feature(default_field_values)]16#![feature(deref_patterns)]17#![feature(iter_intersperse)]18#![feature(rustc_attrs)]19#![feature(trim_prefix_suffix)]20#![recursion_limit = "256"]21// tidy-alphabetical-end2223use std::cell::Ref;24use std::collections::BTreeSet;25use std::ops::ControlFlow;26use std::sync::Arc;27use std::{fmt, mem};2829use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};30use effective_visibilities::EffectiveVisibilitiesVisitor;31use error_helper::{ImportSuggestion, LabelSuggestion, StructCtor, Suggestion};32use hygiene::Macros20NormalizedSyntaxContext;33use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};34use late::{35 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,36 UnnecessaryQualification,37};38pub use macros::registered_tools_ast;39use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};40use rustc_arena::{DroplessArena, TypedArena};41use rustc_ast::node_id::NodeMap;42use rustc_ast::{43 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,44 GenericArg, GenericArgs, Generics, NodeId, Path, attr,45};46use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};47use rustc_data_structures::intern::Interned;48use rustc_data_structures::steal::Steal;49use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};50use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};51use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};52use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};53use rustc_feature::BUILTIN_ATTRIBUTES;54use rustc_hir::attrs::StrippedCfgItem;55use rustc_hir::def::Namespace::{self, *};56use rustc_hir::def::{57 self, CtorOf, DefKind, DocLinkResMap, MacroKinds, NonMacroAttrKind, PartialRes, PerNS,58};59use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};60use rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};61use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate, find_attr};62use rustc_index::bit_set::DenseBitSet;63use rustc_metadata::creader::CStore;64use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};65use rustc_middle::middle::privacy::EffectiveVisibilities;66use rustc_middle::query::Providers;67use rustc_middle::ty::{68 self, DelegationInfo, MainDefinition, PerOwnerResolverData, RegisteredTools,69 ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,70};71use rustc_middle::{bug, span_bug};72use rustc_session::config::CrateType;73use rustc_session::lint::builtin::PRIVATE_MACRO_USE;74use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};75use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};76use smallvec::{SmallVec, smallvec};77use tracing::{debug, instrument};7879use crate::error_helper::OnUnknownData;80use crate::ref_mut::{CmCell, CmRefCell};8182mod build_reduced_graph;83mod check_unused;84mod def_collector;85mod diagnostics;86mod effective_visibilities;87mod error_helper;88mod ident;89mod imports;90mod late;91mod macros;92pub mod rustdoc;9394type Res = def::Res<NodeId>;9596#[derive(Copy, Clone, PartialEq, Debug)]97enum Determinacy {98 Determined,99 Undetermined,100}101102impl Determinacy {103 fn determined(determined: bool) -> Determinacy {104 if determined { Determinacy::Determined } else { Determinacy::Undetermined }105 }106}107108/// A specific scope in which a name can be looked up.109#[derive(Clone, Copy, Debug)]110enum Scope<'ra> {111 /// Inert attributes registered by derive macros.112 DeriveHelpers(LocalExpnId),113 /// Inert attributes registered by derive macros, but used before they are actually declared.114 /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`115 /// is turned into a hard error.116 DeriveHelpersCompat,117 /// Textual `let`-like scopes introduced by `macro_rules!` items.118 MacroRules(MacroRulesScopeRef<'ra>),119 /// Non-glob names declared in the given module.120 /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`121 /// lint if it should be reported.122 ModuleNonGlobs(Module<'ra>, Option<NodeId>),123 /// Glob names declared in the given module.124 /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`125 /// lint if it should be reported.126 ModuleGlobs(Module<'ra>, Option<NodeId>),127 /// Names introduced by `#[macro_use]` attributes on `extern crate` items.128 MacroUsePrelude,129 /// Built-in attributes.130 BuiltinAttrs,131 /// Extern prelude names introduced by `extern crate` items.132 ExternPreludeItems,133 /// Extern prelude names introduced by `--extern` flags.134 ExternPreludeFlags,135 /// Tool modules introduced with `#![register_tool]`.136 ToolPrelude,137 /// Standard library prelude introduced with an internal `#[prelude_import]` import.138 StdLibPrelude,139 /// Built-in types.140 BuiltinTypes,141}142143/// Names from different contexts may want to visit different subsets of all specific scopes144/// with different restrictions when looking up the resolution.145#[derive(Clone, Copy, Debug)]146enum ScopeSet<'ra> {147 /// All scopes with the given namespace.148 All(Namespace),149 /// Two scopes inside a module, for non-glob and glob bindings.150 Module(Namespace, Module<'ra>),151 /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).152 ModuleAndExternPrelude(Namespace, Module<'ra>),153 /// Just two extern prelude scopes.154 ExternPrelude,155 /// Same as `All(MacroNS)`, but with the given macro kind restriction.156 Macro(MacroKind),157}158159/// Everything you need to know about a name's location to resolve it.160/// Serves as a starting point for the scope visitor.161/// This struct is currently used only for early resolution (imports and macros),162/// but not for late resolution yet.163#[derive(Clone, Copy, Debug)]164struct ParentScope<'ra> {165 module: Module<'ra>,166 expansion: LocalExpnId,167 macro_rules: MacroRulesScopeRef<'ra>,168 derives: &'ra [ast::Path],169}170171impl<'ra> ParentScope<'ra> {172 /// Creates a parent scope with the passed argument used as the module scope component,173 /// and other scope components set to default empty values.174 fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {175 ParentScope {176 module: module.to_module(),177 expansion: LocalExpnId::ROOT,178 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),179 derives: &[],180 }181 }182}183184#[derive(Copy, Debug, Clone)]185struct InvocationParent {186 parent_def: LocalDefId,187 impl_trait_context: ImplTraitContext,188 in_attr: bool,189 const_arg_context: ConstArgContext,190 owner: NodeId,191}192193impl InvocationParent {194 const ROOT: Self = Self {195 parent_def: CRATE_DEF_ID,196 impl_trait_context: ImplTraitContext::Existential,197 in_attr: false,198 const_arg_context: ConstArgContext::NonDirect,199 owner: CRATE_NODE_ID,200 };201}202203#[derive(Copy, Debug, Clone)]204enum ImplTraitContext {205 Existential,206 Universal,207 InBinding,208}209210#[derive(Copy, Clone, Debug)]211enum ConstArgContext {212 Direct,213 /// Either inside of an `AnonConst` or not inside a const argument at all.214 NonDirect,215}216217/// Used for tracking import use types which will be used for redundant import checking.218///219/// ### Used::Scope Example220///221/// ```rust,compile_fail222/// #![deny(redundant_imports)]223/// use std::mem::drop;224/// fn main() {225/// let s = Box::new(32);226/// drop(s);227/// }228/// ```229///230/// Used::Other is for other situations like module-relative uses.231#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]232enum Used {233 Scope,234 Other,235}236237#[derive(Debug)]238struct BindingError {239 name: Ident,240 origin: Vec<(Span, ast::Pat)>,241 target: Vec<ast::Pat>,242 could_be_path: bool,243}244245#[derive(Debug)]246enum ResolutionError<'ra> {247 /// Error E0401: can't use type or const parameters from outer item.248 GenericParamsFromOuterItem {249 outer_res: Res,250 has_generic_params: HasGenericParams,251 def_kind: DefKind,252 /// 1. label span, 2. item span, 3. item kind253 inner_item: Option<(Span, Span, ast::ItemKind)>,254 current_self_ty: Option<String>,255 },256 /// Error E0403: the name is already used for a type or const parameter in this generic257 /// parameter list.258 NameAlreadyUsedInParameterList(Ident, Span),259 /// Error E0407: method is not a member of trait.260 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),261 /// Error E0437: type is not a member of trait.262 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),263 /// Error E0438: const is not a member of trait.264 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),265 /// Error E0408: variable `{}` is not bound in all patterns.266 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),267 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.268 VariableBoundWithDifferentMode(Ident, Span),269 /// Error E0415: identifier is bound more than once in this parameter list.270 IdentifierBoundMoreThanOnceInParameterList(Ident),271 /// Error E0416: identifier is bound more than once in the same pattern.272 IdentifierBoundMoreThanOnceInSamePattern(Ident),273 /// Error E0426: use of undeclared label.274 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },275 /// Error E0433: failed to resolve.276 FailedToResolve {277 segment: Symbol,278 label: String,279 suggestion: Option<Suggestion>,280 module: Option<ModuleOrUniformRoot<'ra>>,281 message: String,282 },283 /// Error E0434: can't capture dynamic environment in a fn item.284 CannotCaptureDynamicEnvironmentInFnItem,285 /// Error E0435: attempt to use a non-constant value in a constant.286 AttemptToUseNonConstantValueInConstant {287 ident: Ident,288 suggestion: &'static str,289 current: &'static str,290 type_span: Option<Span>,291 },292 /// Error E0530: `X` bindings cannot shadow `Y`s.293 BindingShadowsSomethingUnacceptable {294 shadowing_binding: PatternSource,295 name: Symbol,296 participle: &'static str,297 article: &'static str,298 shadowed_binding: Res,299 shadowed_binding_span: Span,300 },301 /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.302 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),303 // FIXME(generic_const_parameter_types): This should give custom output specifying it's only304 // problematic to use *forward declared* parameters when the feature is enabled.305 /// ERROR E0770: the type of const parameters must not depend on other generic parameters.306 ParamInTyOfConstParam { name: Symbol },307 /// generic parameters must not be used inside const evaluations.308 ///309 /// This error is only emitted when using `min_const_generics`.310 ParamInNonTrivialAnonConst {311 is_gca: bool,312 name: Symbol,313 param_kind: ParamKindInNonTrivialAnonConst,314 },315 /// generic parameters must not be used inside enum discriminants.316 ///317 /// This error is emitted even with `generic_const_exprs`.318 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },319 /// Error E0735: generic parameters with a default cannot use `Self`320 ForwardDeclaredSelf(ForwardGenericParamBanReason),321 /// Error E0767: use of unreachable label322 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },323 /// Error E0323, E0324, E0325: mismatch between trait item and impl item.324 TraitImplMismatch {325 name: Ident,326 kind: &'static str,327 trait_path: String,328 trait_item_span: Span,329 code: ErrCode,330 },331 /// Error E0201: multiple impl items for the same trait item.332 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },333 /// Inline asm `sym` operand must refer to a `fn` or `static`.334 InvalidAsmSym,335 /// `self` used instead of `Self` in a generic parameter336 LowercaseSelf,337 /// A never pattern has a binding.338 BindingInNeverPattern,339}340341#[derive(Debug)]342enum VisResolutionError {343 Relative2018(Span, ast::Path),344 AncestorOnly(Span),345 FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),346 ExpectedFound(Span, String, Res),347 Indeterminate(Span),348 ModuleOnly(Span),349}350351/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path352/// segments' which don't have the rest of an AST or HIR `PathSegment`.353#[derive(Clone, Copy, Debug)]354struct Segment {355 ident: Ident,356 id: Option<NodeId>,357 /// Signals whether this `PathSegment` has generic arguments.358 has_generic_args: bool,359 /// Signals whether this `PathSegment` has lifetime arguments.360 has_lifetime_args: bool,361 args_span: Span,362}363364impl Segment {365 fn from_path(path: &Path) -> Vec<Segment> {366 path.segments.iter().map(|s| s.into()).collect()367 }368369 fn from_ident(ident: Ident) -> Segment {370 Segment {371 ident,372 id: None,373 has_generic_args: false,374 has_lifetime_args: false,375 args_span: DUMMY_SP,376 }377 }378379 fn names_to_string(segments: &[Segment]) -> String {380 names_to_string(segments.iter().map(|seg| seg.ident.name))381 }382}383384impl<'a> From<&'a ast::PathSegment> for Segment {385 fn from(seg: &'a ast::PathSegment) -> Segment {386 let has_generic_args = seg.args.is_some();387 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {388 match args {389 GenericArgs::AngleBracketed(args) => {390 let found_lifetimes = args391 .args392 .iter()393 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));394 (args.span, found_lifetimes)395 }396 GenericArgs::Parenthesized(args) => (args.span, true),397 GenericArgs::ParenthesizedElided(span) => (*span, true),398 }399 } else {400 (DUMMY_SP, false)401 };402 Segment {403 ident: seg.ident,404 id: Some(seg.id),405 has_generic_args,406 has_lifetime_args,407 args_span,408 }409 }410}411412/// Name declaration used during late resolution.413#[derive(Debug, Copy, Clone)]414enum LateDecl<'ra> {415 /// A regular name declaration.416 Decl(Decl<'ra>),417 /// A name definition from a rib, e.g. a local variable.418 /// Omits most of the data from regular `Decl` for performance reasons.419 RibDef(Res),420}421422impl<'ra> LateDecl<'ra> {423 fn res(self) -> Res {424 match self {425 LateDecl::Decl(binding) => binding.res(),426 LateDecl::RibDef(res) => res,427 }428 }429}430431#[derive(Copy, Clone, PartialEq, Debug)]432enum ModuleOrUniformRoot<'ra> {433 /// Regular module.434 Module(Module<'ra>),435436 /// Virtual module that denotes resolution in a module with fallback to extern prelude.437 /// Used for paths starting with `::` coming from 2015 edition macros438 /// used in 2018+ edition crates.439 ModuleAndExternPrelude(Module<'ra>),440441 /// Virtual module that denotes resolution in extern prelude.442 /// Used for paths starting with `::` on 2018 edition.443 ExternPrelude,444445 /// Virtual module that denotes resolution in current scope.446 /// Used only for resolving single-segment imports. The reason it exists is that import paths447 /// are always split into two parts, the first of which should be some kind of module.448 CurrentScope,449450 /// Virtual module for the resolution of base names of namespaced crates,451 /// where the base name doesn't correspond to a module in the extern prelude.452 /// E.g. `my_api::utils` is in the prelude, but `my_api` is not.453 OpenModule(Symbol),454}455456#[derive(Debug)]457enum PathResult<'ra> {458 Module(ModuleOrUniformRoot<'ra>),459 NonModule(PartialRes),460 Indeterminate,461 Failed {462 span: Span,463 label: String,464 suggestion: Option<Suggestion>,465 is_error_from_last_segment: bool,466 /// The final module being resolved, for instance:467 ///468 /// ```compile_fail469 /// mod a {470 /// mod b {471 /// mod c {}472 /// }473 /// }474 ///475 /// use a::not_exist::c;476 /// ```477 ///478 /// In this case, `module` will point to `a`.479 module: Option<ModuleOrUniformRoot<'ra>>,480 /// The segment of target481 segment: Ident,482 error_implied_by_parse_error: bool,483 message: String,484 note: Option<String>,485 },486}487488impl<'ra> PathResult<'ra> {489 fn failed(490 ident: Ident,491 is_error_from_last_segment: bool,492 finalize: bool,493 error_implied_by_parse_error: bool,494 module: Option<ModuleOrUniformRoot<'ra>>,495 label_and_suggestion_and_note: impl FnOnce() -> (496 String,497 String,498 Option<Suggestion>,499 Option<String>,500 ),501 ) -> PathResult<'ra> {502 let (message, label, suggestion, note) = if finalize {503 label_and_suggestion_and_note()504 } else {505 // FIXME: this output isn't actually present in the test suite.506 (format!("cannot find `{ident}` in this scope"), String::new(), None, None)507 };508 PathResult::Failed {509 span: ident.span,510 segment: ident,511 label,512 suggestion,513 is_error_from_last_segment,514 module,515 error_implied_by_parse_error,516 message,517 note,518 }519 }520}521522#[derive(Debug)]523enum ModuleKind {524 /// An anonymous module; e.g., just a block.525 ///526 /// ```527 /// fn main() {528 /// fn f() {} // (1)529 /// { // This is an anonymous module530 /// f(); // This resolves to (2) as we are inside the block.531 /// fn f() {} // (2)532 /// }533 /// f(); // Resolves to (1)534 /// }535 /// ```536 Block,537 /// Any module with a name.538 ///539 /// This could be:540 ///541 /// * A normal module – either `mod from_file;` or `mod from_block { }` –542 /// or the crate root (which is conceptually a top-level module).543 /// The crate root will have `None` for the symbol.544 /// * A trait or an enum (it implicitly contains associated types, methods and variant545 /// constructors).546 Def(DefKind, DefId, NodeId, Option<Symbol>),547}548549impl ModuleKind {550 fn opt_def_id(&self) -> Option<DefId> {551 match self {552 ModuleKind::Def(_, def_id, _, _) => Some(*def_id),553 _ => None,554 }555 }556557 fn def_id(&self) -> DefId {558 self.opt_def_id().expect("`Module::def_id` is called on a block module")559 }560561 fn is_local(&self) -> bool {562 match self {563 ModuleKind::Def(_, def_id, ..) => def_id.is_local(),564 ModuleKind::Block => true,565 }566 }567}568569/// Combination of a symbol and its macros 2.0 normalized hygiene context.570/// Used as a key in various kinds of name containers, including modules (as a part of slightly571/// larger `BindingKey`) and preludes.572///573/// Often passed around together with `orig_ident_span: Span`, which is an unnormalized span574/// of the original `Ident` from which `IdentKey` was obtained. This span is not used in map keys,575/// but used in a number of other scenarios - diagnostics, edition checks, `allow_unstable` checks576/// and similar. This is required because macros 2.0 normalization is lossy and the normalized577/// spans / syntax contexts no longer contain parts of macro backtraces, while the original span578/// contains everything.579#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]580struct IdentKey {581 name: Symbol,582 ctxt: Macros20NormalizedSyntaxContext,583}584585impl IdentKey {586 #[inline]587 fn new(ident: Ident) -> IdentKey {588 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }589 }590591 #[inline]592 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {593 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);594 (IdentKey { name: ident.name, ctxt }, def)595 }596597 #[inline]598 fn with_root_ctxt(name: Symbol) -> Self {599 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());600 IdentKey { name, ctxt }601 }602603 #[inline]604 fn orig(self, orig_ident_span: Span) -> Ident {605 Ident::new(self.name, orig_ident_span)606 }607}608609/// A key that identifies a binding in a given `Module`.610///611/// Multiple bindings in the same module can have the same key (in a valid612/// program) if all but one of them come from glob imports.613#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]614struct BindingKey {615 /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the616 /// identifier.617 ident: IdentKey,618 ns: Namespace,619 /// When we add an underscore binding (with ident `_`) to some module, this field has620 /// a non-zero value that uniquely identifies this binding in that module.621 /// For non-underscore bindings this field is zero.622 /// When a key is constructed for name lookup (as opposed to name definition), this field is623 /// also zero, even for underscore names, so for underscores the lookup will never succeed.624 disambiguator: u32,625}626627impl BindingKey {628 fn new(ident: IdentKey, ns: Namespace) -> Self {629 BindingKey { ident, ns, disambiguator: 0 }630 }631632 fn new_disambiguated(633 ident: IdentKey,634 ns: Namespace,635 disambiguator: impl FnOnce() -> u32,636 ) -> BindingKey {637 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };638 BindingKey { ident, ns, disambiguator }639 }640}641642type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;643644/// One node in the tree of modules.645///646/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:647///648/// * `mod`649/// * crate root (aka, top-level anonymous module)650/// * `enum`651/// * `trait`652/// * curly-braced block with statements653///654/// You can use [`ModuleData::kind`] to determine the kind of module this is.655struct ModuleData<'ra> {656 /// The direct parent module (it may not be a `mod`, however).657 parent: Option<Module<'ra>>,658 /// What kind of module this is, because this may not be a `mod`.659 kind: ModuleKind,660661 /// Mapping between names and their (possibly in-progress) resolutions in this module.662 /// Resolutions in modules from other crates are not populated until accessed.663 lazy_resolutions: Resolutions<'ra>,664 /// True if this is a module from other crate that needs to be populated on access.665 populate_on_access: CacheCell<bool>,666 /// Used to disambiguate underscore items (`const _: T = ...`) in the module.667 underscore_disambiguator: CmCell<u32>,668669 /// Macro invocations that can expand into items in this module.670 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,671672 /// Whether `#[no_implicit_prelude]` is active.673 no_implicit_prelude: bool,674675 glob_importers: CmRefCell<Vec<Import<'ra>>>,676 globs: CmRefCell<Vec<Import<'ra>>>,677678 /// Used to memoize the traits in this module for faster searches through all traits in scope.679 traits: CmRefCell<680 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool /* lint ambiguous */)]>>,681 >,682683 /// Span of the module itself. Used for error reporting.684 span: Span,685686 expansion: ExpnId,687688 /// Declaration for implicitly declared names that come with a module,689 /// like `self` (not yet used), or `crate`/`$crate` (for root modules).690 self_decl: Option<Decl<'ra>>,691}692693/// All modules are unique and allocated on a same arena,694/// so we can use referential equality to compare them.695#[derive(Clone, Copy, PartialEq, Eq, Hash)]696#[rustc_pass_by_value]697struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);698699/// Same as `Module`, but is guaranteed to be from the current crate.700#[derive(Clone, Copy, PartialEq, Eq, Hash)]701#[rustc_pass_by_value]702struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);703704/// Same as `Module`, but is guaranteed to be from an external crate.705#[derive(Clone, Copy, PartialEq, Eq, Hash)]706#[rustc_pass_by_value]707struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);708709// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the710// contained data.711// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees712// are upheld.713impl std::hash::Hash for ModuleData<'_> {714 fn hash<H>(&self, _: &mut H)715 where716 H: std::hash::Hasher,717 {718 unreachable!()719 }720}721722impl<'ra> ModuleData<'ra> {723 fn new(724 parent: Option<Module<'ra>>,725 kind: ModuleKind,726 expansion: ExpnId,727 span: Span,728 no_implicit_prelude: bool,729 vis: Visibility<DefId>,730 arenas: &'ra ResolverArenas<'ra>,731 ) -> Self {732 let is_foreign = !kind.is_local();733 let self_decl = match kind {734 ModuleKind::Def(def_kind, def_id, ..) => {735 let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);736 Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))737 }738 ModuleKind::Block => None,739 };740 ModuleData {741 parent,742 kind,743 lazy_resolutions: Default::default(),744 populate_on_access: CacheCell::new(is_foreign),745 underscore_disambiguator: CmCell::new(0),746 unexpanded_invocations: Default::default(),747 no_implicit_prelude,748 glob_importers: CmRefCell::new(Vec::new()),749 globs: CmRefCell::new(Vec::new()),750 traits: CmRefCell::new(None),751 span,752 expansion,753 self_decl,754 }755 }756757 /// Get name of the module.758 fn name(&self) -> Option<Symbol> {759 match self.kind {760 ModuleKind::Block => None,761 ModuleKind::Def(.., name) => name,762 }763 }764765 fn opt_def_id(&self) -> Option<DefId> {766 self.kind.opt_def_id()767 }768769 fn def_id(&self) -> DefId {770 self.kind.def_id()771 }772773 fn is_local(&self) -> bool {774 self.kind.is_local()775 }776777 fn has_unexpanded_invocations(&self) -> bool {778 !self.unexpanded_invocations.borrow().is_empty()779 }780781 fn res(&self) -> Option<Res> {782 match self.kind {783 ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),784 _ => None,785 }786 }787788 fn def_kind(&self) -> Option<DefKind> {789 match self.kind {790 ModuleKind::Def(def_kind, ..) => Some(def_kind),791 ModuleKind::Block => None,792 }793 }794}795796impl<'ra> Module<'ra> {797 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(798 self,799 resolver: &R,800 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),801 ) {802 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {803 let name_resolution = name_resolution.borrow();804 if let Some(decl) = name_resolution.best_decl() {805 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);806 }807 }808 }809810 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(811 self,812 resolver: &mut R,813 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),814 ) {815 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {816 let name_resolution = name_resolution.borrow();817 if let Some(decl) = name_resolution.best_decl() {818 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);819 }820 }821 }822823 /// This modifies `self` in place. The traits will be stored in `self.traits`.824 fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {825 let mut traits = self.traits.borrow_mut(resolver.as_ref());826 if traits.is_none() {827 let mut collected_traits = Vec::new();828 self.for_each_child(resolver, |r, ident, _, ns, binding| {829 if ns != TypeNS {830 return;831 }832 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {833 collected_traits.push((834 ident.name,835 binding,836 r.as_ref().get_module(def_id),837 binding.is_ambiguity_recursive(),838 ));839 }840 });841 *traits = Some(collected_traits.into_boxed_slice());842 }843 }844845 // `self` resolves to the first module ancestor that `is_normal`.846 fn is_normal(self) -> bool {847 self.def_kind() == Some(DefKind::Mod)848 }849850 fn is_trait(self) -> bool {851 matches!(self.def_kind(), Some(DefKind::Trait))852 }853854 fn nearest_item_scope(self) -> Module<'ra> {855 match self.def_kind() {856 Some(DefKind::Enum | DefKind::Trait) => {857 self.parent.expect("enum or trait module without a parent")858 }859 _ => self,860 }861 }862863 /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).864 /// This may be the crate root.865 fn nearest_parent_mod(self) -> DefId {866 match self.kind {867 ModuleKind::Def(DefKind::Mod, def_id, _, _) => def_id,868 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),869 }870 }871872 /// The [`NodeId`] of the nearest `mod` item ancestor (which may be this module).873 /// This may be the crate root.874 fn nearest_parent_mod_node_id(self) -> NodeId {875 match self.kind {876 ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,877 _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),878 }879 }880881 fn is_ancestor_of(self, mut other: Self) -> bool {882 while self != other {883 if let Some(parent) = other.parent {884 other = parent;885 } else {886 return false;887 }888 }889 true890 }891892 #[track_caller]893 fn expect_local(self) -> LocalModule<'ra> {894 match self.kind {895 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {896 span_bug!(self.span, "unexpected extern module: {self:?}")897 }898 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),899 }900 }901902 #[track_caller]903 fn expect_extern(self) -> ExternModule<'ra> {904 match self.kind {905 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),906 ModuleKind::Def(..) | ModuleKind::Block => {907 span_bug!(self.span, "unexpected local module: {self:?}")908 }909 }910 }911}912913impl<'ra> LocalModule<'ra> {914 fn new(915 parent: Option<LocalModule<'ra>>,916 kind: ModuleKind,917 vis: Visibility<DefId>,918 expn_id: ExpnId,919 span: Span,920 no_implicit_prelude: bool,921 arenas: &'ra ResolverArenas<'ra>,922 ) -> LocalModule<'ra> {923 assert!(kind.is_local());924 let parent = parent.map(|m| m.to_module());925 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);926 LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))927 }928929 fn to_module(self) -> Module<'ra> {930 Module(self.0)931 }932}933934impl<'ra> ExternModule<'ra> {935 fn new(936 parent: Option<ExternModule<'ra>>,937 kind: ModuleKind,938 vis: Visibility<DefId>,939 expn_id: ExpnId,940 span: Span,941 no_implicit_prelude: bool,942 arenas: &'ra ResolverArenas<'ra>,943 ) -> ExternModule<'ra> {944 assert!(!kind.is_local());945 let parent = parent.map(|m| m.to_module());946 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);947 ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))948 }949950 fn to_module(self) -> Module<'ra> {951 Module(self.0)952 }953}954955impl<'ra> std::ops::Deref for Module<'ra> {956 type Target = ModuleData<'ra>;957958 fn deref(&self) -> &Self::Target {959 &self.0960 }961}962963impl<'ra> std::ops::Deref for LocalModule<'ra> {964 type Target = ModuleData<'ra>;965966 fn deref(&self) -> &Self::Target {967 &self.0968 }969}970971impl<'ra> std::ops::Deref for ExternModule<'ra> {972 type Target = ModuleData<'ra>;973974 fn deref(&self) -> &Self::Target {975 &self.0976 }977}978979impl<'ra> fmt::Debug for Module<'ra> {980 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {981 match self.res() {982 None => write!(f, "block"),983 Some(res) => write!(f, "{:?}", res),984 }985 }986}987988impl<'ra> fmt::Debug for LocalModule<'ra> {989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {990 self.to_module().fmt(f)991 }992}993994/// Data associated with any name declaration.995#[derive(Clone, Debug)]996struct DeclData<'ra> {997 kind: DeclKind<'ra>,998 ambiguity: CmCell<Option<(Decl<'ra>, bool /*warning*/)>>,999 expansion: LocalExpnId,1000 span: Span,1001 initial_vis: Visibility<DefId>,1002 /// If the declaration refers to an ambiguous glob set, then this is the most visible1003 /// declaration from the set, if its visibility is different from `initial_vis`.1004 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,1005 /// If the declaration refers to an ambiguous glob set, then this is the least visible1006 /// declaration from the set, if its visibility is different from `initial_vis`.1007 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,1008 parent_module: Option<Module<'ra>>,1009}10101011/// All name declarations are unique and allocated on a same arena,1012/// so we can use referential equality to compare them.1013type Decl<'ra> = Interned<'ra, DeclData<'ra>>;10141015// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the1016// contained data.1017// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees1018// are upheld.1019impl std::hash::Hash for DeclData<'_> {1020 fn hash<H>(&self, _: &mut H)1021 where1022 H: std::hash::Hasher,1023 {1024 unreachable!()1025 }1026}10271028/// Name declaration kind.1029#[derive(Clone, Copy, Debug)]1030enum DeclKind<'ra> {1031 /// The name declaration is a definition (possibly without a `DefId`),1032 /// can be provided by source code or built into the language.1033 Def(Res),1034 /// The name declaration is a link to another name declaration.1035 Import { source_decl: Decl<'ra>, import: Import<'ra> },1036}10371038impl<'ra> DeclKind<'ra> {1039 /// Is this an import declaration?1040 fn is_import(&self) -> bool {1041 matches!(*self, DeclKind::Import { .. })1042 }1043}10441045#[derive(Debug)]1046struct PrivacyError<'ra> {1047 ident: Ident,1048 decl: Decl<'ra>,1049 dedup_span: Span,1050 outermost_res: Option<(Res, Ident)>,1051 parent_scope: ParentScope<'ra>,1052 /// Is the format `use a::{b,c}`?1053 single_nested: bool,1054 source: Option<ast::Expr>,1055}10561057#[derive(Debug)]1058struct UseError<'a> {1059 err: Diag<'a>,1060 /// Candidates which user could `use` to access the missing type.1061 candidates: Vec<ImportSuggestion>,1062 /// The `NodeId` of the module to place the use-statements in.1063 node_id: NodeId,1064 /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).1065 instead: bool,1066 /// Extra free-form suggestion.1067 suggestion: Option<(Span, &'static str, String, Applicability)>,1068 /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling1069 /// the user to import the item directly.1070 path: Vec<Segment>,1071 /// Whether the expected source is a call1072 is_call: bool,1073}10741075#[derive(Debug)]1076struct DelayedVisResolutionError<'ra> {1077 vis: ast::Visibility,1078 parent_scope: ParentScope<'ra>,1079 error: VisResolutionError,1080}10811082#[derive(Clone, Copy, PartialEq, Debug)]1083enum AmbiguityKind {1084 BuiltinAttr,1085 DeriveHelper,1086 MacroRulesVsModularized,1087 GlobVsOuter,1088 GlobVsGlob,1089 GlobVsExpanded,1090 MoreExpandedVsOuter,1091}10921093impl AmbiguityKind {1094 fn descr(self) -> &'static str {1095 match self {1096 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",1097 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",1098 AmbiguityKind::MacroRulesVsModularized => {1099 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"1100 }1101 AmbiguityKind::GlobVsOuter => {1102 "a conflict between a name from a glob import and an outer scope during import or macro resolution"1103 }1104 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",1105 AmbiguityKind::GlobVsExpanded => {1106 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"1107 }1108 AmbiguityKind::MoreExpandedVsOuter => {1109 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"1110 }1111 }1112 }1113}11141115#[derive(Clone, Copy, PartialEq)]1116enum AmbiguityWarning {1117 GlobImport,1118 PanicImport,1119}11201121struct AmbiguityError<'ra> {1122 kind: AmbiguityKind,1123 ambig_vis: Option<(Visibility, Visibility)>,1124 ident: Ident,1125 b1: Decl<'ra>,1126 b2: Decl<'ra>,1127 scope1: Scope<'ra>,1128 scope2: Scope<'ra>,1129 warning: Option<AmbiguityWarning>,1130}11311132impl<'ra> DeclData<'ra> {1133 fn vis(&self) -> Visibility<DefId> {1134 // Select the maximum visibility if there are multiple ambiguous glob imports.1135 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)1136 }11371138 fn min_vis(&self) -> Visibility<DefId> {1139 // Select the minimum visibility if there are multiple ambiguous glob imports.1140 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)1141 }11421143 fn res(&self) -> Res {1144 match self.kind {1145 DeclKind::Def(res) => res,1146 DeclKind::Import { source_decl, .. } => source_decl.res(),1147 }1148 }11491150 fn import_source(&self) -> Decl<'ra> {1151 match self.kind {1152 DeclKind::Import { source_decl, .. } => source_decl,1153 _ => unreachable!(),1154 }1155 }11561157 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {1158 match self.ambiguity.get() {1159 Some((ambig_binding, _)) => Some((self, ambig_binding)),1160 None => match self.kind {1161 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),1162 _ => None,1163 },1164 }1165 }11661167 fn is_ambiguity_recursive(&self) -> bool {1168 self.ambiguity.get().is_some()1169 || match self.kind {1170 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),1171 _ => false,1172 }1173 }11741175 fn is_possibly_imported_variant(&self) -> bool {1176 match self.kind {1177 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),1178 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {1179 true1180 }1181 DeclKind::Def(..) => false,1182 }1183 }11841185 fn is_extern_crate(&self) -> bool {1186 match self.kind {1187 DeclKind::Import { import, .. } => {1188 matches!(import.kind, ImportKind::ExternCrate { .. })1189 }1190 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),1191 _ => false,1192 }1193 }11941195 fn is_import(&self) -> bool {1196 matches!(self.kind, DeclKind::Import { .. })1197 }11981199 /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might1200 /// not be perceived as such by users, so treat it as a non-import in some diagnostics.1201 fn is_import_user_facing(&self) -> bool {1202 matches!(self.kind, DeclKind::Import { import, .. }1203 if !matches!(import.kind, ImportKind::MacroExport))1204 }12051206 fn is_glob_import(&self) -> bool {1207 match self.kind {1208 DeclKind::Import { import, .. } => import.is_glob(),1209 _ => false,1210 }1211 }12121213 fn is_assoc_item(&self) -> bool {1214 matches!(1215 self.res(),1216 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)1217 )1218 }12191220 fn macro_kinds(&self) -> Option<MacroKinds> {1221 self.res().macro_kinds()1222 }12231224 fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {1225 let mut reexport_chain = SmallVec::new();1226 let mut next_binding = self;1227 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {1228 reexport_chain.push(import.simplify());1229 next_binding = source_decl;1230 }1231 reexport_chain1232 }12331234 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`1235 // at some expansion round `max(invoc, binding)` when they both emerged from macros.1236 // Then this function returns `true` if `self` may emerge from a macro *after* that1237 // in some later round and screw up our previously found resolution.1238 // See more detailed explanation in1239 // https://github.com/rust-lang/rust/pull/53778#issuecomment-4192240491240 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {1241 // self > max(invoc, decl) => !(self <= invoc || self <= decl)1242 // Expansions are partially ordered, so "may appear after" is an inversion of1243 // "certainly appears before or simultaneously" and includes unordered cases.1244 let self_parent_expansion = self.expansion;1245 let other_parent_expansion = decl.expansion;1246 let certainly_before_other_or_simultaneously =1247 other_parent_expansion.is_descendant_of(self_parent_expansion);1248 let certainly_before_invoc_or_simultaneously =1249 invoc_parent_expansion.is_descendant_of(self_parent_expansion);1250 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)1251 }12521253 /// Returns whether this declaration may be shadowed or overwritten by something else later.1254 /// FIXME: this function considers `unexpanded_invocations`, but not `single_imports`, so1255 /// the declaration may not be as "determined" as we think.1256 /// FIXME: relationship between this function and similar `NameResolution::determined_decl`1257 /// is unclear.1258 fn determined(&self) -> bool {1259 match &self.kind {1260 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {1261 !import.parent_scope.module.has_unexpanded_invocations() && source_decl.determined()1262 }1263 _ => true,1264 }1265 }1266}12671268#[derive(Debug)]1269struct ExternPreludeEntry<'ra> {1270 /// Name declaration from an `extern crate` item.1271 /// The boolean flag is true is `item_decl` is non-redundant, happens either when1272 /// `flag_decl` is `None`, or when `extern crate` introducing `item_decl` used renaming.1273 item_decl: Option<(Decl<'ra>, Span, /* introduced by item */ bool)>,1274 /// Name declaration from an `--extern` flag, lazily populated on first use.1275 flag_decl: Option<1276 CacheCell<(1277 PendingDecl<'ra>,1278 /* finalized */ bool,1279 /* open flag (namespaced crate) */ bool,1280 )>,1281 >,1282}12831284impl ExternPreludeEntry<'_> {1285 fn introduced_by_item(&self) -> bool {1286 matches!(self.item_decl, Some((.., true)))1287 }12881289 fn flag() -> Self {1290 ExternPreludeEntry {1291 item_decl: None,1292 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),1293 }1294 }12951296 fn open_flag() -> Self {1297 ExternPreludeEntry {1298 item_decl: None,1299 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),1300 }1301 }13021303 fn span(&self) -> Span {1304 match self.item_decl {1305 Some((_, span, _)) => span,1306 None => DUMMY_SP,1307 }1308 }1309}13101311struct DeriveData {1312 resolutions: Vec<DeriveResolution>,1313 helper_attrs: Vec<(usize, IdentKey, Span)>,1314 // if this list keeps getting extended, we could use `bitflags`,1315 // something like what [`rustc_type_ir::flags::TypeFlags`] is doing.1316 has_derive_copy: bool,1317 has_derive_ord: bool,1318}13191320pub struct ResolverOutputs<'tcx> {1321 pub global_ctxt: ResolverGlobalCtxt,1322 pub ast_lowering: ResolverAstLowering<'tcx>,1323}13241325#[derive(Debug)]1326struct DelegationFnSig {1327 pub has_self: bool,1328}13291330/// The main resolver class.1331///1332/// This is the visitor that walks the whole crate.1333pub struct Resolver<'ra, 'tcx> {1334 tcx: TyCtxt<'tcx>,13351336 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.1337 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),13381339 graph_root: LocalModule<'ra>,13401341 /// Assert that we are in speculative resolution mode.1342 assert_speculative: bool,13431344 prelude: Option<Module<'ra>> = None,1345 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,13461347 /// N.B., this is used only for better diagnostics, not name resolution itself.1348 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),1349 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),13501351 /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.1352 /// Used for hints during error reporting.1353 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),13541355 /// All imports known to succeed or fail.1356 determined_imports: Vec<Import<'ra>> = Vec::new(),13571358 /// All non-determined imports.1359 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),13601361 // Spans for local variables found during pattern resolution.1362 // Used for suggestions during error reporting.1363 pat_span_map: NodeMap<Span> = Default::default(),13641365 /// Resolutions for nodes that have a single resolution.1366 partial_res_map: NodeMap<PartialRes> = Default::default(),1367 /// An import will be inserted into this map if it has been used.1368 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),1369 /// Lifetime parameters that lowering will have to introduce.1370 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, MissingLifetimeKind)>> = Default::default(),13711372 /// `CrateNum` resolutions of `extern crate` items.1373 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),1374 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),1375 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),13761377 /// A map from nodes to anonymous modules.1378 /// Anonymous modules are pseudo-modules that are implicitly created around items1379 /// contained within blocks.1380 ///1381 /// For example, if we have this:1382 ///1383 /// fn f() {1384 /// fn g() {1385 /// ...1386 /// }1387 /// }1388 ///1389 /// There will be an anonymous module created around `g` with the ID of the1390 /// entry block for `f`.1391 block_map: NodeMap<LocalModule<'ra>> = Default::default(),1392 /// A fake module that contains no definition and no prelude. Used so that1393 /// some AST passes can generate identifiers that only resolve to local or1394 /// lang items.1395 empty_module: LocalModule<'ra>,1396 /// All local modules, including blocks.1397 local_modules: Vec<LocalModule<'ra>>,1398 /// Eagerly populated map of all local non-block modules.1399 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,1400 /// Lazily populated cache of modules loaded from external crates.1401 extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,14021403 /// Maps glob imports to the names of items actually imported.1404 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,1405 glob_error: Option<ErrorGuaranteed> = None,1406 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),1407 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),1408 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,14091410 /// Privacy errors are delayed until the end in order to deduplicate them.1411 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),1412 /// Ambiguity errors are delayed for deduplication.1413 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),1414 issue_145575_hack_applied: bool = false,1415 /// `use` injections are delayed for better placement and deduplication.1416 use_injections: Vec<UseError<'tcx>> = Vec::new(),1417 /// Visibility path resolution failures are delayed until all modules are collected.1418 delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),1419 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.1420 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),14211422 arenas: &'ra ResolverArenas<'ra>,1423 dummy_decl: Decl<'ra>,1424 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,1425 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,1426 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,1427 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),1428 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),1429 registered_tools: &'tcx RegisteredTools,1430 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,1431 /// Eagerly populated map of all local macro definitions.1432 local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),1433 /// Lazily populated cache of macro definitions loaded from external crates.1434 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,1435 dummy_ext_bang: &'ra Arc<SyntaxExtension>,1436 dummy_ext_derive: &'ra Arc<SyntaxExtension>,1437 non_macro_attr: &'ra Arc<SyntaxExtension>,1438 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),1439 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),1440 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,1441 /// A map from the macro to all its potentially unused arms and the `LocalDefId` of the macro itself.1442 unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,1443 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),1444 /// Traces collected during macro resolution and validated when it's complete.1445 single_segment_macro_resolutions:1446 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,1447 multi_segment_macro_resolutions:1448 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,1449 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),1450 /// `derive(Copy)` marks items they are applied to so they are treated specially later.1451 /// Derive macros cannot modify the item themselves and have to store the markers in the global1452 /// context, so they attach the markers to derive container IDs using this resolver table.1453 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),1454 containers_deriving_ord: FxHashSet<LocalExpnId> = default::fx_hash_set(),1455 /// Parent scopes in which the macros were invoked.1456 /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.1457 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),1458 /// `macro_rules` scopes *produced* by expanding the macro invocations,1459 /// include all the `macro_rules` items and other invocations generated by them.1460 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),1461 /// `macro_rules` scopes produced by `macro_rules` item definitions.1462 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),1463 /// Helper attributes that are in scope for the given expansion.1464 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),1465 /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute1466 /// with the given `ExpnId`.1467 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),14681469 /// Avoid duplicated errors for "name already defined".1470 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),14711472 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),14731474 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),14751476 /// Table for mapping struct IDs into struct constructor IDs,1477 /// it's not used during normal resolution, only for better error reporting.1478 /// Also includes of list of each fields visibility1479 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),14801481 /// for all the struct1482 /// it's not used during normal resolution, only for better error reporting.1483 struct_generics: LocalDefIdMap<Generics> = Default::default(),14841485 lint_buffer: LintBuffer,14861487 next_node_id: NodeId = CRATE_NODE_ID,14881489 /// Preserves per owner data once the owner is finished resolving.1490 owners: NodeMap<PerOwnerResolverData<'tcx>>,14911492 /// An entry of `owners` that gets taken out and reinserted whenever an owner is handled.1493 current_owner: PerOwnerResolverData<'tcx>,14941495 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,14961497 /// Indices of unnamed struct or variant fields with unresolved attributes.1498 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),1499 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`1500 /// we know what parent node that fragment should be attached to thanks to this table,1501 /// and how the `impl Trait` fragments were introduced.1502 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,15031504 /// Amount of lifetime parameters for each item in the crate.1505 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),1506 /// Generic args to suggest for required params (e.g. `<'_>`, `<_, _>`), if any.1507 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),1508 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),1509 delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,15101511 main_def: Option<MainDefinition> = None,1512 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,1513 /// A list of proc macro LocalDefIds, written out in the order in which1514 /// they are declared in the static array generated by proc_macro_harness.1515 proc_macros: Vec<LocalDefId> = Vec::new(),1516 confused_type_with_std_module: FxIndexMap<Span, Span>,15171518 /// Names of items that were stripped out via cfg with their corresponding cfg meta item.1519 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),15201521 effective_visibilities: EffectiveVisibilities,1522 macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,15231524 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,1525 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,1526 all_macro_rules: UnordSet<Symbol> = Default::default(),15271528 /// Invocation ids of all glob delegations.1529 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),1530 /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.1531 /// Needed because glob delegations wait for all other neighboring macros to expand.1532 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),1533 /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.1534 /// Needed because glob delegations exclude explicitly defined names.1535 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),15361537 /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`1538 /// could be a crate that wasn't imported. For diagnostics use only.1539 current_crate_outer_attr_insert_span: Span,15401541 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),15421543 /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we1544 /// don't need to run it more than once.1545 all_crate_macros_already_registered: bool = false,15461547 // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types1548 // that were encountered during resolution. These names are used to generate item names1549 // for APITs, so we don't want to leak details of resolution into these names.1550 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),15511552 /// Stores `#[diagnostic::on_unknown]` attributes placed on module declarations.1553 on_unknown_data: FxHashMap<LocalDefId, OnUnknownData>,1554}15551556/// This provides memory for the rest of the crate. The `'ra` lifetime that is1557/// used by many types in this crate is an abbreviation of `ResolverArenas`.1558#[derive(Default)]1559pub struct ResolverArenas<'ra> {1560 modules: TypedArena<ModuleData<'ra>>,1561 imports: TypedArena<ImportData<'ra>>,1562 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,1563 ast_paths: TypedArena<ast::Path>,1564 macros: TypedArena<Arc<SyntaxExtension>>,1565 dropless: DroplessArena,1566}15671568impl<'ra> ResolverArenas<'ra> {1569 fn new_def_decl(1570 &'ra self,1571 res: Res,1572 vis: Visibility<DefId>,1573 span: Span,1574 expansion: LocalExpnId,1575 parent_module: Option<Module<'ra>>,1576 ) -> Decl<'ra> {1577 self.alloc_decl(DeclData {1578 kind: DeclKind::Def(res),1579 ambiguity: CmCell::new(None),1580 initial_vis: vis,1581 ambiguity_vis_max: CmCell::new(None),1582 ambiguity_vis_min: CmCell::new(None),1583 span,1584 expansion,1585 parent_module,1586 })1587 }15881589 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {1590 self.new_def_decl(res, Visibility::Public, span, expn_id, None)1591 }15921593 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {1594 Interned::new_unchecked(self.dropless.alloc(data))1595 }1596 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {1597 Interned::new_unchecked(self.imports.alloc(import))1598 }1599 fn alloc_name_resolution(1600 &'ra self,1601 orig_ident_span: Span,1602 ) -> &'ra CmRefCell<NameResolution<'ra>> {1603 self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))1604 }1605 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {1606 self.dropless.alloc(CacheCell::new(scope))1607 }1608 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {1609 self.dropless.alloc(decl)1610 }1611 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {1612 self.ast_paths.alloc_from_iter(paths.iter().cloned())1613 }1614 fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {1615 self.macros.alloc(Arc::new(ext))1616 }1617 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {1618 self.dropless.alloc_from_iter(spans)1619 }1620}16211622impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {1623 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {1624 self1625 }1626}16271628impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {1629 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {1630 self1631 }1632}16331634impl<'tcx> Resolver<'_, 'tcx> {1635 /// Only call this in analyses after the resolver has finished.1636 /// Panics if the node id is currently not in the owner storage,1637 /// e.g. because it's further up in the current visitor stack.1638 fn owner_def_id(&self, owner: NodeId) -> LocalDefId {1639 self.owners[&owner].def_id1640 }16411642 /// Only call this in analyses after the resolver has finished.1643 /// Panics if the node id is currently not in the owner storage,1644 /// e.g. because it's further up in the current visitor stack.1645 fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {1646 self.owners[&owner].node_id_to_def_id[&id]1647 }16481649 /// Get the `DefId` of a child of the current owner1650 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {1651 self.current_owner.node_id_to_def_id.get(&node).copied()1652 }16531654 /// Get the `DefId` of a child of the current owner1655 fn local_def_id(&self, node: NodeId) -> LocalDefId {1656 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))1657 }16581659 /// Adds a definition with a parent definition.1660 fn create_def(1661 &mut self,1662 parent: LocalDefId,1663 node_id: ast::NodeId,1664 name: Option<Symbol>,1665 def_kind: DefKind,1666 expn_id: ExpnId,1667 span: Span,1668 is_owner: bool,1669 ) -> TyCtxtFeed<'tcx, LocalDefId> {1670 assert!(1671 !self.current_owner.node_id_to_def_id.contains_key(&node_id),1672 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",1673 node_id,1674 name,1675 def_kind,1676 self.tcx1677 .definitions_untracked()1678 .def_key(self.current_owner.node_id_to_def_id[&node_id]),1679 );16801681 let disambiguator = self.disambiguators.get_or_create(parent);16821683 // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`1684 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);1685 let def_id = feed.def_id();16861687 // Create the definition.1688 if expn_id != ExpnId::root() {1689 self.expn_that_defined.insert(def_id, expn_id);1690 }16911692 // A relative span's parent must be an absolute span.1693 debug_assert_eq!(span.data_untracked().parent, None);1694 let _id = self.tcx.untracked().source_span.push(span);1695 debug_assert_eq!(_id, def_id);16961697 // Some things for which we allocate `LocalDefId`s don't correspond to1698 // anything in the AST, so they don't have a `NodeId`. For these cases1699 // we don't need a mapping from `NodeId` to `LocalDefId`.1700 if node_id != ast::DUMMY_NODE_ID && !is_owner {1701 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);1702 self.current_owner.node_id_to_def_id.insert(node_id, def_id);1703 }17041705 feed1706 }17071708 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {1709 if let Some(def_id) = def_id.as_local() {1710 self.item_generics_num_lifetimes[&def_id]1711 } else {1712 self.tcx.generics_of(def_id).own_counts().lifetimes1713 }1714 }17151716 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {1717 if let Some(def_id) = def_id.as_local() {1718 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()1719 } else {1720 let required = self1721 .tcx1722 .generics_of(def_id)1723 .own_params1724 .iter()1725 .filter_map(|param| match param.kind {1726 ty::GenericParamDefKind::Lifetime => Some("'_"),1727 ty::GenericParamDefKind::Type { has_default, .. }1728 | ty::GenericParamDefKind::Const { has_default } => {1729 if has_default {1730 None1731 } else {1732 Some("_")1733 }1734 }1735 })1736 .collect::<Vec<_>>();17371738 if required.is_empty() { String::new() } else { format!("<{}>", required.join(", ")) }1739 }1740 }17411742 pub fn tcx(&self) -> TyCtxt<'tcx> {1743 self.tcx1744 }17451746 /// This function is very slow, as it iterates over the entire1747 /// [PerOwnerResolverData::node_id_to_def_id] map for all [Resolver::owners]1748 /// just to find the [NodeId]1749 /// that corresponds to the given [LocalDefId]. Only use this in1750 /// diagnostics code paths. Do not use this during macro expansion,1751 /// as it will not find any node ids within your current expansion's stack.1752 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {1753 self.owners1754 .items()1755 .flat_map(|(_, data)| {1756 data.node_id_to_def_id1757 .items()1758 .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))1759 })1760 .filter(|(_, v)| **v == def_id)1761 .map(|(k, _)| *k)1762 .get_only()1763 .unwrap()1764 }1765}17661767impl<'ra, 'tcx> Resolver<'ra, 'tcx> {1768 pub fn new(1769 tcx: TyCtxt<'tcx>,1770 attrs: &[ast::Attribute],1771 crate_span: Span,1772 current_crate_outer_attr_insert_span: Span,1773 arenas: &'ra ResolverArenas<'ra>,1774 ) -> Resolver<'ra, 'tcx> {1775 let root_def_id = CRATE_DEF_ID.to_def_id();1776 let graph_root = LocalModule::new(1777 None,1778 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),1779 Visibility::Public,1780 ExpnId::root(),1781 crate_span,1782 attr::contains_name(attrs, sym::no_implicit_prelude),1783 arenas,1784 );1785 let local_modules = vec![graph_root];1786 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);1787 let empty_module = LocalModule::new(1788 None,1789 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),1790 Visibility::Public,1791 ExpnId::root(),1792 DUMMY_SP,1793 true,1794 arenas,1795 );17961797 let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);1798 let crate_feed = tcx.create_local_crate_def_id(crate_span);17991800 crate_feed.def_kind(DefKind::Mod);1801 let mut owners = NodeMap::default();1802 owners.insert(CRATE_NODE_ID, owner_data);18031804 let mut invocation_parents = FxHashMap::default();1805 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);18061807 let extern_prelude = build_extern_prelude(tcx, attrs);1808 let registered_tools = tcx.registered_tools(());1809 let edition = tcx.sess.edition();18101811 let mut on_unknown_data = default::fx_hash_map();1812 if let Some(directive) = OnUnknownData::from_attrs(tcx, attrs) {1813 on_unknown_data.insert(CRATE_DEF_ID, directive);1814 }18151816 let mut resolver = Resolver {1817 tcx,18181819 // The outermost module has def ID 0; this is not reflected in the1820 // AST.1821 graph_root,1822 assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now1823 extern_prelude,18241825 empty_module,1826 local_modules,1827 local_module_map,1828 extern_module_map: Default::default(),18291830 glob_map: Default::default(),1831 maybe_unused_trait_imports: Default::default(),18321833 arenas,1834 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),1835 builtin_type_decls: PrimTy::ALL1836 .iter()1837 .map(|prim_ty| {1838 let res = Res::PrimTy(*prim_ty);1839 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);1840 (prim_ty.name(), decl)1841 })1842 .collect(),1843 builtin_attr_decls: BUILTIN_ATTRIBUTES1844 .iter()1845 .map(|builtin_attr| {1846 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));1847 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);1848 (*builtin_attr, decl)1849 })1850 .collect(),1851 registered_tool_decls: registered_tools1852 .iter()1853 .map(|&ident| {1854 let res = Res::ToolMod;1855 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);1856 (IdentKey::new(ident), decl)1857 })1858 .collect(),1859 registered_tools,1860 macro_use_prelude: Default::default(),1861 extern_macro_map: Default::default(),1862 dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),1863 dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),1864 non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),1865 unused_macros: Default::default(),1866 unused_macro_rules: Default::default(),1867 single_segment_macro_resolutions: Default::default(),1868 multi_segment_macro_resolutions: Default::default(),1869 lint_buffer: LintBuffer::default(),1870 owners,1871 current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),1872 invocation_parents,1873 trait_impls: Default::default(),1874 confused_type_with_std_module: Default::default(),1875 stripped_cfg_items: Default::default(),1876 effective_visibilities: Default::default(),1877 macro_reachable_adts: Default::default(),1878 doc_link_resolutions: Default::default(),1879 doc_link_traits_in_scope: Default::default(),1880 current_crate_outer_attr_insert_span,1881 disambiguators: Default::default(),1882 delegation_infos: Default::default(),1883 on_unknown_data,1884 ..1885 };18861887 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);1888 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);1889 resolver.feed_visibility(crate_feed, Visibility::Public);18901891 resolver1892 }18931894 fn new_local_module(1895 &mut self,1896 parent: Option<LocalModule<'ra>>,1897 kind: ModuleKind,1898 expn_id: ExpnId,1899 span: Span,1900 no_implicit_prelude: bool,1901 ) -> LocalModule<'ra> {1902 let vis =1903 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));1904 let module =1905 LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);1906 self.local_modules.push(module);1907 if let Some(def_id) = module.opt_def_id() {1908 self.local_module_map.insert(def_id.expect_local(), module);1909 }1910 module1911 }19121913 fn new_extern_module(1914 &self,1915 parent: Option<ExternModule<'ra>>,1916 kind: ModuleKind,1917 expn_id: ExpnId,1918 span: Span,1919 no_implicit_prelude: bool,1920 ) -> ExternModule<'ra> {1921 let def_id = kind.def_id();1922 let module = ExternModule::new(1923 parent,1924 kind,1925 self.tcx.visibility(def_id),1926 expn_id,1927 span,1928 no_implicit_prelude,1929 self.arenas,1930 );1931 self.extern_module_map.borrow_mut().insert(def_id, module);1932 module1933 }19341935 fn next_node_id(&mut self) -> NodeId {1936 let start = self.next_node_id;1937 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");1938 self.next_node_id = ast::NodeId::from_u32(next);1939 start1940 }19411942 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {1943 let start = self.next_node_id;1944 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");1945 self.next_node_id = ast::NodeId::from_usize(end);1946 start..self.next_node_id1947 }19481949 pub fn lint_buffer(&mut self) -> &mut LintBuffer {1950 &mut self.lint_buffer1951 }19521953 pub fn arenas() -> ResolverArenas<'ra> {1954 Default::default()1955 }19561957 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {1958 feed.visibility(vis.to_def_id());1959 self.visibilities_for_hashing.push((feed.def_id(), vis));1960 }19611962 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {1963 let proc_macros = self.proc_macros;1964 let expn_that_defined = self.expn_that_defined;1965 let extern_crate_map = self.extern_crate_map;1966 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;1967 let glob_map = self.glob_map;1968 let main_def = self.main_def;1969 let confused_type_with_std_module = self.confused_type_with_std_module;1970 let effective_visibilities = self.effective_visibilities;19711972 let stripped_cfg_items = self1973 .stripped_cfg_items1974 .into_iter()1975 .filter_map(|item| {1976 let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();1977 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })1978 })1979 .collect();1980 let disambiguators = self1981 .disambiguators1982 .into_items()1983 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))1984 .collect();19851986 let global_ctxt = ResolverGlobalCtxt {1987 expn_that_defined,1988 visibilities_for_hashing: self.visibilities_for_hashing,1989 effective_visibilities,1990 macro_reachable_adts: self.macro_reachable_adts,1991 extern_crate_map,1992 module_children: self.module_children,1993 ambig_module_children: self.ambig_module_children,1994 glob_map,1995 maybe_unused_trait_imports,1996 main_def,1997 trait_impls: self.trait_impls,1998 proc_macros,1999 confused_type_with_std_module,2000 doc_link_resolutions: self.doc_link_resolutions,
Findings
✓ No findings reported for this file.