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_typeck`.
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![feature(box_patterns)]
11 #![feature(drain_filter)]
12 #![feature(if_let_guard)]
13 #![feature(iter_intersperse)]
14 #![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::AccessLevels;
45 use rustc_middle::span_bug;
46 use rustc_middle::ty::query::Providers;
47 use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, ResolverOutputs};
48 use rustc_query_system::ich::StableHashingContext;
49 use rustc_session::cstore::{CrateStore, CrateStoreDyn, MetadataLoaderDyn};
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;
60 use std::{cmp, fmt, ptr};
63 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
64 use imports::{Import, ImportKind, ImportResolver, NameResolution};
65 use late::{HasGenericParams, PathSource, PatternSource};
66 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
68 use crate::access_levels::AccessLevelsVisitor;
70 type Res = def::Res<NodeId>;
73 mod build_reduced_graph;
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>),
108 // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
109 // lint if it should be reported.
110 Module(Module<'a>, Option<NodeId>),
119 /// Names from different contexts may want to visit different subsets of all specific scopes
120 /// with different restrictions when looking up the resolution.
121 /// This enum is currently used only for early resolution (imports and macros),
122 /// but not for late resolution yet.
123 #[derive(Clone, Copy)]
125 /// All scopes with the given namespace.
126 All(Namespace, /*is_import*/ bool),
127 /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
128 AbsolutePath(Namespace),
129 /// All scopes with macro namespace and the given macro kind restriction.
131 /// All scopes with the given namespace, used for partially performing late resolution.
132 /// The node id enables lints and is used for reporting them.
133 Late(Namespace, Module<'a>, Option<NodeId>),
136 /// Everything you need to know about a name's location to resolve it.
137 /// Serves as a starting point for the scope visitor.
138 /// This struct is currently used only for early resolution (imports and macros),
139 /// but not for late resolution yet.
140 #[derive(Clone, Copy, Debug)]
141 pub struct ParentScope<'a> {
142 pub module: Module<'a>,
143 expansion: LocalExpnId,
144 pub macro_rules: MacroRulesScopeRef<'a>,
145 derives: &'a [ast::Path],
148 impl<'a> ParentScope<'a> {
149 /// Creates a parent scope with the passed argument used as the module scope component,
150 /// and other scope components set to default empty values.
151 pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
154 expansion: LocalExpnId::ROOT,
155 macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
161 #[derive(Copy, Debug, Clone)]
162 enum ImplTraitContext {
164 Universal(LocalDefId),
168 struct BindingError {
170 origin: BTreeSet<Span>,
171 target: BTreeSet<Span>,
175 impl PartialOrd for BindingError {
176 fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
177 Some(self.cmp(other))
181 impl PartialEq for BindingError {
182 fn eq(&self, other: &BindingError) -> bool {
183 self.name == other.name
187 impl Ord for BindingError {
188 fn cmp(&self, other: &BindingError) -> cmp::Ordering {
189 self.name.cmp(&other.name)
193 enum ResolutionError<'a> {
194 /// Error E0401: can't use type or const parameters from outer function.
195 GenericParamsFromOuterFunction(Res, HasGenericParams),
196 /// Error E0403: the name is already used for a type or const parameter in this generic
198 NameAlreadyUsedInParameterList(Symbol, Span),
199 /// Error E0407: method is not a member of trait.
200 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
201 /// Error E0437: type is not a member of trait.
202 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
203 /// Error E0438: const is not a member of trait.
204 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
205 /// Error E0408: variable `{}` is not bound in all patterns.
206 VariableNotBoundInPattern(BindingError, ParentScope<'a>),
207 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
208 VariableBoundWithDifferentMode(Symbol, Span),
209 /// Error E0415: identifier is bound more than once in this parameter list.
210 IdentifierBoundMoreThanOnceInParameterList(Symbol),
211 /// Error E0416: identifier is bound more than once in the same pattern.
212 IdentifierBoundMoreThanOnceInSamePattern(Symbol),
213 /// Error E0426: use of undeclared label.
214 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
215 /// Error E0429: `self` imports are only allowed within a `{ }` list.
216 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
217 /// Error E0430: `self` import can only appear once in the list.
218 SelfImportCanOnlyAppearOnceInTheList,
219 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
220 SelfImportOnlyInImportListWithNonEmptyPrefix,
221 /// Error E0433: failed to resolve.
222 FailedToResolve { label: String, suggestion: Option<Suggestion> },
223 /// Error E0434: can't capture dynamic environment in a fn item.
224 CannotCaptureDynamicEnvironmentInFnItem,
225 /// Error E0435: attempt to use a non-constant value in a constant.
226 AttemptToUseNonConstantValueInConstant(
228 /* suggestion */ &'static str,
229 /* current */ &'static str,
231 /// Error E0530: `X` bindings cannot shadow `Y`s.
232 BindingShadowsSomethingUnacceptable {
233 shadowing_binding: PatternSource,
235 participle: &'static str,
236 article: &'static str,
237 shadowed_binding: Res,
238 shadowed_binding_span: Span,
240 /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
241 ForwardDeclaredGenericParam,
242 /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
243 ParamInTyOfConstParam(Symbol),
244 /// generic parameters must not be used inside const evaluations.
246 /// This error is only emitted when using `min_const_generics`.
247 ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
248 /// Error E0735: generic parameters with a default cannot use `Self`
249 SelfInGenericParamDefault,
250 /// Error E0767: use of unreachable label
251 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
252 /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
257 trait_item_span: Span,
258 code: rustc_errors::DiagnosticId,
260 /// Inline asm `sym` operand must refer to a `fn` or `static`.
264 enum VisResolutionError<'a> {
265 Relative2018(Span, &'a ast::Path),
267 FailedToResolve(Span, String, Option<Suggestion>),
268 ExpectedFound(Span, String, Res),
273 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
274 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
275 #[derive(Clone, Copy, Debug)]
279 /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
280 /// nonsensical suggestions.
281 has_generic_args: bool,
282 /// Signals whether this `PathSegment` has lifetime arguments.
283 has_lifetime_args: bool,
288 fn from_path(path: &Path) -> Vec<Segment> {
289 path.segments.iter().map(|s| s.into()).collect()
292 fn from_ident(ident: Ident) -> Segment {
296 has_generic_args: false,
297 has_lifetime_args: false,
302 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
306 has_generic_args: false,
307 has_lifetime_args: false,
312 fn names_to_string(segments: &[Segment]) -> String {
313 names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
317 impl<'a> From<&'a ast::PathSegment> for Segment {
318 fn from(seg: &'a ast::PathSegment) -> Segment {
319 let has_generic_args = seg.args.is_some();
320 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
322 GenericArgs::AngleBracketed(args) => {
323 let found_lifetimes = args
326 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
327 (args.span, found_lifetimes)
329 GenericArgs::Parenthesized(args) => (args.span, true),
344 /// An intermediate resolution result.
346 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
347 /// items are visible in their whole block, while `Res`es only from the place they are defined
350 enum LexicalScopeBinding<'a> {
351 Item(&'a NameBinding<'a>),
355 impl<'a> LexicalScopeBinding<'a> {
356 fn res(self) -> Res {
358 LexicalScopeBinding::Item(binding) => binding.res(),
359 LexicalScopeBinding::Res(res) => res,
364 #[derive(Copy, Clone, Debug)]
365 enum ModuleOrUniformRoot<'a> {
369 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
370 CrateRootAndExternPrelude,
372 /// Virtual module that denotes resolution in extern prelude.
373 /// Used for paths starting with `::` on 2018 edition.
376 /// Virtual module that denotes resolution in current scope.
377 /// Used only for resolving single-segment imports. The reason it exists is that import paths
378 /// are always split into two parts, the first of which should be some kind of module.
382 impl ModuleOrUniformRoot<'_> {
383 fn same_def(lhs: Self, rhs: Self) -> bool {
385 (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
389 ModuleOrUniformRoot::CrateRootAndExternPrelude,
390 ModuleOrUniformRoot::CrateRootAndExternPrelude,
392 | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
393 | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
399 #[derive(Clone, Debug)]
400 enum PathResult<'a> {
401 Module(ModuleOrUniformRoot<'a>),
402 NonModule(PartialRes),
407 suggestion: Option<Suggestion>,
408 is_error_from_last_segment: bool,
412 impl<'a> PathResult<'a> {
415 is_error_from_last_segment: bool,
417 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
418 ) -> PathResult<'a> {
419 let (label, suggestion) =
420 if finalize { label_and_suggestion() } else { (String::new(), None) };
421 PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
427 /// An anonymous module; e.g., just a block.
432 /// { // This is an anonymous module
433 /// f(); // This resolves to (2) as we are inside the block.
436 /// f(); // Resolves to (1)
440 /// Any module with a name.
444 /// * A normal module – either `mod from_file;` or `mod from_block { }` –
445 /// or the crate root (which is conceptually a top-level module).
446 /// Note that the crate root's [name][Self::name] will be [`kw::Empty`].
447 /// * A trait or an enum (it implicitly contains associated types, methods and variant
449 Def(DefKind, DefId, Symbol),
453 /// Get name of the module.
454 pub fn name(&self) -> Option<Symbol> {
456 ModuleKind::Block => None,
457 ModuleKind::Def(.., name) => Some(*name),
462 /// A key that identifies a binding in a given `Module`.
464 /// Multiple bindings in the same module can have the same key (in a valid
465 /// program) if all but one of them come from glob imports.
466 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
468 /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
472 /// 0 if ident is not `_`, otherwise a value that's unique to the specific
473 /// `_` in the expanded AST that introduced this binding.
477 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
479 /// One node in the tree of modules.
481 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
484 /// * crate root (aka, top-level anonymous module)
487 /// * curly-braced block with statements
489 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
490 pub struct ModuleData<'a> {
491 /// The direct parent module (it may not be a `mod`, however).
492 parent: Option<Module<'a>>,
493 /// What kind of module this is, because this may not be a `mod`.
496 /// Mapping between names and their (possibly in-progress) resolutions in this module.
497 /// Resolutions in modules from other crates are not populated until accessed.
498 lazy_resolutions: Resolutions<'a>,
499 /// True if this is a module from other crate that needs to be populated on access.
500 populate_on_access: Cell<bool>,
502 /// Macro invocations that can expand into items in this module.
503 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
505 /// Whether `#[no_implicit_prelude]` is active.
506 no_implicit_prelude: bool,
508 glob_importers: RefCell<Vec<&'a Import<'a>>>,
509 globs: RefCell<Vec<&'a Import<'a>>>,
511 /// Used to memoize the traits in this module for faster searches through all traits in scope.
512 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
514 /// Span of the module itself. Used for error reporting.
520 type Module<'a> = &'a ModuleData<'a>;
522 impl<'a> ModuleData<'a> {
524 parent: Option<Module<'a>>,
528 no_implicit_prelude: bool,
530 let is_foreign = match kind {
531 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
532 ModuleKind::Block => false,
537 lazy_resolutions: Default::default(),
538 populate_on_access: Cell::new(is_foreign),
539 unexpanded_invocations: Default::default(),
541 glob_importers: RefCell::new(Vec::new()),
542 globs: RefCell::new(Vec::new()),
543 traits: RefCell::new(None),
549 fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
551 R: AsMut<Resolver<'a>>,
552 F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
554 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
555 if let Some(binding) = name_resolution.borrow().binding {
556 f(resolver, key.ident, key.ns, binding);
561 /// This modifies `self` in place. The traits will be stored in `self.traits`.
562 fn ensure_traits<R>(&'a self, resolver: &mut R)
564 R: AsMut<Resolver<'a>>,
566 let mut traits = self.traits.borrow_mut();
567 if traits.is_none() {
568 let mut collected_traits = Vec::new();
569 self.for_each_child(resolver, |_, name, ns, binding| {
573 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
574 collected_traits.push((name, binding))
577 *traits = Some(collected_traits.into_boxed_slice());
581 fn res(&self) -> Option<Res> {
583 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
588 // Public for rustdoc.
589 pub fn def_id(&self) -> DefId {
590 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
593 fn opt_def_id(&self) -> Option<DefId> {
595 ModuleKind::Def(_, def_id, _) => Some(def_id),
600 // `self` resolves to the first module ancestor that `is_normal`.
601 fn is_normal(&self) -> bool {
602 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
605 fn is_trait(&self) -> bool {
606 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
609 fn nearest_item_scope(&'a self) -> Module<'a> {
611 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
612 self.parent.expect("enum or trait module without a parent")
618 /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
619 /// This may be the crate root.
620 fn nearest_parent_mod(&self) -> DefId {
622 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
623 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
627 fn is_ancestor_of(&self, mut other: &Self) -> bool {
628 while !ptr::eq(self, other) {
629 if let Some(parent) = other.parent {
639 impl<'a> fmt::Debug for ModuleData<'a> {
640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 write!(f, "{:?}", self.res())
645 /// Records a possibly-private value, type, or module definition.
646 #[derive(Clone, Debug)]
647 pub struct NameBinding<'a> {
648 kind: NameBindingKind<'a>,
649 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
650 expansion: LocalExpnId,
655 pub trait ToNameBinding<'a> {
656 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
659 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
660 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
665 #[derive(Clone, Debug)]
666 enum NameBindingKind<'a> {
667 Res(Res, /* is_macro_export */ bool),
669 Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
672 impl<'a> NameBindingKind<'a> {
673 /// Is this a name binding of an import?
674 fn is_import(&self) -> bool {
675 matches!(*self, NameBindingKind::Import { .. })
679 struct PrivacyError<'a> {
681 binding: &'a NameBinding<'a>,
685 struct UseError<'a> {
686 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
687 /// Candidates which user could `use` to access the missing type.
688 candidates: Vec<ImportSuggestion>,
689 /// The `DefId` of the module to place the use-statements in.
691 /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
693 /// Extra free-form suggestion.
694 suggestion: Option<(Span, &'static str, String, Applicability)>,
695 /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
696 /// the user to import the item directly.
700 #[derive(Clone, Copy, PartialEq, Debug)]
705 MacroRulesVsModularized,
713 fn descr(self) -> &'static str {
715 AmbiguityKind::Import => "multiple potential import sources",
716 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
717 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
718 AmbiguityKind::MacroRulesVsModularized => {
719 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
721 AmbiguityKind::GlobVsOuter => {
722 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
724 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
725 AmbiguityKind::GlobVsExpanded => {
726 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
728 AmbiguityKind::MoreExpandedVsOuter => {
729 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
735 /// Miscellaneous bits of metadata for better ambiguity error reporting.
736 #[derive(Clone, Copy, PartialEq)]
737 enum AmbiguityErrorMisc {
744 struct AmbiguityError<'a> {
747 b1: &'a NameBinding<'a>,
748 b2: &'a NameBinding<'a>,
749 misc1: AmbiguityErrorMisc,
750 misc2: AmbiguityErrorMisc,
753 impl<'a> NameBinding<'a> {
754 fn module(&self) -> Option<Module<'a>> {
756 NameBindingKind::Module(module) => Some(module),
757 NameBindingKind::Import { binding, .. } => binding.module(),
762 fn res(&self) -> Res {
764 NameBindingKind::Res(res, _) => res,
765 NameBindingKind::Module(module) => module.res().unwrap(),
766 NameBindingKind::Import { binding, .. } => binding.res(),
770 fn is_ambiguity(&self) -> bool {
771 self.ambiguity.is_some()
773 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
778 fn is_possibly_imported_variant(&self) -> bool {
780 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
781 NameBindingKind::Res(
782 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
785 NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
789 fn is_extern_crate(&self) -> bool {
791 NameBindingKind::Import {
792 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
795 NameBindingKind::Module(&ModuleData {
796 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
798 }) => def_id.is_crate_root(),
803 fn is_import(&self) -> bool {
804 matches!(self.kind, NameBindingKind::Import { .. })
807 fn is_glob_import(&self) -> bool {
809 NameBindingKind::Import { import, .. } => import.is_glob(),
814 fn is_importable(&self) -> bool {
817 Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
821 fn macro_kind(&self) -> Option<MacroKind> {
822 self.res().macro_kind()
825 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
826 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
827 // Then this function returns `true` if `self` may emerge from a macro *after* that
828 // in some later round and screw up our previously found resolution.
829 // See more detailed explanation in
830 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
833 invoc_parent_expansion: LocalExpnId,
834 binding: &NameBinding<'_>,
836 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
837 // Expansions are partially ordered, so "may appear after" is an inversion of
838 // "certainly appears before or simultaneously" and includes unordered cases.
839 let self_parent_expansion = self.expansion;
840 let other_parent_expansion = binding.expansion;
841 let certainly_before_other_or_simultaneously =
842 other_parent_expansion.is_descendant_of(self_parent_expansion);
843 let certainly_before_invoc_or_simultaneously =
844 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
845 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
849 #[derive(Debug, Default, Clone)]
850 pub struct ExternPreludeEntry<'a> {
851 extern_crate_item: Option<&'a NameBinding<'a>>,
852 pub introduced_by_item: bool,
855 /// Used for better errors for E0773
856 enum BuiltinMacroState {
857 NotYetSeen(SyntaxExtensionKind),
862 resolutions: DeriveResolutions,
863 helper_attrs: Vec<(usize, Ident)>,
864 has_derive_copy: bool,
869 ext: Lrc<SyntaxExtension>,
873 /// The main resolver class.
875 /// This is the visitor that walks the whole crate.
876 pub struct Resolver<'a> {
877 session: &'a Session,
879 definitions: Definitions,
880 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
881 expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
882 /// Reference span for definitions.
883 source_span: IndexVec<LocalDefId, Span>,
885 graph_root: Module<'a>,
887 prelude: Option<Module<'a>>,
888 extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
890 /// N.B., this is used only for better diagnostics, not name resolution itself.
891 has_self: FxHashSet<DefId>,
893 /// Names of fields of an item `DefId` accessible with dot syntax.
894 /// Used for hints during error reporting.
895 field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
897 /// All imports known to succeed or fail.
898 determined_imports: Vec<&'a Import<'a>>,
900 /// All non-determined imports.
901 indeterminate_imports: Vec<&'a Import<'a>>,
903 // Spans for local variables found during pattern resolution.
904 // Used for suggestions during error reporting.
905 pat_span_map: NodeMap<Span>,
907 /// Resolutions for nodes that have a single resolution.
908 partial_res_map: NodeMap<PartialRes>,
909 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
910 import_res_map: NodeMap<PerNS<Option<Res>>>,
911 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
912 label_res_map: NodeMap<NodeId>,
913 /// Resolutions for lifetimes.
914 lifetimes_res_map: NodeMap<LifetimeRes>,
915 /// Mapping from generics `def_id`s to TAIT generics `def_id`s.
916 /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic
917 /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this
918 /// field from the original parameter 'a to the new parameter 'a1.
919 generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>,
920 /// Lifetime parameters that lowering will have to introduce.
921 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
923 /// `CrateNum` resolutions of `extern crate` items.
924 extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
925 reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
926 trait_map: NodeMap<Vec<TraitCandidate>>,
928 /// A map from nodes to anonymous modules.
929 /// Anonymous modules are pseudo-modules that are implicitly created around items
930 /// contained within blocks.
932 /// For example, if we have this:
940 /// There will be an anonymous module created around `g` with the ID of the
941 /// entry block for `f`.
942 block_map: NodeMap<Module<'a>>,
943 /// A fake module that contains no definition and no prelude. Used so that
944 /// some AST passes can generate identifiers that only resolve to local or
946 empty_module: Module<'a>,
947 module_map: FxHashMap<DefId, Module<'a>>,
948 binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
949 underscore_disambiguator: u32,
951 /// Maps glob imports to the names of items actually imported.
952 glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
953 /// Visibilities in "lowered" form, for all entities that have them.
954 visibilities: FxHashMap<LocalDefId, ty::Visibility>,
955 has_pub_restricted: bool,
956 used_imports: FxHashSet<NodeId>,
957 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
958 maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
960 /// Privacy errors are delayed until the end in order to deduplicate them.
961 privacy_errors: Vec<PrivacyError<'a>>,
962 /// Ambiguity errors are delayed for deduplication.
963 ambiguity_errors: Vec<AmbiguityError<'a>>,
964 /// `use` injections are delayed for better placement and deduplication.
965 use_injections: Vec<UseError<'a>>,
966 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
967 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
969 arenas: &'a ResolverArenas<'a>,
970 dummy_binding: &'a NameBinding<'a>,
972 crate_loader: CrateLoader<'a>,
973 macro_names: FxHashSet<Ident>,
974 builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
975 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
976 /// the surface (`macro` items in libcore), but are actually attributes or derives.
977 builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
978 registered_tools: RegisteredTools,
979 macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
980 macro_map: FxHashMap<DefId, MacroData>,
981 dummy_ext_bang: Lrc<SyntaxExtension>,
982 dummy_ext_derive: Lrc<SyntaxExtension>,
983 non_macro_attr: Lrc<SyntaxExtension>,
984 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
985 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
986 unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
987 unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
988 proc_macro_stubs: FxHashSet<LocalDefId>,
989 /// Traces collected during macro resolution and validated when it's complete.
990 single_segment_macro_resolutions:
991 Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
992 multi_segment_macro_resolutions:
993 Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
994 builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
995 /// `derive(Copy)` marks items they are applied to so they are treated specially later.
996 /// Derive macros cannot modify the item themselves and have to store the markers in the global
997 /// context, so they attach the markers to derive container IDs using this resolver table.
998 containers_deriving_copy: FxHashSet<LocalExpnId>,
999 /// Parent scopes in which the macros were invoked.
1000 /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1001 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
1002 /// `macro_rules` scopes *produced* by expanding the macro invocations,
1003 /// include all the `macro_rules` items and other invocations generated by them.
1004 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
1005 /// `macro_rules` scopes produced by `macro_rules` item definitions.
1006 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
1007 /// Helper attributes that are in scope for the given expansion.
1008 helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
1009 /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1010 /// with the given `ExpnId`.
1011 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1013 /// Avoid duplicated errors for "name already defined".
1014 name_already_seen: FxHashMap<Symbol, Span>,
1016 potentially_unused_imports: Vec<&'a Import<'a>>,
1018 /// Table for mapping struct IDs into struct constructor IDs,
1019 /// it's not used during normal resolution, only for better error reporting.
1020 /// Also includes of list of each fields visibility
1021 struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>,
1023 /// Features enabled for this crate.
1024 active_features: FxHashSet<Symbol>,
1026 lint_buffer: LintBuffer,
1028 next_node_id: NodeId,
1030 node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1031 def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1033 /// Indices of unnamed struct or variant fields with unresolved attributes.
1034 placeholder_field_indices: FxHashMap<NodeId, usize>,
1035 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1036 /// we know what parent node that fragment should be attached to thanks to this table,
1037 /// and how the `impl Trait` fragments were introduced.
1038 invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1040 /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1041 /// FIXME: Replace with a more general AST map (together with some other fields).
1042 trait_impl_items: FxHashSet<LocalDefId>,
1044 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1045 /// Amount of lifetime parameters for each item in the crate.
1046 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1048 main_def: Option<MainDefinition>,
1049 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1050 /// A list of proc macro LocalDefIds, written out in the order in which
1051 /// they are declared in the static array generated by proc_macro_harness.
1052 proc_macros: Vec<NodeId>,
1053 confused_type_with_std_module: FxHashMap<Span, Span>,
1055 access_levels: AccessLevels,
1058 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1060 pub struct ResolverArenas<'a> {
1061 modules: TypedArena<ModuleData<'a>>,
1062 local_modules: RefCell<Vec<Module<'a>>>,
1063 imports: TypedArena<Import<'a>>,
1064 name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1065 ast_paths: TypedArena<ast::Path>,
1066 dropless: DroplessArena,
1069 impl<'a> ResolverArenas<'a> {
1072 parent: Option<Module<'a>>,
1076 no_implicit_prelude: bool,
1077 module_map: &mut FxHashMap<DefId, Module<'a>>,
1080 self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1081 let def_id = module.opt_def_id();
1082 if def_id.map_or(true, |def_id| def_id.is_local()) {
1083 self.local_modules.borrow_mut().push(module);
1085 if let Some(def_id) = def_id {
1086 module_map.insert(def_id, module);
1090 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1091 self.local_modules.borrow()
1093 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1094 self.dropless.alloc(name_binding)
1096 fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1097 self.imports.alloc(import)
1099 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1100 self.name_resolutions.alloc(Default::default())
1102 fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1103 Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1105 fn alloc_macro_rules_binding(
1107 binding: MacroRulesBinding<'a>,
1108 ) -> &'a MacroRulesBinding<'a> {
1109 self.dropless.alloc(binding)
1111 fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1112 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1114 fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1115 self.dropless.alloc_from_iter(spans)
1119 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1120 fn as_mut(&mut self) -> &mut Resolver<'a> {
1125 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1127 fn opt_parent(self, id: DefId) -> Option<DefId> {
1128 match id.as_local() {
1129 Some(id) => self.definitions.def_key(id).parent,
1130 None => self.cstore().def_key(id).parent,
1132 .map(|index| DefId { index, ..id })
1137 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1138 self.node_id_to_def_id.get(&node).copied()
1141 pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1142 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1145 /// Adds a definition with a parent definition.
1149 node_id: ast::NodeId,
1155 !self.node_id_to_def_id.contains_key(&node_id),
1156 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1159 self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1162 let def_id = self.definitions.create_def(parent, data);
1164 // Create the definition.
1165 if expn_id != ExpnId::root() {
1166 self.expn_that_defined.insert(def_id, expn_id);
1169 // A relative span's parent must be an absolute span.
1170 debug_assert_eq!(span.data_untracked().parent, None);
1171 let _id = self.source_span.push(span);
1172 debug_assert_eq!(_id, def_id);
1174 // Some things for which we allocate `LocalDefId`s don't correspond to
1175 // anything in the AST, so they don't have a `NodeId`. For these cases
1176 // we don't need a mapping from `NodeId` to `LocalDefId`.
1177 if node_id != ast::DUMMY_NODE_ID {
1178 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1179 self.node_id_to_def_id.insert(node_id, def_id);
1181 assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1186 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1187 if let Some(def_id) = def_id.as_local() {
1188 self.item_generics_num_lifetimes[&def_id]
1190 self.cstore().item_generics_num_lifetimes(def_id, self.session)
1195 impl<'a> Resolver<'a> {
1197 session: &'a Session,
1200 metadata_loader: Box<MetadataLoaderDyn>,
1201 arenas: &'a ResolverArenas<'a>,
1203 let root_def_id = CRATE_DEF_ID.to_def_id();
1204 let mut module_map = FxHashMap::default();
1205 let graph_root = arenas.new_module(
1207 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1209 krate.spans.inner_span,
1210 session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1213 let empty_module = arenas.new_module(
1215 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1219 &mut FxHashMap::default(),
1222 let definitions = Definitions::new(session.local_stable_crate_id());
1224 let mut visibilities = FxHashMap::default();
1225 visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1227 let mut def_id_to_node_id = IndexVec::default();
1228 assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1229 let mut node_id_to_def_id = FxHashMap::default();
1230 node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1232 let mut invocation_parents = FxHashMap::default();
1233 invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1235 let mut source_span = IndexVec::default();
1236 let _id = source_span.push(krate.spans.inner_span);
1237 debug_assert_eq!(_id, CRATE_DEF_ID);
1239 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1243 .filter(|(_, entry)| entry.add_prelude)
1244 .map(|(name, _)| (Ident::from_str(name), Default::default()))
1247 if !session.contains_name(&krate.attrs, sym::no_core) {
1248 extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1249 if !session.contains_name(&krate.attrs, sym::no_std) {
1250 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1254 let registered_tools = macros::registered_tools(session, &krate.attrs);
1256 let features = session.features_untracked();
1258 let mut resolver = Resolver {
1262 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 generics_def_id_map: Vec::new(),
1283 extra_lifetime_params_map: Default::default(),
1284 extern_crate_map: Default::default(),
1285 reexport_map: FxHashMap::default(),
1286 trait_map: NodeMap::default(),
1287 underscore_disambiguator: 0,
1290 block_map: Default::default(),
1291 binding_parent_modules: FxHashMap::default(),
1292 ast_transform_scopes: FxHashMap::default(),
1294 glob_map: Default::default(),
1296 has_pub_restricted: false,
1297 used_imports: FxHashSet::default(),
1298 maybe_unused_trait_imports: Default::default(),
1299 maybe_unused_extern_crates: Vec::new(),
1301 privacy_errors: Vec::new(),
1302 ambiguity_errors: Vec::new(),
1303 use_injections: Vec::new(),
1304 macro_expanded_macro_export_errors: BTreeSet::new(),
1307 dummy_binding: arenas.alloc_name_binding(NameBinding {
1308 kind: NameBindingKind::Res(Res::Err, false),
1310 expansion: LocalExpnId::ROOT,
1312 vis: ty::Visibility::Public,
1315 crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1316 macro_names: FxHashSet::default(),
1317 builtin_macros: Default::default(),
1318 builtin_macro_kinds: Default::default(),
1320 macro_use_prelude: FxHashMap::default(),
1321 macro_map: FxHashMap::default(),
1322 dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1323 dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1324 non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1325 invocation_parent_scopes: Default::default(),
1326 output_macro_rules_scopes: Default::default(),
1327 macro_rules_scopes: Default::default(),
1328 helper_attrs: Default::default(),
1329 derive_data: Default::default(),
1330 local_macro_def_scopes: FxHashMap::default(),
1331 name_already_seen: FxHashMap::default(),
1332 potentially_unused_imports: Vec::new(),
1333 struct_constructors: Default::default(),
1334 unused_macros: Default::default(),
1335 unused_macro_rules: Default::default(),
1336 proc_macro_stubs: Default::default(),
1337 single_segment_macro_resolutions: Default::default(),
1338 multi_segment_macro_resolutions: Default::default(),
1339 builtin_attrs: Default::default(),
1340 containers_deriving_copy: Default::default(),
1341 active_features: features
1342 .declared_lib_features
1344 .map(|(feat, ..)| *feat)
1345 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1347 lint_buffer: LintBuffer::default(),
1348 next_node_id: CRATE_NODE_ID,
1351 placeholder_field_indices: Default::default(),
1353 trait_impl_items: Default::default(),
1354 legacy_const_generic_args: Default::default(),
1355 item_generics_num_lifetimes: Default::default(),
1356 main_def: Default::default(),
1357 trait_impls: Default::default(),
1358 proc_macros: Default::default(),
1359 confused_type_with_std_module: Default::default(),
1360 access_levels: Default::default(),
1363 let root_parent_scope = ParentScope::module(graph_root, &resolver);
1364 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1371 parent: Option<Module<'a>>,
1375 no_implicit_prelude: bool,
1377 let module_map = &mut self.module_map;
1378 self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1381 pub fn next_node_id(&mut self) -> NodeId {
1382 let start = self.next_node_id;
1383 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1384 self.next_node_id = ast::NodeId::from_u32(next);
1388 pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1389 let start = self.next_node_id;
1390 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1391 self.next_node_id = ast::NodeId::from_usize(end);
1392 start..self.next_node_id
1395 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1396 &mut self.lint_buffer
1399 pub fn arenas() -> ResolverArenas<'a> {
1403 pub fn into_outputs(
1405 ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1406 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1407 let definitions = self.definitions;
1408 let cstore = Box::new(self.crate_loader.into_cstore());
1409 let source_span = self.source_span;
1410 let expn_that_defined = self.expn_that_defined;
1411 let visibilities = self.visibilities;
1412 let has_pub_restricted = self.has_pub_restricted;
1413 let extern_crate_map = self.extern_crate_map;
1414 let reexport_map = self.reexport_map;
1415 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1416 let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1417 let glob_map = self.glob_map;
1418 let main_def = self.main_def;
1419 let confused_type_with_std_module = self.confused_type_with_std_module;
1420 let access_levels = self.access_levels;
1421 let resolutions = ResolverOutputs {
1430 maybe_unused_trait_imports,
1431 maybe_unused_extern_crates,
1432 extern_prelude: self
1435 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1438 trait_impls: self.trait_impls,
1440 confused_type_with_std_module,
1441 registered_tools: self.registered_tools,
1443 let resolutions_lowering = ty::ResolverAstLowering {
1444 legacy_const_generic_args: self.legacy_const_generic_args,
1445 partial_res_map: self.partial_res_map,
1446 import_res_map: self.import_res_map,
1447 label_res_map: self.label_res_map,
1448 lifetimes_res_map: self.lifetimes_res_map,
1449 generics_def_id_map: self.generics_def_id_map,
1450 extra_lifetime_params_map: self.extra_lifetime_params_map,
1451 next_node_id: self.next_node_id,
1452 node_id_to_def_id: self.node_id_to_def_id,
1453 def_id_to_node_id: self.def_id_to_node_id,
1454 trait_map: self.trait_map,
1455 builtin_macro_kinds: self.builtin_macro_kinds,
1457 (definitions, cstore, resolutions, resolutions_lowering)
1460 pub fn clone_outputs(
1462 ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1463 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1464 let definitions = self.definitions.clone();
1465 let cstore = Box::new(self.cstore().clone());
1466 let resolutions = ResolverOutputs {
1467 source_span: self.source_span.clone(),
1468 expn_that_defined: self.expn_that_defined.clone(),
1469 visibilities: self.visibilities.clone(),
1470 has_pub_restricted: self.has_pub_restricted,
1471 extern_crate_map: self.extern_crate_map.clone(),
1472 reexport_map: self.reexport_map.clone(),
1473 glob_map: self.glob_map.clone(),
1474 maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1475 maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1476 extern_prelude: self
1479 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1481 main_def: self.main_def,
1482 trait_impls: self.trait_impls.clone(),
1484 confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1485 registered_tools: self.registered_tools.clone(),
1486 access_levels: self.access_levels.clone(),
1488 let resolutions_lowering = ty::ResolverAstLowering {
1489 legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1490 partial_res_map: self.partial_res_map.clone(),
1491 import_res_map: self.import_res_map.clone(),
1492 label_res_map: self.label_res_map.clone(),
1493 lifetimes_res_map: self.lifetimes_res_map.clone(),
1494 generics_def_id_map: self.generics_def_id_map.clone(),
1495 extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1496 next_node_id: self.next_node_id.clone(),
1497 node_id_to_def_id: self.node_id_to_def_id.clone(),
1498 def_id_to_node_id: self.def_id_to_node_id.clone(),
1499 trait_map: self.trait_map.clone(),
1500 builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1502 (definitions, cstore, resolutions, resolutions_lowering)
1505 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1506 StableHashingContext::new(
1509 self.crate_loader.cstore(),
1514 pub fn cstore(&self) -> &CStore {
1515 self.crate_loader.cstore()
1518 fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1520 MacroKind::Bang => self.dummy_ext_bang.clone(),
1521 MacroKind::Derive => self.dummy_ext_derive.clone(),
1522 MacroKind::Attr => self.non_macro_attr.clone(),
1526 /// Runs the function on each namespace.
1527 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1533 fn is_builtin_macro(&mut self, res: Res) -> bool {
1534 self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1537 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1539 match ctxt.outer_expn_data().macro_def_id {
1540 Some(def_id) => return def_id,
1541 None => ctxt.remove_mark(),
1546 /// Entry point to crate resolution.
1547 pub fn resolve_crate(&mut self, krate: &Crate) {
1548 self.session.time("resolve_crate", || {
1549 self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1550 self.session.time("resolve_access_levels", || {
1551 AccessLevelsVisitor::compute_access_levels(self, krate)
1553 self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1554 self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1555 self.session.time("resolve_main", || self.resolve_main());
1556 self.session.time("resolve_check_unused", || self.check_unused(krate));
1557 self.session.time("resolve_report_errors", || self.report_errors(krate));
1558 self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1562 pub fn traits_in_scope(
1564 current_trait: Option<Module<'a>>,
1565 parent_scope: &ParentScope<'a>,
1566 ctxt: SyntaxContext,
1567 assoc_item: Option<(Symbol, Namespace)>,
1568 ) -> Vec<TraitCandidate> {
1569 let mut found_traits = Vec::new();
1571 if let Some(module) = current_trait {
1572 if self.trait_may_have_item(Some(module), assoc_item) {
1573 let def_id = module.def_id();
1574 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1578 self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1580 Scope::Module(module, _) => {
1581 this.traits_in_module(module, assoc_item, &mut found_traits);
1583 Scope::StdLibPrelude => {
1584 if let Some(module) = this.prelude {
1585 this.traits_in_module(module, assoc_item, &mut found_traits);
1588 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1589 _ => unreachable!(),
1597 fn traits_in_module(
1600 assoc_item: Option<(Symbol, Namespace)>,
1601 found_traits: &mut Vec<TraitCandidate>,
1603 module.ensure_traits(self);
1604 let traits = module.traits.borrow();
1605 for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1606 if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1607 let def_id = trait_binding.res().def_id();
1608 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1609 found_traits.push(TraitCandidate { def_id, import_ids });
1614 // List of traits in scope is pruned on best effort basis. We reject traits not having an
1615 // associated item with the given name and namespace (if specified). This is a conservative
1616 // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1617 // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1618 // associated items.
1619 fn trait_may_have_item(
1621 trait_module: Option<Module<'a>>,
1622 assoc_item: Option<(Symbol, Namespace)>,
1624 match (trait_module, assoc_item) {
1625 (Some(trait_module), Some((name, ns))) => {
1626 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1627 let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1628 assoc_ns == ns && assoc_ident.name == name
1635 fn find_transitive_imports(
1637 mut kind: &NameBindingKind<'_>,
1639 ) -> SmallVec<[LocalDefId; 1]> {
1640 let mut import_ids = smallvec![];
1641 while let NameBindingKind::Import { import, binding, .. } = kind {
1642 let id = self.local_def_id(import.id);
1643 self.maybe_unused_trait_imports.insert(id);
1644 self.add_to_glob_map(&import, trait_name);
1645 import_ids.push(id);
1646 kind = &binding.kind;
1651 fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1652 let ident = ident.normalize_to_macros_2_0();
1653 let disambiguator = if ident.name == kw::Underscore {
1654 self.underscore_disambiguator += 1;
1655 self.underscore_disambiguator
1659 BindingKey { ident, ns, disambiguator }
1662 fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1663 if module.populate_on_access.get() {
1664 module.populate_on_access.set(false);
1665 self.build_reduced_graph_external(module);
1667 &module.lazy_resolutions
1674 ) -> &'a RefCell<NameResolution<'a>> {
1676 .resolutions(module)
1679 .or_insert_with(|| self.arenas.alloc_name_resolution())
1685 used_binding: &'a NameBinding<'a>,
1686 is_lexical_scope: bool,
1688 if let Some((b2, kind)) = used_binding.ambiguity {
1689 self.ambiguity_errors.push(AmbiguityError {
1694 misc1: AmbiguityErrorMisc::None,
1695 misc2: AmbiguityErrorMisc::None,
1698 if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1699 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1700 // but not introduce it, as used if they are accessed from lexical scope.
1701 if is_lexical_scope {
1702 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1703 if let Some(crate_item) = entry.extern_crate_item {
1704 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1711 import.used.set(true);
1712 self.used_imports.insert(import.id);
1713 self.add_to_glob_map(&import, ident);
1714 self.record_use(ident, binding, false);
1719 fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1720 if import.is_glob() {
1721 let def_id = self.local_def_id(import.id);
1722 self.glob_map.entry(def_id).or_default().insert(ident.name);
1726 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1727 debug!("resolve_crate_root({:?})", ident);
1728 let mut ctxt = ident.span.ctxt();
1729 let mark = if ident.name == kw::DollarCrate {
1730 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1731 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1732 // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1733 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1734 // definitions actually produced by `macro` and `macro` definitions produced by
1735 // `macro_rules!`, but at least such configurations are not stable yet.
1736 ctxt = ctxt.normalize_to_macro_rules();
1738 "resolve_crate_root: marks={:?}",
1739 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1741 let mut iter = ctxt.marks().into_iter().rev().peekable();
1742 let mut result = None;
1743 // Find the last opaque mark from the end if it exists.
1744 while let Some(&(mark, transparency)) = iter.peek() {
1745 if transparency == Transparency::Opaque {
1746 result = Some(mark);
1753 "resolve_crate_root: found opaque mark {:?} {:?}",
1755 result.map(|r| r.expn_data())
1757 // Then find the last semi-transparent mark from the end if it exists.
1758 for (mark, transparency) in iter {
1759 if transparency == Transparency::SemiTransparent {
1760 result = Some(mark);
1766 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1768 result.map(|r| r.expn_data())
1772 debug!("resolve_crate_root: not DollarCrate");
1773 ctxt = ctxt.normalize_to_macros_2_0();
1774 ctxt.adjust(ExpnId::root())
1776 let module = match mark {
1777 Some(def) => self.expn_def_scope(def),
1780 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1783 return self.graph_root;
1786 let module = self.expect_module(
1787 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1790 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1799 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1800 let mut module = self.expect_module(module.nearest_parent_mod());
1801 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1802 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1803 module = self.expect_module(parent.nearest_parent_mod());
1808 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1809 debug!("(recording res) recording {:?} for {}", resolution, node_id);
1810 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1811 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1815 fn record_pat_span(&mut self, node: NodeId, span: Span) {
1816 debug!("(recording pat) recording {:?} for {:?}", node, span);
1817 self.pat_span_map.insert(node, span);
1820 fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
1821 vis.is_accessible_from(module.nearest_parent_mod(), self)
1824 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1825 if let Some(old_module) =
1826 self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1828 if !ptr::eq(module, old_module) {
1829 span_bug!(binding.span, "parent module is reset for binding");
1834 fn disambiguate_macro_rules_vs_modularized(
1836 macro_rules: &'a NameBinding<'a>,
1837 modularized: &'a NameBinding<'a>,
1839 // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1840 // is disambiguated to mitigate regressions from macro modularization.
1841 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1843 self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1844 self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1846 (Some(macro_rules), Some(modularized)) => {
1847 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1848 && modularized.is_ancestor_of(macro_rules)
1854 fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1855 if ident.is_path_segment_keyword() {
1856 // Make sure `self`, `super` etc produce an error when passed to here.
1859 self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1860 if let Some(binding) = entry.extern_crate_item {
1861 if finalize && entry.introduced_by_item {
1862 self.record_use(ident, binding, false);
1866 let crate_id = if finalize {
1867 let Some(crate_id) =
1868 self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1871 self.crate_loader.maybe_process_path_extern(ident.name)?
1873 let crate_root = self.expect_module(crate_id.as_def_id());
1875 (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT)
1876 .to_name_binding(self.arenas),
1882 /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1883 /// isn't something that can be returned because it can't be made to live that long,
1884 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1885 /// just that an error occurred.
1886 pub fn resolve_rustdoc_path(
1890 mut parent_scope: ParentScope<'a>,
1893 Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1894 if let Some(segment) = segments.first_mut() {
1895 if segment.ident.name == kw::Crate {
1896 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1897 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1898 // replacing `crate` with `self` and changing the current module should achieve
1900 segment.ident.name = kw::SelfLower;
1901 parent_scope.module =
1902 self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1903 } else if segment.ident.name == kw::Empty {
1904 segment.ident.name = kw::PathRoot;
1908 match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1909 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1910 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1911 Some(path_res.base_res())
1913 PathResult::Module(ModuleOrUniformRoot::ExternPrelude)
1914 | PathResult::NonModule(..)
1915 | PathResult::Failed { .. } => None,
1916 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1921 /// For local modules returns only reexports, for external modules returns all children.
1922 pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1923 if let Some(def_id) = def_id.as_local() {
1924 self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1926 self.cstore().module_children_untracked(def_id, self.session)
1931 pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1932 let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1934 MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1935 _ => unreachable!(),
1939 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1941 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1942 def_id.as_local().map(|def_id| self.source_span[def_id])
1945 /// Retrieves the name of the given `DefId`.
1947 pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
1948 let def_key = match def_id.as_local() {
1949 Some(def_id) => self.definitions.def_key(def_id),
1950 None => self.cstore().def_key(def_id),
1952 def_key.get_opt_name()
1955 /// Checks if an expression refers to a function marked with
1956 /// `#[rustc_legacy_const_generics]` and returns the argument index list
1957 /// from the attribute.
1958 pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1959 if let ExprKind::Path(None, path) = &expr.kind {
1960 // Don't perform legacy const generics rewriting if the path already
1961 // has generic arguments.
1962 if path.segments.last().unwrap().args.is_some() {
1966 let partial_res = self.partial_res_map.get(&expr.id)?;
1967 if partial_res.unresolved_segments() != 0 {
1971 if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() {
1972 // We only support cross-crate argument rewriting. Uses
1973 // within the same crate should be updated to use the new
1974 // const generics style.
1975 if def_id.is_local() {
1979 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1985 .item_attrs_untracked(def_id, self.session)
1986 .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1987 let mut ret = Vec::new();
1988 for meta in attr.meta_item_list()? {
1989 match meta.literal()?.kind {
1990 LitKind::Int(a, _) => ret.push(a as usize),
1991 _ => panic!("invalid arg index"),
1994 // Cache the lookup to avoid parsing attributes for an iterm multiple times.
1995 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2002 fn resolve_main(&mut self) {
2003 let module = self.graph_root;
2004 let ident = Ident::with_dummy_span(sym::main);
2005 let parent_scope = &ParentScope::module(module, self);
2007 let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2008 ModuleOrUniformRoot::Module(module),
2016 let res = name_binding.res();
2017 let is_import = name_binding.is_import();
2018 let span = name_binding.span;
2019 if let Res::Def(DefKind::Fn, _) = res {
2020 self.record_use(ident, name_binding, false);
2022 self.main_def = Some(MainDefinition { res, is_import, span });
2026 fn names_to_string(names: &[Symbol]) -> String {
2027 let mut result = String::new();
2028 for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2030 result.push_str("::");
2032 if Ident::with_dummy_span(*name).is_raw_guess() {
2033 result.push_str("r#");
2035 result.push_str(name.as_str());
2040 fn path_names_to_string(path: &Path) -> String {
2041 names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2044 /// A somewhat inefficient routine to obtain the name of a module.
2045 fn module_to_string(module: Module<'_>) -> Option<String> {
2046 let mut names = Vec::new();
2048 fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2049 if let ModuleKind::Def(.., name) = module.kind {
2050 if let Some(parent) = module.parent {
2052 collect_mod(names, parent);
2055 names.push(Symbol::intern("<opaque>"));
2056 collect_mod(names, module.parent.unwrap());
2059 collect_mod(&mut names, module);
2061 if names.is_empty() {
2065 Some(names_to_string(&names))
2068 #[derive(Copy, Clone, Debug)]
2070 /// Node ID for linting.
2072 /// Span of the whole path or some its characteristic fragment.
2073 /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2075 /// Span of the path start, suitable for prepending something to to it.
2076 /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2078 /// Whether to report privacy errors or silently return "no resolution" for them,
2079 /// similarly to speculative resolution.
2080 report_private: bool,
2084 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2085 Finalize::with_root_span(node_id, path_span, path_span)
2088 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2089 Finalize { node_id, path_span, root_span, report_private: true }
2093 pub fn provide(providers: &mut Providers) {
2094 late::lifetimes::provide(providers);