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