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