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