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