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