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