]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/lib.rs
Rollup merge of #101462 - aDotInTheVoid:rdj-enum-field-2, r=GuillaumeGomez
[rust.git] / compiler / rustc_resolve / src / lib.rs
1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
2 //!
3 //! Module structure of the crate is built here.
4 //! Paths in macros, imports, expressions, types, patterns are resolved here.
5 //! Label and lifetime names are resolved here as well.
6 //!
7 //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_typeck`.
8
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(let_else)]
16 #![feature(never_type)]
17 #![recursion_limit = "256"]
18 #![allow(rustdoc::private_intra_doc_links)]
19 #![allow(rustc::potential_query_instability)]
20
21 #[macro_use]
22 extern crate tracing;
23
24 pub use rustc_hir::def::{Namespace, PerNS};
25
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};
56
57 use smallvec::{smallvec, SmallVec};
58 use std::cell::{Cell, RefCell};
59 use std::collections::BTreeSet;
60 use std::{cmp, fmt, ptr};
61
62 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
63 use imports::{Import, ImportKind, ImportResolver, NameResolution};
64 use late::{HasGenericParams, PathSource, PatternSource};
65 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
66
67 use crate::access_levels::AccessLevelsVisitor;
68
69 type Res = def::Res<NodeId>;
70
71 mod access_levels;
72 mod build_reduced_graph;
73 mod check_unused;
74 mod def_collector;
75 mod diagnostics;
76 mod ident;
77 mod imports;
78 mod late;
79 mod macros;
80
81 enum Weak {
82     Yes,
83     No,
84 }
85
86 #[derive(Copy, Clone, PartialEq, Debug)]
87 pub enum Determinacy {
88     Determined,
89     Undetermined,
90 }
91
92 impl Determinacy {
93     fn determined(determined: bool) -> Determinacy {
94         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
95     }
96 }
97
98 /// A specific scope in which a name can be looked up.
99 /// This enum is currently used only for early resolution (imports and macros),
100 /// but not for late resolution yet.
101 #[derive(Clone, Copy)]
102 enum Scope<'a> {
103     DeriveHelpers(LocalExpnId),
104     DeriveHelpersCompat,
105     MacroRules(MacroRulesScopeRef<'a>),
106     CrateRoot,
107     // The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
108     // lint if it should be reported.
109     Module(Module<'a>, Option<NodeId>),
110     MacroUsePrelude,
111     BuiltinAttrs,
112     ExternPrelude,
113     ToolPrelude,
114     StdLibPrelude,
115     BuiltinTypes,
116 }
117
118 /// Names from different contexts may want to visit different subsets of all specific scopes
119 /// with different restrictions when looking up the resolution.
120 /// This enum is currently used only for early resolution (imports and macros),
121 /// but not for late resolution yet.
122 #[derive(Clone, Copy)]
123 enum ScopeSet<'a> {
124     /// All scopes with the given namespace.
125     All(Namespace, /*is_import*/ bool),
126     /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
127     AbsolutePath(Namespace),
128     /// All scopes with macro namespace and the given macro kind restriction.
129     Macro(MacroKind),
130     /// All scopes with the given namespace, used for partially performing late resolution.
131     /// The node id enables lints and is used for reporting them.
132     Late(Namespace, Module<'a>, Option<NodeId>),
133 }
134
135 /// Everything you need to know about a name's location to resolve it.
136 /// Serves as a starting point for the scope visitor.
137 /// This struct is currently used only for early resolution (imports and macros),
138 /// but not for late resolution yet.
139 #[derive(Clone, Copy, Debug)]
140 pub struct ParentScope<'a> {
141     pub module: Module<'a>,
142     expansion: LocalExpnId,
143     pub macro_rules: MacroRulesScopeRef<'a>,
144     derives: &'a [ast::Path],
145 }
146
147 impl<'a> ParentScope<'a> {
148     /// Creates a parent scope with the passed argument used as the module scope component,
149     /// and other scope components set to default empty values.
150     pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
151         ParentScope {
152             module,
153             expansion: LocalExpnId::ROOT,
154             macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
155             derives: &[],
156         }
157     }
158 }
159
160 #[derive(Copy, Debug, Clone)]
161 enum ImplTraitContext {
162     Existential,
163     Universal(LocalDefId),
164 }
165
166 #[derive(Eq)]
167 struct BindingError {
168     name: Symbol,
169     origin: BTreeSet<Span>,
170     target: BTreeSet<Span>,
171     could_be_path: bool,
172 }
173
174 impl PartialOrd for BindingError {
175     fn partial_cmp(&self, other: &BindingError) -> Option<cmp::Ordering> {
176         Some(self.cmp(other))
177     }
178 }
179
180 impl PartialEq for BindingError {
181     fn eq(&self, other: &BindingError) -> bool {
182         self.name == other.name
183     }
184 }
185
186 impl Ord for BindingError {
187     fn cmp(&self, other: &BindingError) -> cmp::Ordering {
188         self.name.cmp(&other.name)
189     }
190 }
191
192 enum ResolutionError<'a> {
193     /// Error E0401: can't use type or const parameters from outer function.
194     GenericParamsFromOuterFunction(Res, HasGenericParams),
195     /// Error E0403: the name is already used for a type or const parameter in this generic
196     /// parameter list.
197     NameAlreadyUsedInParameterList(Symbol, Span),
198     /// Error E0407: method is not a member of trait.
199     MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
200     /// Error E0437: type is not a member of trait.
201     TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
202     /// Error E0438: const is not a member of trait.
203     ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
204     /// Error E0408: variable `{}` is not bound in all patterns.
205     VariableNotBoundInPattern(BindingError, ParentScope<'a>),
206     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
207     VariableBoundWithDifferentMode(Symbol, Span),
208     /// Error E0415: identifier is bound more than once in this parameter list.
209     IdentifierBoundMoreThanOnceInParameterList(Symbol),
210     /// Error E0416: identifier is bound more than once in the same pattern.
211     IdentifierBoundMoreThanOnceInSamePattern(Symbol),
212     /// Error E0426: use of undeclared label.
213     UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
214     /// Error E0429: `self` imports are only allowed within a `{ }` list.
215     SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
216     /// Error E0430: `self` import can only appear once in the list.
217     SelfImportCanOnlyAppearOnceInTheList,
218     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
219     SelfImportOnlyInImportListWithNonEmptyPrefix,
220     /// Error E0433: failed to resolve.
221     FailedToResolve { label: String, suggestion: Option<Suggestion> },
222     /// Error E0434: can't capture dynamic environment in a fn item.
223     CannotCaptureDynamicEnvironmentInFnItem,
224     /// Error E0435: attempt to use a non-constant value in a constant.
225     AttemptToUseNonConstantValueInConstant(
226         Ident,
227         /* suggestion */ &'static str,
228         /* current */ &'static str,
229     ),
230     /// Error E0530: `X` bindings cannot shadow `Y`s.
231     BindingShadowsSomethingUnacceptable {
232         shadowing_binding: PatternSource,
233         name: Symbol,
234         participle: &'static str,
235         article: &'static str,
236         shadowed_binding: Res,
237         shadowed_binding_span: Span,
238     },
239     /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
240     ForwardDeclaredGenericParam,
241     /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
242     ParamInTyOfConstParam(Symbol),
243     /// generic parameters must not be used inside const evaluations.
244     ///
245     /// This error is only emitted when using `min_const_generics`.
246     ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
247     /// Error E0735: generic parameters with a default cannot use `Self`
248     SelfInGenericParamDefault,
249     /// Error E0767: use of unreachable label
250     UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
251     /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
252     TraitImplMismatch {
253         name: Symbol,
254         kind: &'static str,
255         trait_path: String,
256         trait_item_span: Span,
257         code: rustc_errors::DiagnosticId,
258     },
259     /// Inline asm `sym` operand must refer to a `fn` or `static`.
260     InvalidAsmSym,
261 }
262
263 enum VisResolutionError<'a> {
264     Relative2018(Span, &'a ast::Path),
265     AncestorOnly(Span),
266     FailedToResolve(Span, String, Option<Suggestion>),
267     ExpectedFound(Span, String, Res),
268     Indeterminate(Span),
269     ModuleOnly(Span),
270 }
271
272 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
273 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
274 #[derive(Clone, Copy, Debug)]
275 pub struct Segment {
276     ident: Ident,
277     id: Option<NodeId>,
278     /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
279     /// nonsensical suggestions.
280     has_generic_args: bool,
281     /// Signals whether this `PathSegment` has lifetime arguments.
282     has_lifetime_args: bool,
283     args_span: Span,
284 }
285
286 impl Segment {
287     fn from_path(path: &Path) -> Vec<Segment> {
288         path.segments.iter().map(|s| s.into()).collect()
289     }
290
291     fn from_ident(ident: Ident) -> Segment {
292         Segment {
293             ident,
294             id: None,
295             has_generic_args: false,
296             has_lifetime_args: false,
297             args_span: DUMMY_SP,
298         }
299     }
300
301     fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
302         Segment {
303             ident,
304             id: Some(id),
305             has_generic_args: false,
306             has_lifetime_args: false,
307             args_span: DUMMY_SP,
308         }
309     }
310
311     fn names_to_string(segments: &[Segment]) -> String {
312         names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
313     }
314 }
315
316 impl<'a> From<&'a ast::PathSegment> for Segment {
317     fn from(seg: &'a ast::PathSegment) -> Segment {
318         let has_generic_args = seg.args.is_some();
319         let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
320             match args {
321                 GenericArgs::AngleBracketed(args) => {
322                     let found_lifetimes = args
323                         .args
324                         .iter()
325                         .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
326                     (args.span, found_lifetimes)
327                 }
328                 GenericArgs::Parenthesized(args) => (args.span, true),
329             }
330         } else {
331             (DUMMY_SP, false)
332         };
333         Segment {
334             ident: seg.ident,
335             id: Some(seg.id),
336             has_generic_args,
337             has_lifetime_args,
338             args_span,
339         }
340     }
341 }
342
343 /// An intermediate resolution result.
344 ///
345 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
346 /// items are visible in their whole block, while `Res`es only from the place they are defined
347 /// forward.
348 #[derive(Debug)]
349 enum LexicalScopeBinding<'a> {
350     Item(&'a NameBinding<'a>),
351     Res(Res),
352 }
353
354 impl<'a> LexicalScopeBinding<'a> {
355     fn res(self) -> Res {
356         match self {
357             LexicalScopeBinding::Item(binding) => binding.res(),
358             LexicalScopeBinding::Res(res) => res,
359         }
360     }
361 }
362
363 #[derive(Copy, Clone, Debug)]
364 enum ModuleOrUniformRoot<'a> {
365     /// Regular module.
366     Module(Module<'a>),
367
368     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
369     CrateRootAndExternPrelude,
370
371     /// Virtual module that denotes resolution in extern prelude.
372     /// Used for paths starting with `::` on 2018 edition.
373     ExternPrelude,
374
375     /// Virtual module that denotes resolution in current scope.
376     /// Used only for resolving single-segment imports. The reason it exists is that import paths
377     /// are always split into two parts, the first of which should be some kind of module.
378     CurrentScope,
379 }
380
381 impl ModuleOrUniformRoot<'_> {
382     fn same_def(lhs: Self, rhs: Self) -> bool {
383         match (lhs, rhs) {
384             (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
385                 ptr::eq(lhs, rhs)
386             }
387             (
388                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
389                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
390             )
391             | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
392             | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
393             _ => false,
394         }
395     }
396 }
397
398 #[derive(Clone, Debug)]
399 enum PathResult<'a> {
400     Module(ModuleOrUniformRoot<'a>),
401     NonModule(PartialRes),
402     Indeterminate,
403     Failed {
404         span: Span,
405         label: String,
406         suggestion: Option<Suggestion>,
407         is_error_from_last_segment: bool,
408     },
409 }
410
411 impl<'a> PathResult<'a> {
412     fn failed(
413         span: Span,
414         is_error_from_last_segment: bool,
415         finalize: bool,
416         label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
417     ) -> PathResult<'a> {
418         let (label, suggestion) =
419             if finalize { label_and_suggestion() } else { (String::new(), None) };
420         PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
421     }
422 }
423
424 #[derive(Debug)]
425 enum ModuleKind {
426     /// An anonymous module; e.g., just a block.
427     ///
428     /// ```
429     /// fn main() {
430     ///     fn f() {} // (1)
431     ///     { // This is an anonymous module
432     ///         f(); // This resolves to (2) as we are inside the block.
433     ///         fn f() {} // (2)
434     ///     }
435     ///     f(); // Resolves to (1)
436     /// }
437     /// ```
438     Block,
439     /// Any module with a name.
440     ///
441     /// This could be:
442     ///
443     /// * A normal module â€“ either `mod from_file;` or `mod from_block { }` â€“
444     ///   or the crate root (which is conceptually a top-level module).
445     ///   Note that the crate root's [name][Self::name] will be [`kw::Empty`].
446     /// * A trait or an enum (it implicitly contains associated types, methods and variant
447     ///   constructors).
448     Def(DefKind, DefId, Symbol),
449 }
450
451 impl ModuleKind {
452     /// Get name of the module.
453     pub fn name(&self) -> Option<Symbol> {
454         match self {
455             ModuleKind::Block => None,
456             ModuleKind::Def(.., name) => Some(*name),
457         }
458     }
459 }
460
461 /// A key that identifies a binding in a given `Module`.
462 ///
463 /// Multiple bindings in the same module can have the same key (in a valid
464 /// program) if all but one of them come from glob imports.
465 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
466 struct BindingKey {
467     /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
468     /// identifier.
469     ident: Ident,
470     ns: Namespace,
471     /// 0 if ident is not `_`, otherwise a value that's unique to the specific
472     /// `_` in the expanded AST that introduced this binding.
473     disambiguator: u32,
474 }
475
476 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
477
478 /// One node in the tree of modules.
479 ///
480 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
481 ///
482 /// * `mod`
483 /// * crate root (aka, top-level anonymous module)
484 /// * `enum`
485 /// * `trait`
486 /// * curly-braced block with statements
487 ///
488 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
489 pub struct ModuleData<'a> {
490     /// The direct parent module (it may not be a `mod`, however).
491     parent: Option<Module<'a>>,
492     /// What kind of module this is, because this may not be a `mod`.
493     kind: ModuleKind,
494
495     /// Mapping between names and their (possibly in-progress) resolutions in this module.
496     /// Resolutions in modules from other crates are not populated until accessed.
497     lazy_resolutions: Resolutions<'a>,
498     /// True if this is a module from other crate that needs to be populated on access.
499     populate_on_access: Cell<bool>,
500
501     /// Macro invocations that can expand into items in this module.
502     unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
503
504     /// Whether `#[no_implicit_prelude]` is active.
505     no_implicit_prelude: bool,
506
507     glob_importers: RefCell<Vec<&'a Import<'a>>>,
508     globs: RefCell<Vec<&'a Import<'a>>>,
509
510     /// Used to memoize the traits in this module for faster searches through all traits in scope.
511     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
512
513     /// Span of the module itself. Used for error reporting.
514     span: Span,
515
516     expansion: ExpnId,
517 }
518
519 type Module<'a> = &'a ModuleData<'a>;
520
521 impl<'a> ModuleData<'a> {
522     fn new(
523         parent: Option<Module<'a>>,
524         kind: ModuleKind,
525         expansion: ExpnId,
526         span: Span,
527         no_implicit_prelude: bool,
528     ) -> Self {
529         let is_foreign = match kind {
530             ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
531             ModuleKind::Block => false,
532         };
533         ModuleData {
534             parent,
535             kind,
536             lazy_resolutions: Default::default(),
537             populate_on_access: Cell::new(is_foreign),
538             unexpanded_invocations: Default::default(),
539             no_implicit_prelude,
540             glob_importers: RefCell::new(Vec::new()),
541             globs: RefCell::new(Vec::new()),
542             traits: RefCell::new(None),
543             span,
544             expansion,
545         }
546     }
547
548     fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
549     where
550         R: AsMut<Resolver<'a>>,
551         F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
552     {
553         for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
554             if let Some(binding) = name_resolution.borrow().binding {
555                 f(resolver, key.ident, key.ns, binding);
556             }
557         }
558     }
559
560     /// This modifies `self` in place. The traits will be stored in `self.traits`.
561     fn ensure_traits<R>(&'a self, resolver: &mut R)
562     where
563         R: AsMut<Resolver<'a>>,
564     {
565         let mut traits = self.traits.borrow_mut();
566         if traits.is_none() {
567             let mut collected_traits = Vec::new();
568             self.for_each_child(resolver, |_, name, ns, binding| {
569                 if ns != TypeNS {
570                     return;
571                 }
572                 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
573                     collected_traits.push((name, binding))
574                 }
575             });
576             *traits = Some(collected_traits.into_boxed_slice());
577         }
578     }
579
580     fn res(&self) -> Option<Res> {
581         match self.kind {
582             ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
583             _ => None,
584         }
585     }
586
587     // Public for rustdoc.
588     pub fn def_id(&self) -> DefId {
589         self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
590     }
591
592     fn opt_def_id(&self) -> Option<DefId> {
593         match self.kind {
594             ModuleKind::Def(_, def_id, _) => Some(def_id),
595             _ => None,
596         }
597     }
598
599     // `self` resolves to the first module ancestor that `is_normal`.
600     fn is_normal(&self) -> bool {
601         matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
602     }
603
604     fn is_trait(&self) -> bool {
605         matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
606     }
607
608     fn nearest_item_scope(&'a self) -> Module<'a> {
609         match self.kind {
610             ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
611                 self.parent.expect("enum or trait module without a parent")
612             }
613             _ => self,
614         }
615     }
616
617     /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
618     /// This may be the crate root.
619     fn nearest_parent_mod(&self) -> DefId {
620         match self.kind {
621             ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
622             _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
623         }
624     }
625
626     fn is_ancestor_of(&self, mut other: &Self) -> bool {
627         while !ptr::eq(self, other) {
628             if let Some(parent) = other.parent {
629                 other = parent;
630             } else {
631                 return false;
632             }
633         }
634         true
635     }
636 }
637
638 impl<'a> fmt::Debug for ModuleData<'a> {
639     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640         write!(f, "{:?}", self.res())
641     }
642 }
643
644 /// Records a possibly-private value, type, or module definition.
645 #[derive(Clone, Debug)]
646 pub struct NameBinding<'a> {
647     kind: NameBindingKind<'a>,
648     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
649     expansion: LocalExpnId,
650     span: Span,
651     vis: ty::Visibility,
652 }
653
654 pub trait ToNameBinding<'a> {
655     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
656 }
657
658 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
659     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
660         self
661     }
662 }
663
664 #[derive(Clone, Debug)]
665 enum NameBindingKind<'a> {
666     Res(Res, /* is_macro_export */ bool),
667     Module(Module<'a>),
668     Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
669 }
670
671 impl<'a> NameBindingKind<'a> {
672     /// Is this a name binding of an import?
673     fn is_import(&self) -> bool {
674         matches!(*self, NameBindingKind::Import { .. })
675     }
676 }
677
678 struct PrivacyError<'a> {
679     ident: Ident,
680     binding: &'a NameBinding<'a>,
681     dedup_span: Span,
682 }
683
684 struct UseError<'a> {
685     err: DiagnosticBuilder<'a, ErrorGuaranteed>,
686     /// Candidates which user could `use` to access the missing type.
687     candidates: Vec<ImportSuggestion>,
688     /// The `DefId` of the module to place the use-statements in.
689     def_id: DefId,
690     /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
691     instead: bool,
692     /// Extra free-form suggestion.
693     suggestion: Option<(Span, &'static str, String, Applicability)>,
694     /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
695     /// the user to import the item directly.
696     path: Vec<Segment>,
697 }
698
699 #[derive(Clone, Copy, PartialEq, Debug)]
700 enum AmbiguityKind {
701     Import,
702     BuiltinAttr,
703     DeriveHelper,
704     MacroRulesVsModularized,
705     GlobVsOuter,
706     GlobVsGlob,
707     GlobVsExpanded,
708     MoreExpandedVsOuter,
709 }
710
711 impl AmbiguityKind {
712     fn descr(self) -> &'static str {
713         match self {
714             AmbiguityKind::Import => "multiple potential import sources",
715             AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
716             AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
717             AmbiguityKind::MacroRulesVsModularized => {
718                 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
719             }
720             AmbiguityKind::GlobVsOuter => {
721                 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
722             }
723             AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
724             AmbiguityKind::GlobVsExpanded => {
725                 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
726             }
727             AmbiguityKind::MoreExpandedVsOuter => {
728                 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
729             }
730         }
731     }
732 }
733
734 /// Miscellaneous bits of metadata for better ambiguity error reporting.
735 #[derive(Clone, Copy, PartialEq)]
736 enum AmbiguityErrorMisc {
737     SuggestCrate,
738     SuggestSelf,
739     FromPrelude,
740     None,
741 }
742
743 struct AmbiguityError<'a> {
744     kind: AmbiguityKind,
745     ident: Ident,
746     b1: &'a NameBinding<'a>,
747     b2: &'a NameBinding<'a>,
748     misc1: AmbiguityErrorMisc,
749     misc2: AmbiguityErrorMisc,
750 }
751
752 impl<'a> NameBinding<'a> {
753     fn module(&self) -> Option<Module<'a>> {
754         match self.kind {
755             NameBindingKind::Module(module) => Some(module),
756             NameBindingKind::Import { binding, .. } => binding.module(),
757             _ => None,
758         }
759     }
760
761     fn res(&self) -> Res {
762         match self.kind {
763             NameBindingKind::Res(res, _) => res,
764             NameBindingKind::Module(module) => module.res().unwrap(),
765             NameBindingKind::Import { binding, .. } => binding.res(),
766         }
767     }
768
769     fn is_ambiguity(&self) -> bool {
770         self.ambiguity.is_some()
771             || match self.kind {
772                 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
773                 _ => false,
774             }
775     }
776
777     fn is_possibly_imported_variant(&self) -> bool {
778         match self.kind {
779             NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
780             NameBindingKind::Res(
781                 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
782                 _,
783             ) => true,
784             NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
785         }
786     }
787
788     fn is_extern_crate(&self) -> bool {
789         match self.kind {
790             NameBindingKind::Import {
791                 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
792                 ..
793             } => true,
794             NameBindingKind::Module(&ModuleData {
795                 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
796                 ..
797             }) => def_id.is_crate_root(),
798             _ => false,
799         }
800     }
801
802     fn is_import(&self) -> bool {
803         matches!(self.kind, NameBindingKind::Import { .. })
804     }
805
806     fn is_glob_import(&self) -> bool {
807         match self.kind {
808             NameBindingKind::Import { import, .. } => import.is_glob(),
809             _ => false,
810         }
811     }
812
813     fn is_importable(&self) -> bool {
814         !matches!(
815             self.res(),
816             Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
817         )
818     }
819
820     fn macro_kind(&self) -> Option<MacroKind> {
821         self.res().macro_kind()
822     }
823
824     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
825     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
826     // Then this function returns `true` if `self` may emerge from a macro *after* that
827     // in some later round and screw up our previously found resolution.
828     // See more detailed explanation in
829     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
830     fn may_appear_after(
831         &self,
832         invoc_parent_expansion: LocalExpnId,
833         binding: &NameBinding<'_>,
834     ) -> bool {
835         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
836         // Expansions are partially ordered, so "may appear after" is an inversion of
837         // "certainly appears before or simultaneously" and includes unordered cases.
838         let self_parent_expansion = self.expansion;
839         let other_parent_expansion = binding.expansion;
840         let certainly_before_other_or_simultaneously =
841             other_parent_expansion.is_descendant_of(self_parent_expansion);
842         let certainly_before_invoc_or_simultaneously =
843             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
844         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
845     }
846 }
847
848 #[derive(Debug, Default, Clone)]
849 pub struct ExternPreludeEntry<'a> {
850     extern_crate_item: Option<&'a NameBinding<'a>>,
851     pub introduced_by_item: bool,
852 }
853
854 /// Used for better errors for E0773
855 enum BuiltinMacroState {
856     NotYetSeen(SyntaxExtensionKind),
857     AlreadySeen(Span),
858 }
859
860 struct DeriveData {
861     resolutions: DeriveResolutions,
862     helper_attrs: Vec<(usize, Ident)>,
863     has_derive_copy: bool,
864 }
865
866 #[derive(Clone)]
867 struct MacroData {
868     ext: Lrc<SyntaxExtension>,
869     macro_rules: bool,
870 }
871
872 /// The main resolver class.
873 ///
874 /// This is the visitor that walks the whole crate.
875 pub struct Resolver<'a> {
876     session: &'a Session,
877
878     definitions: Definitions,
879     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
880     expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
881     /// Reference span for definitions.
882     source_span: IndexVec<LocalDefId, Span>,
883
884     graph_root: Module<'a>,
885
886     prelude: Option<Module<'a>>,
887     extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
888
889     /// N.B., this is used only for better diagnostics, not name resolution itself.
890     has_self: FxHashSet<DefId>,
891
892     /// Names of fields of an item `DefId` accessible with dot syntax.
893     /// Used for hints during error reporting.
894     field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
895
896     /// All imports known to succeed or fail.
897     determined_imports: Vec<&'a Import<'a>>,
898
899     /// All non-determined imports.
900     indeterminate_imports: Vec<&'a Import<'a>>,
901
902     // Spans for local variables found during pattern resolution.
903     // Used for suggestions during error reporting.
904     pat_span_map: NodeMap<Span>,
905
906     /// Resolutions for nodes that have a single resolution.
907     partial_res_map: NodeMap<PartialRes>,
908     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
909     import_res_map: NodeMap<PerNS<Option<Res>>>,
910     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
911     label_res_map: NodeMap<NodeId>,
912     /// Resolutions for lifetimes.
913     lifetimes_res_map: NodeMap<LifetimeRes>,
914     /// Lifetime parameters that lowering will have to introduce.
915     extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
916
917     /// `CrateNum` resolutions of `extern crate` items.
918     extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
919     reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
920     trait_map: NodeMap<Vec<TraitCandidate>>,
921
922     /// A map from nodes to anonymous modules.
923     /// Anonymous modules are pseudo-modules that are implicitly created around items
924     /// contained within blocks.
925     ///
926     /// For example, if we have this:
927     ///
928     ///  fn f() {
929     ///      fn g() {
930     ///          ...
931     ///      }
932     ///  }
933     ///
934     /// There will be an anonymous module created around `g` with the ID of the
935     /// entry block for `f`.
936     block_map: NodeMap<Module<'a>>,
937     /// A fake module that contains no definition and no prelude. Used so that
938     /// some AST passes can generate identifiers that only resolve to local or
939     /// language items.
940     empty_module: Module<'a>,
941     module_map: FxHashMap<DefId, Module<'a>>,
942     binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
943     underscore_disambiguator: u32,
944
945     /// Maps glob imports to the names of items actually imported.
946     glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
947     /// Visibilities in "lowered" form, for all entities that have them.
948     visibilities: FxHashMap<LocalDefId, ty::Visibility>,
949     has_pub_restricted: bool,
950     used_imports: FxHashSet<NodeId>,
951     maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
952     maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
953
954     /// Privacy errors are delayed until the end in order to deduplicate them.
955     privacy_errors: Vec<PrivacyError<'a>>,
956     /// Ambiguity errors are delayed for deduplication.
957     ambiguity_errors: Vec<AmbiguityError<'a>>,
958     /// `use` injections are delayed for better placement and deduplication.
959     use_injections: Vec<UseError<'a>>,
960     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
961     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
962
963     arenas: &'a ResolverArenas<'a>,
964     dummy_binding: &'a NameBinding<'a>,
965
966     crate_loader: CrateLoader<'a>,
967     macro_names: FxHashSet<Ident>,
968     builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
969     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
970     /// the surface (`macro` items in libcore), but are actually attributes or derives.
971     builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
972     registered_tools: RegisteredTools,
973     macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
974     macro_map: FxHashMap<DefId, MacroData>,
975     dummy_ext_bang: Lrc<SyntaxExtension>,
976     dummy_ext_derive: Lrc<SyntaxExtension>,
977     non_macro_attr: Lrc<SyntaxExtension>,
978     local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
979     ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
980     unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
981     unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
982     proc_macro_stubs: FxHashSet<LocalDefId>,
983     /// Traces collected during macro resolution and validated when it's complete.
984     single_segment_macro_resolutions:
985         Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
986     multi_segment_macro_resolutions:
987         Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
988     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
989     /// `derive(Copy)` marks items they are applied to so they are treated specially later.
990     /// Derive macros cannot modify the item themselves and have to store the markers in the global
991     /// context, so they attach the markers to derive container IDs using this resolver table.
992     containers_deriving_copy: FxHashSet<LocalExpnId>,
993     /// Parent scopes in which the macros were invoked.
994     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
995     invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
996     /// `macro_rules` scopes *produced* by expanding the macro invocations,
997     /// include all the `macro_rules` items and other invocations generated by them.
998     output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
999     /// `macro_rules` scopes produced by `macro_rules` item definitions.
1000     macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
1001     /// Helper attributes that are in scope for the given expansion.
1002     helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
1003     /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1004     /// with the given `ExpnId`.
1005     derive_data: FxHashMap<LocalExpnId, DeriveData>,
1006
1007     /// Avoid duplicated errors for "name already defined".
1008     name_already_seen: FxHashMap<Symbol, Span>,
1009
1010     potentially_unused_imports: Vec<&'a Import<'a>>,
1011
1012     /// Table for mapping struct IDs into struct constructor IDs,
1013     /// it's not used during normal resolution, only for better error reporting.
1014     /// Also includes of list of each fields visibility
1015     struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>,
1016
1017     /// Features enabled for this crate.
1018     active_features: FxHashSet<Symbol>,
1019
1020     lint_buffer: LintBuffer,
1021
1022     next_node_id: NodeId,
1023
1024     node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1025     def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1026
1027     /// Indices of unnamed struct or variant fields with unresolved attributes.
1028     placeholder_field_indices: FxHashMap<NodeId, usize>,
1029     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1030     /// we know what parent node that fragment should be attached to thanks to this table,
1031     /// and how the `impl Trait` fragments were introduced.
1032     invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1033
1034     /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1035     /// FIXME: Replace with a more general AST map (together with some other fields).
1036     trait_impl_items: FxHashSet<LocalDefId>,
1037
1038     legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1039     /// Amount of lifetime parameters for each item in the crate.
1040     item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1041
1042     main_def: Option<MainDefinition>,
1043     trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1044     /// A list of proc macro LocalDefIds, written out in the order in which
1045     /// they are declared in the static array generated by proc_macro_harness.
1046     proc_macros: Vec<NodeId>,
1047     confused_type_with_std_module: FxHashMap<Span, Span>,
1048
1049     access_levels: AccessLevels,
1050 }
1051
1052 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1053 #[derive(Default)]
1054 pub struct ResolverArenas<'a> {
1055     modules: TypedArena<ModuleData<'a>>,
1056     local_modules: RefCell<Vec<Module<'a>>>,
1057     imports: TypedArena<Import<'a>>,
1058     name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1059     ast_paths: TypedArena<ast::Path>,
1060     dropless: DroplessArena,
1061 }
1062
1063 impl<'a> ResolverArenas<'a> {
1064     fn new_module(
1065         &'a self,
1066         parent: Option<Module<'a>>,
1067         kind: ModuleKind,
1068         expn_id: ExpnId,
1069         span: Span,
1070         no_implicit_prelude: bool,
1071         module_map: &mut FxHashMap<DefId, Module<'a>>,
1072     ) -> Module<'a> {
1073         let module =
1074             self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1075         let def_id = module.opt_def_id();
1076         if def_id.map_or(true, |def_id| def_id.is_local()) {
1077             self.local_modules.borrow_mut().push(module);
1078         }
1079         if let Some(def_id) = def_id {
1080             module_map.insert(def_id, module);
1081         }
1082         module
1083     }
1084     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1085         self.local_modules.borrow()
1086     }
1087     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1088         self.dropless.alloc(name_binding)
1089     }
1090     fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1091         self.imports.alloc(import)
1092     }
1093     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1094         self.name_resolutions.alloc(Default::default())
1095     }
1096     fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1097         Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1098     }
1099     fn alloc_macro_rules_binding(
1100         &'a self,
1101         binding: MacroRulesBinding<'a>,
1102     ) -> &'a MacroRulesBinding<'a> {
1103         self.dropless.alloc(binding)
1104     }
1105     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1106         self.ast_paths.alloc_from_iter(paths.iter().cloned())
1107     }
1108     fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1109         self.dropless.alloc_from_iter(spans)
1110     }
1111 }
1112
1113 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1114     fn as_mut(&mut self) -> &mut Resolver<'a> {
1115         self
1116     }
1117 }
1118
1119 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1120     #[inline]
1121     fn opt_parent(self, id: DefId) -> Option<DefId> {
1122         match id.as_local() {
1123             Some(id) => self.definitions.def_key(id).parent,
1124             None => self.cstore().def_key(id).parent,
1125         }
1126         .map(|index| DefId { index, ..id })
1127     }
1128 }
1129
1130 impl Resolver<'_> {
1131     fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1132         self.node_id_to_def_id.get(&node).copied()
1133     }
1134
1135     pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1136         self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1137     }
1138
1139     /// Adds a definition with a parent definition.
1140     fn create_def(
1141         &mut self,
1142         parent: LocalDefId,
1143         node_id: ast::NodeId,
1144         data: DefPathData,
1145         expn_id: ExpnId,
1146         span: Span,
1147     ) -> LocalDefId {
1148         assert!(
1149             !self.node_id_to_def_id.contains_key(&node_id),
1150             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1151             node_id,
1152             data,
1153             self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1154         );
1155
1156         let def_id = self.definitions.create_def(parent, data);
1157
1158         // Create the definition.
1159         if expn_id != ExpnId::root() {
1160             self.expn_that_defined.insert(def_id, expn_id);
1161         }
1162
1163         // A relative span's parent must be an absolute span.
1164         debug_assert_eq!(span.data_untracked().parent, None);
1165         let _id = self.source_span.push(span);
1166         debug_assert_eq!(_id, def_id);
1167
1168         // Some things for which we allocate `LocalDefId`s don't correspond to
1169         // anything in the AST, so they don't have a `NodeId`. For these cases
1170         // we don't need a mapping from `NodeId` to `LocalDefId`.
1171         if node_id != ast::DUMMY_NODE_ID {
1172             debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1173             self.node_id_to_def_id.insert(node_id, def_id);
1174         }
1175         assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1176
1177         def_id
1178     }
1179
1180     fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1181         if let Some(def_id) = def_id.as_local() {
1182             self.item_generics_num_lifetimes[&def_id]
1183         } else {
1184             self.cstore().item_generics_num_lifetimes(def_id, self.session)
1185         }
1186     }
1187 }
1188
1189 impl<'a> Resolver<'a> {
1190     pub fn new(
1191         session: &'a Session,
1192         krate: &Crate,
1193         crate_name: &str,
1194         metadata_loader: Box<MetadataLoaderDyn>,
1195         arenas: &'a ResolverArenas<'a>,
1196     ) -> Resolver<'a> {
1197         let root_def_id = CRATE_DEF_ID.to_def_id();
1198         let mut module_map = FxHashMap::default();
1199         let graph_root = arenas.new_module(
1200             None,
1201             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1202             ExpnId::root(),
1203             krate.spans.inner_span,
1204             session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1205             &mut module_map,
1206         );
1207         let empty_module = arenas.new_module(
1208             None,
1209             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1210             ExpnId::root(),
1211             DUMMY_SP,
1212             true,
1213             &mut FxHashMap::default(),
1214         );
1215
1216         let definitions = Definitions::new(session.local_stable_crate_id());
1217
1218         let mut visibilities = FxHashMap::default();
1219         visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1220
1221         let mut def_id_to_node_id = IndexVec::default();
1222         assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1223         let mut node_id_to_def_id = FxHashMap::default();
1224         node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1225
1226         let mut invocation_parents = FxHashMap::default();
1227         invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1228
1229         let mut source_span = IndexVec::default();
1230         let _id = source_span.push(krate.spans.inner_span);
1231         debug_assert_eq!(_id, CRATE_DEF_ID);
1232
1233         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1234             .opts
1235             .externs
1236             .iter()
1237             .filter(|(_, entry)| entry.add_prelude)
1238             .map(|(name, _)| (Ident::from_str(name), Default::default()))
1239             .collect();
1240
1241         if !session.contains_name(&krate.attrs, sym::no_core) {
1242             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1243             if !session.contains_name(&krate.attrs, sym::no_std) {
1244                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1245             }
1246         }
1247
1248         let registered_tools = macros::registered_tools(session, &krate.attrs);
1249
1250         let features = session.features_untracked();
1251
1252         let mut resolver = Resolver {
1253             session,
1254
1255             definitions,
1256             expn_that_defined: Default::default(),
1257             source_span,
1258
1259             // The outermost module has def ID 0; this is not reflected in the
1260             // AST.
1261             graph_root,
1262             prelude: None,
1263             extern_prelude,
1264
1265             has_self: FxHashSet::default(),
1266             field_names: FxHashMap::default(),
1267
1268             determined_imports: Vec::new(),
1269             indeterminate_imports: Vec::new(),
1270
1271             pat_span_map: Default::default(),
1272             partial_res_map: Default::default(),
1273             import_res_map: Default::default(),
1274             label_res_map: Default::default(),
1275             lifetimes_res_map: Default::default(),
1276             extra_lifetime_params_map: Default::default(),
1277             extern_crate_map: Default::default(),
1278             reexport_map: FxHashMap::default(),
1279             trait_map: NodeMap::default(),
1280             underscore_disambiguator: 0,
1281             empty_module,
1282             module_map,
1283             block_map: Default::default(),
1284             binding_parent_modules: FxHashMap::default(),
1285             ast_transform_scopes: FxHashMap::default(),
1286
1287             glob_map: Default::default(),
1288             visibilities,
1289             has_pub_restricted: false,
1290             used_imports: FxHashSet::default(),
1291             maybe_unused_trait_imports: Default::default(),
1292             maybe_unused_extern_crates: Vec::new(),
1293
1294             privacy_errors: Vec::new(),
1295             ambiguity_errors: Vec::new(),
1296             use_injections: Vec::new(),
1297             macro_expanded_macro_export_errors: BTreeSet::new(),
1298
1299             arenas,
1300             dummy_binding: arenas.alloc_name_binding(NameBinding {
1301                 kind: NameBindingKind::Res(Res::Err, false),
1302                 ambiguity: None,
1303                 expansion: LocalExpnId::ROOT,
1304                 span: DUMMY_SP,
1305                 vis: ty::Visibility::Public,
1306             }),
1307
1308             crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1309             macro_names: FxHashSet::default(),
1310             builtin_macros: Default::default(),
1311             builtin_macro_kinds: Default::default(),
1312             registered_tools,
1313             macro_use_prelude: FxHashMap::default(),
1314             macro_map: FxHashMap::default(),
1315             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1316             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1317             non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1318             invocation_parent_scopes: Default::default(),
1319             output_macro_rules_scopes: Default::default(),
1320             macro_rules_scopes: Default::default(),
1321             helper_attrs: Default::default(),
1322             derive_data: Default::default(),
1323             local_macro_def_scopes: FxHashMap::default(),
1324             name_already_seen: FxHashMap::default(),
1325             potentially_unused_imports: Vec::new(),
1326             struct_constructors: Default::default(),
1327             unused_macros: Default::default(),
1328             unused_macro_rules: Default::default(),
1329             proc_macro_stubs: Default::default(),
1330             single_segment_macro_resolutions: Default::default(),
1331             multi_segment_macro_resolutions: Default::default(),
1332             builtin_attrs: Default::default(),
1333             containers_deriving_copy: Default::default(),
1334             active_features: features
1335                 .declared_lib_features
1336                 .iter()
1337                 .map(|(feat, ..)| *feat)
1338                 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1339                 .collect(),
1340             lint_buffer: LintBuffer::default(),
1341             next_node_id: CRATE_NODE_ID,
1342             node_id_to_def_id,
1343             def_id_to_node_id,
1344             placeholder_field_indices: Default::default(),
1345             invocation_parents,
1346             trait_impl_items: Default::default(),
1347             legacy_const_generic_args: Default::default(),
1348             item_generics_num_lifetimes: Default::default(),
1349             main_def: Default::default(),
1350             trait_impls: Default::default(),
1351             proc_macros: Default::default(),
1352             confused_type_with_std_module: Default::default(),
1353             access_levels: Default::default(),
1354         };
1355
1356         let root_parent_scope = ParentScope::module(graph_root, &resolver);
1357         resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1358
1359         resolver
1360     }
1361
1362     fn new_module(
1363         &mut self,
1364         parent: Option<Module<'a>>,
1365         kind: ModuleKind,
1366         expn_id: ExpnId,
1367         span: Span,
1368         no_implicit_prelude: bool,
1369     ) -> Module<'a> {
1370         let module_map = &mut self.module_map;
1371         self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1372     }
1373
1374     pub fn next_node_id(&mut self) -> NodeId {
1375         let start = self.next_node_id;
1376         let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1377         self.next_node_id = ast::NodeId::from_u32(next);
1378         start
1379     }
1380
1381     pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1382         let start = self.next_node_id;
1383         let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1384         self.next_node_id = ast::NodeId::from_usize(end);
1385         start..self.next_node_id
1386     }
1387
1388     pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1389         &mut self.lint_buffer
1390     }
1391
1392     pub fn arenas() -> ResolverArenas<'a> {
1393         Default::default()
1394     }
1395
1396     pub fn into_outputs(
1397         self,
1398     ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1399         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1400         let definitions = self.definitions;
1401         let cstore = Box::new(self.crate_loader.into_cstore());
1402         let source_span = self.source_span;
1403         let expn_that_defined = self.expn_that_defined;
1404         let visibilities = self.visibilities;
1405         let has_pub_restricted = self.has_pub_restricted;
1406         let extern_crate_map = self.extern_crate_map;
1407         let reexport_map = self.reexport_map;
1408         let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1409         let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1410         let glob_map = self.glob_map;
1411         let main_def = self.main_def;
1412         let confused_type_with_std_module = self.confused_type_with_std_module;
1413         let access_levels = self.access_levels;
1414         let resolutions = ResolverOutputs {
1415             source_span,
1416             expn_that_defined,
1417             visibilities,
1418             has_pub_restricted,
1419             access_levels,
1420             extern_crate_map,
1421             reexport_map,
1422             glob_map,
1423             maybe_unused_trait_imports,
1424             maybe_unused_extern_crates,
1425             extern_prelude: self
1426                 .extern_prelude
1427                 .iter()
1428                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1429                 .collect(),
1430             main_def,
1431             trait_impls: self.trait_impls,
1432             proc_macros,
1433             confused_type_with_std_module,
1434             registered_tools: self.registered_tools,
1435         };
1436         let resolutions_lowering = ty::ResolverAstLowering {
1437             legacy_const_generic_args: self.legacy_const_generic_args,
1438             partial_res_map: self.partial_res_map,
1439             import_res_map: self.import_res_map,
1440             label_res_map: self.label_res_map,
1441             lifetimes_res_map: self.lifetimes_res_map,
1442             extra_lifetime_params_map: self.extra_lifetime_params_map,
1443             next_node_id: self.next_node_id,
1444             node_id_to_def_id: self.node_id_to_def_id,
1445             def_id_to_node_id: self.def_id_to_node_id,
1446             trait_map: self.trait_map,
1447             builtin_macro_kinds: self.builtin_macro_kinds,
1448         };
1449         (definitions, cstore, resolutions, resolutions_lowering)
1450     }
1451
1452     pub fn clone_outputs(
1453         &self,
1454     ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1455         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1456         let definitions = self.definitions.clone();
1457         let cstore = Box::new(self.cstore().clone());
1458         let resolutions = ResolverOutputs {
1459             source_span: self.source_span.clone(),
1460             expn_that_defined: self.expn_that_defined.clone(),
1461             visibilities: self.visibilities.clone(),
1462             has_pub_restricted: self.has_pub_restricted,
1463             extern_crate_map: self.extern_crate_map.clone(),
1464             reexport_map: self.reexport_map.clone(),
1465             glob_map: self.glob_map.clone(),
1466             maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1467             maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1468             extern_prelude: self
1469                 .extern_prelude
1470                 .iter()
1471                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1472                 .collect(),
1473             main_def: self.main_def,
1474             trait_impls: self.trait_impls.clone(),
1475             proc_macros,
1476             confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1477             registered_tools: self.registered_tools.clone(),
1478             access_levels: self.access_levels.clone(),
1479         };
1480         let resolutions_lowering = ty::ResolverAstLowering {
1481             legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1482             partial_res_map: self.partial_res_map.clone(),
1483             import_res_map: self.import_res_map.clone(),
1484             label_res_map: self.label_res_map.clone(),
1485             lifetimes_res_map: self.lifetimes_res_map.clone(),
1486             extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1487             next_node_id: self.next_node_id.clone(),
1488             node_id_to_def_id: self.node_id_to_def_id.clone(),
1489             def_id_to_node_id: self.def_id_to_node_id.clone(),
1490             trait_map: self.trait_map.clone(),
1491             builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1492         };
1493         (definitions, cstore, resolutions, resolutions_lowering)
1494     }
1495
1496     fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1497         StableHashingContext::new(
1498             self.session,
1499             &self.definitions,
1500             self.crate_loader.cstore(),
1501             &self.source_span,
1502         )
1503     }
1504
1505     pub fn cstore(&self) -> &CStore {
1506         self.crate_loader.cstore()
1507     }
1508
1509     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1510         match macro_kind {
1511             MacroKind::Bang => self.dummy_ext_bang.clone(),
1512             MacroKind::Derive => self.dummy_ext_derive.clone(),
1513             MacroKind::Attr => self.non_macro_attr.clone(),
1514         }
1515     }
1516
1517     /// Runs the function on each namespace.
1518     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1519         f(self, TypeNS);
1520         f(self, ValueNS);
1521         f(self, MacroNS);
1522     }
1523
1524     fn is_builtin_macro(&mut self, res: Res) -> bool {
1525         self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1526     }
1527
1528     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1529         loop {
1530             match ctxt.outer_expn_data().macro_def_id {
1531                 Some(def_id) => return def_id,
1532                 None => ctxt.remove_mark(),
1533             };
1534         }
1535     }
1536
1537     /// Entry point to crate resolution.
1538     pub fn resolve_crate(&mut self, krate: &Crate) {
1539         self.session.time("resolve_crate", || {
1540             self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1541             self.session.time("resolve_access_levels", || {
1542                 AccessLevelsVisitor::compute_access_levels(self, krate)
1543             });
1544             self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1545             self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1546             self.session.time("resolve_main", || self.resolve_main());
1547             self.session.time("resolve_check_unused", || self.check_unused(krate));
1548             self.session.time("resolve_report_errors", || self.report_errors(krate));
1549             self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1550         });
1551     }
1552
1553     pub fn traits_in_scope(
1554         &mut self,
1555         current_trait: Option<Module<'a>>,
1556         parent_scope: &ParentScope<'a>,
1557         ctxt: SyntaxContext,
1558         assoc_item: Option<(Symbol, Namespace)>,
1559     ) -> Vec<TraitCandidate> {
1560         let mut found_traits = Vec::new();
1561
1562         if let Some(module) = current_trait {
1563             if self.trait_may_have_item(Some(module), assoc_item) {
1564                 let def_id = module.def_id();
1565                 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1566             }
1567         }
1568
1569         self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1570             match scope {
1571                 Scope::Module(module, _) => {
1572                     this.traits_in_module(module, assoc_item, &mut found_traits);
1573                 }
1574                 Scope::StdLibPrelude => {
1575                     if let Some(module) = this.prelude {
1576                         this.traits_in_module(module, assoc_item, &mut found_traits);
1577                     }
1578                 }
1579                 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1580                 _ => unreachable!(),
1581             }
1582             None::<()>
1583         });
1584
1585         found_traits
1586     }
1587
1588     fn traits_in_module(
1589         &mut self,
1590         module: Module<'a>,
1591         assoc_item: Option<(Symbol, Namespace)>,
1592         found_traits: &mut Vec<TraitCandidate>,
1593     ) {
1594         module.ensure_traits(self);
1595         let traits = module.traits.borrow();
1596         for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1597             if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1598                 let def_id = trait_binding.res().def_id();
1599                 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1600                 found_traits.push(TraitCandidate { def_id, import_ids });
1601             }
1602         }
1603     }
1604
1605     // List of traits in scope is pruned on best effort basis. We reject traits not having an
1606     // associated item with the given name and namespace (if specified). This is a conservative
1607     // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1608     // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1609     // associated items.
1610     fn trait_may_have_item(
1611         &mut self,
1612         trait_module: Option<Module<'a>>,
1613         assoc_item: Option<(Symbol, Namespace)>,
1614     ) -> bool {
1615         match (trait_module, assoc_item) {
1616             (Some(trait_module), Some((name, ns))) => {
1617                 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1618                     let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1619                     assoc_ns == ns && assoc_ident.name == name
1620                 })
1621             }
1622             _ => true,
1623         }
1624     }
1625
1626     fn find_transitive_imports(
1627         &mut self,
1628         mut kind: &NameBindingKind<'_>,
1629         trait_name: Ident,
1630     ) -> SmallVec<[LocalDefId; 1]> {
1631         let mut import_ids = smallvec![];
1632         while let NameBindingKind::Import { import, binding, .. } = kind {
1633             let id = self.local_def_id(import.id);
1634             self.maybe_unused_trait_imports.insert(id);
1635             self.add_to_glob_map(&import, trait_name);
1636             import_ids.push(id);
1637             kind = &binding.kind;
1638         }
1639         import_ids
1640     }
1641
1642     fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1643         let ident = ident.normalize_to_macros_2_0();
1644         let disambiguator = if ident.name == kw::Underscore {
1645             self.underscore_disambiguator += 1;
1646             self.underscore_disambiguator
1647         } else {
1648             0
1649         };
1650         BindingKey { ident, ns, disambiguator }
1651     }
1652
1653     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1654         if module.populate_on_access.get() {
1655             module.populate_on_access.set(false);
1656             self.build_reduced_graph_external(module);
1657         }
1658         &module.lazy_resolutions
1659     }
1660
1661     fn resolution(
1662         &mut self,
1663         module: Module<'a>,
1664         key: BindingKey,
1665     ) -> &'a RefCell<NameResolution<'a>> {
1666         *self
1667             .resolutions(module)
1668             .borrow_mut()
1669             .entry(key)
1670             .or_insert_with(|| self.arenas.alloc_name_resolution())
1671     }
1672
1673     fn record_use(
1674         &mut self,
1675         ident: Ident,
1676         used_binding: &'a NameBinding<'a>,
1677         is_lexical_scope: bool,
1678     ) {
1679         if let Some((b2, kind)) = used_binding.ambiguity {
1680             self.ambiguity_errors.push(AmbiguityError {
1681                 kind,
1682                 ident,
1683                 b1: used_binding,
1684                 b2,
1685                 misc1: AmbiguityErrorMisc::None,
1686                 misc2: AmbiguityErrorMisc::None,
1687             });
1688         }
1689         if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1690             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1691             // but not introduce it, as used if they are accessed from lexical scope.
1692             if is_lexical_scope {
1693                 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1694                     if let Some(crate_item) = entry.extern_crate_item {
1695                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1696                             return;
1697                         }
1698                     }
1699                 }
1700             }
1701             used.set(true);
1702             import.used.set(true);
1703             self.used_imports.insert(import.id);
1704             self.add_to_glob_map(&import, ident);
1705             self.record_use(ident, binding, false);
1706         }
1707     }
1708
1709     #[inline]
1710     fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1711         if import.is_glob() {
1712             let def_id = self.local_def_id(import.id);
1713             self.glob_map.entry(def_id).or_default().insert(ident.name);
1714         }
1715     }
1716
1717     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1718         debug!("resolve_crate_root({:?})", ident);
1719         let mut ctxt = ident.span.ctxt();
1720         let mark = if ident.name == kw::DollarCrate {
1721             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1722             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1723             // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1724             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1725             // definitions actually produced by `macro` and `macro` definitions produced by
1726             // `macro_rules!`, but at least such configurations are not stable yet.
1727             ctxt = ctxt.normalize_to_macro_rules();
1728             debug!(
1729                 "resolve_crate_root: marks={:?}",
1730                 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1731             );
1732             let mut iter = ctxt.marks().into_iter().rev().peekable();
1733             let mut result = None;
1734             // Find the last opaque mark from the end if it exists.
1735             while let Some(&(mark, transparency)) = iter.peek() {
1736                 if transparency == Transparency::Opaque {
1737                     result = Some(mark);
1738                     iter.next();
1739                 } else {
1740                     break;
1741                 }
1742             }
1743             debug!(
1744                 "resolve_crate_root: found opaque mark {:?} {:?}",
1745                 result,
1746                 result.map(|r| r.expn_data())
1747             );
1748             // Then find the last semi-transparent mark from the end if it exists.
1749             for (mark, transparency) in iter {
1750                 if transparency == Transparency::SemiTransparent {
1751                     result = Some(mark);
1752                 } else {
1753                     break;
1754                 }
1755             }
1756             debug!(
1757                 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1758                 result,
1759                 result.map(|r| r.expn_data())
1760             );
1761             result
1762         } else {
1763             debug!("resolve_crate_root: not DollarCrate");
1764             ctxt = ctxt.normalize_to_macros_2_0();
1765             ctxt.adjust(ExpnId::root())
1766         };
1767         let module = match mark {
1768             Some(def) => self.expn_def_scope(def),
1769             None => {
1770                 debug!(
1771                     "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1772                     ident, ident.span
1773                 );
1774                 return self.graph_root;
1775             }
1776         };
1777         let module = self.expect_module(
1778             module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1779         );
1780         debug!(
1781             "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1782             ident,
1783             module,
1784             module.kind.name(),
1785             ident.span
1786         );
1787         module
1788     }
1789
1790     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1791         let mut module = self.expect_module(module.nearest_parent_mod());
1792         while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1793             let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1794             module = self.expect_module(parent.nearest_parent_mod());
1795         }
1796         module
1797     }
1798
1799     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1800         debug!("(recording res) recording {:?} for {}", resolution, node_id);
1801         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1802             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1803         }
1804     }
1805
1806     fn record_pat_span(&mut self, node: NodeId, span: Span) {
1807         debug!("(recording pat) recording {:?} for {:?}", node, span);
1808         self.pat_span_map.insert(node, span);
1809     }
1810
1811     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
1812         vis.is_accessible_from(module.nearest_parent_mod(), self)
1813     }
1814
1815     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1816         if let Some(old_module) =
1817             self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1818         {
1819             if !ptr::eq(module, old_module) {
1820                 span_bug!(binding.span, "parent module is reset for binding");
1821             }
1822         }
1823     }
1824
1825     fn disambiguate_macro_rules_vs_modularized(
1826         &self,
1827         macro_rules: &'a NameBinding<'a>,
1828         modularized: &'a NameBinding<'a>,
1829     ) -> bool {
1830         // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1831         // is disambiguated to mitigate regressions from macro modularization.
1832         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1833         match (
1834             self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1835             self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1836         ) {
1837             (Some(macro_rules), Some(modularized)) => {
1838                 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1839                     && modularized.is_ancestor_of(macro_rules)
1840             }
1841             _ => false,
1842         }
1843     }
1844
1845     fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1846         if ident.is_path_segment_keyword() {
1847             // Make sure `self`, `super` etc produce an error when passed to here.
1848             return None;
1849         }
1850         self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1851             if let Some(binding) = entry.extern_crate_item {
1852                 if finalize && entry.introduced_by_item {
1853                     self.record_use(ident, binding, false);
1854                 }
1855                 Some(binding)
1856             } else {
1857                 let crate_id = if finalize {
1858                     let Some(crate_id) =
1859                         self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1860                     crate_id
1861                 } else {
1862                     self.crate_loader.maybe_process_path_extern(ident.name)?
1863                 };
1864                 let crate_root = self.expect_module(crate_id.as_def_id());
1865                 Some(
1866                     (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT)
1867                         .to_name_binding(self.arenas),
1868                 )
1869             }
1870         })
1871     }
1872
1873     /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1874     /// isn't something that can be returned because it can't be made to live that long,
1875     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1876     /// just that an error occurred.
1877     pub fn resolve_rustdoc_path(
1878         &mut self,
1879         path_str: &str,
1880         ns: Namespace,
1881         mut parent_scope: ParentScope<'a>,
1882     ) -> Option<Res> {
1883         let mut segments =
1884             Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1885         if let Some(segment) = segments.first_mut() {
1886             if segment.ident.name == kw::Crate {
1887                 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1888                 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1889                 // replacing `crate` with `self` and changing the current module should achieve
1890                 // the same effect.
1891                 segment.ident.name = kw::SelfLower;
1892                 parent_scope.module =
1893                     self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1894             } else if segment.ident.name == kw::Empty {
1895                 segment.ident.name = kw::PathRoot;
1896             }
1897         }
1898
1899         match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1900             PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1901             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1902                 Some(path_res.base_res())
1903             }
1904             PathResult::Module(ModuleOrUniformRoot::ExternPrelude)
1905             | PathResult::NonModule(..)
1906             | PathResult::Failed { .. } => None,
1907             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1908         }
1909     }
1910
1911     /// For rustdoc.
1912     /// For local modules returns only reexports, for external modules returns all children.
1913     pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1914         if let Some(def_id) = def_id.as_local() {
1915             self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1916         } else {
1917             self.cstore().module_children_untracked(def_id, self.session)
1918         }
1919     }
1920
1921     /// For rustdoc.
1922     pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1923         let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1924         match scope.get() {
1925             MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1926             _ => unreachable!(),
1927         }
1928     }
1929
1930     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1931     #[inline]
1932     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1933         def_id.as_local().map(|def_id| self.source_span[def_id])
1934     }
1935
1936     /// Retrieves the name of the given `DefId`.
1937     #[inline]
1938     pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
1939         let def_key = match def_id.as_local() {
1940             Some(def_id) => self.definitions.def_key(def_id),
1941             None => self.cstore().def_key(def_id),
1942         };
1943         def_key.get_opt_name()
1944     }
1945
1946     /// Checks if an expression refers to a function marked with
1947     /// `#[rustc_legacy_const_generics]` and returns the argument index list
1948     /// from the attribute.
1949     pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1950         if let ExprKind::Path(None, path) = &expr.kind {
1951             // Don't perform legacy const generics rewriting if the path already
1952             // has generic arguments.
1953             if path.segments.last().unwrap().args.is_some() {
1954                 return None;
1955             }
1956
1957             let partial_res = self.partial_res_map.get(&expr.id)?;
1958             if partial_res.unresolved_segments() != 0 {
1959                 return None;
1960             }
1961
1962             if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() {
1963                 // We only support cross-crate argument rewriting. Uses
1964                 // within the same crate should be updated to use the new
1965                 // const generics style.
1966                 if def_id.is_local() {
1967                     return None;
1968                 }
1969
1970                 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1971                     return v.clone();
1972                 }
1973
1974                 let attr = self
1975                     .cstore()
1976                     .item_attrs_untracked(def_id, self.session)
1977                     .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1978                 let mut ret = Vec::new();
1979                 for meta in attr.meta_item_list()? {
1980                     match meta.literal()?.kind {
1981                         LitKind::Int(a, _) => ret.push(a as usize),
1982                         _ => panic!("invalid arg index"),
1983                     }
1984                 }
1985                 // Cache the lookup to avoid parsing attributes for an item multiple times.
1986                 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
1987                 return Some(ret);
1988             }
1989         }
1990         None
1991     }
1992
1993     fn resolve_main(&mut self) {
1994         let module = self.graph_root;
1995         let ident = Ident::with_dummy_span(sym::main);
1996         let parent_scope = &ParentScope::module(module, self);
1997
1998         let Ok(name_binding) = self.maybe_resolve_ident_in_module(
1999             ModuleOrUniformRoot::Module(module),
2000             ident,
2001             ValueNS,
2002             parent_scope,
2003         ) else {
2004             return;
2005         };
2006
2007         let res = name_binding.res();
2008         let is_import = name_binding.is_import();
2009         let span = name_binding.span;
2010         if let Res::Def(DefKind::Fn, _) = res {
2011             self.record_use(ident, name_binding, false);
2012         }
2013         self.main_def = Some(MainDefinition { res, is_import, span });
2014     }
2015
2016     // Items that go to reexport table encoded to metadata and visible through it to other crates.
2017     fn is_reexport(&self, binding: &NameBinding<'a>) -> Option<def::Res<!>> {
2018         // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
2019         // into the crate root to actual `NameBindingKind::Import`.
2020         if binding.is_import()
2021             || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
2022         {
2023             let res = binding.res().expect_non_local();
2024             // Ambiguous imports are treated as errors at this point and are
2025             // not exposed to other crates (see #36837 for more details).
2026             if res != def::Res::Err && !binding.is_ambiguity() {
2027                 return Some(res);
2028             }
2029         }
2030
2031         return None;
2032     }
2033 }
2034
2035 fn names_to_string(names: &[Symbol]) -> String {
2036     let mut result = String::new();
2037     for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2038         if i > 0 {
2039             result.push_str("::");
2040         }
2041         if Ident::with_dummy_span(*name).is_raw_guess() {
2042             result.push_str("r#");
2043         }
2044         result.push_str(name.as_str());
2045     }
2046     result
2047 }
2048
2049 fn path_names_to_string(path: &Path) -> String {
2050     names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2051 }
2052
2053 /// A somewhat inefficient routine to obtain the name of a module.
2054 fn module_to_string(module: Module<'_>) -> Option<String> {
2055     let mut names = Vec::new();
2056
2057     fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2058         if let ModuleKind::Def(.., name) = module.kind {
2059             if let Some(parent) = module.parent {
2060                 names.push(name);
2061                 collect_mod(names, parent);
2062             }
2063         } else {
2064             names.push(Symbol::intern("<opaque>"));
2065             collect_mod(names, module.parent.unwrap());
2066         }
2067     }
2068     collect_mod(&mut names, module);
2069
2070     if names.is_empty() {
2071         return None;
2072     }
2073     names.reverse();
2074     Some(names_to_string(&names))
2075 }
2076
2077 #[derive(Copy, Clone, Debug)]
2078 struct Finalize {
2079     /// Node ID for linting.
2080     node_id: NodeId,
2081     /// Span of the whole path or some its characteristic fragment.
2082     /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2083     path_span: Span,
2084     /// Span of the path start, suitable for prepending something to to it.
2085     /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2086     root_span: Span,
2087     /// Whether to report privacy errors or silently return "no resolution" for them,
2088     /// similarly to speculative resolution.
2089     report_private: bool,
2090 }
2091
2092 impl Finalize {
2093     fn new(node_id: NodeId, path_span: Span) -> Finalize {
2094         Finalize::with_root_span(node_id, path_span, path_span)
2095     }
2096
2097     fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2098         Finalize { node_id, path_span, root_span, report_private: true }
2099     }
2100 }
2101
2102 pub fn provide(providers: &mut Providers) {
2103     late::lifetimes::provide(providers);
2104 }