]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/lib.rs
Adjust cfgs
[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_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,
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     /// Mapping from generics `def_id`s to TAIT generics `def_id`s.
916     /// For each captured lifetime (e.g., 'a), we create a new lifetime parameter that is a generic
917     /// defined on the TAIT, so we have type Foo<'a1> = ... and we establish a mapping in this
918     /// field from the original parameter 'a to the new parameter 'a1.
919     generics_def_id_map: Vec<FxHashMap<LocalDefId, LocalDefId>>,
920     /// Lifetime parameters that lowering will have to introduce.
921     extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
922
923     /// `CrateNum` resolutions of `extern crate` items.
924     extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
925     reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
926     trait_map: NodeMap<Vec<TraitCandidate>>,
927
928     /// A map from nodes to anonymous modules.
929     /// Anonymous modules are pseudo-modules that are implicitly created around items
930     /// contained within blocks.
931     ///
932     /// For example, if we have this:
933     ///
934     ///  fn f() {
935     ///      fn g() {
936     ///          ...
937     ///      }
938     ///  }
939     ///
940     /// There will be an anonymous module created around `g` with the ID of the
941     /// entry block for `f`.
942     block_map: NodeMap<Module<'a>>,
943     /// A fake module that contains no definition and no prelude. Used so that
944     /// some AST passes can generate identifiers that only resolve to local or
945     /// language items.
946     empty_module: Module<'a>,
947     module_map: FxHashMap<DefId, Module<'a>>,
948     binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
949     underscore_disambiguator: u32,
950
951     /// Maps glob imports to the names of items actually imported.
952     glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
953     /// Visibilities in "lowered" form, for all entities that have them.
954     visibilities: FxHashMap<LocalDefId, ty::Visibility>,
955     has_pub_restricted: bool,
956     used_imports: FxHashSet<NodeId>,
957     maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
958     maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
959
960     /// Privacy errors are delayed until the end in order to deduplicate them.
961     privacy_errors: Vec<PrivacyError<'a>>,
962     /// Ambiguity errors are delayed for deduplication.
963     ambiguity_errors: Vec<AmbiguityError<'a>>,
964     /// `use` injections are delayed for better placement and deduplication.
965     use_injections: Vec<UseError<'a>>,
966     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
967     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
968
969     arenas: &'a ResolverArenas<'a>,
970     dummy_binding: &'a NameBinding<'a>,
971
972     crate_loader: CrateLoader<'a>,
973     macro_names: FxHashSet<Ident>,
974     builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
975     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
976     /// the surface (`macro` items in libcore), but are actually attributes or derives.
977     builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
978     registered_attrs: FxHashSet<Ident>,
979     registered_tools: RegisteredTools,
980     macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
981     macro_map: FxHashMap<DefId, MacroData>,
982     dummy_ext_bang: Lrc<SyntaxExtension>,
983     dummy_ext_derive: Lrc<SyntaxExtension>,
984     non_macro_attr: Lrc<SyntaxExtension>,
985     local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
986     ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
987     unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
988     unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
989     proc_macro_stubs: FxHashSet<LocalDefId>,
990     /// Traces collected during macro resolution and validated when it's complete.
991     single_segment_macro_resolutions:
992         Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
993     multi_segment_macro_resolutions:
994         Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
995     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
996     /// `derive(Copy)` marks items they are applied to so they are treated specially later.
997     /// Derive macros cannot modify the item themselves and have to store the markers in the global
998     /// context, so they attach the markers to derive container IDs using this resolver table.
999     containers_deriving_copy: FxHashSet<LocalExpnId>,
1000     /// Parent scopes in which the macros were invoked.
1001     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1002     invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
1003     /// `macro_rules` scopes *produced* by expanding the macro invocations,
1004     /// include all the `macro_rules` items and other invocations generated by them.
1005     output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
1006     /// `macro_rules` scopes produced by `macro_rules` item definitions.
1007     macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
1008     /// Helper attributes that are in scope for the given expansion.
1009     helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
1010     /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1011     /// with the given `ExpnId`.
1012     derive_data: FxHashMap<LocalExpnId, DeriveData>,
1013
1014     /// Avoid duplicated errors for "name already defined".
1015     name_already_seen: FxHashMap<Symbol, Span>,
1016
1017     potentially_unused_imports: Vec<&'a Import<'a>>,
1018
1019     /// Table for mapping struct IDs into struct constructor IDs,
1020     /// it's not used during normal resolution, only for better error reporting.
1021     /// Also includes of list of each fields visibility
1022     struct_constructors: DefIdMap<(Res, ty::Visibility, Vec<ty::Visibility>)>,
1023
1024     /// Features enabled for this crate.
1025     active_features: FxHashSet<Symbol>,
1026
1027     lint_buffer: LintBuffer,
1028
1029     next_node_id: NodeId,
1030
1031     node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1032     def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1033
1034     /// Indices of unnamed struct or variant fields with unresolved attributes.
1035     placeholder_field_indices: FxHashMap<NodeId, usize>,
1036     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1037     /// we know what parent node that fragment should be attached to thanks to this table,
1038     /// and how the `impl Trait` fragments were introduced.
1039     invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1040
1041     /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1042     /// FIXME: Replace with a more general AST map (together with some other fields).
1043     trait_impl_items: FxHashSet<LocalDefId>,
1044
1045     legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1046     /// Amount of lifetime parameters for each item in the crate.
1047     item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1048
1049     main_def: Option<MainDefinition>,
1050     trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1051     /// A list of proc macro LocalDefIds, written out in the order in which
1052     /// they are declared in the static array generated by proc_macro_harness.
1053     proc_macros: Vec<NodeId>,
1054     confused_type_with_std_module: FxHashMap<Span, Span>,
1055
1056     access_levels: AccessLevels,
1057 }
1058
1059 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1060 #[derive(Default)]
1061 pub struct ResolverArenas<'a> {
1062     modules: TypedArena<ModuleData<'a>>,
1063     local_modules: RefCell<Vec<Module<'a>>>,
1064     imports: TypedArena<Import<'a>>,
1065     name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1066     ast_paths: TypedArena<ast::Path>,
1067     dropless: DroplessArena,
1068 }
1069
1070 impl<'a> ResolverArenas<'a> {
1071     fn new_module(
1072         &'a self,
1073         parent: Option<Module<'a>>,
1074         kind: ModuleKind,
1075         expn_id: ExpnId,
1076         span: Span,
1077         no_implicit_prelude: bool,
1078         module_map: &mut FxHashMap<DefId, Module<'a>>,
1079     ) -> Module<'a> {
1080         let module =
1081             self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1082         let def_id = module.opt_def_id();
1083         if def_id.map_or(true, |def_id| def_id.is_local()) {
1084             self.local_modules.borrow_mut().push(module);
1085         }
1086         if let Some(def_id) = def_id {
1087             module_map.insert(def_id, module);
1088         }
1089         module
1090     }
1091     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1092         self.local_modules.borrow()
1093     }
1094     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1095         self.dropless.alloc(name_binding)
1096     }
1097     fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1098         self.imports.alloc(import)
1099     }
1100     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1101         self.name_resolutions.alloc(Default::default())
1102     }
1103     fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1104         Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1105     }
1106     fn alloc_macro_rules_binding(
1107         &'a self,
1108         binding: MacroRulesBinding<'a>,
1109     ) -> &'a MacroRulesBinding<'a> {
1110         self.dropless.alloc(binding)
1111     }
1112     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1113         self.ast_paths.alloc_from_iter(paths.iter().cloned())
1114     }
1115     fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1116         self.dropless.alloc_from_iter(spans)
1117     }
1118 }
1119
1120 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1121     fn as_mut(&mut self) -> &mut Resolver<'a> {
1122         self
1123     }
1124 }
1125
1126 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1127     #[inline]
1128     fn opt_parent(self, id: DefId) -> Option<DefId> {
1129         match id.as_local() {
1130             Some(id) => self.definitions.def_key(id).parent,
1131             None => self.cstore().def_key(id).parent,
1132         }
1133         .map(|index| DefId { index, ..id })
1134     }
1135 }
1136
1137 impl Resolver<'_> {
1138     fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1139         self.node_id_to_def_id.get(&node).copied()
1140     }
1141
1142     pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1143         self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1144     }
1145
1146     /// Adds a definition with a parent definition.
1147     fn create_def(
1148         &mut self,
1149         parent: LocalDefId,
1150         node_id: ast::NodeId,
1151         data: DefPathData,
1152         expn_id: ExpnId,
1153         span: Span,
1154     ) -> LocalDefId {
1155         assert!(
1156             !self.node_id_to_def_id.contains_key(&node_id),
1157             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1158             node_id,
1159             data,
1160             self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1161         );
1162
1163         let def_id = self.definitions.create_def(parent, data);
1164
1165         // Create the definition.
1166         if expn_id != ExpnId::root() {
1167             self.expn_that_defined.insert(def_id, expn_id);
1168         }
1169
1170         // A relative span's parent must be an absolute span.
1171         debug_assert_eq!(span.data_untracked().parent, None);
1172         let _id = self.source_span.push(span);
1173         debug_assert_eq!(_id, def_id);
1174
1175         // Some things for which we allocate `LocalDefId`s don't correspond to
1176         // anything in the AST, so they don't have a `NodeId`. For these cases
1177         // we don't need a mapping from `NodeId` to `LocalDefId`.
1178         if node_id != ast::DUMMY_NODE_ID {
1179             debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1180             self.node_id_to_def_id.insert(node_id, def_id);
1181         }
1182         assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1183
1184         def_id
1185     }
1186
1187     fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1188         if let Some(def_id) = def_id.as_local() {
1189             self.item_generics_num_lifetimes[&def_id]
1190         } else {
1191             self.cstore().item_generics_num_lifetimes(def_id, self.session)
1192         }
1193     }
1194 }
1195
1196 impl<'a> Resolver<'a> {
1197     pub fn new(
1198         session: &'a Session,
1199         krate: &Crate,
1200         crate_name: &str,
1201         metadata_loader: Box<MetadataLoaderDyn>,
1202         arenas: &'a ResolverArenas<'a>,
1203     ) -> Resolver<'a> {
1204         let root_def_id = CRATE_DEF_ID.to_def_id();
1205         let mut module_map = FxHashMap::default();
1206         let graph_root = arenas.new_module(
1207             None,
1208             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1209             ExpnId::root(),
1210             krate.spans.inner_span,
1211             session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1212             &mut module_map,
1213         );
1214         let empty_module = arenas.new_module(
1215             None,
1216             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1217             ExpnId::root(),
1218             DUMMY_SP,
1219             true,
1220             &mut FxHashMap::default(),
1221         );
1222
1223         let definitions = Definitions::new(session.local_stable_crate_id());
1224
1225         let mut visibilities = FxHashMap::default();
1226         visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1227
1228         let mut def_id_to_node_id = IndexVec::default();
1229         assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1230         let mut node_id_to_def_id = FxHashMap::default();
1231         node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1232
1233         let mut invocation_parents = FxHashMap::default();
1234         invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1235
1236         let mut source_span = IndexVec::default();
1237         let _id = source_span.push(krate.spans.inner_span);
1238         debug_assert_eq!(_id, CRATE_DEF_ID);
1239
1240         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1241             .opts
1242             .externs
1243             .iter()
1244             .filter(|(_, entry)| entry.add_prelude)
1245             .map(|(name, _)| (Ident::from_str(name), Default::default()))
1246             .collect();
1247
1248         if !session.contains_name(&krate.attrs, sym::no_core) {
1249             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1250             if !session.contains_name(&krate.attrs, sym::no_std) {
1251                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1252             }
1253         }
1254
1255         let (registered_attrs, registered_tools) =
1256             macros::registered_attrs_and_tools(session, &krate.attrs);
1257
1258         let features = session.features_untracked();
1259
1260         let mut resolver = Resolver {
1261             session,
1262
1263             definitions,
1264             expn_that_defined: Default::default(),
1265             source_span,
1266
1267             // The outermost module has def ID 0; this is not reflected in the
1268             // AST.
1269             graph_root,
1270             prelude: None,
1271             extern_prelude,
1272
1273             has_self: FxHashSet::default(),
1274             field_names: FxHashMap::default(),
1275
1276             determined_imports: Vec::new(),
1277             indeterminate_imports: Vec::new(),
1278
1279             pat_span_map: Default::default(),
1280             partial_res_map: Default::default(),
1281             import_res_map: Default::default(),
1282             label_res_map: Default::default(),
1283             lifetimes_res_map: Default::default(),
1284             generics_def_id_map: Vec::new(),
1285             extra_lifetime_params_map: Default::default(),
1286             extern_crate_map: Default::default(),
1287             reexport_map: FxHashMap::default(),
1288             trait_map: NodeMap::default(),
1289             underscore_disambiguator: 0,
1290             empty_module,
1291             module_map,
1292             block_map: Default::default(),
1293             binding_parent_modules: FxHashMap::default(),
1294             ast_transform_scopes: FxHashMap::default(),
1295
1296             glob_map: Default::default(),
1297             visibilities,
1298             has_pub_restricted: false,
1299             used_imports: FxHashSet::default(),
1300             maybe_unused_trait_imports: Default::default(),
1301             maybe_unused_extern_crates: Vec::new(),
1302
1303             privacy_errors: Vec::new(),
1304             ambiguity_errors: Vec::new(),
1305             use_injections: Vec::new(),
1306             macro_expanded_macro_export_errors: BTreeSet::new(),
1307
1308             arenas,
1309             dummy_binding: arenas.alloc_name_binding(NameBinding {
1310                 kind: NameBindingKind::Res(Res::Err, false),
1311                 ambiguity: None,
1312                 expansion: LocalExpnId::ROOT,
1313                 span: DUMMY_SP,
1314                 vis: ty::Visibility::Public,
1315             }),
1316
1317             crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1318             macro_names: FxHashSet::default(),
1319             builtin_macros: Default::default(),
1320             builtin_macro_kinds: Default::default(),
1321             registered_attrs,
1322             registered_tools,
1323             macro_use_prelude: FxHashMap::default(),
1324             macro_map: FxHashMap::default(),
1325             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1326             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1327             non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1328             invocation_parent_scopes: Default::default(),
1329             output_macro_rules_scopes: Default::default(),
1330             macro_rules_scopes: Default::default(),
1331             helper_attrs: Default::default(),
1332             derive_data: Default::default(),
1333             local_macro_def_scopes: FxHashMap::default(),
1334             name_already_seen: FxHashMap::default(),
1335             potentially_unused_imports: Vec::new(),
1336             struct_constructors: Default::default(),
1337             unused_macros: Default::default(),
1338             unused_macro_rules: Default::default(),
1339             proc_macro_stubs: Default::default(),
1340             single_segment_macro_resolutions: Default::default(),
1341             multi_segment_macro_resolutions: Default::default(),
1342             builtin_attrs: Default::default(),
1343             containers_deriving_copy: Default::default(),
1344             active_features: features
1345                 .declared_lib_features
1346                 .iter()
1347                 .map(|(feat, ..)| *feat)
1348                 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1349                 .collect(),
1350             lint_buffer: LintBuffer::default(),
1351             next_node_id: CRATE_NODE_ID,
1352             node_id_to_def_id,
1353             def_id_to_node_id,
1354             placeholder_field_indices: Default::default(),
1355             invocation_parents,
1356             trait_impl_items: Default::default(),
1357             legacy_const_generic_args: Default::default(),
1358             item_generics_num_lifetimes: Default::default(),
1359             main_def: Default::default(),
1360             trait_impls: Default::default(),
1361             proc_macros: Default::default(),
1362             confused_type_with_std_module: Default::default(),
1363             access_levels: Default::default(),
1364         };
1365
1366         let root_parent_scope = ParentScope::module(graph_root, &resolver);
1367         resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1368
1369         resolver
1370     }
1371
1372     fn new_module(
1373         &mut self,
1374         parent: Option<Module<'a>>,
1375         kind: ModuleKind,
1376         expn_id: ExpnId,
1377         span: Span,
1378         no_implicit_prelude: bool,
1379     ) -> Module<'a> {
1380         let module_map = &mut self.module_map;
1381         self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1382     }
1383
1384     pub fn next_node_id(&mut self) -> NodeId {
1385         let start = self.next_node_id;
1386         let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1387         self.next_node_id = ast::NodeId::from_u32(next);
1388         start
1389     }
1390
1391     pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1392         let start = self.next_node_id;
1393         let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1394         self.next_node_id = ast::NodeId::from_usize(end);
1395         start..self.next_node_id
1396     }
1397
1398     pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1399         &mut self.lint_buffer
1400     }
1401
1402     pub fn arenas() -> ResolverArenas<'a> {
1403         Default::default()
1404     }
1405
1406     pub fn into_outputs(
1407         self,
1408     ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1409         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1410         let definitions = self.definitions;
1411         let cstore = Box::new(self.crate_loader.into_cstore());
1412         let source_span = self.source_span;
1413         let expn_that_defined = self.expn_that_defined;
1414         let visibilities = self.visibilities;
1415         let has_pub_restricted = self.has_pub_restricted;
1416         let extern_crate_map = self.extern_crate_map;
1417         let reexport_map = self.reexport_map;
1418         let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1419         let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1420         let glob_map = self.glob_map;
1421         let main_def = self.main_def;
1422         let confused_type_with_std_module = self.confused_type_with_std_module;
1423         let access_levels = self.access_levels;
1424         let resolutions = ResolverOutputs {
1425             source_span,
1426             expn_that_defined,
1427             visibilities,
1428             has_pub_restricted,
1429             access_levels,
1430             extern_crate_map,
1431             reexport_map,
1432             glob_map,
1433             maybe_unused_trait_imports,
1434             maybe_unused_extern_crates,
1435             extern_prelude: self
1436                 .extern_prelude
1437                 .iter()
1438                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1439                 .collect(),
1440             main_def,
1441             trait_impls: self.trait_impls,
1442             proc_macros,
1443             confused_type_with_std_module,
1444             registered_tools: self.registered_tools,
1445         };
1446         let resolutions_lowering = ty::ResolverAstLowering {
1447             legacy_const_generic_args: self.legacy_const_generic_args,
1448             partial_res_map: self.partial_res_map,
1449             import_res_map: self.import_res_map,
1450             label_res_map: self.label_res_map,
1451             lifetimes_res_map: self.lifetimes_res_map,
1452             generics_def_id_map: self.generics_def_id_map,
1453             extra_lifetime_params_map: self.extra_lifetime_params_map,
1454             next_node_id: self.next_node_id,
1455             node_id_to_def_id: self.node_id_to_def_id,
1456             def_id_to_node_id: self.def_id_to_node_id,
1457             trait_map: self.trait_map,
1458             builtin_macro_kinds: self.builtin_macro_kinds,
1459         };
1460         (definitions, cstore, resolutions, resolutions_lowering)
1461     }
1462
1463     pub fn clone_outputs(
1464         &self,
1465     ) -> (Definitions, Box<CrateStoreDyn>, ResolverOutputs, ty::ResolverAstLowering) {
1466         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1467         let definitions = self.definitions.clone();
1468         let cstore = Box::new(self.cstore().clone());
1469         let resolutions = ResolverOutputs {
1470             source_span: self.source_span.clone(),
1471             expn_that_defined: self.expn_that_defined.clone(),
1472             visibilities: self.visibilities.clone(),
1473             has_pub_restricted: self.has_pub_restricted,
1474             extern_crate_map: self.extern_crate_map.clone(),
1475             reexport_map: self.reexport_map.clone(),
1476             glob_map: self.glob_map.clone(),
1477             maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1478             maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1479             extern_prelude: self
1480                 .extern_prelude
1481                 .iter()
1482                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1483                 .collect(),
1484             main_def: self.main_def,
1485             trait_impls: self.trait_impls.clone(),
1486             proc_macros,
1487             confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1488             registered_tools: self.registered_tools.clone(),
1489             access_levels: self.access_levels.clone(),
1490         };
1491         let resolutions_lowering = ty::ResolverAstLowering {
1492             legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1493             partial_res_map: self.partial_res_map.clone(),
1494             import_res_map: self.import_res_map.clone(),
1495             label_res_map: self.label_res_map.clone(),
1496             lifetimes_res_map: self.lifetimes_res_map.clone(),
1497             generics_def_id_map: self.generics_def_id_map.clone(),
1498             extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1499             next_node_id: self.next_node_id.clone(),
1500             node_id_to_def_id: self.node_id_to_def_id.clone(),
1501             def_id_to_node_id: self.def_id_to_node_id.clone(),
1502             trait_map: self.trait_map.clone(),
1503             builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1504         };
1505         (definitions, cstore, resolutions, resolutions_lowering)
1506     }
1507
1508     fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1509         StableHashingContext::new(
1510             self.session,
1511             &self.definitions,
1512             self.crate_loader.cstore(),
1513             &self.source_span,
1514         )
1515     }
1516
1517     pub fn cstore(&self) -> &CStore {
1518         self.crate_loader.cstore()
1519     }
1520
1521     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1522         match macro_kind {
1523             MacroKind::Bang => self.dummy_ext_bang.clone(),
1524             MacroKind::Derive => self.dummy_ext_derive.clone(),
1525             MacroKind::Attr => self.non_macro_attr.clone(),
1526         }
1527     }
1528
1529     /// Runs the function on each namespace.
1530     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1531         f(self, TypeNS);
1532         f(self, ValueNS);
1533         f(self, MacroNS);
1534     }
1535
1536     fn is_builtin_macro(&mut self, res: Res) -> bool {
1537         self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1538     }
1539
1540     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1541         loop {
1542             match ctxt.outer_expn_data().macro_def_id {
1543                 Some(def_id) => return def_id,
1544                 None => ctxt.remove_mark(),
1545             };
1546         }
1547     }
1548
1549     /// Entry point to crate resolution.
1550     pub fn resolve_crate(&mut self, krate: &Crate) {
1551         self.session.time("resolve_crate", || {
1552             self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1553             self.session.time("resolve_access_levels", || {
1554                 AccessLevelsVisitor::compute_access_levels(self, krate)
1555             });
1556             self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1557             self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1558             self.session.time("resolve_main", || self.resolve_main());
1559             self.session.time("resolve_check_unused", || self.check_unused(krate));
1560             self.session.time("resolve_report_errors", || self.report_errors(krate));
1561             self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1562         });
1563     }
1564
1565     pub fn traits_in_scope(
1566         &mut self,
1567         current_trait: Option<Module<'a>>,
1568         parent_scope: &ParentScope<'a>,
1569         ctxt: SyntaxContext,
1570         assoc_item: Option<(Symbol, Namespace)>,
1571     ) -> Vec<TraitCandidate> {
1572         let mut found_traits = Vec::new();
1573
1574         if let Some(module) = current_trait {
1575             if self.trait_may_have_item(Some(module), assoc_item) {
1576                 let def_id = module.def_id();
1577                 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1578             }
1579         }
1580
1581         self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1582             match scope {
1583                 Scope::Module(module, _) => {
1584                     this.traits_in_module(module, assoc_item, &mut found_traits);
1585                 }
1586                 Scope::StdLibPrelude => {
1587                     if let Some(module) = this.prelude {
1588                         this.traits_in_module(module, assoc_item, &mut found_traits);
1589                     }
1590                 }
1591                 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1592                 _ => unreachable!(),
1593             }
1594             None::<()>
1595         });
1596
1597         found_traits
1598     }
1599
1600     fn traits_in_module(
1601         &mut self,
1602         module: Module<'a>,
1603         assoc_item: Option<(Symbol, Namespace)>,
1604         found_traits: &mut Vec<TraitCandidate>,
1605     ) {
1606         module.ensure_traits(self);
1607         let traits = module.traits.borrow();
1608         for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1609             if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1610                 let def_id = trait_binding.res().def_id();
1611                 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1612                 found_traits.push(TraitCandidate { def_id, import_ids });
1613             }
1614         }
1615     }
1616
1617     // List of traits in scope is pruned on best effort basis. We reject traits not having an
1618     // associated item with the given name and namespace (if specified). This is a conservative
1619     // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1620     // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1621     // associated items.
1622     fn trait_may_have_item(
1623         &mut self,
1624         trait_module: Option<Module<'a>>,
1625         assoc_item: Option<(Symbol, Namespace)>,
1626     ) -> bool {
1627         match (trait_module, assoc_item) {
1628             (Some(trait_module), Some((name, ns))) => {
1629                 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1630                     let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1631                     assoc_ns == ns && assoc_ident.name == name
1632                 })
1633             }
1634             _ => true,
1635         }
1636     }
1637
1638     fn find_transitive_imports(
1639         &mut self,
1640         mut kind: &NameBindingKind<'_>,
1641         trait_name: Ident,
1642     ) -> SmallVec<[LocalDefId; 1]> {
1643         let mut import_ids = smallvec![];
1644         while let NameBindingKind::Import { import, binding, .. } = kind {
1645             let id = self.local_def_id(import.id);
1646             self.maybe_unused_trait_imports.insert(id);
1647             self.add_to_glob_map(&import, trait_name);
1648             import_ids.push(id);
1649             kind = &binding.kind;
1650         }
1651         import_ids
1652     }
1653
1654     fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1655         let ident = ident.normalize_to_macros_2_0();
1656         let disambiguator = if ident.name == kw::Underscore {
1657             self.underscore_disambiguator += 1;
1658             self.underscore_disambiguator
1659         } else {
1660             0
1661         };
1662         BindingKey { ident, ns, disambiguator }
1663     }
1664
1665     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1666         if module.populate_on_access.get() {
1667             module.populate_on_access.set(false);
1668             self.build_reduced_graph_external(module);
1669         }
1670         &module.lazy_resolutions
1671     }
1672
1673     fn resolution(
1674         &mut self,
1675         module: Module<'a>,
1676         key: BindingKey,
1677     ) -> &'a RefCell<NameResolution<'a>> {
1678         *self
1679             .resolutions(module)
1680             .borrow_mut()
1681             .entry(key)
1682             .or_insert_with(|| self.arenas.alloc_name_resolution())
1683     }
1684
1685     fn record_use(
1686         &mut self,
1687         ident: Ident,
1688         used_binding: &'a NameBinding<'a>,
1689         is_lexical_scope: bool,
1690     ) {
1691         if let Some((b2, kind)) = used_binding.ambiguity {
1692             self.ambiguity_errors.push(AmbiguityError {
1693                 kind,
1694                 ident,
1695                 b1: used_binding,
1696                 b2,
1697                 misc1: AmbiguityErrorMisc::None,
1698                 misc2: AmbiguityErrorMisc::None,
1699             });
1700         }
1701         if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1702             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1703             // but not introduce it, as used if they are accessed from lexical scope.
1704             if is_lexical_scope {
1705                 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1706                     if let Some(crate_item) = entry.extern_crate_item {
1707                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1708                             return;
1709                         }
1710                     }
1711                 }
1712             }
1713             used.set(true);
1714             import.used.set(true);
1715             self.used_imports.insert(import.id);
1716             self.add_to_glob_map(&import, ident);
1717             self.record_use(ident, binding, false);
1718         }
1719     }
1720
1721     #[inline]
1722     fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1723         if import.is_glob() {
1724             let def_id = self.local_def_id(import.id);
1725             self.glob_map.entry(def_id).or_default().insert(ident.name);
1726         }
1727     }
1728
1729     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1730         debug!("resolve_crate_root({:?})", ident);
1731         let mut ctxt = ident.span.ctxt();
1732         let mark = if ident.name == kw::DollarCrate {
1733             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1734             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1735             // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1736             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1737             // definitions actually produced by `macro` and `macro` definitions produced by
1738             // `macro_rules!`, but at least such configurations are not stable yet.
1739             ctxt = ctxt.normalize_to_macro_rules();
1740             debug!(
1741                 "resolve_crate_root: marks={:?}",
1742                 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1743             );
1744             let mut iter = ctxt.marks().into_iter().rev().peekable();
1745             let mut result = None;
1746             // Find the last opaque mark from the end if it exists.
1747             while let Some(&(mark, transparency)) = iter.peek() {
1748                 if transparency == Transparency::Opaque {
1749                     result = Some(mark);
1750                     iter.next();
1751                 } else {
1752                     break;
1753                 }
1754             }
1755             debug!(
1756                 "resolve_crate_root: found opaque mark {:?} {:?}",
1757                 result,
1758                 result.map(|r| r.expn_data())
1759             );
1760             // Then find the last semi-transparent mark from the end if it exists.
1761             for (mark, transparency) in iter {
1762                 if transparency == Transparency::SemiTransparent {
1763                     result = Some(mark);
1764                 } else {
1765                     break;
1766                 }
1767             }
1768             debug!(
1769                 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1770                 result,
1771                 result.map(|r| r.expn_data())
1772             );
1773             result
1774         } else {
1775             debug!("resolve_crate_root: not DollarCrate");
1776             ctxt = ctxt.normalize_to_macros_2_0();
1777             ctxt.adjust(ExpnId::root())
1778         };
1779         let module = match mark {
1780             Some(def) => self.expn_def_scope(def),
1781             None => {
1782                 debug!(
1783                     "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1784                     ident, ident.span
1785                 );
1786                 return self.graph_root;
1787             }
1788         };
1789         let module = self.expect_module(
1790             module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1791         );
1792         debug!(
1793             "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1794             ident,
1795             module,
1796             module.kind.name(),
1797             ident.span
1798         );
1799         module
1800     }
1801
1802     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1803         let mut module = self.expect_module(module.nearest_parent_mod());
1804         while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1805             let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1806             module = self.expect_module(parent.nearest_parent_mod());
1807         }
1808         module
1809     }
1810
1811     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1812         debug!("(recording res) recording {:?} for {}", resolution, node_id);
1813         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1814             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1815         }
1816     }
1817
1818     fn record_pat_span(&mut self, node: NodeId, span: Span) {
1819         debug!("(recording pat) recording {:?} for {:?}", node, span);
1820         self.pat_span_map.insert(node, span);
1821     }
1822
1823     fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool {
1824         vis.is_accessible_from(module.nearest_parent_mod(), self)
1825     }
1826
1827     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1828         if let Some(old_module) =
1829             self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1830         {
1831             if !ptr::eq(module, old_module) {
1832                 span_bug!(binding.span, "parent module is reset for binding");
1833             }
1834         }
1835     }
1836
1837     fn disambiguate_macro_rules_vs_modularized(
1838         &self,
1839         macro_rules: &'a NameBinding<'a>,
1840         modularized: &'a NameBinding<'a>,
1841     ) -> bool {
1842         // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1843         // is disambiguated to mitigate regressions from macro modularization.
1844         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1845         match (
1846             self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1847             self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1848         ) {
1849             (Some(macro_rules), Some(modularized)) => {
1850                 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1851                     && modularized.is_ancestor_of(macro_rules)
1852             }
1853             _ => false,
1854         }
1855     }
1856
1857     fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1858         if ident.is_path_segment_keyword() {
1859             // Make sure `self`, `super` etc produce an error when passed to here.
1860             return None;
1861         }
1862         self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1863             if let Some(binding) = entry.extern_crate_item {
1864                 if finalize && entry.introduced_by_item {
1865                     self.record_use(ident, binding, false);
1866                 }
1867                 Some(binding)
1868             } else {
1869                 let crate_id = if finalize {
1870                     let Some(crate_id) =
1871                         self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1872                     crate_id
1873                 } else {
1874                     self.crate_loader.maybe_process_path_extern(ident.name)?
1875                 };
1876                 let crate_root = self.expect_module(crate_id.as_def_id());
1877                 Some(
1878                     (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT)
1879                         .to_name_binding(self.arenas),
1880                 )
1881             }
1882         })
1883     }
1884
1885     /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1886     /// isn't something that can be returned because it can't be made to live that long,
1887     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1888     /// just that an error occurred.
1889     pub fn resolve_rustdoc_path(
1890         &mut self,
1891         path_str: &str,
1892         ns: Namespace,
1893         mut parent_scope: ParentScope<'a>,
1894     ) -> Option<Res> {
1895         let mut segments =
1896             Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1897         if let Some(segment) = segments.first_mut() {
1898             if segment.ident.name == kw::Crate {
1899                 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1900                 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1901                 // replacing `crate` with `self` and changing the current module should achieve
1902                 // the same effect.
1903                 segment.ident.name = kw::SelfLower;
1904                 parent_scope.module =
1905                     self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1906             } else if segment.ident.name == kw::Empty {
1907                 segment.ident.name = kw::PathRoot;
1908             }
1909         }
1910
1911         match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1912             PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1913             PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
1914                 Some(path_res.base_res())
1915             }
1916             PathResult::Module(ModuleOrUniformRoot::ExternPrelude)
1917             | PathResult::NonModule(..)
1918             | PathResult::Failed { .. } => None,
1919             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1920         }
1921     }
1922
1923     /// For rustdoc.
1924     /// For local modules returns only reexports, for external modules returns all children.
1925     pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1926         if let Some(def_id) = def_id.as_local() {
1927             self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1928         } else {
1929             self.cstore().module_children_untracked(def_id, self.session)
1930         }
1931     }
1932
1933     /// For rustdoc.
1934     pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1935         let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1936         match scope.get() {
1937             MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1938             _ => unreachable!(),
1939         }
1940     }
1941
1942     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1943     #[inline]
1944     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1945         def_id.as_local().map(|def_id| self.source_span[def_id])
1946     }
1947
1948     /// Checks if an expression refers to a function marked with
1949     /// `#[rustc_legacy_const_generics]` and returns the argument index list
1950     /// from the attribute.
1951     pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1952         if let ExprKind::Path(None, path) = &expr.kind {
1953             // Don't perform legacy const generics rewriting if the path already
1954             // has generic arguments.
1955             if path.segments.last().unwrap().args.is_some() {
1956                 return None;
1957             }
1958
1959             let partial_res = self.partial_res_map.get(&expr.id)?;
1960             if partial_res.unresolved_segments() != 0 {
1961                 return None;
1962             }
1963
1964             if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() {
1965                 // We only support cross-crate argument rewriting. Uses
1966                 // within the same crate should be updated to use the new
1967                 // const generics style.
1968                 if def_id.is_local() {
1969                     return None;
1970                 }
1971
1972                 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1973                     return v.clone();
1974                 }
1975
1976                 let attr = self
1977                     .cstore()
1978                     .item_attrs_untracked(def_id, self.session)
1979                     .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1980                 let mut ret = Vec::new();
1981                 for meta in attr.meta_item_list()? {
1982                     match meta.literal()?.kind {
1983                         LitKind::Int(a, _) => ret.push(a as usize),
1984                         _ => panic!("invalid arg index"),
1985                     }
1986                 }
1987                 // Cache the lookup to avoid parsing attributes for an iterm multiple times.
1988                 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
1989                 return Some(ret);
1990             }
1991         }
1992         None
1993     }
1994
1995     fn resolve_main(&mut self) {
1996         let module = self.graph_root;
1997         let ident = Ident::with_dummy_span(sym::main);
1998         let parent_scope = &ParentScope::module(module, self);
1999
2000         let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2001             ModuleOrUniformRoot::Module(module),
2002             ident,
2003             ValueNS,
2004             parent_scope,
2005         ) else {
2006             return;
2007         };
2008
2009         let res = name_binding.res();
2010         let is_import = name_binding.is_import();
2011         let span = name_binding.span;
2012         if let Res::Def(DefKind::Fn, _) = res {
2013             self.record_use(ident, name_binding, false);
2014         }
2015         self.main_def = Some(MainDefinition { res, is_import, span });
2016     }
2017 }
2018
2019 fn names_to_string(names: &[Symbol]) -> String {
2020     let mut result = String::new();
2021     for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2022         if i > 0 {
2023             result.push_str("::");
2024         }
2025         if Ident::with_dummy_span(*name).is_raw_guess() {
2026             result.push_str("r#");
2027         }
2028         result.push_str(name.as_str());
2029     }
2030     result
2031 }
2032
2033 fn path_names_to_string(path: &Path) -> String {
2034     names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2035 }
2036
2037 /// A somewhat inefficient routine to obtain the name of a module.
2038 fn module_to_string(module: Module<'_>) -> Option<String> {
2039     let mut names = Vec::new();
2040
2041     fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2042         if let ModuleKind::Def(.., name) = module.kind {
2043             if let Some(parent) = module.parent {
2044                 names.push(name);
2045                 collect_mod(names, parent);
2046             }
2047         } else {
2048             names.push(Symbol::intern("<opaque>"));
2049             collect_mod(names, module.parent.unwrap());
2050         }
2051     }
2052     collect_mod(&mut names, module);
2053
2054     if names.is_empty() {
2055         return None;
2056     }
2057     names.reverse();
2058     Some(names_to_string(&names))
2059 }
2060
2061 #[derive(Copy, Clone, Debug)]
2062 struct Finalize {
2063     /// Node ID for linting.
2064     node_id: NodeId,
2065     /// Span of the whole path or some its characteristic fragment.
2066     /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2067     path_span: Span,
2068     /// Span of the path start, suitable for prepending something to to it.
2069     /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2070     root_span: Span,
2071     /// Whether to report privacy errors or silently return "no resolution" for them,
2072     /// similarly to speculative resolution.
2073     report_private: bool,
2074 }
2075
2076 impl Finalize {
2077     fn new(node_id: NodeId, path_span: Span) -> Finalize {
2078         Finalize::with_root_span(node_id, path_span, path_span)
2079     }
2080
2081     fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2082         Finalize { node_id, path_span, root_span, report_private: true }
2083     }
2084 }
2085
2086 pub fn provide(providers: &mut Providers) {
2087     late::lifetimes::provide(providers);
2088 }