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(control_flow_into_value)]
17#![feature(decl_macro)]
18#![feature(default_field_values)]
19#![feature(if_let_guard)]
20#![feature(iter_intersperse)]
21#![feature(ptr_as_ref_unchecked)]
22#![feature(rustc_attrs)]
23#![feature(trim_prefix_suffix)]
24#![recursion_limit = "256"]
25use std::cell::Ref;
28use std::collections::BTreeSet;
29use std::fmt::{self};
30use std::ops::ControlFlow;
31use std::sync::Arc;
32
33use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
34use effective_visibilities::EffectiveVisibilitiesVisitor;
35use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
36use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
37use late::{
38 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
39 UnnecessaryQualification,
40};
41use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
42use rustc_arena::{DroplessArena, TypedArena};
43use rustc_ast::node_id::NodeMap;
44use rustc_ast::{
45 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
46 NodeId, Path, attr,
47};
48use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
49use rustc_data_structures::intern::Interned;
50use rustc_data_structures::steal::Steal;
51use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
52use rustc_data_structures::unord::{UnordMap, UnordSet};
53use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
54use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
55use rustc_feature::BUILTIN_ATTRIBUTES;
56use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
57use rustc_hir::def::Namespace::{self, *};
58use rustc_hir::def::{
59 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
60 PerNS,
61};
62use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
63use rustc_hir::definitions::DisambiguatorState;
64use rustc_hir::{PrimTy, TraitCandidate, find_attr};
65use rustc_index::bit_set::DenseBitSet;
66use rustc_metadata::creader::CStore;
67use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
68use rustc_middle::middle::privacy::EffectiveVisibilities;
69use rustc_middle::query::Providers;
70use rustc_middle::span_bug;
71use rustc_middle::ty::{
72 self, DelegationFnSig, DelegationInfo, Feed, MainDefinition, RegisteredTools,
73 ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
74};
75use rustc_query_system::ich::StableHashingContext;
76use rustc_session::config::CrateType;
77use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
78use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
79use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
80use smallvec::{SmallVec, smallvec};
81use tracing::debug;
82
83type Res = def::Res<NodeId>;
84
85mod build_reduced_graph;
86mod check_unused;
87mod def_collector;
88mod diagnostics;
89mod effective_visibilities;
90mod errors;
91mod ident;
92mod imports;
93mod late;
94mod macros;
95pub mod rustdoc;
96
97pub use macros::registered_tools_ast;
98
99use crate::ref_mut::{CmCell, CmRefCell};
100
101rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
102
103#[derive(Copy, Clone, PartialEq, Debug)]
104enum Determinacy {
105 Determined,
106 Undetermined,
107}
108
109impl Determinacy {
110 fn determined(determined: bool) -> Determinacy {
111 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
112 }
113}
114
115#[derive(Clone, Copy, Debug)]
117enum Scope<'ra> {
118 DeriveHelpers(LocalExpnId),
120 DeriveHelpersCompat,
124 MacroRules(MacroRulesScopeRef<'ra>),
126 ModuleNonGlobs(Module<'ra>, Option<NodeId>),
130 ModuleGlobs(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 Module(Namespace, Module<'ra>),
158 ModuleAndExternPrelude(Namespace, Module<'ra>),
160 ExternPrelude,
162 Macro(MacroKind),
164}
165
166#[derive(Clone, Copy, Debug)]
171struct ParentScope<'ra> {
172 module: Module<'ra>,
173 expansion: LocalExpnId,
174 macro_rules: MacroRulesScopeRef<'ra>,
175 derives: &'ra [ast::Path],
176}
177
178impl<'ra> ParentScope<'ra> {
179 fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
182 ParentScope {
183 module,
184 expansion: LocalExpnId::ROOT,
185 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
186 derives: &[],
187 }
188 }
189}
190
191#[derive(Copy, Debug, Clone)]
192struct InvocationParent {
193 parent_def: LocalDefId,
194 impl_trait_context: ImplTraitContext,
195 in_attr: bool,
196 const_arg_context: ConstArgContext,
197}
198
199impl InvocationParent {
200 const ROOT: Self = Self {
201 parent_def: CRATE_DEF_ID,
202 impl_trait_context: ImplTraitContext::Existential,
203 in_attr: false,
204 const_arg_context: ConstArgContext::NonDirect,
205 };
206}
207
208#[derive(Copy, Debug, Clone)]
209enum ImplTraitContext {
210 Existential,
211 Universal,
212 InBinding,
213}
214
215#[derive(Copy, Clone, Debug)]
216enum ConstArgContext {
217 Direct,
218 NonDirect,
220}
221
222#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
237enum Used {
238 Scope,
239 Other,
240}
241
242#[derive(Debug)]
243struct BindingError {
244 name: Ident,
245 origin: Vec<(Span, ast::Pat)>,
246 target: Vec<ast::Pat>,
247 could_be_path: bool,
248}
249
250#[derive(Debug)]
251enum ResolutionError<'ra> {
252 GenericParamsFromOuterItem {
254 outer_res: Res,
255 has_generic_params: HasGenericParams,
256 def_kind: DefKind,
257 inner_item: Option<(Span, ast::ItemKind)>,
258 current_self_ty: Option<String>,
259 },
260 NameAlreadyUsedInParameterList(Ident, Span),
263 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
265 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
267 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
269 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
271 VariableBoundWithDifferentMode(Ident, Span),
273 IdentifierBoundMoreThanOnceInParameterList(Ident),
275 IdentifierBoundMoreThanOnceInSamePattern(Ident),
277 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
279 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
281 SelfImportCanOnlyAppearOnceInTheList,
283 SelfImportOnlyInImportListWithNonEmptyPrefix,
285 FailedToResolve {
287 segment: Option<Symbol>,
288 label: String,
289 suggestion: Option<Suggestion>,
290 module: Option<ModuleOrUniformRoot<'ra>>,
291 },
292 CannotCaptureDynamicEnvironmentInFnItem,
294 AttemptToUseNonConstantValueInConstant {
296 ident: Ident,
297 suggestion: &'static str,
298 current: &'static str,
299 type_span: Option<Span>,
300 },
301 BindingShadowsSomethingUnacceptable {
303 shadowing_binding: PatternSource,
304 name: Symbol,
305 participle: &'static str,
306 article: &'static str,
307 shadowed_binding: Res,
308 shadowed_binding_span: Span,
309 },
310 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
312 ParamInTyOfConstParam { name: Symbol },
316 ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
320 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
324 ForwardDeclaredSelf(ForwardGenericParamBanReason),
326 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
328 TraitImplMismatch {
330 name: Ident,
331 kind: &'static str,
332 trait_path: String,
333 trait_item_span: Span,
334 code: ErrCode,
335 },
336 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
338 InvalidAsmSym,
340 LowercaseSelf,
342 BindingInNeverPattern,
344}
345
346enum VisResolutionError<'a> {
347 Relative2018(Span, &'a ast::Path),
348 AncestorOnly(Span),
349 FailedToResolve(Span, String, Option<Suggestion>),
350 ExpectedFound(Span, String, Res),
351 Indeterminate(Span),
352 ModuleOnly(Span),
353}
354
355#[derive(Clone, Copy, Debug)]
358struct Segment {
359 ident: Ident,
360 id: Option<NodeId>,
361 has_generic_args: bool,
364 has_lifetime_args: bool,
366 args_span: Span,
367}
368
369impl Segment {
370 fn from_path(path: &Path) -> Vec<Segment> {
371 path.segments.iter().map(|s| s.into()).collect()
372 }
373
374 fn from_ident(ident: Ident) -> Segment {
375 Segment {
376 ident,
377 id: None,
378 has_generic_args: false,
379 has_lifetime_args: false,
380 args_span: DUMMY_SP,
381 }
382 }
383
384 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
385 Segment {
386 ident,
387 id: Some(id),
388 has_generic_args: false,
389 has_lifetime_args: false,
390 args_span: DUMMY_SP,
391 }
392 }
393
394 fn names_to_string(segments: &[Segment]) -> String {
395 names_to_string(segments.iter().map(|seg| seg.ident.name))
396 }
397}
398
399impl<'a> From<&'a ast::PathSegment> for Segment {
400 fn from(seg: &'a ast::PathSegment) -> Segment {
401 let has_generic_args = seg.args.is_some();
402 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
403 match args {
404 GenericArgs::AngleBracketed(args) => {
405 let found_lifetimes = args
406 .args
407 .iter()
408 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
409 (args.span, found_lifetimes)
410 }
411 GenericArgs::Parenthesized(args) => (args.span, true),
412 GenericArgs::ParenthesizedElided(span) => (*span, true),
413 }
414 } else {
415 (DUMMY_SP, false)
416 };
417 Segment {
418 ident: seg.ident,
419 id: Some(seg.id),
420 has_generic_args,
421 has_lifetime_args,
422 args_span,
423 }
424 }
425}
426
427#[derive(Debug, Copy, Clone)]
429enum LateDecl<'ra> {
430 Decl(Decl<'ra>),
432 RibDef(Res),
435}
436
437impl<'ra> LateDecl<'ra> {
438 fn res(self) -> Res {
439 match self {
440 LateDecl::Decl(binding) => binding.res(),
441 LateDecl::RibDef(res) => res,
442 }
443 }
444}
445
446#[derive(Copy, Clone, PartialEq, Debug)]
447enum ModuleOrUniformRoot<'ra> {
448 Module(Module<'ra>),
450
451 ModuleAndExternPrelude(Module<'ra>),
455
456 ExternPrelude,
459
460 CurrentScope,
464}
465
466#[derive(Debug)]
467enum PathResult<'ra> {
468 Module(ModuleOrUniformRoot<'ra>),
469 NonModule(PartialRes),
470 Indeterminate,
471 Failed {
472 span: Span,
473 label: String,
474 suggestion: Option<Suggestion>,
475 is_error_from_last_segment: bool,
476 module: Option<ModuleOrUniformRoot<'ra>>,
490 segment_name: Symbol,
492 error_implied_by_parse_error: bool,
493 },
494}
495
496impl<'ra> PathResult<'ra> {
497 fn failed(
498 ident: Ident,
499 is_error_from_last_segment: bool,
500 finalize: bool,
501 error_implied_by_parse_error: bool,
502 module: Option<ModuleOrUniformRoot<'ra>>,
503 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
504 ) -> PathResult<'ra> {
505 let (label, suggestion) =
506 if finalize { label_and_suggestion() } else { (String::new(), None) };
507 PathResult::Failed {
508 span: ident.span,
509 segment_name: ident.name,
510 label,
511 suggestion,
512 is_error_from_last_segment,
513 module,
514 error_implied_by_parse_error,
515 }
516 }
517}
518
519#[derive(Debug)]
520enum ModuleKind {
521 Block,
534 Def(DefKind, DefId, Option<Symbol>),
544}
545
546impl ModuleKind {
547 fn name(&self) -> Option<Symbol> {
549 match *self {
550 ModuleKind::Block => None,
551 ModuleKind::Def(.., name) => name,
552 }
553 }
554}
555
556#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
561struct BindingKey {
562 ident: Macros20NormalizedIdent,
565 ns: Namespace,
566 disambiguator: u32,
572}
573
574impl BindingKey {
575 fn new(ident: Macros20NormalizedIdent, ns: Namespace) -> Self {
576 BindingKey { ident, ns, disambiguator: 0 }
577 }
578
579 fn new_disambiguated(
580 ident: Macros20NormalizedIdent,
581 ns: Namespace,
582 disambiguator: impl FnOnce() -> u32,
583 ) -> BindingKey {
584 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
585 BindingKey { ident, ns, disambiguator }
586 }
587}
588
589type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
590
591struct ModuleData<'ra> {
603 parent: Option<Module<'ra>>,
605 kind: ModuleKind,
607
608 lazy_resolutions: Resolutions<'ra>,
611 populate_on_access: CacheCell<bool>,
613 underscore_disambiguator: CmCell<u32>,
615
616 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
618
619 no_implicit_prelude: bool,
621
622 glob_importers: CmRefCell<Vec<Import<'ra>>>,
623 globs: CmRefCell<Vec<Import<'ra>>>,
624
625 traits: CmRefCell<Option<Box<[(Macros20NormalizedIdent, Decl<'ra>, Option<Module<'ra>>)]>>>,
627
628 span: Span,
630
631 expansion: ExpnId,
632
633 self_decl: Option<Decl<'ra>>,
636}
637
638#[derive(Clone, Copy, PartialEq, Eq, Hash)]
641#[rustc_pass_by_value]
642struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
643
644impl std::hash::Hash for ModuleData<'_> {
649 fn hash<H>(&self, _: &mut H)
650 where
651 H: std::hash::Hasher,
652 {
653 unreachable!()
654 }
655}
656
657impl<'ra> ModuleData<'ra> {
658 fn new(
659 parent: Option<Module<'ra>>,
660 kind: ModuleKind,
661 expansion: ExpnId,
662 span: Span,
663 no_implicit_prelude: bool,
664 self_decl: Option<Decl<'ra>>,
665 ) -> Self {
666 let is_foreign = match kind {
667 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
668 ModuleKind::Block => false,
669 };
670 ModuleData {
671 parent,
672 kind,
673 lazy_resolutions: Default::default(),
674 populate_on_access: CacheCell::new(is_foreign),
675 underscore_disambiguator: CmCell::new(0),
676 unexpanded_invocations: Default::default(),
677 no_implicit_prelude,
678 glob_importers: CmRefCell::new(Vec::new()),
679 globs: CmRefCell::new(Vec::new()),
680 traits: CmRefCell::new(None),
681 span,
682 expansion,
683 self_decl,
684 }
685 }
686}
687
688impl<'ra> Module<'ra> {
689 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
690 self,
691 resolver: &R,
692 mut f: impl FnMut(&R, Macros20NormalizedIdent, Namespace, Decl<'ra>),
693 ) {
694 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
695 if let Some(decl) = name_resolution.borrow().best_decl() {
696 f(resolver, key.ident, key.ns, decl);
697 }
698 }
699 }
700
701 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
702 self,
703 resolver: &mut R,
704 mut f: impl FnMut(&mut R, Macros20NormalizedIdent, Namespace, Decl<'ra>),
705 ) {
706 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
707 if let Some(decl) = name_resolution.borrow().best_decl() {
708 f(resolver, key.ident, key.ns, decl);
709 }
710 }
711 }
712
713 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
715 let mut traits = self.traits.borrow_mut(resolver.as_ref());
716 if traits.is_none() {
717 let mut collected_traits = Vec::new();
718 self.for_each_child(resolver, |r, name, ns, binding| {
719 if ns != TypeNS {
720 return;
721 }
722 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
723 collected_traits.push((name, binding, r.as_ref().get_module(def_id)))
724 }
725 });
726 *traits = Some(collected_traits.into_boxed_slice());
727 }
728 }
729
730 fn res(self) -> Option<Res> {
731 match self.kind {
732 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
733 _ => None,
734 }
735 }
736
737 fn def_id(self) -> DefId {
738 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
739 }
740
741 fn opt_def_id(self) -> Option<DefId> {
742 match self.kind {
743 ModuleKind::Def(_, def_id, _) => Some(def_id),
744 _ => None,
745 }
746 }
747
748 fn is_normal(self) -> bool {
750 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
751 }
752
753 fn is_trait(self) -> bool {
754 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
755 }
756
757 fn nearest_item_scope(self) -> Module<'ra> {
758 match self.kind {
759 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
760 self.parent.expect("enum or trait module without a parent")
761 }
762 _ => self,
763 }
764 }
765
766 fn nearest_parent_mod(self) -> DefId {
769 match self.kind {
770 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
771 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
772 }
773 }
774
775 fn is_ancestor_of(self, mut other: Self) -> bool {
776 while self != other {
777 if let Some(parent) = other.parent {
778 other = parent;
779 } else {
780 return false;
781 }
782 }
783 true
784 }
785}
786
787impl<'ra> std::ops::Deref for Module<'ra> {
788 type Target = ModuleData<'ra>;
789
790 fn deref(&self) -> &Self::Target {
791 &self.0
792 }
793}
794
795impl<'ra> fmt::Debug for Module<'ra> {
796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797 match self.kind {
798 ModuleKind::Block => write!(f, "block"),
799 ModuleKind::Def(..) => write!(f, "{:?}", self.res()),
800 }
801 }
802}
803
804#[derive(Clone, Debug)]
806struct DeclData<'ra> {
807 kind: DeclKind<'ra>,
808 ambiguity: CmCell<Option<Decl<'ra>>>,
809 warn_ambiguity: CmCell<bool>,
812 expansion: LocalExpnId,
813 span: Span,
814 vis: CmCell<Visibility<DefId>>,
815}
816
817type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
820
821impl std::hash::Hash for DeclData<'_> {
826 fn hash<H>(&self, _: &mut H)
827 where
828 H: std::hash::Hasher,
829 {
830 unreachable!()
831 }
832}
833
834#[derive(Clone, Copy, Debug)]
836enum DeclKind<'ra> {
837 Def(Res),
840 Import { source_decl: Decl<'ra>, import: Import<'ra> },
842}
843
844impl<'ra> DeclKind<'ra> {
845 fn is_import(&self) -> bool {
847 matches!(*self, DeclKind::Import { .. })
848 }
849}
850
851#[derive(Debug)]
852struct PrivacyError<'ra> {
853 ident: Ident,
854 decl: Decl<'ra>,
855 dedup_span: Span,
856 outermost_res: Option<(Res, Ident)>,
857 parent_scope: ParentScope<'ra>,
858 single_nested: bool,
860 source: Option<ast::Expr>,
861}
862
863#[derive(Debug)]
864struct UseError<'a> {
865 err: Diag<'a>,
866 candidates: Vec<ImportSuggestion>,
868 def_id: DefId,
870 instead: bool,
872 suggestion: Option<(Span, &'static str, String, Applicability)>,
874 path: Vec<Segment>,
877 is_call: bool,
879}
880
881#[derive(Clone, Copy, PartialEq, Debug)]
882enum AmbiguityKind {
883 BuiltinAttr,
884 DeriveHelper,
885 MacroRulesVsModularized,
886 GlobVsOuter,
887 GlobVsGlob,
888 GlobVsExpanded,
889 MoreExpandedVsOuter,
890}
891
892impl AmbiguityKind {
893 fn descr(self) -> &'static str {
894 match self {
895 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
896 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
897 AmbiguityKind::MacroRulesVsModularized => {
898 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
899 }
900 AmbiguityKind::GlobVsOuter => {
901 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
902 }
903 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
904 AmbiguityKind::GlobVsExpanded => {
905 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
906 }
907 AmbiguityKind::MoreExpandedVsOuter => {
908 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
909 }
910 }
911 }
912}
913
914struct AmbiguityError<'ra> {
915 kind: AmbiguityKind,
916 ident: Ident,
917 b1: Decl<'ra>,
918 b2: Decl<'ra>,
919 scope1: Scope<'ra>,
921 scope2: Scope<'ra>,
922 warning: bool,
923}
924
925impl<'ra> DeclData<'ra> {
926 fn vis(&self) -> Visibility<DefId> {
927 self.vis.get()
928 }
929
930 fn res(&self) -> Res {
931 match self.kind {
932 DeclKind::Def(res) => res,
933 DeclKind::Import { source_decl, .. } => source_decl.res(),
934 }
935 }
936
937 fn import_source(&self) -> Decl<'ra> {
938 match self.kind {
939 DeclKind::Import { source_decl, .. } => source_decl,
940 _ => unreachable!(),
941 }
942 }
943
944 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
945 match self.ambiguity.get() {
946 Some(ambig_binding) => Some((self, ambig_binding)),
947 None => match self.kind {
948 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
949 _ => None,
950 },
951 }
952 }
953
954 fn is_ambiguity_recursive(&self) -> bool {
955 self.ambiguity.get().is_some()
956 || match self.kind {
957 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
958 _ => false,
959 }
960 }
961
962 fn warn_ambiguity_recursive(&self) -> bool {
963 self.warn_ambiguity.get()
964 || match self.kind {
965 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
966 _ => false,
967 }
968 }
969
970 fn is_possibly_imported_variant(&self) -> bool {
971 match self.kind {
972 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
973 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
974 true
975 }
976 DeclKind::Def(..) => false,
977 }
978 }
979
980 fn is_extern_crate(&self) -> bool {
981 match self.kind {
982 DeclKind::Import { import, .. } => {
983 matches!(import.kind, ImportKind::ExternCrate { .. })
984 }
985 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
986 _ => false,
987 }
988 }
989
990 fn is_import(&self) -> bool {
991 matches!(self.kind, DeclKind::Import { .. })
992 }
993
994 fn is_import_user_facing(&self) -> bool {
997 matches!(self.kind, DeclKind::Import { import, .. }
998 if !matches!(import.kind, ImportKind::MacroExport))
999 }
1000
1001 fn is_glob_import(&self) -> bool {
1002 match self.kind {
1003 DeclKind::Import { import, .. } => import.is_glob(),
1004 _ => false,
1005 }
1006 }
1007
1008 fn is_assoc_item(&self) -> bool {
1009 matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
1010 }
1011
1012 fn macro_kinds(&self) -> Option<MacroKinds> {
1013 self.res().macro_kinds()
1014 }
1015
1016 fn reexport_chain(self: Decl<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1017 let mut reexport_chain = SmallVec::new();
1018 let mut next_binding = self;
1019 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1020 reexport_chain.push(import.simplify(r));
1021 next_binding = source_decl;
1022 }
1023 reexport_chain
1024 }
1025
1026 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1033 let self_parent_expansion = self.expansion;
1037 let other_parent_expansion = decl.expansion;
1038 let certainly_before_other_or_simultaneously =
1039 other_parent_expansion.is_descendant_of(self_parent_expansion);
1040 let certainly_before_invoc_or_simultaneously =
1041 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1042 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1043 }
1044
1045 fn determined(&self) -> bool {
1049 match &self.kind {
1050 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1051 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1052 && source_decl.determined()
1053 }
1054 _ => true,
1055 }
1056 }
1057}
1058
1059struct ExternPreludeEntry<'ra> {
1060 item_decl: Option<(Decl<'ra>, bool)>,
1064 flag_decl: Option<CacheCell<(PendingDecl<'ra>, bool)>>,
1066}
1067
1068impl ExternPreludeEntry<'_> {
1069 fn introduced_by_item(&self) -> bool {
1070 matches!(self.item_decl, Some((_, true)))
1071 }
1072
1073 fn flag() -> Self {
1074 ExternPreludeEntry {
1075 item_decl: None,
1076 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false))),
1077 }
1078 }
1079}
1080
1081struct DeriveData {
1082 resolutions: Vec<DeriveResolution>,
1083 helper_attrs: Vec<(usize, Macros20NormalizedIdent)>,
1084 has_derive_copy: bool,
1085}
1086
1087struct MacroData {
1088 ext: Arc<SyntaxExtension>,
1089 nrules: usize,
1090 macro_rules: bool,
1091}
1092
1093impl MacroData {
1094 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1095 MacroData { ext, nrules: 0, macro_rules: false }
1096 }
1097}
1098
1099pub struct ResolverOutputs {
1100 pub global_ctxt: ResolverGlobalCtxt,
1101 pub ast_lowering: ResolverAstLowering,
1102}
1103
1104pub struct Resolver<'ra, 'tcx> {
1108 tcx: TyCtxt<'tcx>,
1109
1110 expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1112
1113 graph_root: Module<'ra>,
1114
1115 assert_speculative: bool,
1117
1118 prelude: Option<Module<'ra>> = None,
1119 extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1120
1121 field_names: LocalDefIdMap<Vec<Ident>>,
1123 field_defaults: LocalDefIdMap<Vec<Symbol>>,
1124
1125 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1128
1129 determined_imports: Vec<Import<'ra>> = Vec::new(),
1131
1132 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1134
1135 pat_span_map: NodeMap<Span>,
1138
1139 partial_res_map: NodeMap<PartialRes>,
1141 import_res_map: NodeMap<PerNS<Option<Res>>>,
1143 import_use_map: FxHashMap<Import<'ra>, Used>,
1145 label_res_map: NodeMap<NodeId>,
1147 lifetimes_res_map: NodeMap<LifetimeRes>,
1149 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1151
1152 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1154 module_children: LocalDefIdMap<Vec<ModChild>>,
1155 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
1156 trait_map: NodeMap<Vec<TraitCandidate>>,
1157
1158 block_map: NodeMap<Module<'ra>>,
1173 empty_module: Module<'ra>,
1177 local_modules: Vec<Module<'ra>>,
1179 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1181 extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1183 decl_parent_modules: FxHashMap<Decl<'ra>, Module<'ra>>,
1184
1185 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1187 glob_error: Option<ErrorGuaranteed> = None,
1188 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1189 used_imports: FxHashSet<NodeId>,
1190 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1191
1192 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1194 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1196 issue_145575_hack_applied: bool = false,
1197 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1199 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1201
1202 inaccessible_ctor_reexport: FxHashMap<Span, Span>,
1206
1207 arenas: &'ra ResolverArenas<'ra>,
1208 dummy_decl: Decl<'ra>,
1209 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1210 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1211 registered_tool_decls: FxHashMap<Ident, Decl<'ra>>,
1212 macro_names: FxHashSet<Ident>,
1213 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1214 registered_tools: &'tcx RegisteredTools,
1215 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1216 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1218 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1220 dummy_ext_bang: Arc<SyntaxExtension>,
1221 dummy_ext_derive: Arc<SyntaxExtension>,
1222 non_macro_attr: &'ra MacroData,
1223 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1224 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1225 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1226 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1228 proc_macro_stubs: FxHashSet<LocalDefId>,
1229 single_segment_macro_resolutions:
1231 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1232 multi_segment_macro_resolutions:
1233 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1234 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1235 containers_deriving_copy: FxHashSet<LocalExpnId>,
1239 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1242 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1245 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1247 helper_attrs: FxHashMap<LocalExpnId, Vec<(Macros20NormalizedIdent, Decl<'ra>)>>,
1249 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1252
1253 name_already_seen: FxHashMap<Symbol, Span>,
1255
1256 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1257
1258 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1259
1260 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1264
1265 lint_buffer: LintBuffer,
1266
1267 next_node_id: NodeId = CRATE_NODE_ID,
1268
1269 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1270
1271 disambiguator: DisambiguatorState,
1272
1273 placeholder_field_indices: FxHashMap<NodeId, usize>,
1275 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1279
1280 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1282 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1283 delegation_infos: LocalDefIdMap<DelegationInfo>,
1284
1285 main_def: Option<MainDefinition> = None,
1286 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1287 proc_macros: Vec<LocalDefId> = Vec::new(),
1290 confused_type_with_std_module: FxIndexMap<Span, Span>,
1291 lifetime_elision_allowed: FxHashSet<NodeId>,
1293
1294 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1296
1297 effective_visibilities: EffectiveVisibilities,
1298 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1299 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1300 all_macro_rules: UnordSet<Symbol>,
1301
1302 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1304 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1307 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1310
1311 current_crate_outer_attr_insert_span: Span,
1314
1315 mods_with_parse_errors: FxHashSet<DefId>,
1316
1317 all_crate_macros_already_registered: bool = false,
1320
1321 impl_trait_names: FxHashMap<NodeId, Symbol>,
1325}
1326
1327#[derive(Default)]
1330pub struct ResolverArenas<'ra> {
1331 modules: TypedArena<ModuleData<'ra>>,
1332 imports: TypedArena<ImportData<'ra>>,
1333 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1334 ast_paths: TypedArena<ast::Path>,
1335 macros: TypedArena<MacroData>,
1336 dropless: DroplessArena,
1337}
1338
1339impl<'ra> ResolverArenas<'ra> {
1340 fn new_def_decl(
1341 &'ra self,
1342 res: Res,
1343 vis: Visibility<DefId>,
1344 span: Span,
1345 expansion: LocalExpnId,
1346 ) -> Decl<'ra> {
1347 self.alloc_decl(DeclData {
1348 kind: DeclKind::Def(res),
1349 ambiguity: CmCell::new(None),
1350 warn_ambiguity: CmCell::new(false),
1351 vis: CmCell::new(vis),
1352 span,
1353 expansion,
1354 })
1355 }
1356
1357 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1358 self.new_def_decl(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_decl = match kind {
1370 ModuleKind::Def(def_kind, def_id, _) => {
1371 Some(self.new_pub_def_decl(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_decl,
1382 ))))
1383 }
1384 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1385 Interned::new_unchecked(self.dropless.alloc(data))
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_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1397 self.dropless.alloc(decl)
1398 }
1399 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1400 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1401 }
1402 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1403 self.macros.alloc(macro_data)
1404 }
1405 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1406 self.dropless.alloc_from_iter(spans)
1407 }
1408}
1409
1410impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1411 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1412 self
1413 }
1414}
1415
1416impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1417 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1418 self
1419 }
1420}
1421
1422impl<'tcx> Resolver<'_, 'tcx> {
1423 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1424 self.opt_feed(node).map(|f| f.key())
1425 }
1426
1427 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1428 self.feed(node).key()
1429 }
1430
1431 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1432 self.node_id_to_def_id.get(&node).copied()
1433 }
1434
1435 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1436 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1437 }
1438
1439 fn local_def_kind(&self, node: NodeId) -> DefKind {
1440 self.tcx.def_kind(self.local_def_id(node))
1441 }
1442
1443 fn create_def(
1445 &mut self,
1446 parent: LocalDefId,
1447 node_id: ast::NodeId,
1448 name: Option<Symbol>,
1449 def_kind: DefKind,
1450 expn_id: ExpnId,
1451 span: Span,
1452 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1453 assert!(
1454 !self.node_id_to_def_id.contains_key(&node_id),
1455 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1456 node_id,
1457 name,
1458 def_kind,
1459 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1460 );
1461
1462 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1464 let def_id = feed.def_id();
1465
1466 if expn_id != ExpnId::root() {
1468 self.expn_that_defined.insert(def_id, expn_id);
1469 }
1470
1471 debug_assert_eq!(span.data_untracked().parent, None);
1473 let _id = self.tcx.untracked().source_span.push(span);
1474 debug_assert_eq!(_id, def_id);
1475
1476 if node_id != ast::DUMMY_NODE_ID {
1480 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1481 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1482 }
1483
1484 feed
1485 }
1486
1487 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1488 if let Some(def_id) = def_id.as_local() {
1489 self.item_generics_num_lifetimes[&def_id]
1490 } else {
1491 self.tcx.generics_of(def_id).own_counts().lifetimes
1492 }
1493 }
1494
1495 pub fn tcx(&self) -> TyCtxt<'tcx> {
1496 self.tcx
1497 }
1498
1499 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1504 self.node_id_to_def_id
1505 .items()
1506 .filter(|(_, v)| v.key() == def_id)
1507 .map(|(k, _)| *k)
1508 .get_only()
1509 .unwrap()
1510 }
1511}
1512
1513impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1514 pub fn new(
1515 tcx: TyCtxt<'tcx>,
1516 attrs: &[ast::Attribute],
1517 crate_span: Span,
1518 current_crate_outer_attr_insert_span: Span,
1519 arenas: &'ra ResolverArenas<'ra>,
1520 ) -> Resolver<'ra, 'tcx> {
1521 let root_def_id = CRATE_DEF_ID.to_def_id();
1522 let graph_root = arenas.new_module(
1523 None,
1524 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1525 ExpnId::root(),
1526 crate_span,
1527 attr::contains_name(attrs, sym::no_implicit_prelude),
1528 );
1529 let local_modules = vec![graph_root];
1530 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1531 let empty_module = arenas.new_module(
1532 None,
1533 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1534 ExpnId::root(),
1535 DUMMY_SP,
1536 true,
1537 );
1538
1539 let mut node_id_to_def_id = NodeMap::default();
1540 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1541
1542 crate_feed.def_kind(DefKind::Mod);
1543 let crate_feed = crate_feed.downgrade();
1544 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1545
1546 let mut invocation_parents = FxHashMap::default();
1547 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1548
1549 let mut extern_prelude: FxIndexMap<_, _> = tcx
1550 .sess
1551 .opts
1552 .externs
1553 .iter()
1554 .filter_map(|(name, entry)| {
1555 if entry.add_prelude
1558 && let name = Symbol::intern(name)
1559 && name.can_be_raw()
1560 {
1561 let ident = Macros20NormalizedIdent::with_dummy_span(name);
1562 Some((ident, ExternPreludeEntry::flag()))
1563 } else {
1564 None
1565 }
1566 })
1567 .collect();
1568
1569 if !attr::contains_name(attrs, sym::no_core) {
1570 let ident = Macros20NormalizedIdent::with_dummy_span(sym::core);
1571 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1572 if !attr::contains_name(attrs, sym::no_std) {
1573 let ident = Macros20NormalizedIdent::with_dummy_span(sym::std);
1574 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1575 }
1576 }
1577
1578 let registered_tools = tcx.registered_tools(());
1579 let edition = tcx.sess.edition();
1580
1581 let mut resolver = Resolver {
1582 tcx,
1583
1584 expn_that_defined: Default::default(),
1585
1586 graph_root,
1589 assert_speculative: false, prelude: None,
1591 extern_prelude,
1592
1593 field_names: Default::default(),
1594 field_defaults: Default::default(),
1595 field_visibility_spans: FxHashMap::default(),
1596
1597 pat_span_map: Default::default(),
1598 partial_res_map: Default::default(),
1599 import_res_map: Default::default(),
1600 import_use_map: Default::default(),
1601 label_res_map: Default::default(),
1602 lifetimes_res_map: Default::default(),
1603 extra_lifetime_params_map: Default::default(),
1604 extern_crate_map: Default::default(),
1605 module_children: Default::default(),
1606 ambig_module_children: Default::default(),
1607 trait_map: NodeMap::default(),
1608 empty_module,
1609 local_modules,
1610 local_module_map,
1611 extern_module_map: Default::default(),
1612 block_map: Default::default(),
1613 decl_parent_modules: FxHashMap::default(),
1614 ast_transform_scopes: FxHashMap::default(),
1615
1616 glob_map: Default::default(),
1617 used_imports: FxHashSet::default(),
1618 maybe_unused_trait_imports: Default::default(),
1619 inaccessible_ctor_reexport: Default::default(),
1620
1621 arenas,
1622 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1623 builtin_type_decls: PrimTy::ALL
1624 .iter()
1625 .map(|prim_ty| {
1626 let res = Res::PrimTy(*prim_ty);
1627 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1628 (prim_ty.name(), decl)
1629 })
1630 .collect(),
1631 builtin_attr_decls: BUILTIN_ATTRIBUTES
1632 .iter()
1633 .map(|builtin_attr| {
1634 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1635 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1636 (builtin_attr.name, decl)
1637 })
1638 .collect(),
1639 registered_tool_decls: registered_tools
1640 .iter()
1641 .map(|ident| {
1642 let res = Res::ToolMod;
1643 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1644 (*ident, decl)
1645 })
1646 .collect(),
1647 macro_names: FxHashSet::default(),
1648 builtin_macros: Default::default(),
1649 registered_tools,
1650 macro_use_prelude: Default::default(),
1651 local_macro_map: Default::default(),
1652 extern_macro_map: Default::default(),
1653 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1654 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1655 non_macro_attr: arenas
1656 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1657 invocation_parent_scopes: Default::default(),
1658 output_macro_rules_scopes: Default::default(),
1659 macro_rules_scopes: Default::default(),
1660 helper_attrs: Default::default(),
1661 derive_data: Default::default(),
1662 local_macro_def_scopes: FxHashMap::default(),
1663 name_already_seen: FxHashMap::default(),
1664 struct_constructors: Default::default(),
1665 unused_macros: Default::default(),
1666 unused_macro_rules: Default::default(),
1667 proc_macro_stubs: Default::default(),
1668 single_segment_macro_resolutions: Default::default(),
1669 multi_segment_macro_resolutions: Default::default(),
1670 builtin_attrs: Default::default(),
1671 containers_deriving_copy: Default::default(),
1672 lint_buffer: LintBuffer::default(),
1673 node_id_to_def_id,
1674 disambiguator: DisambiguatorState::new(),
1675 placeholder_field_indices: Default::default(),
1676 invocation_parents,
1677 item_generics_num_lifetimes: Default::default(),
1678 trait_impls: Default::default(),
1679 confused_type_with_std_module: Default::default(),
1680 lifetime_elision_allowed: Default::default(),
1681 stripped_cfg_items: Default::default(),
1682 effective_visibilities: Default::default(),
1683 doc_link_resolutions: Default::default(),
1684 doc_link_traits_in_scope: Default::default(),
1685 all_macro_rules: Default::default(),
1686 delegation_fn_sigs: Default::default(),
1687 glob_delegation_invoc_ids: Default::default(),
1688 impl_unexpanded_invocations: Default::default(),
1689 impl_binding_keys: Default::default(),
1690 current_crate_outer_attr_insert_span,
1691 mods_with_parse_errors: Default::default(),
1692 impl_trait_names: Default::default(),
1693 delegation_infos: Default::default(),
1694 ..
1695 };
1696
1697 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1698 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1699 resolver.feed_visibility(crate_feed, Visibility::Public);
1700
1701 resolver
1702 }
1703
1704 fn new_local_module(
1705 &mut self,
1706 parent: Option<Module<'ra>>,
1707 kind: ModuleKind,
1708 expn_id: ExpnId,
1709 span: Span,
1710 no_implicit_prelude: bool,
1711 ) -> Module<'ra> {
1712 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1713 self.local_modules.push(module);
1714 if let Some(def_id) = module.opt_def_id() {
1715 self.local_module_map.insert(def_id.expect_local(), module);
1716 }
1717 module
1718 }
1719
1720 fn new_extern_module(
1721 &self,
1722 parent: Option<Module<'ra>>,
1723 kind: ModuleKind,
1724 expn_id: ExpnId,
1725 span: Span,
1726 no_implicit_prelude: bool,
1727 ) -> Module<'ra> {
1728 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1729 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1730 module
1731 }
1732
1733 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1734 let mac = self.arenas.alloc_macro(macro_data);
1735 self.local_macro_map.insert(def_id, mac);
1736 mac
1737 }
1738
1739 fn next_node_id(&mut self) -> NodeId {
1740 let start = self.next_node_id;
1741 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1742 self.next_node_id = ast::NodeId::from_u32(next);
1743 start
1744 }
1745
1746 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1747 let start = self.next_node_id;
1748 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1749 self.next_node_id = ast::NodeId::from_usize(end);
1750 start..self.next_node_id
1751 }
1752
1753 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1754 &mut self.lint_buffer
1755 }
1756
1757 pub fn arenas() -> ResolverArenas<'ra> {
1758 Default::default()
1759 }
1760
1761 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1762 let feed = feed.upgrade(self.tcx);
1763 feed.visibility(vis.to_def_id());
1764 self.visibilities_for_hashing.push((feed.def_id(), vis));
1765 }
1766
1767 pub fn into_outputs(self) -> ResolverOutputs {
1768 let proc_macros = self.proc_macros;
1769 let expn_that_defined = self.expn_that_defined;
1770 let extern_crate_map = self.extern_crate_map;
1771 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1772 let glob_map = self.glob_map;
1773 let main_def = self.main_def;
1774 let confused_type_with_std_module = self.confused_type_with_std_module;
1775 let effective_visibilities = self.effective_visibilities;
1776
1777 let stripped_cfg_items = self
1778 .stripped_cfg_items
1779 .into_iter()
1780 .filter_map(|item| {
1781 let parent_module =
1782 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1783 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1784 })
1785 .collect();
1786
1787 let global_ctxt = ResolverGlobalCtxt {
1788 expn_that_defined,
1789 visibilities_for_hashing: self.visibilities_for_hashing,
1790 effective_visibilities,
1791 extern_crate_map,
1792 module_children: self.module_children,
1793 ambig_module_children: self.ambig_module_children,
1794 glob_map,
1795 maybe_unused_trait_imports,
1796 main_def,
1797 trait_impls: self.trait_impls,
1798 proc_macros,
1799 confused_type_with_std_module,
1800 doc_link_resolutions: self.doc_link_resolutions,
1801 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1802 all_macro_rules: self.all_macro_rules,
1803 stripped_cfg_items,
1804 };
1805 let ast_lowering = ty::ResolverAstLowering {
1806 partial_res_map: self.partial_res_map,
1807 import_res_map: self.import_res_map,
1808 label_res_map: self.label_res_map,
1809 lifetimes_res_map: self.lifetimes_res_map,
1810 extra_lifetime_params_map: self.extra_lifetime_params_map,
1811 next_node_id: self.next_node_id,
1812 node_id_to_def_id: self
1813 .node_id_to_def_id
1814 .into_items()
1815 .map(|(k, f)| (k, f.key()))
1816 .collect(),
1817 trait_map: self.trait_map,
1818 lifetime_elision_allowed: self.lifetime_elision_allowed,
1819 lint_buffer: Steal::new(self.lint_buffer),
1820 delegation_fn_sigs: self.delegation_fn_sigs,
1821 delegation_infos: self.delegation_infos,
1822 };
1823 ResolverOutputs { global_ctxt, ast_lowering }
1824 }
1825
1826 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1827 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1828 }
1829
1830 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1831 CStore::from_tcx(self.tcx)
1832 }
1833
1834 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1835 CStore::from_tcx_mut(self.tcx)
1836 }
1837
1838 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1839 match macro_kind {
1840 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1841 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1842 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1843 }
1844 }
1845
1846 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1851 CmResolver::new(self, !self.assert_speculative)
1852 }
1853
1854 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1856 f(self, TypeNS);
1857 f(self, ValueNS);
1858 f(self, MacroNS);
1859 }
1860
1861 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1862 mut self: CmResolver<'r, 'ra, 'tcx>,
1863 mut f: F,
1864 ) {
1865 f(&mut self, TypeNS);
1866 f(&mut self, ValueNS);
1867 f(&mut self, MacroNS);
1868 }
1869
1870 fn is_builtin_macro(&self, res: Res) -> bool {
1871 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1872 }
1873
1874 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1875 loop {
1876 match ctxt.outer_expn_data().macro_def_id {
1877 Some(def_id) => return def_id,
1878 None => ctxt.remove_mark(),
1879 };
1880 }
1881 }
1882
1883 pub fn resolve_crate(&mut self, krate: &Crate) {
1885 self.tcx.sess.time("resolve_crate", || {
1886 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1887 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1888 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1889 });
1890 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1891 self.tcx
1892 .sess
1893 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1894 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1895 self.tcx.sess.time("resolve_main", || self.resolve_main());
1896 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1897 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1898 self.tcx
1899 .sess
1900 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1901 });
1902
1903 self.tcx.untracked().cstore.freeze();
1905 }
1906
1907 fn traits_in_scope(
1908 &mut self,
1909 current_trait: Option<Module<'ra>>,
1910 parent_scope: &ParentScope<'ra>,
1911 ctxt: SyntaxContext,
1912 assoc_item: Option<(Symbol, Namespace)>,
1913 ) -> Vec<TraitCandidate> {
1914 let mut found_traits = Vec::new();
1915
1916 if let Some(module) = current_trait {
1917 if self.trait_may_have_item(Some(module), assoc_item) {
1918 let def_id = module.def_id();
1919 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1920 }
1921 }
1922
1923 let scope_set = ScopeSet::All(TypeNS);
1924 self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1925 match scope {
1926 Scope::ModuleNonGlobs(module, _) => {
1927 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1928 }
1929 Scope::ModuleGlobs(..) => {
1930 }
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: &DeclKind<'_>,
1989 trait_name: Ident,
1990 ) -> SmallVec<[LocalDefId; 1]> {
1991 let mut import_ids = smallvec![];
1992 while let DeclKind::Import { import, source_decl, .. } = 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 = &source_decl.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 {
2041 return true;
2042 }
2043 }
2044 false
2045 }
2046
2047 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2048 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2049 }
2050
2051 fn record_use_inner(
2052 &mut self,
2053 ident: Ident,
2054 used_decl: Decl<'ra>,
2055 used: Used,
2056 warn_ambiguity: bool,
2057 ) {
2058 if let Some(b2) = used_decl.ambiguity.get() {
2059 let ambiguity_error = AmbiguityError {
2060 kind: AmbiguityKind::GlobVsGlob,
2061 ident,
2062 b1: used_decl,
2063 b2,
2064 scope1: Scope::ModuleGlobs(self.empty_module, None),
2065 scope2: Scope::ModuleGlobs(self.empty_module, None),
2066 warning: warn_ambiguity,
2067 };
2068 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2069 self.ambiguity_errors.push(ambiguity_error);
2071 }
2072 }
2073 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2074 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2075 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2078 let empty_module = self.empty_module;
2079 let arenas = self.arenas;
2080 self.cm()
2081 .maybe_resolve_ident_in_module(
2082 ModuleOrUniformRoot::Module(prelude),
2083 ident,
2084 MacroNS,
2085 &ParentScope::module(empty_module, arenas),
2086 None,
2087 )
2088 .is_ok()
2089 });
2090 if !found_in_stdlib_prelude {
2091 self.lint_buffer().buffer_lint(
2092 PRIVATE_MACRO_USE,
2093 import.root_id,
2094 ident.span,
2095 errors::MacroIsPrivate { ident },
2096 );
2097 }
2098 }
2099 if used == Used::Scope
2102 && let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident))
2103 && entry.item_decl == Some((used_decl, false))
2104 {
2105 return;
2106 }
2107 let old_used = self.import_use_map.entry(import).or_insert(used);
2108 if *old_used < used {
2109 *old_used = used;
2110 }
2111 if let Some(id) = import.id() {
2112 self.used_imports.insert(id);
2113 }
2114 self.add_to_glob_map(import, ident);
2115 self.record_use_inner(
2116 ident,
2117 source_decl,
2118 Used::Other,
2119 warn_ambiguity || source_decl.warn_ambiguity.get(),
2120 );
2121 }
2122 }
2123
2124 #[inline]
2125 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2126 if let ImportKind::Glob { id, .. } = import.kind {
2127 let def_id = self.local_def_id(id);
2128 self.glob_map.entry(def_id).or_default().insert(ident.name);
2129 }
2130 }
2131
2132 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2133 debug!("resolve_crate_root({:?})", ident);
2134 let mut ctxt = ident.span.ctxt();
2135 let mark = if ident.name == kw::DollarCrate {
2136 ctxt = ctxt.normalize_to_macro_rules();
2143 debug!(
2144 "resolve_crate_root: marks={:?}",
2145 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2146 );
2147 let mut iter = ctxt.marks().into_iter().rev().peekable();
2148 let mut result = None;
2149 while let Some(&(mark, transparency)) = iter.peek() {
2151 if transparency == Transparency::Opaque {
2152 result = Some(mark);
2153 iter.next();
2154 } else {
2155 break;
2156 }
2157 }
2158 debug!(
2159 "resolve_crate_root: found opaque mark {:?} {:?}",
2160 result,
2161 result.map(|r| r.expn_data())
2162 );
2163 for (mark, transparency) in iter {
2165 if transparency == Transparency::SemiOpaque {
2166 result = Some(mark);
2167 } else {
2168 break;
2169 }
2170 }
2171 debug!(
2172 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2173 result,
2174 result.map(|r| r.expn_data())
2175 );
2176 result
2177 } else {
2178 debug!("resolve_crate_root: not DollarCrate");
2179 ctxt = ctxt.normalize_to_macros_2_0();
2180 ctxt.adjust(ExpnId::root())
2181 };
2182 let module = match mark {
2183 Some(def) => self.expn_def_scope(def),
2184 None => {
2185 debug!(
2186 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2187 ident, ident.span
2188 );
2189 return self.graph_root;
2190 }
2191 };
2192 let module = self.expect_module(
2193 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2194 );
2195 debug!(
2196 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2197 ident,
2198 module,
2199 module.kind.name(),
2200 ident.span
2201 );
2202 module
2203 }
2204
2205 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2206 let mut module = self.expect_module(module.nearest_parent_mod());
2207 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2208 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2209 module = self.expect_module(parent.nearest_parent_mod());
2210 }
2211 module
2212 }
2213
2214 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2215 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2216 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2217 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2218 }
2219 }
2220
2221 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2222 debug!("(recording pat) recording {:?} for {:?}", node, span);
2223 self.pat_span_map.insert(node, span);
2224 }
2225
2226 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2227 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2228 }
2229
2230 fn set_decl_parent_module(&mut self, decl: Decl<'ra>, module: Module<'ra>) {
2231 if let Some(old_module) = self.decl_parent_modules.insert(decl, module) {
2232 if module != old_module {
2233 span_bug!(decl.span, "parent module is reset for a name declaration");
2234 }
2235 }
2236 }
2237
2238 fn disambiguate_macro_rules_vs_modularized(
2239 &self,
2240 macro_rules: Decl<'ra>,
2241 modularized: Decl<'ra>,
2242 ) -> bool {
2243 let macro_rules = &self.decl_parent_modules[¯o_rules];
2251 let modularized = &self.decl_parent_modules[&modularized];
2252 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2253 && modularized.is_ancestor_of(*macro_rules)
2254 }
2255
2256 fn extern_prelude_get_item<'r>(
2257 mut self: CmResolver<'r, 'ra, 'tcx>,
2258 ident: Macros20NormalizedIdent,
2259 finalize: bool,
2260 ) -> Option<Decl<'ra>> {
2261 let entry = self.extern_prelude.get(&ident);
2262 entry.and_then(|entry| entry.item_decl).map(|(decl, _)| {
2263 if finalize {
2264 self.get_mut().record_use(ident.0, decl, Used::Scope);
2265 }
2266 decl
2267 })
2268 }
2269
2270 fn extern_prelude_get_flag(
2271 &self,
2272 ident: Macros20NormalizedIdent,
2273 finalize: bool,
2274 ) -> Option<Decl<'ra>> {
2275 let entry = self.extern_prelude.get(&ident);
2276 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2277 let (pending_decl, finalized) = flag_decl.get();
2278 let decl = match pending_decl {
2279 PendingDecl::Ready(decl) => {
2280 if finalize && !finalized {
2281 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2282 }
2283 decl
2284 }
2285 PendingDecl::Pending => {
2286 debug_assert!(!finalized);
2287 let crate_id = if finalize {
2288 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2289 } else {
2290 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2291 };
2292 crate_id.map(|crate_id| {
2293 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2294 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2295 })
2296 }
2297 };
2298 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized));
2299 decl.or_else(|| finalize.then_some(self.dummy_decl))
2300 })
2301 }
2302
2303 fn resolve_rustdoc_path(
2308 &mut self,
2309 path_str: &str,
2310 ns: Namespace,
2311 parent_scope: ParentScope<'ra>,
2312 ) -> Option<Res> {
2313 let segments: Result<Vec<_>, ()> = path_str
2314 .split("::")
2315 .enumerate()
2316 .map(|(i, s)| {
2317 let sym = if s.is_empty() {
2318 if i == 0 {
2319 kw::PathRoot
2321 } else {
2322 return Err(()); }
2324 } else {
2325 Symbol::intern(s)
2326 };
2327 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2328 })
2329 .collect();
2330 let Ok(segments) = segments else { return None };
2331
2332 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2333 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2334 PathResult::NonModule(path_res) => {
2335 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2336 }
2337 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2338 None
2339 }
2340 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2341 }
2342 }
2343
2344 fn def_span(&self, def_id: DefId) -> Span {
2346 match def_id.as_local() {
2347 Some(def_id) => self.tcx.source_span(def_id),
2348 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2350 }
2351 }
2352
2353 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2354 match def_id.as_local() {
2355 Some(def_id) => self.field_names.get(&def_id).cloned(),
2356 None if matches!(
2357 self.tcx.def_kind(def_id),
2358 DefKind::Struct | DefKind::Union | DefKind::Variant
2359 ) =>
2360 {
2361 Some(
2362 self.tcx
2363 .associated_item_def_ids(def_id)
2364 .iter()
2365 .map(|&def_id| {
2366 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2367 })
2368 .collect(),
2369 )
2370 }
2371 _ => None,
2372 }
2373 }
2374
2375 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2376 match def_id.as_local() {
2377 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2378 None if matches!(
2379 self.tcx.def_kind(def_id),
2380 DefKind::Struct | DefKind::Union | DefKind::Variant
2381 ) =>
2382 {
2383 Some(
2384 self.tcx
2385 .associated_item_def_ids(def_id)
2386 .iter()
2387 .filter_map(|&def_id| {
2388 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2389 })
2390 .collect(),
2391 )
2392 }
2393 _ => None,
2394 }
2395 }
2396
2397 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2401 let ExprKind::Path(None, path) = &expr.kind else {
2402 return None;
2403 };
2404 if path.segments.last().unwrap().args.is_some() {
2407 return None;
2408 }
2409
2410 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2411
2412 if def_id.is_local() {
2416 return None;
2417 }
2418
2419 find_attr!(
2420 self.tcx.get_all_attrs(def_id),
2422 AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2423 )
2424 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2425 }
2426
2427 fn resolve_main(&mut self) {
2428 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2429 if !any_exe {
2431 return;
2432 }
2433
2434 let module = self.graph_root;
2435 let ident = Ident::with_dummy_span(sym::main);
2436 let parent_scope = &ParentScope::module(module, self.arenas);
2437
2438 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2439 ModuleOrUniformRoot::Module(module),
2440 ident,
2441 ValueNS,
2442 parent_scope,
2443 None,
2444 ) else {
2445 return;
2446 };
2447
2448 let res = name_binding.res();
2449 let is_import = name_binding.is_import();
2450 let span = name_binding.span;
2451 if let Res::Def(DefKind::Fn, _) = res {
2452 self.record_use(ident, name_binding, Used::Other);
2453 }
2454 self.main_def = Some(MainDefinition { res, is_import, span });
2455 }
2456}
2457
2458fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2459 let mut result = String::new();
2460 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2461 if i > 0 {
2462 result.push_str("::");
2463 }
2464 if Ident::with_dummy_span(name).is_raw_guess() {
2465 result.push_str("r#");
2466 }
2467 result.push_str(name.as_str());
2468 }
2469 result
2470}
2471
2472fn path_names_to_string(path: &Path) -> String {
2473 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2474}
2475
2476fn module_to_string(mut module: Module<'_>) -> Option<String> {
2478 let mut names = Vec::new();
2479 loop {
2480 if let ModuleKind::Def(.., name) = module.kind {
2481 if let Some(parent) = module.parent {
2482 names.push(name.unwrap());
2484 module = parent
2485 } else {
2486 break;
2487 }
2488 } else {
2489 names.push(sym::opaque_module_name_placeholder);
2490 let Some(parent) = module.parent else {
2491 return None;
2492 };
2493 module = parent;
2494 }
2495 }
2496 if names.is_empty() {
2497 return None;
2498 }
2499 Some(names_to_string(names.iter().rev().copied()))
2500}
2501
2502#[derive(Copy, Clone, PartialEq, Debug)]
2503enum Stage {
2504 Early,
2508 Late,
2511}
2512
2513#[derive(Copy, Clone, Debug)]
2515struct Finalize {
2516 node_id: NodeId,
2518 path_span: Span,
2521 root_span: Span,
2524 report_private: bool = true,
2527 used: Used = Used::Other,
2529 stage: Stage = Stage::Early,
2531}
2532
2533impl Finalize {
2534 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2535 Finalize::with_root_span(node_id, path_span, path_span)
2536 }
2537
2538 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2539 Finalize { node_id, path_span, root_span, .. }
2540 }
2541}
2542
2543pub fn provide(providers: &mut Providers) {
2544 providers.registered_tools = macros::registered_tools;
2545}
2546
2547type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2553
2554use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2558
2559mod ref_mut {
2562 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2563 use std::fmt;
2564 use std::ops::Deref;
2565
2566 use crate::Resolver;
2567
2568 pub(crate) struct RefOrMut<'a, T> {
2570 p: &'a mut T,
2571 mutable: bool,
2572 }
2573
2574 impl<'a, T> Deref for RefOrMut<'a, T> {
2575 type Target = T;
2576
2577 fn deref(&self) -> &Self::Target {
2578 self.p
2579 }
2580 }
2581
2582 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2583 fn as_ref(&self) -> &T {
2584 self.p
2585 }
2586 }
2587
2588 impl<'a, T> RefOrMut<'a, T> {
2589 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2590 RefOrMut { p, mutable }
2591 }
2592
2593 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2595 RefOrMut { p: self.p, mutable: self.mutable }
2596 }
2597
2598 #[track_caller]
2603 pub(crate) fn get_mut(&mut self) -> &mut T {
2604 match self.mutable {
2605 false => panic!("Can't mutably borrow speculative resolver"),
2606 true => self.p,
2607 }
2608 }
2609
2610 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2613 self.p
2614 }
2615 }
2616
2617 #[derive(Default)]
2619 pub(crate) struct CmCell<T>(Cell<T>);
2620
2621 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2623 f.debug_tuple("CmCell").field(&self.get()).finish()
2624 }
2625 }
2626
2627 impl<T: Copy> Clone for CmCell<T> {
2628 fn clone(&self) -> CmCell<T> {
2629 CmCell::new(self.get())
2630 }
2631 }
2632
2633 impl<T: Copy> CmCell<T> {
2634 pub(crate) const fn get(&self) -> T {
2635 self.0.get()
2636 }
2637
2638 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2639 where
2640 T: Copy,
2641 {
2642 let old = self.get();
2643 self.set_unchecked(f(old));
2644 }
2645 }
2646
2647 impl<T> CmCell<T> {
2648 pub(crate) const fn new(value: T) -> CmCell<T> {
2649 CmCell(Cell::new(value))
2650 }
2651
2652 pub(crate) fn set_unchecked(&self, val: T) {
2653 self.0.set(val);
2654 }
2655
2656 pub(crate) fn into_inner(self) -> T {
2657 self.0.into_inner()
2658 }
2659 }
2660
2661 #[derive(Default)]
2663 pub(crate) struct CmRefCell<T>(RefCell<T>);
2664
2665 impl<T> CmRefCell<T> {
2666 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2667 CmRefCell(RefCell::new(value))
2668 }
2669
2670 #[track_caller]
2671 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2672 self.0.borrow_mut()
2673 }
2674
2675 #[track_caller]
2676 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2677 if r.assert_speculative {
2678 panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2679 }
2680 self.borrow_mut_unchecked()
2681 }
2682
2683 #[track_caller]
2684 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2685 self.0.try_borrow_mut()
2686 }
2687
2688 #[track_caller]
2689 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2690 self.0.borrow()
2691 }
2692 }
2693
2694 impl<T: Default> CmRefCell<T> {
2695 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2696 if r.assert_speculative {
2697 panic!("Not allowed to mutate a CmRefCell during speculative resolution");
2698 }
2699 self.0.take()
2700 }
2701 }
2702}