1#![allow(internal_features)]
11#![allow(rustc::diagnostic_outside_of_impl)]
12#![allow(rustc::untranslatable_diagnostic)]
13#![deny(clippy::manual_let_else)]
14#![feature(arbitrary_self_types)]
15#![feature(assert_matches)]
16#![feature(box_patterns)]
17#![feature(control_flow_into_value)]
18#![feature(decl_macro)]
19#![feature(default_field_values)]
20#![feature(if_let_guard)]
21#![feature(iter_intersperse)]
22#![feature(ptr_as_ref_unchecked)]
23#![feature(rustc_attrs)]
24#![feature(trim_prefix_suffix)]
25#![recursion_limit = "256"]
26use std::cell::Ref;
29use std::collections::BTreeSet;
30use std::fmt::{self};
31use std::ops::ControlFlow;
32use std::sync::Arc;
33
34use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
35use effective_visibilities::EffectiveVisibilitiesVisitor;
36use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
37use imports::{Import, ImportData, ImportKind, NameResolution, PendingBinding};
38use late::{
39 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
40 UnnecessaryQualification,
41};
42use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
43use rustc_arena::{DroplessArena, TypedArena};
44use rustc_ast::node_id::NodeMap;
45use rustc_ast::{
46 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
47 LitKind, NodeId, Path, attr,
48};
49use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
50use rustc_data_structures::intern::Interned;
51use rustc_data_structures::steal::Steal;
52use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
53use rustc_data_structures::unord::{UnordMap, UnordSet};
54use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
55use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
56use rustc_feature::BUILTIN_ATTRIBUTES;
57use rustc_hir::attrs::StrippedCfgItem;
58use rustc_hir::def::Namespace::{self, *};
59use rustc_hir::def::{
60 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
61 PerNS,
62};
63use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
64use rustc_hir::definitions::DisambiguatorState;
65use rustc_hir::{PrimTy, TraitCandidate};
66use rustc_index::bit_set::DenseBitSet;
67use rustc_metadata::creader::CStore;
68use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
69use rustc_middle::middle::privacy::EffectiveVisibilities;
70use rustc_middle::query::Providers;
71use rustc_middle::span_bug;
72use rustc_middle::ty::{
73 self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
74 ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
75};
76use rustc_query_system::ich::StableHashingContext;
77use rustc_session::config::CrateType;
78use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
79use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
80use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
81use smallvec::{SmallVec, smallvec};
82use tracing::debug;
83
84type Res = def::Res<NodeId>;
85
86mod build_reduced_graph;
87mod check_unused;
88mod def_collector;
89mod diagnostics;
90mod effective_visibilities;
91mod errors;
92mod ident;
93mod imports;
94mod late;
95mod macros;
96pub mod rustdoc;
97
98pub use macros::registered_tools_ast;
99
100use crate::ref_mut::{CmCell, CmRefCell};
101
102rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
103
104#[derive(Copy, Clone, PartialEq, Debug)]
105enum Determinacy {
106 Determined,
107 Undetermined,
108}
109
110impl Determinacy {
111 fn determined(determined: bool) -> Determinacy {
112 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
113 }
114}
115
116#[derive(Clone, Copy, Debug)]
118enum Scope<'ra> {
119 DeriveHelpers(LocalExpnId),
121 DeriveHelpersCompat,
125 MacroRules(MacroRulesScopeRef<'ra>),
127 Module(Module<'ra>, Option<NodeId>),
131 MacroUsePrelude,
133 BuiltinAttrs,
135 ExternPreludeItems,
137 ExternPreludeFlags,
139 ToolPrelude,
141 StdLibPrelude,
143 BuiltinTypes,
145}
146
147#[derive(Clone, Copy, Debug)]
150enum ScopeSet<'ra> {
151 All(Namespace),
153 ModuleAndExternPrelude(Namespace, Module<'ra>),
155 ExternPrelude,
157 Macro(MacroKind),
159}
160
161#[derive(Clone, Copy, Debug)]
166struct ParentScope<'ra> {
167 module: Module<'ra>,
168 expansion: LocalExpnId,
169 macro_rules: MacroRulesScopeRef<'ra>,
170 derives: &'ra [ast::Path],
171}
172
173impl<'ra> ParentScope<'ra> {
174 fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
177 ParentScope {
178 module,
179 expansion: LocalExpnId::ROOT,
180 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
181 derives: &[],
182 }
183 }
184}
185
186#[derive(Copy, Debug, Clone)]
187struct InvocationParent {
188 parent_def: LocalDefId,
189 impl_trait_context: ImplTraitContext,
190 in_attr: bool,
191}
192
193impl InvocationParent {
194 const ROOT: Self = Self {
195 parent_def: CRATE_DEF_ID,
196 impl_trait_context: ImplTraitContext::Existential,
197 in_attr: false,
198 };
199}
200
201#[derive(Copy, Debug, Clone)]
202enum ImplTraitContext {
203 Existential,
204 Universal,
205 InBinding,
206}
207
208#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
223enum Used {
224 Scope,
225 Other,
226}
227
228#[derive(Debug)]
229struct BindingError {
230 name: Ident,
231 origin: Vec<(Span, ast::Pat)>,
232 target: Vec<ast::Pat>,
233 could_be_path: bool,
234}
235
236#[derive(Debug)]
237enum ResolutionError<'ra> {
238 GenericParamsFromOuterItem {
240 outer_res: Res,
241 has_generic_params: HasGenericParams,
242 def_kind: DefKind,
243 inner_item: Option<(Span, ast::ItemKind)>,
244 current_self_ty: Option<String>,
245 },
246 NameAlreadyUsedInParameterList(Ident, Span),
249 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
251 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
253 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
255 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
257 VariableBoundWithDifferentMode(Ident, Span),
259 IdentifierBoundMoreThanOnceInParameterList(Ident),
261 IdentifierBoundMoreThanOnceInSamePattern(Ident),
263 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
265 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
267 SelfImportCanOnlyAppearOnceInTheList,
269 SelfImportOnlyInImportListWithNonEmptyPrefix,
271 FailedToResolve {
273 segment: Option<Symbol>,
274 label: String,
275 suggestion: Option<Suggestion>,
276 module: Option<ModuleOrUniformRoot<'ra>>,
277 },
278 CannotCaptureDynamicEnvironmentInFnItem,
280 AttemptToUseNonConstantValueInConstant {
282 ident: Ident,
283 suggestion: &'static str,
284 current: &'static str,
285 type_span: Option<Span>,
286 },
287 BindingShadowsSomethingUnacceptable {
289 shadowing_binding: PatternSource,
290 name: Symbol,
291 participle: &'static str,
292 article: &'static str,
293 shadowed_binding: Res,
294 shadowed_binding_span: Span,
295 },
296 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
298 ParamInTyOfConstParam { name: Symbol },
302 ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
306 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
310 ForwardDeclaredSelf(ForwardGenericParamBanReason),
312 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
314 TraitImplMismatch {
316 name: Ident,
317 kind: &'static str,
318 trait_path: String,
319 trait_item_span: Span,
320 code: ErrCode,
321 },
322 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
324 InvalidAsmSym,
326 LowercaseSelf,
328 BindingInNeverPattern,
330}
331
332enum VisResolutionError<'a> {
333 Relative2018(Span, &'a ast::Path),
334 AncestorOnly(Span),
335 FailedToResolve(Span, String, Option<Suggestion>),
336 ExpectedFound(Span, String, Res),
337 Indeterminate(Span),
338 ModuleOnly(Span),
339}
340
341#[derive(Clone, Copy, Debug)]
344struct Segment {
345 ident: Ident,
346 id: Option<NodeId>,
347 has_generic_args: bool,
350 has_lifetime_args: bool,
352 args_span: Span,
353}
354
355impl Segment {
356 fn from_path(path: &Path) -> Vec<Segment> {
357 path.segments.iter().map(|s| s.into()).collect()
358 }
359
360 fn from_ident(ident: Ident) -> Segment {
361 Segment {
362 ident,
363 id: None,
364 has_generic_args: false,
365 has_lifetime_args: false,
366 args_span: DUMMY_SP,
367 }
368 }
369
370 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
371 Segment {
372 ident,
373 id: Some(id),
374 has_generic_args: false,
375 has_lifetime_args: false,
376 args_span: DUMMY_SP,
377 }
378 }
379
380 fn names_to_string(segments: &[Segment]) -> String {
381 names_to_string(segments.iter().map(|seg| seg.ident.name))
382 }
383}
384
385impl<'a> From<&'a ast::PathSegment> for Segment {
386 fn from(seg: &'a ast::PathSegment) -> Segment {
387 let has_generic_args = seg.args.is_some();
388 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
389 match args {
390 GenericArgs::AngleBracketed(args) => {
391 let found_lifetimes = args
392 .args
393 .iter()
394 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
395 (args.span, found_lifetimes)
396 }
397 GenericArgs::Parenthesized(args) => (args.span, true),
398 GenericArgs::ParenthesizedElided(span) => (*span, true),
399 }
400 } else {
401 (DUMMY_SP, false)
402 };
403 Segment {
404 ident: seg.ident,
405 id: Some(seg.id),
406 has_generic_args,
407 has_lifetime_args,
408 args_span,
409 }
410 }
411}
412
413#[derive(Debug, Copy, Clone)]
419enum LexicalScopeBinding<'ra> {
420 Item(NameBinding<'ra>),
421 Res(Res),
422}
423
424impl<'ra> LexicalScopeBinding<'ra> {
425 fn res(self) -> Res {
426 match self {
427 LexicalScopeBinding::Item(binding) => binding.res(),
428 LexicalScopeBinding::Res(res) => res,
429 }
430 }
431}
432
433#[derive(Copy, Clone, PartialEq, Debug)]
434enum ModuleOrUniformRoot<'ra> {
435 Module(Module<'ra>),
437
438 ModuleAndExternPrelude(Module<'ra>),
442
443 ExternPrelude,
446
447 CurrentScope,
451}
452
453#[derive(Debug)]
454enum PathResult<'ra> {
455 Module(ModuleOrUniformRoot<'ra>),
456 NonModule(PartialRes),
457 Indeterminate,
458 Failed {
459 span: Span,
460 label: String,
461 suggestion: Option<Suggestion>,
462 is_error_from_last_segment: bool,
463 module: Option<ModuleOrUniformRoot<'ra>>,
477 segment_name: Symbol,
479 error_implied_by_parse_error: bool,
480 },
481}
482
483impl<'ra> PathResult<'ra> {
484 fn failed(
485 ident: Ident,
486 is_error_from_last_segment: bool,
487 finalize: bool,
488 error_implied_by_parse_error: bool,
489 module: Option<ModuleOrUniformRoot<'ra>>,
490 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
491 ) -> PathResult<'ra> {
492 let (label, suggestion) =
493 if finalize { label_and_suggestion() } else { (String::new(), None) };
494 PathResult::Failed {
495 span: ident.span,
496 segment_name: ident.name,
497 label,
498 suggestion,
499 is_error_from_last_segment,
500 module,
501 error_implied_by_parse_error,
502 }
503 }
504}
505
506#[derive(Debug)]
507enum ModuleKind {
508 Block,
521 Def(DefKind, DefId, Option<Symbol>),
531}
532
533impl ModuleKind {
534 fn name(&self) -> Option<Symbol> {
536 match *self {
537 ModuleKind::Block => None,
538 ModuleKind::Def(.., name) => name,
539 }
540 }
541}
542
543#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
548struct BindingKey {
549 ident: Macros20NormalizedIdent,
552 ns: Namespace,
553 disambiguator: u32,
559}
560
561impl BindingKey {
562 fn new(ident: Ident, ns: Namespace) -> Self {
563 BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator: 0 }
564 }
565
566 fn new_disambiguated(
567 ident: Ident,
568 ns: Namespace,
569 disambiguator: impl FnOnce() -> u32,
570 ) -> BindingKey {
571 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
572 BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator }
573 }
574}
575
576type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
577
578struct ModuleData<'ra> {
590 parent: Option<Module<'ra>>,
592 kind: ModuleKind,
594
595 lazy_resolutions: Resolutions<'ra>,
598 populate_on_access: CacheCell<bool>,
600 underscore_disambiguator: CmCell<u32>,
602
603 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
605
606 no_implicit_prelude: bool,
608
609 glob_importers: CmRefCell<Vec<Import<'ra>>>,
610 globs: CmRefCell<Vec<Import<'ra>>>,
611
612 traits:
614 CmRefCell<Option<Box<[(Macros20NormalizedIdent, NameBinding<'ra>, Option<Module<'ra>>)]>>>,
615
616 span: Span,
618
619 expansion: ExpnId,
620
621 self_binding: Option<NameBinding<'ra>>,
624}
625
626#[derive(Clone, Copy, PartialEq, Eq, Hash)]
629#[rustc_pass_by_value]
630struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
631
632impl std::hash::Hash for ModuleData<'_> {
637 fn hash<H>(&self, _: &mut H)
638 where
639 H: std::hash::Hasher,
640 {
641 unreachable!()
642 }
643}
644
645impl<'ra> ModuleData<'ra> {
646 fn new(
647 parent: Option<Module<'ra>>,
648 kind: ModuleKind,
649 expansion: ExpnId,
650 span: Span,
651 no_implicit_prelude: bool,
652 self_binding: Option<NameBinding<'ra>>,
653 ) -> Self {
654 let is_foreign = match kind {
655 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
656 ModuleKind::Block => false,
657 };
658 ModuleData {
659 parent,
660 kind,
661 lazy_resolutions: Default::default(),
662 populate_on_access: CacheCell::new(is_foreign),
663 underscore_disambiguator: CmCell::new(0),
664 unexpanded_invocations: Default::default(),
665 no_implicit_prelude,
666 glob_importers: CmRefCell::new(Vec::new()),
667 globs: CmRefCell::new(Vec::new()),
668 traits: CmRefCell::new(None),
669 span,
670 expansion,
671 self_binding,
672 }
673 }
674}
675
676impl<'ra> Module<'ra> {
677 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
678 self,
679 resolver: &R,
680 mut f: impl FnMut(&R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
681 ) {
682 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
683 if let Some(binding) = name_resolution.borrow().best_binding() {
684 f(resolver, key.ident, key.ns, binding);
685 }
686 }
687 }
688
689 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
690 self,
691 resolver: &mut R,
692 mut f: impl FnMut(&mut R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
693 ) {
694 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
695 if let Some(binding) = name_resolution.borrow().best_binding() {
696 f(resolver, key.ident, key.ns, binding);
697 }
698 }
699 }
700
701 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
703 let mut traits = self.traits.borrow_mut(resolver.as_ref());
704 if traits.is_none() {
705 let mut collected_traits = Vec::new();
706 self.for_each_child(resolver, |r, name, ns, binding| {
707 if ns != TypeNS {
708 return;
709 }
710 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
711 collected_traits.push((name, binding, r.as_ref().get_module(def_id)))
712 }
713 });
714 *traits = Some(collected_traits.into_boxed_slice());
715 }
716 }
717
718 fn res(self) -> Option<Res> {
719 match self.kind {
720 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
721 _ => None,
722 }
723 }
724
725 fn def_id(self) -> DefId {
726 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
727 }
728
729 fn opt_def_id(self) -> Option<DefId> {
730 match self.kind {
731 ModuleKind::Def(_, def_id, _) => Some(def_id),
732 _ => None,
733 }
734 }
735
736 fn is_normal(self) -> bool {
738 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
739 }
740
741 fn is_trait(self) -> bool {
742 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
743 }
744
745 fn nearest_item_scope(self) -> Module<'ra> {
746 match self.kind {
747 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
748 self.parent.expect("enum or trait module without a parent")
749 }
750 _ => self,
751 }
752 }
753
754 fn nearest_parent_mod(self) -> DefId {
757 match self.kind {
758 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
759 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
760 }
761 }
762
763 fn is_ancestor_of(self, mut other: Self) -> bool {
764 while self != other {
765 if let Some(parent) = other.parent {
766 other = parent;
767 } else {
768 return false;
769 }
770 }
771 true
772 }
773}
774
775impl<'ra> std::ops::Deref for Module<'ra> {
776 type Target = ModuleData<'ra>;
777
778 fn deref(&self) -> &Self::Target {
779 &self.0
780 }
781}
782
783impl<'ra> fmt::Debug for Module<'ra> {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 match self.kind {
786 ModuleKind::Block => write!(f, "block"),
787 ModuleKind::Def(..) => write!(f, "{:?}", self.res()),
788 }
789 }
790}
791
792#[derive(Clone, Copy, Debug)]
794struct NameBindingData<'ra> {
795 kind: NameBindingKind<'ra>,
796 ambiguity: Option<(NameBinding<'ra>, AmbiguityKind)>,
797 warn_ambiguity: bool,
800 expansion: LocalExpnId,
801 span: Span,
802 vis: Visibility<DefId>,
803}
804
805type NameBinding<'ra> = Interned<'ra, NameBindingData<'ra>>;
808
809impl std::hash::Hash for NameBindingData<'_> {
814 fn hash<H>(&self, _: &mut H)
815 where
816 H: std::hash::Hasher,
817 {
818 unreachable!()
819 }
820}
821
822#[derive(Clone, Copy, Debug)]
823enum NameBindingKind<'ra> {
824 Res(Res),
825 Import { binding: NameBinding<'ra>, import: Import<'ra> },
826}
827
828impl<'ra> NameBindingKind<'ra> {
829 fn is_import(&self) -> bool {
831 matches!(*self, NameBindingKind::Import { .. })
832 }
833}
834
835#[derive(Debug)]
836struct PrivacyError<'ra> {
837 ident: Ident,
838 binding: NameBinding<'ra>,
839 dedup_span: Span,
840 outermost_res: Option<(Res, Ident)>,
841 parent_scope: ParentScope<'ra>,
842 single_nested: bool,
844 source: Option<ast::Expr>,
845}
846
847#[derive(Debug)]
848struct UseError<'a> {
849 err: Diag<'a>,
850 candidates: Vec<ImportSuggestion>,
852 def_id: DefId,
854 instead: bool,
856 suggestion: Option<(Span, &'static str, String, Applicability)>,
858 path: Vec<Segment>,
861 is_call: bool,
863}
864
865#[derive(Clone, Copy, PartialEq, Debug)]
866enum AmbiguityKind {
867 BuiltinAttr,
868 DeriveHelper,
869 MacroRulesVsModularized,
870 GlobVsOuter,
871 GlobVsGlob,
872 GlobVsExpanded,
873 MoreExpandedVsOuter,
874}
875
876impl AmbiguityKind {
877 fn descr(self) -> &'static str {
878 match self {
879 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
880 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
881 AmbiguityKind::MacroRulesVsModularized => {
882 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
883 }
884 AmbiguityKind::GlobVsOuter => {
885 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
886 }
887 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
888 AmbiguityKind::GlobVsExpanded => {
889 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
890 }
891 AmbiguityKind::MoreExpandedVsOuter => {
892 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
893 }
894 }
895 }
896}
897
898#[derive(Clone, Copy, PartialEq)]
900enum AmbiguityErrorMisc {
901 SuggestCrate,
902 SuggestSelf,
903 FromPrelude,
904 None,
905}
906
907struct AmbiguityError<'ra> {
908 kind: AmbiguityKind,
909 ident: Ident,
910 b1: NameBinding<'ra>,
911 b2: NameBinding<'ra>,
912 misc1: AmbiguityErrorMisc,
913 misc2: AmbiguityErrorMisc,
914 warning: bool,
915}
916
917impl<'ra> NameBindingData<'ra> {
918 fn res(&self) -> Res {
919 match self.kind {
920 NameBindingKind::Res(res) => res,
921 NameBindingKind::Import { binding, .. } => binding.res(),
922 }
923 }
924
925 fn import_source(&self) -> NameBinding<'ra> {
926 match self.kind {
927 NameBindingKind::Import { binding, .. } => binding,
928 _ => unreachable!(),
929 }
930 }
931
932 fn descent_to_ambiguity(
933 self: NameBinding<'ra>,
934 ) -> Option<(NameBinding<'ra>, NameBinding<'ra>, AmbiguityKind)> {
935 match self.ambiguity {
936 Some((ambig_binding, ambig_kind)) => Some((self, ambig_binding, ambig_kind)),
937 None => match self.kind {
938 NameBindingKind::Import { binding, .. } => binding.descent_to_ambiguity(),
939 _ => None,
940 },
941 }
942 }
943
944 fn is_ambiguity_recursive(&self) -> bool {
945 self.ambiguity.is_some()
946 || match self.kind {
947 NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(),
948 _ => false,
949 }
950 }
951
952 fn warn_ambiguity_recursive(&self) -> bool {
953 self.warn_ambiguity
954 || match self.kind {
955 NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(),
956 _ => false,
957 }
958 }
959
960 fn is_possibly_imported_variant(&self) -> bool {
961 match self.kind {
962 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
963 NameBindingKind::Res(Res::Def(
964 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
965 _,
966 )) => true,
967 NameBindingKind::Res(..) => false,
968 }
969 }
970
971 fn is_extern_crate(&self) -> bool {
972 match self.kind {
973 NameBindingKind::Import { import, .. } => {
974 matches!(import.kind, ImportKind::ExternCrate { .. })
975 }
976 NameBindingKind::Res(Res::Def(_, def_id)) => def_id.is_crate_root(),
977 _ => false,
978 }
979 }
980
981 fn is_import(&self) -> bool {
982 matches!(self.kind, NameBindingKind::Import { .. })
983 }
984
985 fn is_import_user_facing(&self) -> bool {
988 matches!(self.kind, NameBindingKind::Import { import, .. }
989 if !matches!(import.kind, ImportKind::MacroExport))
990 }
991
992 fn is_glob_import(&self) -> bool {
993 match self.kind {
994 NameBindingKind::Import { import, .. } => import.is_glob(),
995 _ => false,
996 }
997 }
998
999 fn is_assoc_item(&self) -> bool {
1000 matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
1001 }
1002
1003 fn macro_kinds(&self) -> Option<MacroKinds> {
1004 self.res().macro_kinds()
1005 }
1006
1007 fn reexport_chain(self: NameBinding<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1008 let mut reexport_chain = SmallVec::new();
1009 let mut next_binding = self;
1010 while let NameBindingKind::Import { binding, import, .. } = next_binding.kind {
1011 reexport_chain.push(import.simplify(r));
1012 next_binding = binding;
1013 }
1014 reexport_chain
1015 }
1016
1017 fn may_appear_after(
1024 &self,
1025 invoc_parent_expansion: LocalExpnId,
1026 binding: NameBinding<'_>,
1027 ) -> bool {
1028 let self_parent_expansion = self.expansion;
1032 let other_parent_expansion = binding.expansion;
1033 let certainly_before_other_or_simultaneously =
1034 other_parent_expansion.is_descendant_of(self_parent_expansion);
1035 let certainly_before_invoc_or_simultaneously =
1036 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1037 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1038 }
1039
1040 fn determined(&self) -> bool {
1044 match &self.kind {
1045 NameBindingKind::Import { binding, import, .. } if import.is_glob() => {
1046 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1047 && binding.determined()
1048 }
1049 _ => true,
1050 }
1051 }
1052}
1053
1054struct ExternPreludeEntry<'ra> {
1055 item_binding: Option<(NameBinding<'ra>, bool)>,
1059 flag_binding: Option<CacheCell<(PendingBinding<'ra>, bool)>>,
1061}
1062
1063impl ExternPreludeEntry<'_> {
1064 fn introduced_by_item(&self) -> bool {
1065 matches!(self.item_binding, Some((_, true)))
1066 }
1067
1068 fn flag() -> Self {
1069 ExternPreludeEntry {
1070 item_binding: None,
1071 flag_binding: Some(CacheCell::new((PendingBinding::Pending, false))),
1072 }
1073 }
1074}
1075
1076struct DeriveData {
1077 resolutions: Vec<DeriveResolution>,
1078 helper_attrs: Vec<(usize, Ident)>,
1079 has_derive_copy: bool,
1080}
1081
1082struct MacroData {
1083 ext: Arc<SyntaxExtension>,
1084 nrules: usize,
1085 macro_rules: bool,
1086}
1087
1088impl MacroData {
1089 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1090 MacroData { ext, nrules: 0, macro_rules: false }
1091 }
1092}
1093
1094pub struct ResolverOutputs {
1095 pub global_ctxt: ResolverGlobalCtxt,
1096 pub ast_lowering: ResolverAstLowering,
1097}
1098
1099pub struct Resolver<'ra, 'tcx> {
1103 tcx: TyCtxt<'tcx>,
1104
1105 expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1107
1108 graph_root: Module<'ra>,
1109
1110 assert_speculative: bool,
1112
1113 prelude: Option<Module<'ra>> = None,
1114 extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1115
1116 field_names: LocalDefIdMap<Vec<Ident>>,
1118 field_defaults: LocalDefIdMap<Vec<Symbol>>,
1119
1120 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1123
1124 determined_imports: Vec<Import<'ra>> = Vec::new(),
1126
1127 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1129
1130 pat_span_map: NodeMap<Span>,
1133
1134 partial_res_map: NodeMap<PartialRes>,
1136 import_res_map: NodeMap<PerNS<Option<Res>>>,
1138 import_use_map: FxHashMap<Import<'ra>, Used>,
1140 label_res_map: NodeMap<NodeId>,
1142 lifetimes_res_map: NodeMap<LifetimeRes>,
1144 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1146
1147 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1149 module_children: LocalDefIdMap<Vec<ModChild>>,
1150 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
1151 trait_map: NodeMap<Vec<TraitCandidate>>,
1152
1153 block_map: NodeMap<Module<'ra>>,
1168 empty_module: Module<'ra>,
1172 local_modules: Vec<Module<'ra>>,
1174 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1176 extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1178 binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1179
1180 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1182 glob_error: Option<ErrorGuaranteed> = None,
1183 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1184 used_imports: FxHashSet<NodeId>,
1185 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1186
1187 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1189 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1191 issue_145575_hack_applied: bool = false,
1192 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1194 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1196
1197 inaccessible_ctor_reexport: FxHashMap<Span, Span>,
1201
1202 arenas: &'ra ResolverArenas<'ra>,
1203 dummy_binding: NameBinding<'ra>,
1204 builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1205 builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1206 registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1207 macro_names: FxHashSet<Ident>,
1208 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1209 registered_tools: &'tcx RegisteredTools,
1210 macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1211 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1213 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1215 dummy_ext_bang: Arc<SyntaxExtension>,
1216 dummy_ext_derive: Arc<SyntaxExtension>,
1217 non_macro_attr: &'ra MacroData,
1218 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1219 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1220 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1221 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1223 proc_macro_stubs: FxHashSet<LocalDefId>,
1224 single_segment_macro_resolutions:
1226 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1227 multi_segment_macro_resolutions:
1228 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1229 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1230 containers_deriving_copy: FxHashSet<LocalExpnId>,
1234 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1237 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1240 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1242 helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1244 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1247
1248 name_already_seen: FxHashMap<Symbol, Span>,
1250
1251 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1252
1253 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1254
1255 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1259
1260 lint_buffer: LintBuffer,
1261
1262 next_node_id: NodeId = CRATE_NODE_ID,
1263
1264 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1265
1266 disambiguator: DisambiguatorState,
1267
1268 placeholder_field_indices: FxHashMap<NodeId, usize>,
1270 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1274
1275 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1276 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1278 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1279
1280 main_def: Option<MainDefinition> = None,
1281 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1282 proc_macros: Vec<LocalDefId> = Vec::new(),
1285 confused_type_with_std_module: FxIndexMap<Span, Span>,
1286 lifetime_elision_allowed: FxHashSet<NodeId>,
1288
1289 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1291
1292 effective_visibilities: EffectiveVisibilities,
1293 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1294 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1295 all_macro_rules: UnordSet<Symbol>,
1296
1297 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1299 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1302 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1305
1306 current_crate_outer_attr_insert_span: Span,
1309
1310 mods_with_parse_errors: FxHashSet<DefId>,
1311
1312 all_crate_macros_already_registered: bool = false,
1315
1316 impl_trait_names: FxHashMap<NodeId, Symbol>,
1320}
1321
1322#[derive(Default)]
1325pub struct ResolverArenas<'ra> {
1326 modules: TypedArena<ModuleData<'ra>>,
1327 imports: TypedArena<ImportData<'ra>>,
1328 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1329 ast_paths: TypedArena<ast::Path>,
1330 macros: TypedArena<MacroData>,
1331 dropless: DroplessArena,
1332}
1333
1334impl<'ra> ResolverArenas<'ra> {
1335 fn new_res_binding(
1336 &'ra self,
1337 res: Res,
1338 vis: Visibility<DefId>,
1339 span: Span,
1340 expansion: LocalExpnId,
1341 ) -> NameBinding<'ra> {
1342 self.alloc_name_binding(NameBindingData {
1343 kind: NameBindingKind::Res(res),
1344 ambiguity: None,
1345 warn_ambiguity: false,
1346 vis,
1347 span,
1348 expansion,
1349 })
1350 }
1351
1352 fn new_pub_res_binding(
1353 &'ra self,
1354 res: Res,
1355 span: Span,
1356 expn_id: LocalExpnId,
1357 ) -> NameBinding<'ra> {
1358 self.new_res_binding(res, Visibility::Public, span, expn_id)
1359 }
1360
1361 fn new_module(
1362 &'ra self,
1363 parent: Option<Module<'ra>>,
1364 kind: ModuleKind,
1365 expn_id: ExpnId,
1366 span: Span,
1367 no_implicit_prelude: bool,
1368 ) -> Module<'ra> {
1369 let self_binding = match kind {
1370 ModuleKind::Def(def_kind, def_id, _) => {
1371 Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT))
1372 }
1373 ModuleKind::Block => None,
1374 };
1375 Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1376 parent,
1377 kind,
1378 expn_id,
1379 span,
1380 no_implicit_prelude,
1381 self_binding,
1382 ))))
1383 }
1384 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1385 Interned::new_unchecked(self.dropless.alloc(name_binding))
1386 }
1387 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1388 Interned::new_unchecked(self.imports.alloc(import))
1389 }
1390 fn alloc_name_resolution(&'ra self) -> &'ra CmRefCell<NameResolution<'ra>> {
1391 self.name_resolutions.alloc(Default::default())
1392 }
1393 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1394 self.dropless.alloc(CacheCell::new(scope))
1395 }
1396 fn alloc_macro_rules_binding(
1397 &'ra self,
1398 binding: MacroRulesBinding<'ra>,
1399 ) -> &'ra MacroRulesBinding<'ra> {
1400 self.dropless.alloc(binding)
1401 }
1402 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1403 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1404 }
1405 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1406 self.macros.alloc(macro_data)
1407 }
1408 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1409 self.dropless.alloc_from_iter(spans)
1410 }
1411}
1412
1413impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1414 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1415 self
1416 }
1417}
1418
1419impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1420 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1421 self
1422 }
1423}
1424
1425impl<'tcx> Resolver<'_, 'tcx> {
1426 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1427 self.opt_feed(node).map(|f| f.key())
1428 }
1429
1430 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1431 self.feed(node).key()
1432 }
1433
1434 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1435 self.node_id_to_def_id.get(&node).copied()
1436 }
1437
1438 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1439 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1440 }
1441
1442 fn local_def_kind(&self, node: NodeId) -> DefKind {
1443 self.tcx.def_kind(self.local_def_id(node))
1444 }
1445
1446 fn create_def(
1448 &mut self,
1449 parent: LocalDefId,
1450 node_id: ast::NodeId,
1451 name: Option<Symbol>,
1452 def_kind: DefKind,
1453 expn_id: ExpnId,
1454 span: Span,
1455 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1456 assert!(
1457 !self.node_id_to_def_id.contains_key(&node_id),
1458 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1459 node_id,
1460 name,
1461 def_kind,
1462 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1463 );
1464
1465 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1467 let def_id = feed.def_id();
1468
1469 if expn_id != ExpnId::root() {
1471 self.expn_that_defined.insert(def_id, expn_id);
1472 }
1473
1474 debug_assert_eq!(span.data_untracked().parent, None);
1476 let _id = self.tcx.untracked().source_span.push(span);
1477 debug_assert_eq!(_id, def_id);
1478
1479 if node_id != ast::DUMMY_NODE_ID {
1483 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1484 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1485 }
1486
1487 feed
1488 }
1489
1490 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1491 if let Some(def_id) = def_id.as_local() {
1492 self.item_generics_num_lifetimes[&def_id]
1493 } else {
1494 self.tcx.generics_of(def_id).own_counts().lifetimes
1495 }
1496 }
1497
1498 pub fn tcx(&self) -> TyCtxt<'tcx> {
1499 self.tcx
1500 }
1501
1502 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1507 self.node_id_to_def_id
1508 .items()
1509 .filter(|(_, v)| v.key() == def_id)
1510 .map(|(k, _)| *k)
1511 .get_only()
1512 .unwrap()
1513 }
1514}
1515
1516impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1517 pub fn new(
1518 tcx: TyCtxt<'tcx>,
1519 attrs: &[ast::Attribute],
1520 crate_span: Span,
1521 current_crate_outer_attr_insert_span: Span,
1522 arenas: &'ra ResolverArenas<'ra>,
1523 ) -> Resolver<'ra, 'tcx> {
1524 let root_def_id = CRATE_DEF_ID.to_def_id();
1525 let graph_root = arenas.new_module(
1526 None,
1527 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1528 ExpnId::root(),
1529 crate_span,
1530 attr::contains_name(attrs, sym::no_implicit_prelude),
1531 );
1532 let local_modules = vec![graph_root];
1533 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1534 let empty_module = arenas.new_module(
1535 None,
1536 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1537 ExpnId::root(),
1538 DUMMY_SP,
1539 true,
1540 );
1541
1542 let mut node_id_to_def_id = NodeMap::default();
1543 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1544
1545 crate_feed.def_kind(DefKind::Mod);
1546 let crate_feed = crate_feed.downgrade();
1547 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1548
1549 let mut invocation_parents = FxHashMap::default();
1550 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1551
1552 let mut extern_prelude: FxIndexMap<_, _> = tcx
1553 .sess
1554 .opts
1555 .externs
1556 .iter()
1557 .filter_map(|(name, entry)| {
1558 if entry.add_prelude
1561 && let name = Symbol::intern(name)
1562 && name.can_be_raw()
1563 {
1564 let ident = Macros20NormalizedIdent::with_dummy_span(name);
1565 Some((ident, ExternPreludeEntry::flag()))
1566 } else {
1567 None
1568 }
1569 })
1570 .collect();
1571
1572 if !attr::contains_name(attrs, sym::no_core) {
1573 let ident = Macros20NormalizedIdent::with_dummy_span(sym::core);
1574 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1575 if !attr::contains_name(attrs, sym::no_std) {
1576 let ident = Macros20NormalizedIdent::with_dummy_span(sym::std);
1577 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1578 }
1579 }
1580
1581 let registered_tools = tcx.registered_tools(());
1582 let edition = tcx.sess.edition();
1583
1584 let mut resolver = Resolver {
1585 tcx,
1586
1587 expn_that_defined: Default::default(),
1588
1589 graph_root,
1592 assert_speculative: false, prelude: None,
1594 extern_prelude,
1595
1596 field_names: Default::default(),
1597 field_defaults: Default::default(),
1598 field_visibility_spans: FxHashMap::default(),
1599
1600 pat_span_map: Default::default(),
1601 partial_res_map: Default::default(),
1602 import_res_map: Default::default(),
1603 import_use_map: Default::default(),
1604 label_res_map: Default::default(),
1605 lifetimes_res_map: Default::default(),
1606 extra_lifetime_params_map: Default::default(),
1607 extern_crate_map: Default::default(),
1608 module_children: Default::default(),
1609 ambig_module_children: Default::default(),
1610 trait_map: NodeMap::default(),
1611 empty_module,
1612 local_modules,
1613 local_module_map,
1614 extern_module_map: Default::default(),
1615 block_map: Default::default(),
1616 binding_parent_modules: FxHashMap::default(),
1617 ast_transform_scopes: FxHashMap::default(),
1618
1619 glob_map: Default::default(),
1620 used_imports: FxHashSet::default(),
1621 maybe_unused_trait_imports: Default::default(),
1622 inaccessible_ctor_reexport: Default::default(),
1623
1624 arenas,
1625 dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1626 builtin_types_bindings: PrimTy::ALL
1627 .iter()
1628 .map(|prim_ty| {
1629 let res = Res::PrimTy(*prim_ty);
1630 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1631 (prim_ty.name(), binding)
1632 })
1633 .collect(),
1634 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1635 .iter()
1636 .map(|builtin_attr| {
1637 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1638 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1639 (builtin_attr.name, binding)
1640 })
1641 .collect(),
1642 registered_tool_bindings: registered_tools
1643 .iter()
1644 .map(|ident| {
1645 let res = Res::ToolMod;
1646 let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1647 (*ident, binding)
1648 })
1649 .collect(),
1650 macro_names: FxHashSet::default(),
1651 builtin_macros: Default::default(),
1652 registered_tools,
1653 macro_use_prelude: Default::default(),
1654 local_macro_map: Default::default(),
1655 extern_macro_map: Default::default(),
1656 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1657 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1658 non_macro_attr: arenas
1659 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1660 invocation_parent_scopes: Default::default(),
1661 output_macro_rules_scopes: Default::default(),
1662 macro_rules_scopes: Default::default(),
1663 helper_attrs: Default::default(),
1664 derive_data: Default::default(),
1665 local_macro_def_scopes: FxHashMap::default(),
1666 name_already_seen: FxHashMap::default(),
1667 struct_constructors: Default::default(),
1668 unused_macros: Default::default(),
1669 unused_macro_rules: Default::default(),
1670 proc_macro_stubs: Default::default(),
1671 single_segment_macro_resolutions: Default::default(),
1672 multi_segment_macro_resolutions: Default::default(),
1673 builtin_attrs: Default::default(),
1674 containers_deriving_copy: Default::default(),
1675 lint_buffer: LintBuffer::default(),
1676 node_id_to_def_id,
1677 disambiguator: DisambiguatorState::new(),
1678 placeholder_field_indices: Default::default(),
1679 invocation_parents,
1680 legacy_const_generic_args: Default::default(),
1681 item_generics_num_lifetimes: Default::default(),
1682 trait_impls: Default::default(),
1683 confused_type_with_std_module: Default::default(),
1684 lifetime_elision_allowed: Default::default(),
1685 stripped_cfg_items: Default::default(),
1686 effective_visibilities: Default::default(),
1687 doc_link_resolutions: Default::default(),
1688 doc_link_traits_in_scope: Default::default(),
1689 all_macro_rules: Default::default(),
1690 delegation_fn_sigs: Default::default(),
1691 glob_delegation_invoc_ids: Default::default(),
1692 impl_unexpanded_invocations: Default::default(),
1693 impl_binding_keys: Default::default(),
1694 current_crate_outer_attr_insert_span,
1695 mods_with_parse_errors: Default::default(),
1696 impl_trait_names: Default::default(),
1697 ..
1698 };
1699
1700 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1701 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1702 resolver.feed_visibility(crate_feed, Visibility::Public);
1703
1704 resolver
1705 }
1706
1707 fn new_local_module(
1708 &mut self,
1709 parent: Option<Module<'ra>>,
1710 kind: ModuleKind,
1711 expn_id: ExpnId,
1712 span: Span,
1713 no_implicit_prelude: bool,
1714 ) -> Module<'ra> {
1715 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1716 self.local_modules.push(module);
1717 if let Some(def_id) = module.opt_def_id() {
1718 self.local_module_map.insert(def_id.expect_local(), module);
1719 }
1720 module
1721 }
1722
1723 fn new_extern_module(
1724 &self,
1725 parent: Option<Module<'ra>>,
1726 kind: ModuleKind,
1727 expn_id: ExpnId,
1728 span: Span,
1729 no_implicit_prelude: bool,
1730 ) -> Module<'ra> {
1731 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1732 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1733 module
1734 }
1735
1736 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1737 let mac = self.arenas.alloc_macro(macro_data);
1738 self.local_macro_map.insert(def_id, mac);
1739 mac
1740 }
1741
1742 fn next_node_id(&mut self) -> NodeId {
1743 let start = self.next_node_id;
1744 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1745 self.next_node_id = ast::NodeId::from_u32(next);
1746 start
1747 }
1748
1749 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1750 let start = self.next_node_id;
1751 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1752 self.next_node_id = ast::NodeId::from_usize(end);
1753 start..self.next_node_id
1754 }
1755
1756 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1757 &mut self.lint_buffer
1758 }
1759
1760 pub fn arenas() -> ResolverArenas<'ra> {
1761 Default::default()
1762 }
1763
1764 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1765 let feed = feed.upgrade(self.tcx);
1766 feed.visibility(vis.to_def_id());
1767 self.visibilities_for_hashing.push((feed.def_id(), vis));
1768 }
1769
1770 pub fn into_outputs(self) -> ResolverOutputs {
1771 let proc_macros = self.proc_macros;
1772 let expn_that_defined = self.expn_that_defined;
1773 let extern_crate_map = self.extern_crate_map;
1774 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1775 let glob_map = self.glob_map;
1776 let main_def = self.main_def;
1777 let confused_type_with_std_module = self.confused_type_with_std_module;
1778 let effective_visibilities = self.effective_visibilities;
1779
1780 let stripped_cfg_items = self
1781 .stripped_cfg_items
1782 .into_iter()
1783 .filter_map(|item| {
1784 let parent_module =
1785 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1786 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1787 })
1788 .collect();
1789
1790 let global_ctxt = ResolverGlobalCtxt {
1791 expn_that_defined,
1792 visibilities_for_hashing: self.visibilities_for_hashing,
1793 effective_visibilities,
1794 extern_crate_map,
1795 module_children: self.module_children,
1796 ambig_module_children: self.ambig_module_children,
1797 glob_map,
1798 maybe_unused_trait_imports,
1799 main_def,
1800 trait_impls: self.trait_impls,
1801 proc_macros,
1802 confused_type_with_std_module,
1803 doc_link_resolutions: self.doc_link_resolutions,
1804 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1805 all_macro_rules: self.all_macro_rules,
1806 stripped_cfg_items,
1807 };
1808 let ast_lowering = ty::ResolverAstLowering {
1809 legacy_const_generic_args: self.legacy_const_generic_args,
1810 partial_res_map: self.partial_res_map,
1811 import_res_map: self.import_res_map,
1812 label_res_map: self.label_res_map,
1813 lifetimes_res_map: self.lifetimes_res_map,
1814 extra_lifetime_params_map: self.extra_lifetime_params_map,
1815 next_node_id: self.next_node_id,
1816 node_id_to_def_id: self
1817 .node_id_to_def_id
1818 .into_items()
1819 .map(|(k, f)| (k, f.key()))
1820 .collect(),
1821 trait_map: self.trait_map,
1822 lifetime_elision_allowed: self.lifetime_elision_allowed,
1823 lint_buffer: Steal::new(self.lint_buffer),
1824 delegation_fn_sigs: self.delegation_fn_sigs,
1825 };
1826 ResolverOutputs { global_ctxt, ast_lowering }
1827 }
1828
1829 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1830 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1831 }
1832
1833 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1834 CStore::from_tcx(self.tcx)
1835 }
1836
1837 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1838 CStore::from_tcx_mut(self.tcx)
1839 }
1840
1841 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1842 match macro_kind {
1843 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1844 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1845 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1846 }
1847 }
1848
1849 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1854 CmResolver::new(self, !self.assert_speculative)
1855 }
1856
1857 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1859 f(self, TypeNS);
1860 f(self, ValueNS);
1861 f(self, MacroNS);
1862 }
1863
1864 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1865 mut self: CmResolver<'r, 'ra, 'tcx>,
1866 mut f: F,
1867 ) {
1868 f(&mut self, TypeNS);
1869 f(&mut self, ValueNS);
1870 f(&mut self, MacroNS);
1871 }
1872
1873 fn is_builtin_macro(&self, res: Res) -> bool {
1874 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1875 }
1876
1877 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1878 loop {
1879 match ctxt.outer_expn_data().macro_def_id {
1880 Some(def_id) => return def_id,
1881 None => ctxt.remove_mark(),
1882 };
1883 }
1884 }
1885
1886 pub fn resolve_crate(&mut self, krate: &Crate) {
1888 self.tcx.sess.time("resolve_crate", || {
1889 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1890 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1891 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1892 });
1893 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1894 self.tcx
1895 .sess
1896 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1897 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1898 self.tcx.sess.time("resolve_main", || self.resolve_main());
1899 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1900 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1901 self.tcx
1902 .sess
1903 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1904 });
1905
1906 self.tcx.untracked().cstore.freeze();
1908 }
1909
1910 fn traits_in_scope(
1911 &mut self,
1912 current_trait: Option<Module<'ra>>,
1913 parent_scope: &ParentScope<'ra>,
1914 ctxt: SyntaxContext,
1915 assoc_item: Option<(Symbol, Namespace)>,
1916 ) -> Vec<TraitCandidate> {
1917 let mut found_traits = Vec::new();
1918
1919 if let Some(module) = current_trait {
1920 if self.trait_may_have_item(Some(module), assoc_item) {
1921 let def_id = module.def_id();
1922 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1923 }
1924 }
1925
1926 let scope_set = ScopeSet::All(TypeNS);
1927 self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1928 match scope {
1929 Scope::Module(module, _) => {
1930 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1931 }
1932 Scope::StdLibPrelude => {
1933 if let Some(module) = this.prelude {
1934 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1935 }
1936 }
1937 Scope::ExternPreludeItems
1938 | Scope::ExternPreludeFlags
1939 | Scope::ToolPrelude
1940 | Scope::BuiltinTypes => {}
1941 _ => unreachable!(),
1942 }
1943 ControlFlow::<()>::Continue(())
1944 });
1945
1946 found_traits
1947 }
1948
1949 fn traits_in_module(
1950 &mut self,
1951 module: Module<'ra>,
1952 assoc_item: Option<(Symbol, Namespace)>,
1953 found_traits: &mut Vec<TraitCandidate>,
1954 ) {
1955 module.ensure_traits(self);
1956 let traits = module.traits.borrow();
1957 for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1958 if self.trait_may_have_item(trait_module, assoc_item) {
1959 let def_id = trait_binding.res().def_id();
1960 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1961 found_traits.push(TraitCandidate { def_id, import_ids });
1962 }
1963 }
1964 }
1965
1966 fn trait_may_have_item(
1972 &self,
1973 trait_module: Option<Module<'ra>>,
1974 assoc_item: Option<(Symbol, Namespace)>,
1975 ) -> bool {
1976 match (trait_module, assoc_item) {
1977 (Some(trait_module), Some((name, ns))) => self
1978 .resolutions(trait_module)
1979 .borrow()
1980 .iter()
1981 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1982 _ => true,
1983 }
1984 }
1985
1986 fn find_transitive_imports(
1987 &mut self,
1988 mut kind: &NameBindingKind<'_>,
1989 trait_name: Ident,
1990 ) -> SmallVec<[LocalDefId; 1]> {
1991 let mut import_ids = smallvec![];
1992 while let NameBindingKind::Import { import, binding, .. } = kind {
1993 if let Some(node_id) = import.id() {
1994 let def_id = self.local_def_id(node_id);
1995 self.maybe_unused_trait_imports.insert(def_id);
1996 import_ids.push(def_id);
1997 }
1998 self.add_to_glob_map(*import, trait_name);
1999 kind = &binding.kind;
2000 }
2001 import_ids
2002 }
2003
2004 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2005 if module.populate_on_access.get() {
2006 module.populate_on_access.set(false);
2007 self.build_reduced_graph_external(module);
2008 }
2009 &module.0.0.lazy_resolutions
2010 }
2011
2012 fn resolution(
2013 &self,
2014 module: Module<'ra>,
2015 key: BindingKey,
2016 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2017 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2018 }
2019
2020 fn resolution_or_default(
2021 &self,
2022 module: Module<'ra>,
2023 key: BindingKey,
2024 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2025 self.resolutions(module)
2026 .borrow_mut_unchecked()
2027 .entry(key)
2028 .or_insert_with(|| self.arenas.alloc_name_resolution())
2029 }
2030
2031 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2033 for ambiguity_error in &self.ambiguity_errors {
2034 if ambiguity_error.kind == ambi.kind
2036 && ambiguity_error.ident == ambi.ident
2037 && ambiguity_error.ident.span == ambi.ident.span
2038 && ambiguity_error.b1.span == ambi.b1.span
2039 && ambiguity_error.b2.span == ambi.b2.span
2040 && ambiguity_error.misc1 == ambi.misc1
2041 && ambiguity_error.misc2 == ambi.misc2
2042 {
2043 return true;
2044 }
2045 }
2046 false
2047 }
2048
2049 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2050 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2051 }
2052
2053 fn record_use_inner(
2054 &mut self,
2055 ident: Ident,
2056 used_binding: NameBinding<'ra>,
2057 used: Used,
2058 warn_ambiguity: bool,
2059 ) {
2060 if let Some((b2, kind)) = used_binding.ambiguity {
2061 let ambiguity_error = AmbiguityError {
2062 kind,
2063 ident,
2064 b1: used_binding,
2065 b2,
2066 misc1: AmbiguityErrorMisc::None,
2067 misc2: AmbiguityErrorMisc::None,
2068 warning: warn_ambiguity,
2069 };
2070 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2071 self.ambiguity_errors.push(ambiguity_error);
2073 }
2074 }
2075 if let NameBindingKind::Import { import, binding } = used_binding.kind {
2076 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2077 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2080 let empty_module = self.empty_module;
2081 let arenas = self.arenas;
2082 self.cm()
2083 .maybe_resolve_ident_in_module(
2084 ModuleOrUniformRoot::Module(prelude),
2085 ident,
2086 MacroNS,
2087 &ParentScope::module(empty_module, arenas),
2088 None,
2089 )
2090 .is_ok()
2091 });
2092 if !found_in_stdlib_prelude {
2093 self.lint_buffer().buffer_lint(
2094 PRIVATE_MACRO_USE,
2095 import.root_id,
2096 ident.span,
2097 errors::MacroIsPrivate { ident },
2098 );
2099 }
2100 }
2101 if used == Used::Scope
2104 && let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident))
2105 && entry.item_binding == Some((used_binding, false))
2106 {
2107 return;
2108 }
2109 let old_used = self.import_use_map.entry(import).or_insert(used);
2110 if *old_used < used {
2111 *old_used = used;
2112 }
2113 if let Some(id) = import.id() {
2114 self.used_imports.insert(id);
2115 }
2116 self.add_to_glob_map(import, ident);
2117 self.record_use_inner(
2118 ident,
2119 binding,
2120 Used::Other,
2121 warn_ambiguity || binding.warn_ambiguity,
2122 );
2123 }
2124 }
2125
2126 #[inline]
2127 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2128 if let ImportKind::Glob { id, .. } = import.kind {
2129 let def_id = self.local_def_id(id);
2130 self.glob_map.entry(def_id).or_default().insert(ident.name);
2131 }
2132 }
2133
2134 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2135 debug!("resolve_crate_root({:?})", ident);
2136 let mut ctxt = ident.span.ctxt();
2137 let mark = if ident.name == kw::DollarCrate {
2138 ctxt = ctxt.normalize_to_macro_rules();
2145 debug!(
2146 "resolve_crate_root: marks={:?}",
2147 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2148 );
2149 let mut iter = ctxt.marks().into_iter().rev().peekable();
2150 let mut result = None;
2151 while let Some(&(mark, transparency)) = iter.peek() {
2153 if transparency == Transparency::Opaque {
2154 result = Some(mark);
2155 iter.next();
2156 } else {
2157 break;
2158 }
2159 }
2160 debug!(
2161 "resolve_crate_root: found opaque mark {:?} {:?}",
2162 result,
2163 result.map(|r| r.expn_data())
2164 );
2165 for (mark, transparency) in iter {
2167 if transparency == Transparency::SemiOpaque {
2168 result = Some(mark);
2169 } else {
2170 break;
2171 }
2172 }
2173 debug!(
2174 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2175 result,
2176 result.map(|r| r.expn_data())
2177 );
2178 result
2179 } else {
2180 debug!("resolve_crate_root: not DollarCrate");
2181 ctxt = ctxt.normalize_to_macros_2_0();
2182 ctxt.adjust(ExpnId::root())
2183 };
2184 let module = match mark {
2185 Some(def) => self.expn_def_scope(def),
2186 None => {
2187 debug!(
2188 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2189 ident, ident.span
2190 );
2191 return self.graph_root;
2192 }
2193 };
2194 let module = self.expect_module(
2195 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2196 );
2197 debug!(
2198 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2199 ident,
2200 module,
2201 module.kind.name(),
2202 ident.span
2203 );
2204 module
2205 }
2206
2207 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2208 let mut module = self.expect_module(module.nearest_parent_mod());
2209 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2210 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2211 module = self.expect_module(parent.nearest_parent_mod());
2212 }
2213 module
2214 }
2215
2216 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2217 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2218 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2219 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2220 }
2221 }
2222
2223 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2224 debug!("(recording pat) recording {:?} for {:?}", node, span);
2225 self.pat_span_map.insert(node, span);
2226 }
2227
2228 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2229 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2230 }
2231
2232 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2233 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2234 if module != old_module {
2235 span_bug!(binding.span, "parent module is reset for binding");
2236 }
2237 }
2238 }
2239
2240 fn disambiguate_macro_rules_vs_modularized(
2241 &self,
2242 macro_rules: NameBinding<'ra>,
2243 modularized: NameBinding<'ra>,
2244 ) -> bool {
2245 let macro_rules = &self.binding_parent_modules[¯o_rules];
2253 let modularized = &self.binding_parent_modules[&modularized];
2254 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2255 && modularized.is_ancestor_of(*macro_rules)
2256 }
2257
2258 fn extern_prelude_get_item<'r>(
2259 mut self: CmResolver<'r, 'ra, 'tcx>,
2260 ident: Ident,
2261 finalize: bool,
2262 ) -> Option<NameBinding<'ra>> {
2263 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2264 entry.and_then(|entry| entry.item_binding).map(|(binding, _)| {
2265 if finalize {
2266 self.get_mut().record_use(ident, binding, Used::Scope);
2267 }
2268 binding
2269 })
2270 }
2271
2272 fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2273 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2274 entry.and_then(|entry| entry.flag_binding.as_ref()).and_then(|flag_binding| {
2275 let (pending_binding, finalized) = flag_binding.get();
2276 let binding = match pending_binding {
2277 PendingBinding::Ready(binding) => {
2278 if finalize && !finalized {
2279 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2280 }
2281 binding
2282 }
2283 PendingBinding::Pending => {
2284 debug_assert!(!finalized);
2285 let crate_id = if finalize {
2286 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2287 } else {
2288 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2289 };
2290 crate_id.map(|crate_id| {
2291 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2292 self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT)
2293 })
2294 }
2295 };
2296 flag_binding.set((PendingBinding::Ready(binding), finalize || finalized));
2297 binding.or_else(|| finalize.then_some(self.dummy_binding))
2298 })
2299 }
2300
2301 fn resolve_rustdoc_path(
2306 &mut self,
2307 path_str: &str,
2308 ns: Namespace,
2309 parent_scope: ParentScope<'ra>,
2310 ) -> Option<Res> {
2311 let segments: Result<Vec<_>, ()> = path_str
2312 .split("::")
2313 .enumerate()
2314 .map(|(i, s)| {
2315 let sym = if s.is_empty() {
2316 if i == 0 {
2317 kw::PathRoot
2319 } else {
2320 return Err(()); }
2322 } else {
2323 Symbol::intern(s)
2324 };
2325 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2326 })
2327 .collect();
2328 let Ok(segments) = segments else { return None };
2329
2330 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2331 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2332 PathResult::NonModule(path_res) => {
2333 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2334 }
2335 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2336 None
2337 }
2338 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2339 }
2340 }
2341
2342 fn def_span(&self, def_id: DefId) -> Span {
2344 match def_id.as_local() {
2345 Some(def_id) => self.tcx.source_span(def_id),
2346 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2348 }
2349 }
2350
2351 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2352 match def_id.as_local() {
2353 Some(def_id) => self.field_names.get(&def_id).cloned(),
2354 None if matches!(
2355 self.tcx.def_kind(def_id),
2356 DefKind::Struct | DefKind::Union | DefKind::Variant
2357 ) =>
2358 {
2359 Some(
2360 self.tcx
2361 .associated_item_def_ids(def_id)
2362 .iter()
2363 .map(|&def_id| {
2364 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2365 })
2366 .collect(),
2367 )
2368 }
2369 _ => None,
2370 }
2371 }
2372
2373 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2374 match def_id.as_local() {
2375 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2376 None if matches!(
2377 self.tcx.def_kind(def_id),
2378 DefKind::Struct | DefKind::Union | DefKind::Variant
2379 ) =>
2380 {
2381 Some(
2382 self.tcx
2383 .associated_item_def_ids(def_id)
2384 .iter()
2385 .filter_map(|&def_id| {
2386 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2387 })
2388 .collect(),
2389 )
2390 }
2391 _ => None,
2392 }
2393 }
2394
2395 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2399 if let ExprKind::Path(None, path) = &expr.kind {
2400 if path.segments.last().unwrap().args.is_some() {
2403 return None;
2404 }
2405
2406 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2407 if let Res::Def(def::DefKind::Fn, def_id) = res {
2408 if def_id.is_local() {
2412 return None;
2413 }
2414
2415 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2416 return v.clone();
2417 }
2418
2419 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2420 let mut ret = Vec::new();
2421 for meta in attr.meta_item_list()? {
2422 match meta.lit()?.kind {
2423 LitKind::Int(a, _) => ret.push(a.get() as usize),
2424 _ => panic!("invalid arg index"),
2425 }
2426 }
2427 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2429 return Some(ret);
2430 }
2431 }
2432 None
2433 }
2434
2435 fn resolve_main(&mut self) {
2436 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2437 if !any_exe {
2439 return;
2440 }
2441
2442 let module = self.graph_root;
2443 let ident = Ident::with_dummy_span(sym::main);
2444 let parent_scope = &ParentScope::module(module, self.arenas);
2445
2446 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2447 ModuleOrUniformRoot::Module(module),
2448 ident,
2449 ValueNS,
2450 parent_scope,
2451 None,
2452 ) else {
2453 return;
2454 };
2455
2456 let res = name_binding.res();
2457 let is_import = name_binding.is_import();
2458 let span = name_binding.span;
2459 if let Res::Def(DefKind::Fn, _) = res {
2460 self.record_use(ident, name_binding, Used::Other);
2461 }
2462 self.main_def = Some(MainDefinition { res, is_import, span });
2463 }
2464}
2465
2466fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2467 let mut result = String::new();
2468 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2469 if i > 0 {
2470 result.push_str("::");
2471 }
2472 if Ident::with_dummy_span(name).is_raw_guess() {
2473 result.push_str("r#");
2474 }
2475 result.push_str(name.as_str());
2476 }
2477 result
2478}
2479
2480fn path_names_to_string(path: &Path) -> String {
2481 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2482}
2483
2484fn module_to_string(mut module: Module<'_>) -> Option<String> {
2486 let mut names = Vec::new();
2487 loop {
2488 if let ModuleKind::Def(.., name) = module.kind {
2489 if let Some(parent) = module.parent {
2490 names.push(name.unwrap());
2492 module = parent
2493 } else {
2494 break;
2495 }
2496 } else {
2497 names.push(sym::opaque_module_name_placeholder);
2498 let Some(parent) = module.parent else {
2499 return None;
2500 };
2501 module = parent;
2502 }
2503 }
2504 if names.is_empty() {
2505 return None;
2506 }
2507 Some(names_to_string(names.iter().rev().copied()))
2508}
2509
2510#[derive(Copy, Clone, PartialEq, Debug)]
2511enum Stage {
2512 Early,
2516 Late,
2519}
2520
2521#[derive(Copy, Clone, Debug)]
2523struct Finalize {
2524 node_id: NodeId,
2526 path_span: Span,
2529 root_span: Span,
2532 report_private: bool = true,
2535 used: Used = Used::Other,
2537 stage: Stage = Stage::Early,
2539}
2540
2541impl Finalize {
2542 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2543 Finalize::with_root_span(node_id, path_span, path_span)
2544 }
2545
2546 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2547 Finalize { node_id, path_span, root_span, .. }
2548 }
2549}
2550
2551pub fn provide(providers: &mut Providers) {
2552 providers.registered_tools = macros::registered_tools;
2553}
2554
2555type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2561
2562use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2566
2567mod ref_mut {
2570 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2571 use std::fmt;
2572 use std::ops::Deref;
2573
2574 use crate::Resolver;
2575
2576 pub(crate) struct RefOrMut<'a, T> {
2578 p: &'a mut T,
2579 mutable: bool,
2580 }
2581
2582 impl<'a, T> Deref for RefOrMut<'a, T> {
2583 type Target = T;
2584
2585 fn deref(&self) -> &Self::Target {
2586 self.p
2587 }
2588 }
2589
2590 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2591 fn as_ref(&self) -> &T {
2592 self.p
2593 }
2594 }
2595
2596 impl<'a, T> RefOrMut<'a, T> {
2597 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2598 RefOrMut { p, mutable }
2599 }
2600
2601 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2603 RefOrMut { p: self.p, mutable: self.mutable }
2604 }
2605
2606 #[track_caller]
2611 pub(crate) fn get_mut(&mut self) -> &mut T {
2612 match self.mutable {
2613 false => panic!("Can't mutably borrow speculative resolver"),
2614 true => self.p,
2615 }
2616 }
2617
2618 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2621 self.p
2622 }
2623 }
2624
2625 #[derive(Default)]
2627 pub(crate) struct CmCell<T>(Cell<T>);
2628
2629 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2631 f.debug_tuple("CmCell").field(&self.get()).finish()
2632 }
2633 }
2634
2635 impl<T: Copy> Clone for CmCell<T> {
2636 fn clone(&self) -> CmCell<T> {
2637 CmCell::new(self.get())
2638 }
2639 }
2640
2641 impl<T: Copy> CmCell<T> {
2642 pub(crate) const fn get(&self) -> T {
2643 self.0.get()
2644 }
2645
2646 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2647 where
2648 T: Copy,
2649 {
2650 let old = self.get();
2651 self.set_unchecked(f(old));
2652 }
2653 }
2654
2655 impl<T> CmCell<T> {
2656 pub(crate) const fn new(value: T) -> CmCell<T> {
2657 CmCell(Cell::new(value))
2658 }
2659
2660 pub(crate) fn set_unchecked(&self, val: T) {
2661 self.0.set(val);
2662 }
2663
2664 pub(crate) fn into_inner(self) -> T {
2665 self.0.into_inner()
2666 }
2667 }
2668
2669 #[derive(Default)]
2671 pub(crate) struct CmRefCell<T>(RefCell<T>);
2672
2673 impl<T> CmRefCell<T> {
2674 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2675 CmRefCell(RefCell::new(value))
2676 }
2677
2678 #[track_caller]
2679 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2680 self.0.borrow_mut()
2681 }
2682
2683 #[track_caller]
2684 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2685 if r.assert_speculative {
2686 panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2687 }
2688 self.borrow_mut_unchecked()
2689 }
2690
2691 #[track_caller]
2692 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2693 self.0.try_borrow_mut()
2694 }
2695
2696 #[track_caller]
2697 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2698 self.0.borrow()
2699 }
2700 }
2701
2702 impl<T: Default> CmRefCell<T> {
2703 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2704 if r.assert_speculative {
2705 panic!("Not allowed to mutate a CmRefCell during speculative resolution");
2706 }
2707 self.0.take()
2708 }
2709 }
2710}