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