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