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(box_patterns)]
11 #![feature(drain_filter)]
12 #![feature(if_let_guard)]
13 #![feature(iter_intersperse)]
14 #![feature(let_chains)]
15 #![feature(never_type)]
16 #![recursion_limit = "256"]
17 #![allow(rustdoc::private_intra_doc_links)]
18 #![allow(rustc::potential_query_instability)]
23 pub use rustc_hir::def::{Namespace, PerNS};
25 use rustc_arena::{DroplessArena, TypedArena};
26 use rustc_ast::node_id::NodeMap;
27 use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
28 use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path};
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
30 use rustc_data_structures::intern::Interned;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed};
33 use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind};
34 use rustc_hir::def::Namespace::*;
35 use rustc_hir::def::{self, CtorOf, DefKind, LifetimeRes, PartialRes};
36 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId};
37 use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
38 use rustc_hir::definitions::{DefPathData, Definitions};
39 use rustc_hir::TraitCandidate;
40 use rustc_index::vec::IndexVec;
41 use rustc_metadata::creader::{CStore, CrateLoader};
42 use rustc_middle::metadata::ModChild;
43 use rustc_middle::middle::privacy::AccessLevels;
44 use rustc_middle::span_bug;
45 use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools, ResolverOutputs};
46 use rustc_query_system::ich::StableHashingContext;
47 use rustc_session::cstore::{CrateStore, CrateStoreDyn, MetadataLoaderDyn};
48 use rustc_session::lint::LintBuffer;
49 use rustc_session::Session;
50 use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
51 use rustc_span::source_map::Spanned;
52 use rustc_span::symbol::{kw, sym, Ident, Symbol};
53 use rustc_span::{Span, DUMMY_SP};
55 use smallvec::{smallvec, SmallVec};
56 use std::cell::{Cell, RefCell};
57 use std::collections::BTreeSet;
60 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
61 use imports::{Import, ImportKind, ImportResolver, NameResolution};
62 use late::{HasGenericParams, PathSource, PatternSource};
63 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
65 use crate::access_levels::AccessLevelsVisitor;
67 type Res = def::Res<NodeId>;
70 mod build_reduced_graph;
84 #[derive(Copy, Clone, PartialEq, Debug)]
85 pub enum Determinacy {
91 fn determined(determined: bool) -> Determinacy {
92 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
96 /// A specific scope in which a name can be looked up.
97 /// This enum is currently used only for early resolution (imports and macros),
98 /// but not for late resolution yet.
99 #[derive(Clone, Copy)]
101 DeriveHelpers(LocalExpnId),
103 MacroRules(MacroRulesScopeRef<'a>),
105 // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
106 // lint if it should be reported.
107 Module(Module<'a>, Option<NodeId>),
116 /// Names from different contexts may want to visit different subsets of all specific scopes
117 /// with different restrictions when looking up the resolution.
118 /// This enum is currently used only for early resolution (imports and macros),
119 /// but not for late resolution yet.
120 #[derive(Clone, Copy)]
122 /// All scopes with the given namespace.
123 All(Namespace, /*is_import*/ bool),
124 /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
125 AbsolutePath(Namespace),
126 /// All scopes with macro namespace and the given macro kind restriction.
128 /// All scopes with the given namespace, used for partially performing late resolution.
129 /// The node id enables lints and is used for reporting them.
130 Late(Namespace, Module<'a>, Option<NodeId>),
133 /// Everything you need to know about a name's location to resolve it.
134 /// Serves as a starting point for the scope visitor.
135 /// This struct is currently used only for early resolution (imports and macros),
136 /// but not for late resolution yet.
137 #[derive(Clone, Copy, Debug)]
138 pub struct ParentScope<'a> {
139 pub module: Module<'a>,
140 expansion: LocalExpnId,
141 pub macro_rules: MacroRulesScopeRef<'a>,
142 derives: &'a [ast::Path],
145 impl<'a> ParentScope<'a> {
146 /// Creates a parent scope with the passed argument used as the module scope component,
147 /// and other scope components set to default empty values.
148 pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
151 expansion: LocalExpnId::ROOT,
152 macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
158 #[derive(Copy, Debug, Clone)]
159 enum ImplTraitContext {
161 Universal(LocalDefId),
164 struct BindingError {
166 origin: BTreeSet<Span>,
167 target: BTreeSet<Span>,
171 enum ResolutionError<'a> {
172 /// Error E0401: can't use type or const parameters from outer function.
173 GenericParamsFromOuterFunction(Res, HasGenericParams),
174 /// Error E0403: the name is already used for a type or const parameter in this generic
176 NameAlreadyUsedInParameterList(Symbol, Span),
177 /// Error E0407: method is not a member of trait.
178 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
179 /// Error E0437: type is not a member of trait.
180 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
181 /// Error E0438: const is not a member of trait.
182 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
183 /// Error E0408: variable `{}` is not bound in all patterns.
184 VariableNotBoundInPattern(BindingError, ParentScope<'a>),
185 /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
186 VariableBoundWithDifferentMode(Symbol, Span),
187 /// Error E0415: identifier is bound more than once in this parameter list.
188 IdentifierBoundMoreThanOnceInParameterList(Symbol),
189 /// Error E0416: identifier is bound more than once in the same pattern.
190 IdentifierBoundMoreThanOnceInSamePattern(Symbol),
191 /// Error E0426: use of undeclared label.
192 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
193 /// Error E0429: `self` imports are only allowed within a `{ }` list.
194 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
195 /// Error E0430: `self` import can only appear once in the list.
196 SelfImportCanOnlyAppearOnceInTheList,
197 /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
198 SelfImportOnlyInImportListWithNonEmptyPrefix,
199 /// Error E0433: failed to resolve.
200 FailedToResolve { label: String, suggestion: Option<Suggestion> },
201 /// Error E0434: can't capture dynamic environment in a fn item.
202 CannotCaptureDynamicEnvironmentInFnItem,
203 /// Error E0435: attempt to use a non-constant value in a constant.
204 AttemptToUseNonConstantValueInConstant(
206 /* suggestion */ &'static str,
207 /* current */ &'static str,
209 /// Error E0530: `X` bindings cannot shadow `Y`s.
210 BindingShadowsSomethingUnacceptable {
211 shadowing_binding: PatternSource,
213 participle: &'static str,
214 article: &'static str,
215 shadowed_binding: Res,
216 shadowed_binding_span: Span,
218 /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
219 ForwardDeclaredGenericParam,
220 /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
221 ParamInTyOfConstParam(Symbol),
222 /// generic parameters must not be used inside const evaluations.
224 /// This error is only emitted when using `min_const_generics`.
225 ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
226 /// Error E0735: generic parameters with a default cannot use `Self`
227 SelfInGenericParamDefault,
228 /// Error E0767: use of unreachable label
229 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
230 /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
235 trait_item_span: Span,
236 code: rustc_errors::DiagnosticId,
238 /// Error E0201: multiple impl items for the same trait item.
239 TraitImplDuplicate { name: Symbol, trait_item_span: Span, old_span: Span },
240 /// Inline asm `sym` operand must refer to a `fn` or `static`.
244 enum VisResolutionError<'a> {
245 Relative2018(Span, &'a ast::Path),
247 FailedToResolve(Span, String, Option<Suggestion>),
248 ExpectedFound(Span, String, Res),
253 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
254 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
255 #[derive(Clone, Copy, Debug)]
259 /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
260 /// nonsensical suggestions.
261 has_generic_args: bool,
262 /// Signals whether this `PathSegment` has lifetime arguments.
263 has_lifetime_args: bool,
268 fn from_path(path: &Path) -> Vec<Segment> {
269 path.segments.iter().map(|s| s.into()).collect()
272 fn from_ident(ident: Ident) -> Segment {
276 has_generic_args: false,
277 has_lifetime_args: false,
282 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
286 has_generic_args: false,
287 has_lifetime_args: false,
292 fn names_to_string(segments: &[Segment]) -> String {
293 names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
297 impl<'a> From<&'a ast::PathSegment> for Segment {
298 fn from(seg: &'a ast::PathSegment) -> Segment {
299 let has_generic_args = seg.args.is_some();
300 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
302 GenericArgs::AngleBracketed(args) => {
303 let found_lifetimes = args
306 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
307 (args.span, found_lifetimes)
309 GenericArgs::Parenthesized(args) => (args.span, true),
324 /// An intermediate resolution result.
326 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
327 /// items are visible in their whole block, while `Res`es only from the place they are defined
330 enum LexicalScopeBinding<'a> {
331 Item(&'a NameBinding<'a>),
335 impl<'a> LexicalScopeBinding<'a> {
336 fn res(self) -> Res {
338 LexicalScopeBinding::Item(binding) => binding.res(),
339 LexicalScopeBinding::Res(res) => res,
344 #[derive(Copy, Clone, Debug)]
345 enum ModuleOrUniformRoot<'a> {
349 /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
350 CrateRootAndExternPrelude,
352 /// Virtual module that denotes resolution in extern prelude.
353 /// Used for paths starting with `::` on 2018 edition.
356 /// Virtual module that denotes resolution in current scope.
357 /// Used only for resolving single-segment imports. The reason it exists is that import paths
358 /// are always split into two parts, the first of which should be some kind of module.
362 impl ModuleOrUniformRoot<'_> {
363 fn same_def(lhs: Self, rhs: Self) -> bool {
365 (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
369 ModuleOrUniformRoot::CrateRootAndExternPrelude,
370 ModuleOrUniformRoot::CrateRootAndExternPrelude,
372 | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
373 | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
379 #[derive(Clone, Debug)]
380 enum PathResult<'a> {
381 Module(ModuleOrUniformRoot<'a>),
382 NonModule(PartialRes),
387 suggestion: Option<Suggestion>,
388 is_error_from_last_segment: bool,
392 impl<'a> PathResult<'a> {
395 is_error_from_last_segment: bool,
397 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
398 ) -> PathResult<'a> {
399 let (label, suggestion) =
400 if finalize { label_and_suggestion() } else { (String::new(), None) };
401 PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
407 /// An anonymous module; e.g., just a block.
412 /// { // This is an anonymous module
413 /// f(); // This resolves to (2) as we are inside the block.
416 /// f(); // Resolves to (1)
420 /// Any module with a name.
424 /// * A normal module – either `mod from_file;` or `mod from_block { }` –
425 /// or the crate root (which is conceptually a top-level module).
426 /// Note that the crate root's [name][Self::name] will be [`kw::Empty`].
427 /// * A trait or an enum (it implicitly contains associated types, methods and variant
429 Def(DefKind, DefId, Symbol),
433 /// Get name of the module.
434 pub fn name(&self) -> Option<Symbol> {
436 ModuleKind::Block => None,
437 ModuleKind::Def(.., name) => Some(*name),
442 /// A key that identifies a binding in a given `Module`.
444 /// Multiple bindings in the same module can have the same key (in a valid
445 /// program) if all but one of them come from glob imports.
446 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
448 /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
452 /// 0 if ident is not `_`, otherwise a value that's unique to the specific
453 /// `_` in the expanded AST that introduced this binding.
457 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
459 /// One node in the tree of modules.
461 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
464 /// * crate root (aka, top-level anonymous module)
467 /// * curly-braced block with statements
469 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
470 pub struct ModuleData<'a> {
471 /// The direct parent module (it may not be a `mod`, however).
472 parent: Option<Module<'a>>,
473 /// What kind of module this is, because this may not be a `mod`.
476 /// Mapping between names and their (possibly in-progress) resolutions in this module.
477 /// Resolutions in modules from other crates are not populated until accessed.
478 lazy_resolutions: Resolutions<'a>,
479 /// True if this is a module from other crate that needs to be populated on access.
480 populate_on_access: Cell<bool>,
482 /// Macro invocations that can expand into items in this module.
483 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
485 /// Whether `#[no_implicit_prelude]` is active.
486 no_implicit_prelude: bool,
488 glob_importers: RefCell<Vec<&'a Import<'a>>>,
489 globs: RefCell<Vec<&'a Import<'a>>>,
491 /// Used to memoize the traits in this module for faster searches through all traits in scope.
492 traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
494 /// Span of the module itself. Used for error reporting.
500 type Module<'a> = &'a ModuleData<'a>;
502 impl<'a> ModuleData<'a> {
504 parent: Option<Module<'a>>,
508 no_implicit_prelude: bool,
510 let is_foreign = match kind {
511 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
512 ModuleKind::Block => false,
517 lazy_resolutions: Default::default(),
518 populate_on_access: Cell::new(is_foreign),
519 unexpanded_invocations: Default::default(),
521 glob_importers: RefCell::new(Vec::new()),
522 globs: RefCell::new(Vec::new()),
523 traits: RefCell::new(None),
529 fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
531 R: AsMut<Resolver<'a>>,
532 F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
534 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
535 if let Some(binding) = name_resolution.borrow().binding {
536 f(resolver, key.ident, key.ns, binding);
541 /// This modifies `self` in place. The traits will be stored in `self.traits`.
542 fn ensure_traits<R>(&'a self, resolver: &mut R)
544 R: AsMut<Resolver<'a>>,
546 let mut traits = self.traits.borrow_mut();
547 if traits.is_none() {
548 let mut collected_traits = Vec::new();
549 self.for_each_child(resolver, |_, name, ns, binding| {
553 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
554 collected_traits.push((name, binding))
557 *traits = Some(collected_traits.into_boxed_slice());
561 fn res(&self) -> Option<Res> {
563 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
568 // Public for rustdoc.
569 pub fn def_id(&self) -> DefId {
570 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
573 fn opt_def_id(&self) -> Option<DefId> {
575 ModuleKind::Def(_, def_id, _) => Some(def_id),
580 // `self` resolves to the first module ancestor that `is_normal`.
581 fn is_normal(&self) -> bool {
582 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
585 fn is_trait(&self) -> bool {
586 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
589 fn nearest_item_scope(&'a self) -> Module<'a> {
591 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
592 self.parent.expect("enum or trait module without a parent")
598 /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
599 /// This may be the crate root.
600 fn nearest_parent_mod(&self) -> DefId {
602 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
603 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
607 fn is_ancestor_of(&self, mut other: &Self) -> bool {
608 while !ptr::eq(self, other) {
609 if let Some(parent) = other.parent {
619 impl<'a> fmt::Debug for ModuleData<'a> {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 write!(f, "{:?}", self.res())
625 /// Records a possibly-private value, type, or module definition.
626 #[derive(Clone, Debug)]
627 pub struct NameBinding<'a> {
628 kind: NameBindingKind<'a>,
629 ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
630 expansion: LocalExpnId,
632 vis: ty::Visibility<DefId>,
635 pub trait ToNameBinding<'a> {
636 fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
639 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
640 fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
645 #[derive(Clone, Debug)]
646 enum NameBindingKind<'a> {
647 Res(Res, /* is_macro_export */ bool),
649 Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
652 impl<'a> NameBindingKind<'a> {
653 /// Is this a name binding of an import?
654 fn is_import(&self) -> bool {
655 matches!(*self, NameBindingKind::Import { .. })
659 struct PrivacyError<'a> {
661 binding: &'a NameBinding<'a>,
665 struct UseError<'a> {
666 err: DiagnosticBuilder<'a, ErrorGuaranteed>,
667 /// Candidates which user could `use` to access the missing type.
668 candidates: Vec<ImportSuggestion>,
669 /// The `DefId` of the module to place the use-statements in.
671 /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
673 /// Extra free-form suggestion.
674 suggestion: Option<(Span, &'static str, String, Applicability)>,
675 /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
676 /// the user to import the item directly.
678 /// Whether the expected source is a call
682 #[derive(Clone, Copy, PartialEq, Debug)]
687 MacroRulesVsModularized,
695 fn descr(self) -> &'static str {
697 AmbiguityKind::Import => "multiple potential import sources",
698 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
699 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
700 AmbiguityKind::MacroRulesVsModularized => {
701 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
703 AmbiguityKind::GlobVsOuter => {
704 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
706 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
707 AmbiguityKind::GlobVsExpanded => {
708 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
710 AmbiguityKind::MoreExpandedVsOuter => {
711 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
717 /// Miscellaneous bits of metadata for better ambiguity error reporting.
718 #[derive(Clone, Copy, PartialEq)]
719 enum AmbiguityErrorMisc {
726 struct AmbiguityError<'a> {
729 b1: &'a NameBinding<'a>,
730 b2: &'a NameBinding<'a>,
731 misc1: AmbiguityErrorMisc,
732 misc2: AmbiguityErrorMisc,
735 impl<'a> NameBinding<'a> {
736 fn module(&self) -> Option<Module<'a>> {
738 NameBindingKind::Module(module) => Some(module),
739 NameBindingKind::Import { binding, .. } => binding.module(),
744 fn res(&self) -> Res {
746 NameBindingKind::Res(res, _) => res,
747 NameBindingKind::Module(module) => module.res().unwrap(),
748 NameBindingKind::Import { binding, .. } => binding.res(),
752 fn is_ambiguity(&self) -> bool {
753 self.ambiguity.is_some()
755 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
760 fn is_possibly_imported_variant(&self) -> bool {
762 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
763 NameBindingKind::Res(
764 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
767 NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
771 fn is_extern_crate(&self) -> bool {
773 NameBindingKind::Import {
774 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
777 NameBindingKind::Module(&ModuleData {
778 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
780 }) => def_id.is_crate_root(),
785 fn is_import(&self) -> bool {
786 matches!(self.kind, NameBindingKind::Import { .. })
789 fn is_glob_import(&self) -> bool {
791 NameBindingKind::Import { import, .. } => import.is_glob(),
796 fn is_importable(&self) -> bool {
799 Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
803 fn macro_kind(&self) -> Option<MacroKind> {
804 self.res().macro_kind()
807 // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
808 // at some expansion round `max(invoc, binding)` when they both emerged from macros.
809 // Then this function returns `true` if `self` may emerge from a macro *after* that
810 // in some later round and screw up our previously found resolution.
811 // See more detailed explanation in
812 // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
815 invoc_parent_expansion: LocalExpnId,
816 binding: &NameBinding<'_>,
818 // self > max(invoc, binding) => !(self <= invoc || self <= binding)
819 // Expansions are partially ordered, so "may appear after" is an inversion of
820 // "certainly appears before or simultaneously" and includes unordered cases.
821 let self_parent_expansion = self.expansion;
822 let other_parent_expansion = binding.expansion;
823 let certainly_before_other_or_simultaneously =
824 other_parent_expansion.is_descendant_of(self_parent_expansion);
825 let certainly_before_invoc_or_simultaneously =
826 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
827 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
831 #[derive(Default, Clone)]
832 pub struct ExternPreludeEntry<'a> {
833 extern_crate_item: Option<&'a NameBinding<'a>>,
834 pub introduced_by_item: bool,
837 /// Used for better errors for E0773
838 enum BuiltinMacroState {
839 NotYetSeen(SyntaxExtensionKind),
844 resolutions: DeriveResolutions,
845 helper_attrs: Vec<(usize, Ident)>,
846 has_derive_copy: bool,
851 ext: Lrc<SyntaxExtension>,
855 /// The main resolver class.
857 /// This is the visitor that walks the whole crate.
858 pub struct Resolver<'a> {
859 session: &'a Session,
861 definitions: Definitions,
862 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
863 expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
864 /// Reference span for definitions.
865 source_span: IndexVec<LocalDefId, Span>,
867 graph_root: Module<'a>,
869 prelude: Option<Module<'a>>,
870 extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
872 /// N.B., this is used only for better diagnostics, not name resolution itself.
873 has_self: FxHashSet<DefId>,
875 /// Names of fields of an item `DefId` accessible with dot syntax.
876 /// Used for hints during error reporting.
877 field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
879 /// All imports known to succeed or fail.
880 determined_imports: Vec<&'a Import<'a>>,
882 /// All non-determined imports.
883 indeterminate_imports: Vec<&'a Import<'a>>,
885 // Spans for local variables found during pattern resolution.
886 // Used for suggestions during error reporting.
887 pat_span_map: NodeMap<Span>,
889 /// Resolutions for nodes that have a single resolution.
890 partial_res_map: NodeMap<PartialRes>,
891 /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
892 import_res_map: NodeMap<PerNS<Option<Res>>>,
893 /// Resolutions for labels (node IDs of their corresponding blocks or loops).
894 label_res_map: NodeMap<NodeId>,
895 /// Resolutions for lifetimes.
896 lifetimes_res_map: NodeMap<LifetimeRes>,
897 /// Lifetime parameters that lowering will have to introduce.
898 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
900 /// `CrateNum` resolutions of `extern crate` items.
901 extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
902 reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
903 trait_map: NodeMap<Vec<TraitCandidate>>,
905 /// A map from nodes to anonymous modules.
906 /// Anonymous modules are pseudo-modules that are implicitly created around items
907 /// contained within blocks.
909 /// For example, if we have this:
917 /// There will be an anonymous module created around `g` with the ID of the
918 /// entry block for `f`.
919 block_map: NodeMap<Module<'a>>,
920 /// A fake module that contains no definition and no prelude. Used so that
921 /// some AST passes can generate identifiers that only resolve to local or
923 empty_module: Module<'a>,
924 module_map: FxHashMap<DefId, Module<'a>>,
925 binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
926 underscore_disambiguator: u32,
928 /// Maps glob imports to the names of items actually imported.
929 glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
930 /// Visibilities in "lowered" form, for all entities that have them.
931 visibilities: FxHashMap<LocalDefId, ty::Visibility>,
932 has_pub_restricted: bool,
933 used_imports: FxHashSet<NodeId>,
934 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
935 maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
937 /// Privacy errors are delayed until the end in order to deduplicate them.
938 privacy_errors: Vec<PrivacyError<'a>>,
939 /// Ambiguity errors are delayed for deduplication.
940 ambiguity_errors: Vec<AmbiguityError<'a>>,
941 /// `use` injections are delayed for better placement and deduplication.
942 use_injections: Vec<UseError<'a>>,
943 /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
944 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
946 arenas: &'a ResolverArenas<'a>,
947 dummy_binding: &'a NameBinding<'a>,
949 crate_loader: CrateLoader<'a>,
950 macro_names: FxHashSet<Ident>,
951 builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
952 /// A small map keeping true kinds of built-in macros that appear to be fn-like on
953 /// the surface (`macro` items in libcore), but are actually attributes or derives.
954 builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
955 registered_tools: RegisteredTools,
956 macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
957 macro_map: FxHashMap<DefId, MacroData>,
958 dummy_ext_bang: Lrc<SyntaxExtension>,
959 dummy_ext_derive: Lrc<SyntaxExtension>,
960 non_macro_attr: Lrc<SyntaxExtension>,
961 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
962 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
963 unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
964 unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
965 proc_macro_stubs: FxHashSet<LocalDefId>,
966 /// Traces collected during macro resolution and validated when it's complete.
967 single_segment_macro_resolutions:
968 Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
969 multi_segment_macro_resolutions:
970 Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
971 builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
972 /// `derive(Copy)` marks items they are applied to so they are treated specially later.
973 /// Derive macros cannot modify the item themselves and have to store the markers in the global
974 /// context, so they attach the markers to derive container IDs using this resolver table.
975 containers_deriving_copy: FxHashSet<LocalExpnId>,
976 /// Parent scopes in which the macros were invoked.
977 /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
978 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
979 /// `macro_rules` scopes *produced* by expanding the macro invocations,
980 /// include all the `macro_rules` items and other invocations generated by them.
981 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
982 /// `macro_rules` scopes produced by `macro_rules` item definitions.
983 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
984 /// Helper attributes that are in scope for the given expansion.
985 helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
986 /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
987 /// with the given `ExpnId`.
988 derive_data: FxHashMap<LocalExpnId, DeriveData>,
990 /// Avoid duplicated errors for "name already defined".
991 name_already_seen: FxHashMap<Symbol, Span>,
993 potentially_unused_imports: Vec<&'a Import<'a>>,
995 /// Table for mapping struct IDs into struct constructor IDs,
996 /// it's not used during normal resolution, only for better error reporting.
997 /// Also includes of list of each fields visibility
998 struct_constructors: DefIdMap<(Res, ty::Visibility<DefId>, Vec<ty::Visibility<DefId>>)>,
1000 /// Features enabled for this crate.
1001 active_features: FxHashSet<Symbol>,
1003 lint_buffer: LintBuffer,
1005 next_node_id: NodeId,
1007 node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1008 def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1010 /// Indices of unnamed struct or variant fields with unresolved attributes.
1011 placeholder_field_indices: FxHashMap<NodeId, usize>,
1012 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1013 /// we know what parent node that fragment should be attached to thanks to this table,
1014 /// and how the `impl Trait` fragments were introduced.
1015 invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1017 /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1018 /// FIXME: Replace with a more general AST map (together with some other fields).
1019 trait_impl_items: FxHashSet<LocalDefId>,
1021 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1022 /// Amount of lifetime parameters for each item in the crate.
1023 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1025 main_def: Option<MainDefinition>,
1026 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1027 /// A list of proc macro LocalDefIds, written out in the order in which
1028 /// they are declared in the static array generated by proc_macro_harness.
1029 proc_macros: Vec<NodeId>,
1030 confused_type_with_std_module: FxHashMap<Span, Span>,
1032 access_levels: AccessLevels,
1035 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1037 pub struct ResolverArenas<'a> {
1038 modules: TypedArena<ModuleData<'a>>,
1039 local_modules: RefCell<Vec<Module<'a>>>,
1040 imports: TypedArena<Import<'a>>,
1041 name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1042 ast_paths: TypedArena<ast::Path>,
1043 dropless: DroplessArena,
1046 impl<'a> ResolverArenas<'a> {
1049 parent: Option<Module<'a>>,
1053 no_implicit_prelude: bool,
1054 module_map: &mut FxHashMap<DefId, Module<'a>>,
1057 self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1058 let def_id = module.opt_def_id();
1059 if def_id.map_or(true, |def_id| def_id.is_local()) {
1060 self.local_modules.borrow_mut().push(module);
1062 if let Some(def_id) = def_id {
1063 module_map.insert(def_id, module);
1067 fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1068 self.local_modules.borrow()
1070 fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1071 self.dropless.alloc(name_binding)
1073 fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1074 self.imports.alloc(import)
1076 fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1077 self.name_resolutions.alloc(Default::default())
1079 fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1080 Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1082 fn alloc_macro_rules_binding(
1084 binding: MacroRulesBinding<'a>,
1085 ) -> &'a MacroRulesBinding<'a> {
1086 self.dropless.alloc(binding)
1088 fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1089 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1091 fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1092 self.dropless.alloc_from_iter(spans)
1096 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1097 fn as_mut(&mut self) -> &mut Resolver<'a> {
1102 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1104 fn opt_parent(self, id: DefId) -> Option<DefId> {
1105 match id.as_local() {
1106 Some(id) => self.definitions.def_key(id).parent,
1107 None => self.cstore().def_key(id).parent,
1109 .map(|index| DefId { index, ..id })
1114 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1115 self.node_id_to_def_id.get(&node).copied()
1118 pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1119 self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1122 /// Adds a definition with a parent definition.
1126 node_id: ast::NodeId,
1132 !self.node_id_to_def_id.contains_key(&node_id),
1133 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1136 self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1139 let def_id = self.definitions.create_def(parent, data);
1141 // Create the definition.
1142 if expn_id != ExpnId::root() {
1143 self.expn_that_defined.insert(def_id, expn_id);
1146 // A relative span's parent must be an absolute span.
1147 debug_assert_eq!(span.data_untracked().parent, None);
1148 let _id = self.source_span.push(span);
1149 debug_assert_eq!(_id, def_id);
1151 // Some things for which we allocate `LocalDefId`s don't correspond to
1152 // anything in the AST, so they don't have a `NodeId`. For these cases
1153 // we don't need a mapping from `NodeId` to `LocalDefId`.
1154 if node_id != ast::DUMMY_NODE_ID {
1155 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1156 self.node_id_to_def_id.insert(node_id, def_id);
1158 assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1163 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1164 if let Some(def_id) = def_id.as_local() {
1165 self.item_generics_num_lifetimes[&def_id]
1167 self.cstore().item_generics_num_lifetimes(def_id, self.session)
1172 impl<'a> Resolver<'a> {
1174 session: &'a Session,
1177 metadata_loader: Box<MetadataLoaderDyn>,
1178 arenas: &'a ResolverArenas<'a>,
1180 let root_def_id = CRATE_DEF_ID.to_def_id();
1181 let mut module_map = FxHashMap::default();
1182 let graph_root = arenas.new_module(
1184 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1186 krate.spans.inner_span,
1187 session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1190 let empty_module = arenas.new_module(
1192 ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1196 &mut FxHashMap::default(),
1199 let definitions = Definitions::new(session.local_stable_crate_id());
1201 let mut visibilities = FxHashMap::default();
1202 visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1204 let mut def_id_to_node_id = IndexVec::default();
1205 assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1206 let mut node_id_to_def_id = FxHashMap::default();
1207 node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1209 let mut invocation_parents = FxHashMap::default();
1210 invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1212 let mut source_span = IndexVec::default();
1213 let _id = source_span.push(krate.spans.inner_span);
1214 debug_assert_eq!(_id, CRATE_DEF_ID);
1216 let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1220 .filter(|(_, entry)| entry.add_prelude)
1221 .map(|(name, _)| (Ident::from_str(name), Default::default()))
1224 if !session.contains_name(&krate.attrs, sym::no_core) {
1225 extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1226 if !session.contains_name(&krate.attrs, sym::no_std) {
1227 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1231 let registered_tools = macros::registered_tools(session, &krate.attrs);
1233 let features = session.features_untracked();
1235 let mut resolver = Resolver {
1239 expn_that_defined: Default::default(),
1242 // The outermost module has def ID 0; this is not reflected in the
1248 has_self: FxHashSet::default(),
1249 field_names: FxHashMap::default(),
1251 determined_imports: Vec::new(),
1252 indeterminate_imports: Vec::new(),
1254 pat_span_map: Default::default(),
1255 partial_res_map: Default::default(),
1256 import_res_map: Default::default(),
1257 label_res_map: Default::default(),
1258 lifetimes_res_map: Default::default(),
1259 extra_lifetime_params_map: Default::default(),
1260 extern_crate_map: Default::default(),
1261 reexport_map: FxHashMap::default(),
1262 trait_map: NodeMap::default(),
1263 underscore_disambiguator: 0,
1266 block_map: Default::default(),
1267 binding_parent_modules: FxHashMap::default(),
1268 ast_transform_scopes: FxHashMap::default(),
1270 glob_map: Default::default(),
1272 has_pub_restricted: false,
1273 used_imports: FxHashSet::default(),
1274 maybe_unused_trait_imports: Default::default(),
1275 maybe_unused_extern_crates: Vec::new(),
1277 privacy_errors: Vec::new(),
1278 ambiguity_errors: Vec::new(),
1279 use_injections: Vec::new(),
1280 macro_expanded_macro_export_errors: BTreeSet::new(),
1283 dummy_binding: arenas.alloc_name_binding(NameBinding {
1284 kind: NameBindingKind::Res(Res::Err, false),
1286 expansion: LocalExpnId::ROOT,
1288 vis: ty::Visibility::Public,
1291 crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1292 macro_names: FxHashSet::default(),
1293 builtin_macros: Default::default(),
1294 builtin_macro_kinds: Default::default(),
1296 macro_use_prelude: FxHashMap::default(),
1297 macro_map: FxHashMap::default(),
1298 dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1299 dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1300 non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1301 invocation_parent_scopes: Default::default(),
1302 output_macro_rules_scopes: Default::default(),
1303 macro_rules_scopes: Default::default(),
1304 helper_attrs: Default::default(),
1305 derive_data: Default::default(),
1306 local_macro_def_scopes: FxHashMap::default(),
1307 name_already_seen: FxHashMap::default(),
1308 potentially_unused_imports: Vec::new(),
1309 struct_constructors: Default::default(),
1310 unused_macros: Default::default(),
1311 unused_macro_rules: Default::default(),
1312 proc_macro_stubs: Default::default(),
1313 single_segment_macro_resolutions: Default::default(),
1314 multi_segment_macro_resolutions: Default::default(),
1315 builtin_attrs: Default::default(),
1316 containers_deriving_copy: Default::default(),
1317 active_features: features
1318 .declared_lib_features
1320 .map(|(feat, ..)| *feat)
1321 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1323 lint_buffer: LintBuffer::default(),
1324 next_node_id: CRATE_NODE_ID,
1327 placeholder_field_indices: Default::default(),
1329 trait_impl_items: Default::default(),
1330 legacy_const_generic_args: Default::default(),
1331 item_generics_num_lifetimes: Default::default(),
1332 main_def: Default::default(),
1333 trait_impls: Default::default(),
1334 proc_macros: Default::default(),
1335 confused_type_with_std_module: Default::default(),
1336 access_levels: Default::default(),
1339 let root_parent_scope = ParentScope::module(graph_root, &resolver);
1340 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1347 parent: Option<Module<'a>>,
1351 no_implicit_prelude: bool,
1353 let module_map = &mut self.module_map;
1354 self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1357 pub fn next_node_id(&mut self) -> NodeId {
1358 let start = self.next_node_id;
1359 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1360 self.next_node_id = ast::NodeId::from_u32(next);
1364 pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1365 let start = self.next_node_id;
1366 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1367 self.next_node_id = ast::NodeId::from_usize(end);
1368 start..self.next_node_id
1371 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1372 &mut self.lint_buffer
1375 pub fn arenas() -> ResolverArenas<'a> {
1379 pub fn into_outputs(
1381 ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1382 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1383 let definitions = self.definitions;
1384 let cstore = Box::new(self.crate_loader.into_cstore());
1385 let source_span = self.source_span;
1386 let expn_that_defined = self.expn_that_defined;
1387 let visibilities = self.visibilities;
1388 let has_pub_restricted = self.has_pub_restricted;
1389 let extern_crate_map = self.extern_crate_map;
1390 let reexport_map = self.reexport_map;
1391 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1392 let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1393 let glob_map = self.glob_map;
1394 let main_def = self.main_def;
1395 let confused_type_with_std_module = self.confused_type_with_std_module;
1396 let access_levels = self.access_levels;
1397 let resolutions = ResolverOutputs {
1406 maybe_unused_trait_imports,
1407 maybe_unused_extern_crates,
1408 extern_prelude: self
1411 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1414 trait_impls: self.trait_impls,
1416 confused_type_with_std_module,
1417 registered_tools: self.registered_tools,
1419 let resolutions_lowering = ty::ResolverAstLowering {
1420 legacy_const_generic_args: self.legacy_const_generic_args,
1421 partial_res_map: self.partial_res_map,
1422 import_res_map: self.import_res_map,
1423 label_res_map: self.label_res_map,
1424 lifetimes_res_map: self.lifetimes_res_map,
1425 extra_lifetime_params_map: self.extra_lifetime_params_map,
1426 next_node_id: self.next_node_id,
1427 node_id_to_def_id: self.node_id_to_def_id,
1428 def_id_to_node_id: self.def_id_to_node_id,
1429 trait_map: self.trait_map,
1430 builtin_macro_kinds: self.builtin_macro_kinds,
1432 (definitions, cstore, resolutions, resolutions_lowering)
1435 pub fn clone_outputs(
1437 ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1438 let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1439 let definitions = self.definitions.clone();
1440 let cstore = Box::new(self.cstore().clone());
1441 let resolutions = ResolverOutputs {
1442 source_span: self.source_span.clone(),
1443 expn_that_defined: self.expn_that_defined.clone(),
1444 visibilities: self.visibilities.clone(),
1445 has_pub_restricted: self.has_pub_restricted,
1446 extern_crate_map: self.extern_crate_map.clone(),
1447 reexport_map: self.reexport_map.clone(),
1448 glob_map: self.glob_map.clone(),
1449 maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1450 maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1451 extern_prelude: self
1454 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1456 main_def: self.main_def,
1457 trait_impls: self.trait_impls.clone(),
1459 confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1460 registered_tools: self.registered_tools.clone(),
1461 access_levels: self.access_levels.clone(),
1463 let resolutions_lowering = ty::ResolverAstLowering {
1464 legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1465 partial_res_map: self.partial_res_map.clone(),
1466 import_res_map: self.import_res_map.clone(),
1467 label_res_map: self.label_res_map.clone(),
1468 lifetimes_res_map: self.lifetimes_res_map.clone(),
1469 extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1470 next_node_id: self.next_node_id.clone(),
1471 node_id_to_def_id: self.node_id_to_def_id.clone(),
1472 def_id_to_node_id: self.def_id_to_node_id.clone(),
1473 trait_map: self.trait_map.clone(),
1474 builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1476 (definitions, cstore, resolutions, resolutions_lowering)
1479 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1480 StableHashingContext::new(
1483 self.crate_loader.cstore(),
1488 pub fn cstore(&self) -> &CStore {
1489 self.crate_loader.cstore()
1492 fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1494 MacroKind::Bang => self.dummy_ext_bang.clone(),
1495 MacroKind::Derive => self.dummy_ext_derive.clone(),
1496 MacroKind::Attr => self.non_macro_attr.clone(),
1500 /// Runs the function on each namespace.
1501 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1507 fn is_builtin_macro(&mut self, res: Res) -> bool {
1508 self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1511 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1513 match ctxt.outer_expn_data().macro_def_id {
1514 Some(def_id) => return def_id,
1515 None => ctxt.remove_mark(),
1520 /// Entry point to crate resolution.
1521 pub fn resolve_crate(&mut self, krate: &Crate) {
1522 self.session.time("resolve_crate", || {
1523 self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1524 self.session.time("resolve_access_levels", || {
1525 AccessLevelsVisitor::compute_access_levels(self, krate)
1527 self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1528 self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1529 self.session.time("resolve_main", || self.resolve_main());
1530 self.session.time("resolve_check_unused", || self.check_unused(krate));
1531 self.session.time("resolve_report_errors", || self.report_errors(krate));
1532 self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1536 pub fn traits_in_scope(
1538 current_trait: Option<Module<'a>>,
1539 parent_scope: &ParentScope<'a>,
1540 ctxt: SyntaxContext,
1541 assoc_item: Option<(Symbol, Namespace)>,
1542 ) -> Vec<TraitCandidate> {
1543 let mut found_traits = Vec::new();
1545 if let Some(module) = current_trait {
1546 if self.trait_may_have_item(Some(module), assoc_item) {
1547 let def_id = module.def_id();
1548 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1552 self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1554 Scope::Module(module, _) => {
1555 this.traits_in_module(module, assoc_item, &mut found_traits);
1557 Scope::StdLibPrelude => {
1558 if let Some(module) = this.prelude {
1559 this.traits_in_module(module, assoc_item, &mut found_traits);
1562 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1563 _ => unreachable!(),
1571 fn traits_in_module(
1574 assoc_item: Option<(Symbol, Namespace)>,
1575 found_traits: &mut Vec<TraitCandidate>,
1577 module.ensure_traits(self);
1578 let traits = module.traits.borrow();
1579 for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1580 if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1581 let def_id = trait_binding.res().def_id();
1582 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1583 found_traits.push(TraitCandidate { def_id, import_ids });
1588 // List of traits in scope is pruned on best effort basis. We reject traits not having an
1589 // associated item with the given name and namespace (if specified). This is a conservative
1590 // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1591 // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1592 // associated items.
1593 fn trait_may_have_item(
1595 trait_module: Option<Module<'a>>,
1596 assoc_item: Option<(Symbol, Namespace)>,
1598 match (trait_module, assoc_item) {
1599 (Some(trait_module), Some((name, ns))) => {
1600 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1601 let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1602 assoc_ns == ns && assoc_ident.name == name
1609 fn find_transitive_imports(
1611 mut kind: &NameBindingKind<'_>,
1613 ) -> SmallVec<[LocalDefId; 1]> {
1614 let mut import_ids = smallvec![];
1615 while let NameBindingKind::Import { import, binding, .. } = kind {
1616 let id = self.local_def_id(import.id);
1617 self.maybe_unused_trait_imports.insert(id);
1618 self.add_to_glob_map(&import, trait_name);
1619 import_ids.push(id);
1620 kind = &binding.kind;
1625 fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1626 let ident = ident.normalize_to_macros_2_0();
1627 let disambiguator = if ident.name == kw::Underscore {
1628 self.underscore_disambiguator += 1;
1629 self.underscore_disambiguator
1633 BindingKey { ident, ns, disambiguator }
1636 fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1637 if module.populate_on_access.get() {
1638 module.populate_on_access.set(false);
1639 self.build_reduced_graph_external(module);
1641 &module.lazy_resolutions
1648 ) -> &'a RefCell<NameResolution<'a>> {
1650 .resolutions(module)
1653 .or_insert_with(|| self.arenas.alloc_name_resolution())
1659 used_binding: &'a NameBinding<'a>,
1660 is_lexical_scope: bool,
1662 if let Some((b2, kind)) = used_binding.ambiguity {
1663 self.ambiguity_errors.push(AmbiguityError {
1668 misc1: AmbiguityErrorMisc::None,
1669 misc2: AmbiguityErrorMisc::None,
1672 if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1673 // Avoid marking `extern crate` items that refer to a name from extern prelude,
1674 // but not introduce it, as used if they are accessed from lexical scope.
1675 if is_lexical_scope {
1676 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1677 if let Some(crate_item) = entry.extern_crate_item {
1678 if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1685 import.used.set(true);
1686 self.used_imports.insert(import.id);
1687 self.add_to_glob_map(&import, ident);
1688 self.record_use(ident, binding, false);
1693 fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1694 if import.is_glob() {
1695 let def_id = self.local_def_id(import.id);
1696 self.glob_map.entry(def_id).or_default().insert(ident.name);
1700 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1701 debug!("resolve_crate_root({:?})", ident);
1702 let mut ctxt = ident.span.ctxt();
1703 let mark = if ident.name == kw::DollarCrate {
1704 // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1705 // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1706 // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1707 // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1708 // definitions actually produced by `macro` and `macro` definitions produced by
1709 // `macro_rules!`, but at least such configurations are not stable yet.
1710 ctxt = ctxt.normalize_to_macro_rules();
1712 "resolve_crate_root: marks={:?}",
1713 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1715 let mut iter = ctxt.marks().into_iter().rev().peekable();
1716 let mut result = None;
1717 // Find the last opaque mark from the end if it exists.
1718 while let Some(&(mark, transparency)) = iter.peek() {
1719 if transparency == Transparency::Opaque {
1720 result = Some(mark);
1727 "resolve_crate_root: found opaque mark {:?} {:?}",
1729 result.map(|r| r.expn_data())
1731 // Then find the last semi-transparent mark from the end if it exists.
1732 for (mark, transparency) in iter {
1733 if transparency == Transparency::SemiTransparent {
1734 result = Some(mark);
1740 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1742 result.map(|r| r.expn_data())
1746 debug!("resolve_crate_root: not DollarCrate");
1747 ctxt = ctxt.normalize_to_macros_2_0();
1748 ctxt.adjust(ExpnId::root())
1750 let module = match mark {
1751 Some(def) => self.expn_def_scope(def),
1754 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1757 return self.graph_root;
1760 let module = self.expect_module(
1761 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1764 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1773 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1774 let mut module = self.expect_module(module.nearest_parent_mod());
1775 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1776 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1777 module = self.expect_module(parent.nearest_parent_mod());
1782 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1783 debug!("(recording res) recording {:?} for {}", resolution, node_id);
1784 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1785 panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1789 fn record_pat_span(&mut self, node: NodeId, span: Span) {
1790 debug!("(recording pat) recording {:?} for {:?}", node, span);
1791 self.pat_span_map.insert(node, span);
1794 fn is_accessible_from(
1796 vis: ty::Visibility<impl Into<DefId>>,
1799 vis.is_accessible_from(module.nearest_parent_mod(), self)
1802 fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1803 if let Some(old_module) =
1804 self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1806 if !ptr::eq(module, old_module) {
1807 span_bug!(binding.span, "parent module is reset for binding");
1812 fn disambiguate_macro_rules_vs_modularized(
1814 macro_rules: &'a NameBinding<'a>,
1815 modularized: &'a NameBinding<'a>,
1817 // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1818 // is disambiguated to mitigate regressions from macro modularization.
1819 // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1821 self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1822 self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1824 (Some(macro_rules), Some(modularized)) => {
1825 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1826 && modularized.is_ancestor_of(macro_rules)
1832 fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1833 if ident.is_path_segment_keyword() {
1834 // Make sure `self`, `super` etc produce an error when passed to here.
1837 self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1838 if let Some(binding) = entry.extern_crate_item {
1839 if finalize && entry.introduced_by_item {
1840 self.record_use(ident, binding, false);
1844 let crate_id = if finalize {
1845 let Some(crate_id) =
1846 self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1849 self.crate_loader.maybe_process_path_extern(ident.name)?
1851 let crate_root = self.expect_module(crate_id.as_def_id());
1852 let vis = ty::Visibility::<LocalDefId>::Public;
1853 Some((crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas))
1858 /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1859 /// isn't something that can be returned because it can't be made to live that long,
1860 /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1861 /// just that an error occurred.
1862 pub fn resolve_rustdoc_path(
1866 mut parent_scope: ParentScope<'a>,
1869 Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1870 if let Some(segment) = segments.first_mut() {
1871 if segment.ident.name == kw::Crate {
1872 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1873 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1874 // replacing `crate` with `self` and changing the current module should achieve
1876 segment.ident.name = kw::SelfLower;
1877 parent_scope.module =
1878 self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1879 } else if segment.ident.name == kw::Empty {
1880 segment.ident.name = kw::PathRoot;
1884 match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1885 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1886 PathResult::NonModule(path_res) => path_res.full_res(),
1887 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
1890 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1895 /// For local modules returns only reexports, for external modules returns all children.
1896 pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1897 if let Some(def_id) = def_id.as_local() {
1898 self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1900 self.cstore().module_children_untracked(def_id, self.session)
1905 pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1906 let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1908 MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1909 _ => unreachable!(),
1913 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1915 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1916 def_id.as_local().map(|def_id| self.source_span[def_id])
1919 /// Retrieves the name of the given `DefId`.
1921 pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
1922 let def_key = match def_id.as_local() {
1923 Some(def_id) => self.definitions.def_key(def_id),
1924 None => self.cstore().def_key(def_id),
1926 def_key.get_opt_name()
1929 /// Checks if an expression refers to a function marked with
1930 /// `#[rustc_legacy_const_generics]` and returns the argument index list
1931 /// from the attribute.
1932 pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1933 if let ExprKind::Path(None, path) = &expr.kind {
1934 // Don't perform legacy const generics rewriting if the path already
1935 // has generic arguments.
1936 if path.segments.last().unwrap().args.is_some() {
1940 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
1941 if let Res::Def(def::DefKind::Fn, def_id) = res {
1942 // We only support cross-crate argument rewriting. Uses
1943 // within the same crate should be updated to use the new
1944 // const generics style.
1945 if def_id.is_local() {
1949 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1955 .item_attrs_untracked(def_id, self.session)
1956 .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1957 let mut ret = Vec::new();
1958 for meta in attr.meta_item_list()? {
1959 match meta.literal()?.kind {
1960 LitKind::Int(a, _) => ret.push(a as usize),
1961 _ => panic!("invalid arg index"),
1964 // Cache the lookup to avoid parsing attributes for an item multiple times.
1965 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
1972 fn resolve_main(&mut self) {
1973 let module = self.graph_root;
1974 let ident = Ident::with_dummy_span(sym::main);
1975 let parent_scope = &ParentScope::module(module, self);
1977 let Ok(name_binding) = self.maybe_resolve_ident_in_module(
1978 ModuleOrUniformRoot::Module(module),
1986 let res = name_binding.res();
1987 let is_import = name_binding.is_import();
1988 let span = name_binding.span;
1989 if let Res::Def(DefKind::Fn, _) = res {
1990 self.record_use(ident, name_binding, false);
1992 self.main_def = Some(MainDefinition { res, is_import, span });
1995 // Items that go to reexport table encoded to metadata and visible through it to other crates.
1996 fn is_reexport(&self, binding: &NameBinding<'a>) -> Option<def::Res<!>> {
1997 // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1998 // into the crate root to actual `NameBindingKind::Import`.
1999 if binding.is_import()
2000 || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
2002 let res = binding.res().expect_non_local();
2003 // Ambiguous imports are treated as errors at this point and are
2004 // not exposed to other crates (see #36837 for more details).
2005 if res != def::Res::Err && !binding.is_ambiguity() {
2014 fn names_to_string(names: &[Symbol]) -> String {
2015 let mut result = String::new();
2016 for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2018 result.push_str("::");
2020 if Ident::with_dummy_span(*name).is_raw_guess() {
2021 result.push_str("r#");
2023 result.push_str(name.as_str());
2028 fn path_names_to_string(path: &Path) -> String {
2029 names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2032 /// A somewhat inefficient routine to obtain the name of a module.
2033 fn module_to_string(module: Module<'_>) -> Option<String> {
2034 let mut names = Vec::new();
2036 fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2037 if let ModuleKind::Def(.., name) = module.kind {
2038 if let Some(parent) = module.parent {
2040 collect_mod(names, parent);
2043 names.push(Symbol::intern("<opaque>"));
2044 collect_mod(names, module.parent.unwrap());
2047 collect_mod(&mut names, module);
2049 if names.is_empty() {
2053 Some(names_to_string(&names))
2056 #[derive(Copy, Clone, Debug)]
2058 /// Node ID for linting.
2060 /// Span of the whole path or some its characteristic fragment.
2061 /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2063 /// Span of the path start, suitable for prepending something to it.
2064 /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2066 /// Whether to report privacy errors or silently return "no resolution" for them,
2067 /// similarly to speculative resolution.
2068 report_private: bool,
2072 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2073 Finalize::with_root_span(node_id, path_span, path_span)
2076 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2077 Finalize { node_id, path_span, root_span, report_private: true }