1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
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.
7 //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![feature(assert_matches)]
11 #![feature(box_patterns)]
12 #![feature(drain_filter)]
13 #![feature(if_let_guard)]
14 #![feature(iter_intersperse)]
15 #![feature(let_chains)]
16 #![feature(never_type)]
17 #![recursion_limit = "256"]
18 #![allow(rustdoc::private_intra_doc_links)]
19 #![allow(rustc::potential_query_instability)]
24 pub use rustc_hir::def::{Namespace, PerNS};
26 use rustc_arena::{DroplessArena, TypedArena};
27 use rustc_ast::node_id::NodeMap;
28 use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
29 use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path};
30 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
31 use rustc_data_structures::intern::Interned;
32 use rustc_data_structures::sync::Lrc;
33 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed};
34 use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind};
35 use rustc_hir::def::Namespace::*;
36 use rustc_hir::def::{self, CtorOf, DefKind, LifetimeRes, PartialRes};
37 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId};
38 use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
39 use rustc_hir::definitions::{DefPathData, Definitions};
40 use rustc_hir::TraitCandidate;
41 use rustc_index::vec::IndexVec;
42 use rustc_metadata::creader::{CStore, CrateLoader};
43 use rustc_middle::metadata::ModChild;
44 use rustc_middle::middle::privacy::EffectiveVisibilities;
45 use rustc_middle::span_bug;
46 use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools};
47 use rustc_middle::ty::{ResolverGlobalCtxt, ResolverOutputs};
48 use rustc_query_system::ich::StableHashingContext;
49 use rustc_session::cstore::{CrateStore, MetadataLoaderDyn, Untracked};
50 use rustc_session::lint::LintBuffer;
51 use rustc_session::Session;
52 use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
53 use rustc_span::source_map::Spanned;
54 use rustc_span::symbol::{kw, sym, Ident, Symbol};
55 use rustc_span::{Span, DUMMY_SP};
57 use smallvec::{smallvec, SmallVec};
58 use std::cell::{Cell, RefCell};
59 use std::collections::BTreeSet;
62 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
63 use imports::{Import, ImportKind, ImportResolver, NameResolution};
64 use late::{HasGenericParams, PathSource, PatternSource};
65 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
67 use crate::effective_visibilities::EffectiveVisibilitiesVisitor;
69 type Res = def::Res<NodeId>;
71 mod build_reduced_graph;
75 mod effective_visibilities;
87 #[derive(Copy, Clone, PartialEq, Debug)]
88 pub enum Determinacy {
94 fn determined(determined: bool) -> Determinacy {
95 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
99 /// A specific scope in which a name can be looked up.
100 /// This enum is currently used only for early resolution (imports and macros),
101 /// but not for late resolution yet.
102 #[derive(Clone, Copy)]
104 DeriveHelpers(LocalExpnId),
106 MacroRules(MacroRulesScopeRef<'a>),
117 /// Names from different contexts may want to visit different subsets of all specific scopes
118 /// with different restrictions when looking up the resolution.
119 /// This enum is currently used only for early resolution (imports and macros),
120 /// but not for late resolution yet.
121 #[derive(Clone, Copy)]
123 /// All scopes with the given namespace.
124 All(Namespace, /*is_import*/ bool),
125 /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
126 AbsolutePath(Namespace),
127 /// All scopes with macro namespace and the given macro kind restriction.
129 /// All scopes with the given namespace, used for partially performing late resolution.
130 /// The node id enables lints and is used for reporting them.
131 Late(Namespace, Module<'a>, Option<NodeId>),
134 /// Everything you need to know about a name's location to resolve it.
135 /// Serves as a starting point for the scope visitor.
136 /// This struct is currently used only for early resolution (imports and macros),
137 /// but not for late resolution yet.
138 #[derive(Clone, Copy, Debug)]
139 pub struct ParentScope<'a> {
140 pub module: Module<'a>,
141 expansion: LocalExpnId,
142 pub macro_rules: MacroRulesScopeRef<'a>,
143 derives: &'a [ast::Path],
146 impl<'a> ParentScope<'a> {
147 /// Creates a parent scope with the passed argument used as the module scope component,
148 /// and other scope components set to default empty values.
149 pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
152 expansion: LocalExpnId::ROOT,
153 macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
159 #[derive(Copy, Debug, Clone)]
160 enum ImplTraitContext {
162 Universal(LocalDefId),
165 struct BindingError {
167 origin: BTreeSet<Span>,
168 target: BTreeSet<Span>,
172 enum ResolutionError<'a> {
173 /// Error E0401: can't use type or const parameters from outer function.
174 GenericParamsFromOuterFunction(Res, HasGenericParams),
175 /// Error E0403: the name is already used for a type or const parameter in this generic
177 NameAlreadyUsedInParameterList(Symbol, Span),
178 /// Error E0407: method is not a member of trait.
179 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
180 /// Error E0437: type is not a member of trait.
181 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
182 /// Error E0438: const is not a member of trait.
183 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
184 /// Error E0408: variable `{}` is not bound in all patterns.
185 VariableNotBoundInPattern(BindingError, ParentScope<'a>),
186 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
187 VariableBoundWithDifferentMode(Symbol, Span),
188 /// Error E0415: identifier is bound more than once in this parameter list.
189 IdentifierBoundMoreThanOnceInParameterList(Symbol),
190 /// Error E0416: identifier is bound more than once in the same pattern.
191 IdentifierBoundMoreThanOnceInSamePattern(Symbol),
192 /// Error E0426: use of undeclared label.
193 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
194 /// Error E0429: `self` imports are only allowed within a `{ }` list.
195 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
196 /// Error E0430: `self` import can only appear once in the list.
197 SelfImportCanOnlyAppearOnceInTheList,
198 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
199 SelfImportOnlyInImportListWithNonEmptyPrefix,
200 /// Error E0433: failed to resolve.
201 FailedToResolve { label: String, suggestion: Option<Suggestion> },
202 /// Error E0434: can't capture dynamic environment in a fn item.
203 CannotCaptureDynamicEnvironmentInFnItem,
204 /// Error E0435: attempt to use a non-constant value in a constant.
205 AttemptToUseNonConstantValueInConstant(
207 /* suggestion */ &'static str,
208 /* current */ &'static str,
210 /// Error E0530: `X` bindings cannot shadow `Y`s.
211 BindingShadowsSomethingUnacceptable {
212 shadowing_binding: PatternSource,
214 participle: &'static str,
215 article: &'static str,
216 shadowed_binding: Res,
217 shadowed_binding_span: Span,
219 /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
220 ForwardDeclaredGenericParam,
221 /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
222 ParamInTyOfConstParam(Symbol),
223 /// generic parameters must not be used inside const evaluations.
225 /// This error is only emitted when using `min_const_generics`.
226 ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
227 /// Error E0735: generic parameters with a default cannot use `Self`
228 SelfInGenericParamDefault,
229 /// Error E0767: use of unreachable label
230 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
231 /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
236 trait_item_span: Span,
237 code: rustc_errors::DiagnosticId,
239 /// Error E0201: multiple impl items for the same trait item.
240 TraitImplDuplicate { name: Symbol, trait_item_span: Span, old_span: Span },
241 /// Inline asm `sym` operand must refer to a `fn` or `static`.
245 enum VisResolutionError<'a> {
246 Relative2018(Span, &'a ast::Path),
248 FailedToResolve(Span, String, Option<Suggestion>),
249 ExpectedFound(Span, String, Res),
254 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
255 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
256 #[derive(Clone, Copy, Debug)]
260 /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
261 /// nonsensical suggestions.
262 has_generic_args: bool,
263 /// Signals whether this `PathSegment` has lifetime arguments.
264 has_lifetime_args: bool,
269 fn from_path(path: &Path) -> Vec<Segment> {
270 path.segments.iter().map(|s| s.into()).collect()
273 fn from_ident(ident: Ident) -> Segment {
277 has_generic_args: false,
278 has_lifetime_args: false,
283 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
287 has_generic_args: false,
288 has_lifetime_args: false,
293 fn names_to_string(segments: &[Segment]) -> String {
294 names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
298 impl<'a> From<&'a ast::PathSegment> for Segment {
299 fn from(seg: &'a ast::PathSegment) -> Segment {
300 let has_generic_args = seg.args.is_some();
301 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
303 GenericArgs::AngleBracketed(args) => {
304 let found_lifetimes = args
307 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
308 (args.span, found_lifetimes)
310 GenericArgs::Parenthesized(args) => (args.span, true),
325 /// An intermediate resolution result.
327 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
328 /// items are visible in their whole block, while `Res`es only from the place they are defined
331 enum LexicalScopeBinding<'a> {
332 Item(&'a NameBinding<'a>),
336 impl<'a> LexicalScopeBinding<'a> {
337 fn res(self) -> Res {
339 LexicalScopeBinding::Item(binding) => binding.res(),
340 LexicalScopeBinding::Res(res) => res,
345 #[derive(Copy, Clone, Debug)]
346 enum ModuleOrUniformRoot<'a> {
350 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
351 CrateRootAndExternPrelude,
353 /// Virtual module that denotes resolution in extern prelude.
354 /// Used for paths starting with `::` on 2018 edition.
357 /// Virtual module that denotes resolution in current scope.
358 /// Used only for resolving single-segment imports. The reason it exists is that import paths
359 /// are always split into two parts, the first of which should be some kind of module.
363 impl ModuleOrUniformRoot<'_> {
364 fn same_def(lhs: Self, rhs: Self) -> bool {
366 (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
370 ModuleOrUniformRoot::CrateRootAndExternPrelude,
371 ModuleOrUniformRoot::CrateRootAndExternPrelude,
373 | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
374 | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
380 #[derive(Clone, Debug)]
381 enum PathResult<'a> {
382 Module(ModuleOrUniformRoot<'a>),
383 NonModule(PartialRes),
388 suggestion: Option<Suggestion>,
389 is_error_from_last_segment: bool,
393 impl<'a> PathResult<'a> {
396 is_error_from_last_segment: bool,
398 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
399 ) -> PathResult<'a> {
400 let (label, suggestion) =
401 if finalize { label_and_suggestion() } else { (String::new(), None) };
402 PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
408 /// An anonymous module; e.g., just a block.
413 /// { // This is an anonymous module
414 /// f(); // This resolves to (2) as we are inside the block.
417 /// f(); // Resolves to (1)
421 /// Any module with a name.
425 /// * A normal module – either `mod from_file;` or `mod from_block { }` –
426 /// or the crate root (which is conceptually a top-level module).
427 /// Note that the crate root's [name][Self::name] will be [`kw::Empty`].
428 /// * A trait or an enum (it implicitly contains associated types, methods and variant
430 Def(DefKind, DefId, Symbol),
434 /// Get name of the module.
435 pub fn name(&self) -> Option<Symbol> {
437 ModuleKind::Block => None,
438 ModuleKind::Def(.., name) => Some(*name),
443 /// A key that identifies a binding in a given `Module`.
445 /// Multiple bindings in the same module can have the same key (in a valid
446 /// program) if all but one of them come from glob imports.
447 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
449 /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
453 /// 0 if ident is not `_`, otherwise a value that's unique to the specific
454 /// `_` in the expanded AST that introduced this binding.
458 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
460 /// One node in the tree of modules.
462 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
465 /// * crate root (aka, top-level anonymous module)
468 /// * curly-braced block with statements
470 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
471 pub struct ModuleData<'a> {
472 /// The direct parent module (it may not be a `mod`, however).
473 parent: Option<Module<'a>>,
474 /// What kind of module this is, because this may not be a `mod`.
477 /// Mapping between names and their (possibly in-progress) resolutions in this module.
478 /// Resolutions in modules from other crates are not populated until accessed.
479 lazy_resolutions: Resolutions<'a>,
480 /// True if this is a module from other crate that needs to be populated on access.
481 populate_on_access: Cell<bool>,
483 /// Macro invocations that can expand into items in this module.
484 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
486 /// Whether `#[no_implicit_prelude]` is active.
487 no_implicit_prelude: bool,
489 glob_importers: RefCell<Vec<&'a Import<'a>>>,
490 globs: RefCell<Vec<&'a Import<'a>>>,
492 /// Used to memoize the traits in this module for faster searches through all traits in scope.
493 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
495 /// Span of the module itself. Used for error reporting.
501 type Module<'a> = &'a ModuleData<'a>;
503 impl<'a> ModuleData<'a> {
505 parent: Option<Module<'a>>,
509 no_implicit_prelude: bool,
511 let is_foreign = match kind {
512 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
513 ModuleKind::Block => false,
518 lazy_resolutions: Default::default(),
519 populate_on_access: Cell::new(is_foreign),
520 unexpanded_invocations: Default::default(),
522 glob_importers: RefCell::new(Vec::new()),
523 globs: RefCell::new(Vec::new()),
524 traits: RefCell::new(None),
530 fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
532 R: AsMut<Resolver<'a>>,
533 F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
535 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
536 if let Some(binding) = name_resolution.borrow().binding {
537 f(resolver, key.ident, key.ns, binding);
542 /// This modifies `self` in place. The traits will be stored in `self.traits`.
543 fn ensure_traits<R>(&'a self, resolver: &mut R)
545 R: AsMut<Resolver<'a>>,
547 let mut traits = self.traits.borrow_mut();
548 if traits.is_none() {
549 let mut collected_traits = Vec::new();
550 self.for_each_child(resolver, |_, name, ns, binding| {
554 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
555 collected_traits.push((name, binding))
558 *traits = Some(collected_traits.into_boxed_slice());
562 fn res(&self) -> Option<Res> {
564 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
569 // Public for rustdoc.
570 pub fn def_id(&self) -> DefId {
571 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
574 fn opt_def_id(&self) -> Option<DefId> {
576 ModuleKind::Def(_, def_id, _) => Some(def_id),
581 // `self` resolves to the first module ancestor that `is_normal`.
582 fn is_normal(&self) -> bool {
583 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
586 fn is_trait(&self) -> bool {
587 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
590 fn nearest_item_scope(&'a self) -> Module<'a> {
592 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
593 self.parent.expect("enum or trait module without a parent")
599 /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
600 /// This may be the crate root.
601 fn nearest_parent_mod(&self) -> DefId {
603 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
604 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
608 fn is_ancestor_of(&self, mut other: &Self) -> bool {
609 while !ptr::eq(self, other) {
610 if let Some(parent) = other.parent {
620 impl<'a> fmt::Debug for ModuleData<'a> {
621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622 write!(f, "{:?}", self.res())
626 /// Records a possibly-private value, type, or module definition.
627 #[derive(Clone, Debug)]
628 pub struct NameBinding<'a> {
629 kind: NameBindingKind<'a>,
630 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
631 expansion: LocalExpnId,
633 vis: ty::Visibility<DefId>,
636 pub trait ToNameBinding<'a> {
637 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
640 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
641 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
646 #[derive(Clone, Debug)]
647 enum NameBindingKind<'a> {
650 Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
653 impl<'a> NameBindingKind<'a> {
654 /// Is this a name binding of an import?
655 fn is_import(&self) -> bool {
656 matches!(*self, NameBindingKind::Import { .. })
660 struct PrivacyError<'a> {
662 binding: &'a NameBinding<'a>,
666 struct UseError<'a> {
667 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
668 /// Candidates which user could `use` to access the missing type.
669 candidates: Vec<ImportSuggestion>,
670 /// The `DefId` of the module to place the use-statements in.
672 /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
674 /// Extra free-form suggestion.
675 suggestion: Option<(Span, &'static str, String, Applicability)>,
676 /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
677 /// the user to import the item directly.
679 /// Whether the expected source is a call
683 #[derive(Clone, Copy, PartialEq, Debug)]
688 MacroRulesVsModularized,
696 fn descr(self) -> &'static str {
698 AmbiguityKind::Import => "multiple potential import sources",
699 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
700 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
701 AmbiguityKind::MacroRulesVsModularized => {
702 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
704 AmbiguityKind::GlobVsOuter => {
705 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
707 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
708 AmbiguityKind::GlobVsExpanded => {
709 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
711 AmbiguityKind::MoreExpandedVsOuter => {
712 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
718 /// Miscellaneous bits of metadata for better ambiguity error reporting.
719 #[derive(Clone, Copy, PartialEq)]
720 enum AmbiguityErrorMisc {
727 struct AmbiguityError<'a> {
730 b1: &'a NameBinding<'a>,
731 b2: &'a NameBinding<'a>,
732 misc1: AmbiguityErrorMisc,
733 misc2: AmbiguityErrorMisc,
736 impl<'a> NameBinding<'a> {
737 fn module(&self) -> Option<Module<'a>> {
739 NameBindingKind::Module(module) => Some(module),
740 NameBindingKind::Import { binding, .. } => binding.module(),
745 fn res(&self) -> Res {
747 NameBindingKind::Res(res) => res,
748 NameBindingKind::Module(module) => module.res().unwrap(),
749 NameBindingKind::Import { binding, .. } => binding.res(),
753 fn is_ambiguity(&self) -> bool {
754 self.ambiguity.is_some()
756 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
761 fn is_possibly_imported_variant(&self) -> bool {
763 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
764 NameBindingKind::Res(Res::Def(
765 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
768 NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
772 fn is_extern_crate(&self) -> bool {
774 NameBindingKind::Import {
775 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
778 NameBindingKind::Module(&ModuleData {
779 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
781 }) => def_id.is_crate_root(),
786 fn is_import(&self) -> bool {
787 matches!(self.kind, NameBindingKind::Import { .. })
790 /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
791 /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
792 fn is_import_user_facing(&self) -> bool {
793 matches!(self.kind, NameBindingKind::Import { import, .. }
794 if !matches!(import.kind, ImportKind::MacroExport))
797 fn is_glob_import(&self) -> bool {
799 NameBindingKind::Import { import, .. } => import.is_glob(),
804 fn is_importable(&self) -> bool {
807 Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
811 fn macro_kind(&self) -> Option<MacroKind> {
812 self.res().macro_kind()
815 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
816 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
817 // Then this function returns `true` if `self` may emerge from a macro *after* that
818 // in some later round and screw up our previously found resolution.
819 // See more detailed explanation in
820 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
823 invoc_parent_expansion: LocalExpnId,
824 binding: &NameBinding<'_>,
826 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
827 // Expansions are partially ordered, so "may appear after" is an inversion of
828 // "certainly appears before or simultaneously" and includes unordered cases.
829 let self_parent_expansion = self.expansion;
830 let other_parent_expansion = binding.expansion;
831 let certainly_before_other_or_simultaneously =
832 other_parent_expansion.is_descendant_of(self_parent_expansion);
833 let certainly_before_invoc_or_simultaneously =
834 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
835 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
839 #[derive(Default, Clone)]
840 pub struct ExternPreludeEntry<'a> {
841 extern_crate_item: Option<&'a NameBinding<'a>>,
842 pub introduced_by_item: bool,
845 /// Used for better errors for E0773
846 enum BuiltinMacroState {
847 NotYetSeen(SyntaxExtensionKind),
852 resolutions: DeriveResolutions,
853 helper_attrs: Vec<(usize, Ident)>,
854 has_derive_copy: bool,
859 ext: Lrc<SyntaxExtension>,
863 /// The main resolver class.
865 /// This is the visitor that walks the whole crate.
866 pub struct Resolver<'a> {
867 session: &'a Session,
869 definitions: Definitions,
870 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
871 expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
873 graph_root: Module<'a>,
875 prelude: Option<Module<'a>>,
876 extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
878 /// N.B., this is used only for better diagnostics, not name resolution itself.
879 has_self: FxHashSet<DefId>,
881 /// Names of fields of an item `DefId` accessible with dot syntax.
882 /// Used for hints during error reporting.
883 field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
885 /// All imports known to succeed or fail.
886 determined_imports: Vec<&'a Import<'a>>,
888 /// All non-determined imports.
889 indeterminate_imports: Vec<&'a Import<'a>>,
891 // Spans for local variables found during pattern resolution.
892 // Used for suggestions during error reporting.
893 pat_span_map: NodeMap<Span>,
895 /// Resolutions for nodes that have a single resolution.
896 partial_res_map: NodeMap<PartialRes>,
897 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
898 import_res_map: NodeMap<PerNS<Option<Res>>>,
899 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
900 label_res_map: NodeMap<NodeId>,
901 /// Resolutions for lifetimes.
902 lifetimes_res_map: NodeMap<LifetimeRes>,
903 /// Lifetime parameters that lowering will have to introduce.
904 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
906 /// `CrateNum` resolutions of `extern crate` items.
907 extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
908 reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
909 trait_map: NodeMap<Vec<TraitCandidate>>,
911 /// A map from nodes to anonymous modules.
912 /// Anonymous modules are pseudo-modules that are implicitly created around items
913 /// contained within blocks.
915 /// For example, if we have this:
923 /// There will be an anonymous module created around `g` with the ID of the
924 /// entry block for `f`.
925 block_map: NodeMap<Module<'a>>,
926 /// A fake module that contains no definition and no prelude. Used so that
927 /// some AST passes can generate identifiers that only resolve to local or
929 empty_module: Module<'a>,
930 module_map: FxHashMap<DefId, Module<'a>>,
931 binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
932 underscore_disambiguator: u32,
934 /// Maps glob imports to the names of items actually imported.
935 glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
936 /// Visibilities in "lowered" form, for all entities that have them.
937 visibilities: FxHashMap<LocalDefId, ty::Visibility>,
938 has_pub_restricted: bool,
939 used_imports: FxHashSet<NodeId>,
940 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
941 maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
943 /// Privacy errors are delayed until the end in order to deduplicate them.
944 privacy_errors: Vec<PrivacyError<'a>>,
945 /// Ambiguity errors are delayed for deduplication.
946 ambiguity_errors: Vec<AmbiguityError<'a>>,
947 /// `use` injections are delayed for better placement and deduplication.
948 use_injections: Vec<UseError<'a>>,
949 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
950 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
952 arenas: &'a ResolverArenas<'a>,
953 dummy_binding: &'a NameBinding<'a>,
955 local_crate_name: Symbol,
956 metadata_loader: Box<MetadataLoaderDyn>,
957 untracked: Untracked,
958 used_extern_options: FxHashSet<Symbol>,
959 macro_names: FxHashSet<Ident>,
960 builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
961 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
962 /// the surface (`macro` items in libcore), but are actually attributes or derives.
963 builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
964 registered_tools: RegisteredTools,
965 macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
966 macro_map: FxHashMap<DefId, MacroData>,
967 dummy_ext_bang: Lrc<SyntaxExtension>,
968 dummy_ext_derive: Lrc<SyntaxExtension>,
969 non_macro_attr: Lrc<SyntaxExtension>,
970 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
971 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
972 unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
973 unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
974 proc_macro_stubs: FxHashSet<LocalDefId>,
975 /// Traces collected during macro resolution and validated when it's complete.
976 single_segment_macro_resolutions:
977 Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
978 multi_segment_macro_resolutions:
979 Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
980 builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
981 /// `derive(Copy)` marks items they are applied to so they are treated specially later.
982 /// Derive macros cannot modify the item themselves and have to store the markers in the global
983 /// context, so they attach the markers to derive container IDs using this resolver table.
984 containers_deriving_copy: FxHashSet<LocalExpnId>,
985 /// Parent scopes in which the macros were invoked.
986 /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
987 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
988 /// `macro_rules` scopes *produced* by expanding the macro invocations,
989 /// include all the `macro_rules` items and other invocations generated by them.
990 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
991 /// `macro_rules` scopes produced by `macro_rules` item definitions.
992 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
993 /// Helper attributes that are in scope for the given expansion.
994 helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
995 /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
996 /// with the given `ExpnId`.
997 derive_data: FxHashMap<LocalExpnId, DeriveData>,
999 /// Avoid duplicated errors for "name already defined".
1000 name_already_seen: FxHashMap<Symbol, Span>,
1002 potentially_unused_imports: Vec<&'a Import<'a>>,
1004 /// Table for mapping struct IDs into struct constructor IDs,
1005 /// it's not used during normal resolution, only for better error reporting.
1006 /// Also includes of list of each fields visibility
1007 struct_constructors: DefIdMap<(Res, ty::Visibility<DefId>, Vec<ty::Visibility<DefId>>)>,
1009 /// Features enabled for this crate.
1010 active_features: FxHashSet<Symbol>,
1012 lint_buffer: LintBuffer,
1014 next_node_id: NodeId,
1016 node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1017 def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1019 /// Indices of unnamed struct or variant fields with unresolved attributes.
1020 placeholder_field_indices: FxHashMap<NodeId, usize>,
1021 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1022 /// we know what parent node that fragment should be attached to thanks to this table,
1023 /// and how the `impl Trait` fragments were introduced.
1024 invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1026 /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1027 /// FIXME: Replace with a more general AST map (together with some other fields).
1028 trait_impl_items: FxHashSet<LocalDefId>,
1030 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1031 /// Amount of lifetime parameters for each item in the crate.
1032 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1034 main_def: Option<MainDefinition>,
1035 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1036 /// A list of proc macro LocalDefIds, written out in the order in which
1037 /// they are declared in the static array generated by proc_macro_harness.
1038 proc_macros: Vec<NodeId>,
1039 confused_type_with_std_module: FxHashMap<Span, Span>,
1040 /// Whether lifetime elision was successful.
1041 lifetime_elision_allowed: FxHashSet<NodeId>,
1043 effective_visibilities: EffectiveVisibilities,
1046 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1048 pub struct ResolverArenas<'a> {
1049 modules: TypedArena<ModuleData<'a>>,
1050 local_modules: RefCell<Vec<Module<'a>>>,
1051 imports: TypedArena<Import<'a>>,
1052 name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1053 ast_paths: TypedArena<ast::Path>,
1054 dropless: DroplessArena,
1057 impl<'a> ResolverArenas<'a> {
1060 parent: Option<Module<'a>>,
1064 no_implicit_prelude: bool,
1065 module_map: &mut FxHashMap<DefId, Module<'a>>,
1068 self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1069 let def_id = module.opt_def_id();
1070 if def_id.map_or(true, |def_id| def_id.is_local()) {
1071 self.local_modules.borrow_mut().push(module);
1073 if let Some(def_id) = def_id {
1074 module_map.insert(def_id, module);
1078 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1079 self.local_modules.borrow()
1081 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1082 self.dropless.alloc(name_binding)
1084 fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1085 self.imports.alloc(import)
1087 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1088 self.name_resolutions.alloc(Default::default())
1090 fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1091 Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1093 fn alloc_macro_rules_binding(
1095 binding: MacroRulesBinding<'a>,
1096 ) -> &'a MacroRulesBinding<'a> {
1097 self.dropless.alloc(binding)
1099 fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1100 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1102 fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1103 self.dropless.alloc_from_iter(spans)
1107 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1108 fn as_mut(&mut self) -> &mut Resolver<'a> {
1113 /// A minimal subset of resolver that can implemenent `DefIdTree`, sometimes
1114 /// required to satisfy borrow checker by avoiding borrowing the whole resolver.
1115 #[derive(Clone, Copy)]
1116 struct ResolverTree<'a>(&'a Definitions, &'a CStore);
1118 impl DefIdTree for ResolverTree<'_> {
1120 fn opt_parent(self, id: DefId) -> Option<DefId> {
1121 let ResolverTree(definitions, cstore) = self;
1122 match id.as_local() {
1123 Some(id) => definitions.def_key(id).parent,
1124 None => cstore.def_key(id).parent,
1126 .map(|index| DefId { index, ..id })
1130 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1132 fn opt_parent(self, id: DefId) -> Option<DefId> {
1133 ResolverTree(&self.definitions, self.cstore()).opt_parent(id)
1138 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1139 self.node_id_to_def_id.get(&node).copied()
1142 pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1143 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1146 /// Adds a definition with a parent definition.
1150 node_id: ast::NodeId,
1156 !self.node_id_to_def_id.contains_key(&node_id),
1157 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1160 self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1163 let def_id = self.definitions.create_def(parent, data);
1165 // Create the definition.
1166 if expn_id != ExpnId::root() {
1167 self.expn_that_defined.insert(def_id, expn_id);
1170 // A relative span's parent must be an absolute span.
1171 debug_assert_eq!(span.data_untracked().parent, None);
1172 let _id = self.untracked.source_span.push(span);
1173 debug_assert_eq!(_id, def_id);
1175 // Some things for which we allocate `LocalDefId`s don't correspond to
1176 // anything in the AST, so they don't have a `NodeId`. For these cases
1177 // we don't need a mapping from `NodeId` to `LocalDefId`.
1178 if node_id != ast::DUMMY_NODE_ID {
1179 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1180 self.node_id_to_def_id.insert(node_id, def_id);
1182 assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1187 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1188 if let Some(def_id) = def_id.as_local() {
1189 self.item_generics_num_lifetimes[&def_id]
1191 self.cstore().item_generics_num_lifetimes(def_id, self.session)
1196 impl<'a> Resolver<'a> {
1198 session: &'a Session,
1201 metadata_loader: Box<MetadataLoaderDyn>,
1202 arenas: &'a ResolverArenas<'a>,
1204 let root_def_id = CRATE_DEF_ID.to_def_id();
1205 let mut module_map = FxHashMap::default();
1206 let graph_root = arenas.new_module(
1208 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1210 krate.spans.inner_span,
1211 session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1214 let empty_module = arenas.new_module(
1216 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1220 &mut FxHashMap::default(),
1223 let definitions = Definitions::new(session.local_stable_crate_id());
1225 let mut visibilities = FxHashMap::default();
1226 visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1228 let mut def_id_to_node_id = IndexVec::default();
1229 assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1230 let mut node_id_to_def_id = FxHashMap::default();
1231 node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1233 let mut invocation_parents = FxHashMap::default();
1234 invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1236 let mut source_span = IndexVec::default();
1237 let _id = source_span.push(krate.spans.inner_span);
1238 debug_assert_eq!(_id, CRATE_DEF_ID);
1240 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1244 .filter(|(_, entry)| entry.add_prelude)
1245 .map(|(name, _)| (Ident::from_str(name), Default::default()))
1248 if !session.contains_name(&krate.attrs, sym::no_core) {
1249 extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1250 if !session.contains_name(&krate.attrs, sym::no_std) {
1251 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1255 let registered_tools = macros::registered_tools(session, &krate.attrs);
1257 let features = session.features_untracked();
1259 let mut resolver = Resolver {
1263 expn_that_defined: Default::default(),
1265 // The outermost module has def ID 0; this is not reflected in the
1271 has_self: FxHashSet::default(),
1272 field_names: FxHashMap::default(),
1274 determined_imports: Vec::new(),
1275 indeterminate_imports: Vec::new(),
1277 pat_span_map: Default::default(),
1278 partial_res_map: Default::default(),
1279 import_res_map: Default::default(),
1280 label_res_map: Default::default(),
1281 lifetimes_res_map: Default::default(),
1282 extra_lifetime_params_map: Default::default(),
1283 extern_crate_map: Default::default(),
1284 reexport_map: FxHashMap::default(),
1285 trait_map: NodeMap::default(),
1286 underscore_disambiguator: 0,
1289 block_map: Default::default(),
1290 binding_parent_modules: FxHashMap::default(),
1291 ast_transform_scopes: FxHashMap::default(),
1293 glob_map: Default::default(),
1295 has_pub_restricted: false,
1296 used_imports: FxHashSet::default(),
1297 maybe_unused_trait_imports: Default::default(),
1298 maybe_unused_extern_crates: Vec::new(),
1300 privacy_errors: Vec::new(),
1301 ambiguity_errors: Vec::new(),
1302 use_injections: Vec::new(),
1303 macro_expanded_macro_export_errors: BTreeSet::new(),
1306 dummy_binding: arenas.alloc_name_binding(NameBinding {
1307 kind: NameBindingKind::Res(Res::Err),
1309 expansion: LocalExpnId::ROOT,
1311 vis: ty::Visibility::Public,
1315 local_crate_name: crate_name,
1316 used_extern_options: Default::default(),
1317 untracked: Untracked { cstore: Box::new(CStore::new(session)), source_span },
1318 macro_names: FxHashSet::default(),
1319 builtin_macros: Default::default(),
1320 builtin_macro_kinds: Default::default(),
1322 macro_use_prelude: FxHashMap::default(),
1323 macro_map: FxHashMap::default(),
1324 dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1325 dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1326 non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1327 invocation_parent_scopes: Default::default(),
1328 output_macro_rules_scopes: Default::default(),
1329 macro_rules_scopes: Default::default(),
1330 helper_attrs: Default::default(),
1331 derive_data: Default::default(),
1332 local_macro_def_scopes: FxHashMap::default(),
1333 name_already_seen: FxHashMap::default(),
1334 potentially_unused_imports: Vec::new(),
1335 struct_constructors: Default::default(),
1336 unused_macros: Default::default(),
1337 unused_macro_rules: Default::default(),
1338 proc_macro_stubs: Default::default(),
1339 single_segment_macro_resolutions: Default::default(),
1340 multi_segment_macro_resolutions: Default::default(),
1341 builtin_attrs: Default::default(),
1342 containers_deriving_copy: Default::default(),
1343 active_features: features
1344 .declared_lib_features
1346 .map(|(feat, ..)| *feat)
1347 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1349 lint_buffer: LintBuffer::default(),
1350 next_node_id: CRATE_NODE_ID,
1353 placeholder_field_indices: Default::default(),
1355 trait_impl_items: Default::default(),
1356 legacy_const_generic_args: Default::default(),
1357 item_generics_num_lifetimes: Default::default(),
1358 main_def: Default::default(),
1359 trait_impls: Default::default(),
1360 proc_macros: Default::default(),
1361 confused_type_with_std_module: Default::default(),
1362 lifetime_elision_allowed: Default::default(),
1363 effective_visibilities: Default::default(),
1366 let root_parent_scope = ParentScope::module(graph_root, &resolver);
1367 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1374 parent: Option<Module<'a>>,
1378 no_implicit_prelude: bool,
1380 let module_map = &mut self.module_map;
1381 self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1384 pub fn next_node_id(&mut self) -> NodeId {
1385 let start = self.next_node_id;
1386 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1387 self.next_node_id = ast::NodeId::from_u32(next);
1391 pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1392 let start = self.next_node_id;
1393 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1394 self.next_node_id = ast::NodeId::from_usize(end);
1395 start..self.next_node_id
1398 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1399 &mut self.lint_buffer
1402 pub fn arenas() -> ResolverArenas<'a> {
1406 pub fn into_outputs(self) -> ResolverOutputs {
1407 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1408 let definitions = self.definitions;
1409 let expn_that_defined = self.expn_that_defined;
1410 let visibilities = self.visibilities;
1411 let has_pub_restricted = self.has_pub_restricted;
1412 let extern_crate_map = self.extern_crate_map;
1413 let reexport_map = self.reexport_map;
1414 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1415 let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1416 let glob_map = self.glob_map;
1417 let main_def = self.main_def;
1418 let confused_type_with_std_module = self.confused_type_with_std_module;
1419 let effective_visibilities = self.effective_visibilities;
1420 let untracked = self.untracked;
1421 let global_ctxt = ResolverGlobalCtxt {
1425 effective_visibilities,
1429 maybe_unused_trait_imports,
1430 maybe_unused_extern_crates,
1431 extern_prelude: self
1434 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1437 trait_impls: self.trait_impls,
1439 confused_type_with_std_module,
1440 registered_tools: self.registered_tools,
1442 let ast_lowering = ty::ResolverAstLowering {
1443 legacy_const_generic_args: self.legacy_const_generic_args,
1444 partial_res_map: self.partial_res_map,
1445 import_res_map: self.import_res_map,
1446 label_res_map: self.label_res_map,
1447 lifetimes_res_map: self.lifetimes_res_map,
1448 extra_lifetime_params_map: self.extra_lifetime_params_map,
1449 next_node_id: self.next_node_id,
1450 node_id_to_def_id: self.node_id_to_def_id,
1451 def_id_to_node_id: self.def_id_to_node_id,
1452 trait_map: self.trait_map,
1453 builtin_macro_kinds: self.builtin_macro_kinds,
1454 lifetime_elision_allowed: self.lifetime_elision_allowed,
1456 ResolverOutputs { definitions, global_ctxt, ast_lowering, untracked }
1459 pub fn clone_outputs(&self) -> ResolverOutputs {
1460 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1461 let definitions = self.definitions.clone();
1462 let cstore = Box::new(self.cstore().clone());
1463 let untracked = Untracked { cstore, source_span: self.untracked.source_span.clone() };
1464 let global_ctxt = ResolverGlobalCtxt {
1465 expn_that_defined: self.expn_that_defined.clone(),
1466 visibilities: self.visibilities.clone(),
1467 has_pub_restricted: self.has_pub_restricted,
1468 extern_crate_map: self.extern_crate_map.clone(),
1469 reexport_map: self.reexport_map.clone(),
1470 glob_map: self.glob_map.clone(),
1471 maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1472 maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1473 extern_prelude: self
1476 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1478 main_def: self.main_def,
1479 trait_impls: self.trait_impls.clone(),
1481 confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1482 registered_tools: self.registered_tools.clone(),
1483 effective_visibilities: self.effective_visibilities.clone(),
1485 let ast_lowering = ty::ResolverAstLowering {
1486 legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1487 partial_res_map: self.partial_res_map.clone(),
1488 import_res_map: self.import_res_map.clone(),
1489 label_res_map: self.label_res_map.clone(),
1490 lifetimes_res_map: self.lifetimes_res_map.clone(),
1491 extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1492 next_node_id: self.next_node_id.clone(),
1493 node_id_to_def_id: self.node_id_to_def_id.clone(),
1494 def_id_to_node_id: self.def_id_to_node_id.clone(),
1495 trait_map: self.trait_map.clone(),
1496 builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1497 lifetime_elision_allowed: self.lifetime_elision_allowed.clone(),
1499 ResolverOutputs { definitions, global_ctxt, ast_lowering, untracked }
1502 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1503 StableHashingContext::new(self.session, &self.definitions, &self.untracked)
1506 pub fn crate_loader(&mut self) -> CrateLoader<'_> {
1509 &*self.metadata_loader,
1510 self.local_crate_name,
1511 &mut *self.untracked.cstore.untracked_as_any().downcast_mut().unwrap(),
1513 &mut self.used_extern_options,
1517 pub fn cstore(&self) -> &CStore {
1518 self.untracked.cstore.as_any().downcast_ref().unwrap()
1521 fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1523 MacroKind::Bang => self.dummy_ext_bang.clone(),
1524 MacroKind::Derive => self.dummy_ext_derive.clone(),
1525 MacroKind::Attr => self.non_macro_attr.clone(),
1529 /// Runs the function on each namespace.
1530 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1536 fn is_builtin_macro(&mut self, res: Res) -> bool {
1537 self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1540 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1542 match ctxt.outer_expn_data().macro_def_id {
1543 Some(def_id) => return def_id,
1544 None => ctxt.remove_mark(),
1549 /// Entry point to crate resolution.
1550 pub fn resolve_crate(&mut self, krate: &Crate) {
1551 self.session.time("resolve_crate", || {
1552 self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1553 self.session.time("compute_effective_visibilities", || {
1554 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1556 self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1557 self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1558 self.session.time("resolve_main", || self.resolve_main());
1559 self.session.time("resolve_check_unused", || self.check_unused(krate));
1560 self.session.time("resolve_report_errors", || self.report_errors(krate));
1561 self.session.time("resolve_postprocess", || self.crate_loader().postprocess(krate));
1565 pub fn traits_in_scope(
1567 current_trait: Option<Module<'a>>,
1568 parent_scope: &ParentScope<'a>,
1569 ctxt: SyntaxContext,
1570 assoc_item: Option<(Symbol, Namespace)>,
1571 ) -> Vec<TraitCandidate> {
1572 let mut found_traits = Vec::new();
1574 if let Some(module) = current_trait {
1575 if self.trait_may_have_item(Some(module), assoc_item) {
1576 let def_id = module.def_id();
1577 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1581 self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1583 Scope::Module(module) => {
1584 this.traits_in_module(module, assoc_item, &mut found_traits);
1586 Scope::StdLibPrelude => {
1587 if let Some(module) = this.prelude {
1588 this.traits_in_module(module, assoc_item, &mut found_traits);
1591 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1592 _ => unreachable!(),
1600 fn traits_in_module(
1603 assoc_item: Option<(Symbol, Namespace)>,
1604 found_traits: &mut Vec<TraitCandidate>,
1606 module.ensure_traits(self);
1607 let traits = module.traits.borrow();
1608 for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1609 if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1610 let def_id = trait_binding.res().def_id();
1611 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1612 found_traits.push(TraitCandidate { def_id, import_ids });
1617 // List of traits in scope is pruned on best effort basis. We reject traits not having an
1618 // associated item with the given name and namespace (if specified). This is a conservative
1619 // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1620 // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1621 // associated items.
1622 fn trait_may_have_item(
1624 trait_module: Option<Module<'a>>,
1625 assoc_item: Option<(Symbol, Namespace)>,
1627 match (trait_module, assoc_item) {
1628 (Some(trait_module), Some((name, ns))) => {
1629 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1630 let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1631 assoc_ns == ns && assoc_ident.name == name
1638 fn find_transitive_imports(
1640 mut kind: &NameBindingKind<'_>,
1642 ) -> SmallVec<[LocalDefId; 1]> {
1643 let mut import_ids = smallvec![];
1644 while let NameBindingKind::Import { import, binding, .. } = kind {
1645 if let Some(node_id) = import.id() {
1646 let def_id = self.local_def_id(node_id);
1647 self.maybe_unused_trait_imports.insert(def_id);
1648 import_ids.push(def_id);
1650 self.add_to_glob_map(&import, trait_name);
1651 kind = &binding.kind;
1656 fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1657 let ident = ident.normalize_to_macros_2_0();
1658 let disambiguator = if ident.name == kw::Underscore {
1659 self.underscore_disambiguator += 1;
1660 self.underscore_disambiguator
1664 BindingKey { ident, ns, disambiguator }
1667 fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1668 if module.populate_on_access.get() {
1669 module.populate_on_access.set(false);
1670 self.build_reduced_graph_external(module);
1672 &module.lazy_resolutions
1679 ) -> &'a RefCell<NameResolution<'a>> {
1681 .resolutions(module)
1684 .or_insert_with(|| self.arenas.alloc_name_resolution())
1690 used_binding: &'a NameBinding<'a>,
1691 is_lexical_scope: bool,
1693 if let Some((b2, kind)) = used_binding.ambiguity {
1694 self.ambiguity_errors.push(AmbiguityError {
1699 misc1: AmbiguityErrorMisc::None,
1700 misc2: AmbiguityErrorMisc::None,
1703 if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1704 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1705 // but not introduce it, as used if they are accessed from lexical scope.
1706 if is_lexical_scope {
1707 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1708 if let Some(crate_item) = entry.extern_crate_item {
1709 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1716 import.used.set(true);
1717 if let Some(id) = import.id() {
1718 self.used_imports.insert(id);
1720 self.add_to_glob_map(&import, ident);
1721 self.record_use(ident, binding, false);
1726 fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1727 if let ImportKind::Glob { id, .. } = import.kind {
1728 let def_id = self.local_def_id(id);
1729 self.glob_map.entry(def_id).or_default().insert(ident.name);
1733 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1734 debug!("resolve_crate_root({:?})", ident);
1735 let mut ctxt = ident.span.ctxt();
1736 let mark = if ident.name == kw::DollarCrate {
1737 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1738 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1739 // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1740 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1741 // definitions actually produced by `macro` and `macro` definitions produced by
1742 // `macro_rules!`, but at least such configurations are not stable yet.
1743 ctxt = ctxt.normalize_to_macro_rules();
1745 "resolve_crate_root: marks={:?}",
1746 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1748 let mut iter = ctxt.marks().into_iter().rev().peekable();
1749 let mut result = None;
1750 // Find the last opaque mark from the end if it exists.
1751 while let Some(&(mark, transparency)) = iter.peek() {
1752 if transparency == Transparency::Opaque {
1753 result = Some(mark);
1760 "resolve_crate_root: found opaque mark {:?} {:?}",
1762 result.map(|r| r.expn_data())
1764 // Then find the last semi-transparent mark from the end if it exists.
1765 for (mark, transparency) in iter {
1766 if transparency == Transparency::SemiTransparent {
1767 result = Some(mark);
1773 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1775 result.map(|r| r.expn_data())
1779 debug!("resolve_crate_root: not DollarCrate");
1780 ctxt = ctxt.normalize_to_macros_2_0();
1781 ctxt.adjust(ExpnId::root())
1783 let module = match mark {
1784 Some(def) => self.expn_def_scope(def),
1787 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1790 return self.graph_root;
1793 let module = self.expect_module(
1794 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1797 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1806 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1807 let mut module = self.expect_module(module.nearest_parent_mod());
1808 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1809 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1810 module = self.expect_module(parent.nearest_parent_mod());
1815 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1816 debug!("(recording res) recording {:?} for {}", resolution, node_id);
1817 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1818 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1822 fn record_pat_span(&mut self, node: NodeId, span: Span) {
1823 debug!("(recording pat) recording {:?} for {:?}", node, span);
1824 self.pat_span_map.insert(node, span);
1827 fn is_accessible_from(
1829 vis: ty::Visibility<impl Into<DefId>>,
1832 vis.is_accessible_from(module.nearest_parent_mod(), self)
1835 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1836 if let Some(old_module) =
1837 self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1839 if !ptr::eq(module, old_module) {
1840 span_bug!(binding.span, "parent module is reset for binding");
1845 fn disambiguate_macro_rules_vs_modularized(
1847 macro_rules: &'a NameBinding<'a>,
1848 modularized: &'a NameBinding<'a>,
1850 // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1851 // is disambiguated to mitigate regressions from macro modularization.
1852 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1854 self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1855 self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1857 (Some(macro_rules), Some(modularized)) => {
1858 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1859 && modularized.is_ancestor_of(macro_rules)
1865 fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1866 if ident.is_path_segment_keyword() {
1867 // Make sure `self`, `super` etc produce an error when passed to here.
1870 self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1871 if let Some(binding) = entry.extern_crate_item {
1872 if finalize && entry.introduced_by_item {
1873 self.record_use(ident, binding, false);
1877 let crate_id = if finalize {
1878 let Some(crate_id) =
1879 self.crate_loader().process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1882 self.crate_loader().maybe_process_path_extern(ident.name)?
1884 let crate_root = self.expect_module(crate_id.as_def_id());
1885 let vis = ty::Visibility::<LocalDefId>::Public;
1886 Some((crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas))
1891 /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1892 /// isn't something that can be returned because it can't be made to live that long,
1893 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1894 /// just that an error occurred.
1895 pub fn resolve_rustdoc_path(
1899 mut parent_scope: ParentScope<'a>,
1902 Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1903 if let Some(segment) = segments.first_mut() {
1904 if segment.ident.name == kw::Crate {
1905 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1906 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1907 // replacing `crate` with `self` and changing the current module should achieve
1909 segment.ident.name = kw::SelfLower;
1910 parent_scope.module =
1911 self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1912 } else if segment.ident.name == kw::Empty {
1913 segment.ident.name = kw::PathRoot;
1917 match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1918 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1919 PathResult::NonModule(path_res) => path_res.full_res(),
1920 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
1923 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1928 /// For local modules returns only reexports, for external modules returns all children.
1929 pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1930 if let Some(def_id) = def_id.as_local() {
1931 self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1933 self.cstore().module_children_untracked(def_id, self.session).collect()
1938 pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1939 let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1941 MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1942 _ => unreachable!(),
1947 pub fn get_partial_res(&self, node_id: NodeId) -> Option<PartialRes> {
1948 self.partial_res_map.get(&node_id).copied()
1951 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1953 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1954 def_id.as_local().map(|def_id| self.untracked.source_span[def_id])
1957 /// Retrieves the name of the given `DefId`.
1959 pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
1960 let def_key = match def_id.as_local() {
1961 Some(def_id) => self.definitions.def_key(def_id),
1962 None => self.cstore().def_key(def_id),
1964 def_key.get_opt_name()
1967 /// Checks if an expression refers to a function marked with
1968 /// `#[rustc_legacy_const_generics]` and returns the argument index list
1969 /// from the attribute.
1970 pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1971 if let ExprKind::Path(None, path) = &expr.kind {
1972 // Don't perform legacy const generics rewriting if the path already
1973 // has generic arguments.
1974 if path.segments.last().unwrap().args.is_some() {
1978 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
1979 if let Res::Def(def::DefKind::Fn, def_id) = res {
1980 // We only support cross-crate argument rewriting. Uses
1981 // within the same crate should be updated to use the new
1982 // const generics style.
1983 if def_id.is_local() {
1987 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1993 .item_attrs_untracked(def_id, self.session)
1994 .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1995 let mut ret = Vec::new();
1996 for meta in attr.meta_item_list()? {
1997 match meta.lit()?.kind {
1998 LitKind::Int(a, _) => ret.push(a as usize),
1999 _ => panic!("invalid arg index"),
2002 // Cache the lookup to avoid parsing attributes for an item multiple times.
2003 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2010 fn resolve_main(&mut self) {
2011 let module = self.graph_root;
2012 let ident = Ident::with_dummy_span(sym::main);
2013 let parent_scope = &ParentScope::module(module, self);
2015 let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2016 ModuleOrUniformRoot::Module(module),
2024 let res = name_binding.res();
2025 let is_import = name_binding.is_import();
2026 let span = name_binding.span;
2027 if let Res::Def(DefKind::Fn, _) = res {
2028 self.record_use(ident, name_binding, false);
2030 self.main_def = Some(MainDefinition { res, is_import, span });
2033 // Items that go to reexport table encoded to metadata and visible through it to other crates.
2034 fn is_reexport(&self, binding: &NameBinding<'a>) -> Option<def::Res<!>> {
2035 if binding.is_import() {
2036 let res = binding.res().expect_non_local();
2037 // Ambiguous imports are treated as errors at this point and are
2038 // not exposed to other crates (see #36837 for more details).
2039 if res != def::Res::Err && !binding.is_ambiguity() {
2048 fn names_to_string(names: &[Symbol]) -> String {
2049 let mut result = String::new();
2050 for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2052 result.push_str("::");
2054 if Ident::with_dummy_span(*name).is_raw_guess() {
2055 result.push_str("r#");
2057 result.push_str(name.as_str());
2062 fn path_names_to_string(path: &Path) -> String {
2063 names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2066 /// A somewhat inefficient routine to obtain the name of a module.
2067 fn module_to_string(module: Module<'_>) -> Option<String> {
2068 let mut names = Vec::new();
2070 fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2071 if let ModuleKind::Def(.., name) = module.kind {
2072 if let Some(parent) = module.parent {
2074 collect_mod(names, parent);
2077 names.push(Symbol::intern("<opaque>"));
2078 collect_mod(names, module.parent.unwrap());
2081 collect_mod(&mut names, module);
2083 if names.is_empty() {
2087 Some(names_to_string(&names))
2090 #[derive(Copy, Clone, Debug)]
2092 /// Node ID for linting.
2094 /// Span of the whole path or some its characteristic fragment.
2095 /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2097 /// Span of the path start, suitable for prepending something to it.
2098 /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2100 /// Whether to report privacy errors or silently return "no resolution" for them,
2101 /// similarly to speculative resolution.
2102 report_private: bool,
2106 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2107 Finalize::with_root_span(node_id, path_span, path_span)
2110 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2111 Finalize { node_id, path_span, root_span, report_private: true }