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: Ident, ns: Namespace) -> Self {
576 BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator: 0 }
577 }
578
579 fn new_disambiguated(
580 ident: Ident,
581 ns: Namespace,
582 disambiguator: impl FnOnce() -> u32,
583 ) -> BindingKey {
584 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
585 BindingKey { ident: Macros20NormalizedIdent::new(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, Copy, Debug)]
806struct DeclData<'ra> {
807 kind: DeclKind<'ra>,
808 ambiguity: Option<Decl<'ra>>,
809 warn_ambiguity: bool,
812 expansion: LocalExpnId,
813 span: Span,
814 vis: 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 res(&self) -> Res {
927 match self.kind {
928 DeclKind::Def(res) => res,
929 DeclKind::Import { source_decl, .. } => source_decl.res(),
930 }
931 }
932
933 fn import_source(&self) -> Decl<'ra> {
934 match self.kind {
935 DeclKind::Import { source_decl, .. } => source_decl,
936 _ => unreachable!(),
937 }
938 }
939
940 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
941 match self.ambiguity {
942 Some(ambig_binding) => Some((self, ambig_binding)),
943 None => match self.kind {
944 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
945 _ => None,
946 },
947 }
948 }
949
950 fn is_ambiguity_recursive(&self) -> bool {
951 self.ambiguity.is_some()
952 || match self.kind {
953 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
954 _ => false,
955 }
956 }
957
958 fn warn_ambiguity_recursive(&self) -> bool {
959 self.warn_ambiguity
960 || match self.kind {
961 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
962 _ => false,
963 }
964 }
965
966 fn is_possibly_imported_variant(&self) -> bool {
967 match self.kind {
968 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
969 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
970 true
971 }
972 DeclKind::Def(..) => false,
973 }
974 }
975
976 fn is_extern_crate(&self) -> bool {
977 match self.kind {
978 DeclKind::Import { import, .. } => {
979 matches!(import.kind, ImportKind::ExternCrate { .. })
980 }
981 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
982 _ => false,
983 }
984 }
985
986 fn is_import(&self) -> bool {
987 matches!(self.kind, DeclKind::Import { .. })
988 }
989
990 fn is_import_user_facing(&self) -> bool {
993 matches!(self.kind, DeclKind::Import { import, .. }
994 if !matches!(import.kind, ImportKind::MacroExport))
995 }
996
997 fn is_glob_import(&self) -> bool {
998 match self.kind {
999 DeclKind::Import { import, .. } => import.is_glob(),
1000 _ => false,
1001 }
1002 }
1003
1004 fn is_assoc_item(&self) -> bool {
1005 matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
1006 }
1007
1008 fn macro_kinds(&self) -> Option<MacroKinds> {
1009 self.res().macro_kinds()
1010 }
1011
1012 fn reexport_chain(self: Decl<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1013 let mut reexport_chain = SmallVec::new();
1014 let mut next_binding = self;
1015 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1016 reexport_chain.push(import.simplify(r));
1017 next_binding = source_decl;
1018 }
1019 reexport_chain
1020 }
1021
1022 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1029 let self_parent_expansion = self.expansion;
1033 let other_parent_expansion = decl.expansion;
1034 let certainly_before_other_or_simultaneously =
1035 other_parent_expansion.is_descendant_of(self_parent_expansion);
1036 let certainly_before_invoc_or_simultaneously =
1037 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1038 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1039 }
1040
1041 fn determined(&self) -> bool {
1045 match &self.kind {
1046 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1047 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1048 && source_decl.determined()
1049 }
1050 _ => true,
1051 }
1052 }
1053}
1054
1055struct ExternPreludeEntry<'ra> {
1056 item_decl: Option<(Decl<'ra>, bool)>,
1060 flag_decl: Option<CacheCell<(PendingDecl<'ra>, bool)>>,
1062}
1063
1064impl ExternPreludeEntry<'_> {
1065 fn introduced_by_item(&self) -> bool {
1066 matches!(self.item_decl, Some((_, true)))
1067 }
1068
1069 fn flag() -> Self {
1070 ExternPreludeEntry {
1071 item_decl: None,
1072 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false))),
1073 }
1074 }
1075}
1076
1077struct DeriveData {
1078 resolutions: Vec<DeriveResolution>,
1079 helper_attrs: Vec<(usize, Ident)>,
1080 has_derive_copy: bool,
1081}
1082
1083struct MacroData {
1084 ext: Arc<SyntaxExtension>,
1085 nrules: usize,
1086 macro_rules: bool,
1087}
1088
1089impl MacroData {
1090 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1091 MacroData { ext, nrules: 0, macro_rules: false }
1092 }
1093}
1094
1095pub struct ResolverOutputs {
1096 pub global_ctxt: ResolverGlobalCtxt,
1097 pub ast_lowering: ResolverAstLowering,
1098}
1099
1100pub struct Resolver<'ra, 'tcx> {
1104 tcx: TyCtxt<'tcx>,
1105
1106 expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1108
1109 graph_root: Module<'ra>,
1110
1111 assert_speculative: bool,
1113
1114 prelude: Option<Module<'ra>> = None,
1115 extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1116
1117 field_names: LocalDefIdMap<Vec<Ident>>,
1119 field_defaults: LocalDefIdMap<Vec<Symbol>>,
1120
1121 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1124
1125 determined_imports: Vec<Import<'ra>> = Vec::new(),
1127
1128 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1130
1131 pat_span_map: NodeMap<Span>,
1134
1135 partial_res_map: NodeMap<PartialRes>,
1137 import_res_map: NodeMap<PerNS<Option<Res>>>,
1139 import_use_map: FxHashMap<Import<'ra>, Used>,
1141 label_res_map: NodeMap<NodeId>,
1143 lifetimes_res_map: NodeMap<LifetimeRes>,
1145 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1147
1148 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1150 module_children: LocalDefIdMap<Vec<ModChild>>,
1151 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
1152 trait_map: NodeMap<Vec<TraitCandidate>>,
1153
1154 block_map: NodeMap<Module<'ra>>,
1169 empty_module: Module<'ra>,
1173 local_modules: Vec<Module<'ra>>,
1175 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1177 extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1179 decl_parent_modules: FxHashMap<Decl<'ra>, Module<'ra>>,
1180
1181 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1183 glob_error: Option<ErrorGuaranteed> = None,
1184 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1185 used_imports: FxHashSet<NodeId>,
1186 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1187
1188 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1190 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1192 issue_145575_hack_applied: bool = false,
1193 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1195 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1197
1198 inaccessible_ctor_reexport: FxHashMap<Span, Span>,
1202
1203 arenas: &'ra ResolverArenas<'ra>,
1204 dummy_decl: Decl<'ra>,
1205 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1206 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1207 registered_tool_decls: FxHashMap<Ident, Decl<'ra>>,
1208 macro_names: FxHashSet<Ident>,
1209 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1210 registered_tools: &'tcx RegisteredTools,
1211 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1212 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1214 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1216 dummy_ext_bang: Arc<SyntaxExtension>,
1217 dummy_ext_derive: Arc<SyntaxExtension>,
1218 non_macro_attr: &'ra MacroData,
1219 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1220 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1221 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1222 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1224 proc_macro_stubs: FxHashSet<LocalDefId>,
1225 single_segment_macro_resolutions:
1227 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1228 multi_segment_macro_resolutions:
1229 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1230 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1231 containers_deriving_copy: FxHashSet<LocalExpnId>,
1235 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1238 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1241 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1243 helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, Decl<'ra>)>>,
1245 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1248
1249 name_already_seen: FxHashMap<Symbol, Span>,
1251
1252 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1253
1254 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1255
1256 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1260
1261 lint_buffer: LintBuffer,
1262
1263 next_node_id: NodeId = CRATE_NODE_ID,
1264
1265 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1266
1267 disambiguator: DisambiguatorState,
1268
1269 placeholder_field_indices: FxHashMap<NodeId, usize>,
1271 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1275
1276 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1278 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1279 delegation_infos: LocalDefIdMap<DelegationInfo>,
1280
1281 main_def: Option<MainDefinition> = None,
1282 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1283 proc_macros: Vec<LocalDefId> = Vec::new(),
1286 confused_type_with_std_module: FxIndexMap<Span, Span>,
1287 lifetime_elision_allowed: FxHashSet<NodeId>,
1289
1290 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1292
1293 effective_visibilities: EffectiveVisibilities,
1294 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1295 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1296 all_macro_rules: UnordSet<Symbol>,
1297
1298 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1300 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1303 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1306
1307 current_crate_outer_attr_insert_span: Span,
1310
1311 mods_with_parse_errors: FxHashSet<DefId>,
1312
1313 all_crate_macros_already_registered: bool = false,
1316
1317 impl_trait_names: FxHashMap<NodeId, Symbol>,
1321}
1322
1323#[derive(Default)]
1326pub struct ResolverArenas<'ra> {
1327 modules: TypedArena<ModuleData<'ra>>,
1328 imports: TypedArena<ImportData<'ra>>,
1329 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1330 ast_paths: TypedArena<ast::Path>,
1331 macros: TypedArena<MacroData>,
1332 dropless: DroplessArena,
1333}
1334
1335impl<'ra> ResolverArenas<'ra> {
1336 fn new_def_decl(
1337 &'ra self,
1338 res: Res,
1339 vis: Visibility<DefId>,
1340 span: Span,
1341 expansion: LocalExpnId,
1342 ) -> Decl<'ra> {
1343 self.alloc_decl(DeclData {
1344 kind: DeclKind::Def(res),
1345 ambiguity: None,
1346 warn_ambiguity: false,
1347 vis,
1348 span,
1349 expansion,
1350 })
1351 }
1352
1353 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1354 self.new_def_decl(res, Visibility::Public, span, expn_id)
1355 }
1356
1357 fn new_module(
1358 &'ra self,
1359 parent: Option<Module<'ra>>,
1360 kind: ModuleKind,
1361 expn_id: ExpnId,
1362 span: Span,
1363 no_implicit_prelude: bool,
1364 ) -> Module<'ra> {
1365 let self_decl = match kind {
1366 ModuleKind::Def(def_kind, def_id, _) => {
1367 Some(self.new_pub_def_decl(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT))
1368 }
1369 ModuleKind::Block => None,
1370 };
1371 Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1372 parent,
1373 kind,
1374 expn_id,
1375 span,
1376 no_implicit_prelude,
1377 self_decl,
1378 ))))
1379 }
1380 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1381 Interned::new_unchecked(self.dropless.alloc(data))
1382 }
1383 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1384 Interned::new_unchecked(self.imports.alloc(import))
1385 }
1386 fn alloc_name_resolution(&'ra self) -> &'ra CmRefCell<NameResolution<'ra>> {
1387 self.name_resolutions.alloc(Default::default())
1388 }
1389 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1390 self.dropless.alloc(CacheCell::new(scope))
1391 }
1392 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1393 self.dropless.alloc(decl)
1394 }
1395 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1396 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1397 }
1398 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1399 self.macros.alloc(macro_data)
1400 }
1401 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1402 self.dropless.alloc_from_iter(spans)
1403 }
1404}
1405
1406impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1407 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1408 self
1409 }
1410}
1411
1412impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1413 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1414 self
1415 }
1416}
1417
1418impl<'tcx> Resolver<'_, 'tcx> {
1419 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1420 self.opt_feed(node).map(|f| f.key())
1421 }
1422
1423 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1424 self.feed(node).key()
1425 }
1426
1427 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1428 self.node_id_to_def_id.get(&node).copied()
1429 }
1430
1431 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1432 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1433 }
1434
1435 fn local_def_kind(&self, node: NodeId) -> DefKind {
1436 self.tcx.def_kind(self.local_def_id(node))
1437 }
1438
1439 fn create_def(
1441 &mut self,
1442 parent: LocalDefId,
1443 node_id: ast::NodeId,
1444 name: Option<Symbol>,
1445 def_kind: DefKind,
1446 expn_id: ExpnId,
1447 span: Span,
1448 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1449 assert!(
1450 !self.node_id_to_def_id.contains_key(&node_id),
1451 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1452 node_id,
1453 name,
1454 def_kind,
1455 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1456 );
1457
1458 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1460 let def_id = feed.def_id();
1461
1462 if expn_id != ExpnId::root() {
1464 self.expn_that_defined.insert(def_id, expn_id);
1465 }
1466
1467 debug_assert_eq!(span.data_untracked().parent, None);
1469 let _id = self.tcx.untracked().source_span.push(span);
1470 debug_assert_eq!(_id, def_id);
1471
1472 if node_id != ast::DUMMY_NODE_ID {
1476 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1477 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1478 }
1479
1480 feed
1481 }
1482
1483 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1484 if let Some(def_id) = def_id.as_local() {
1485 self.item_generics_num_lifetimes[&def_id]
1486 } else {
1487 self.tcx.generics_of(def_id).own_counts().lifetimes
1488 }
1489 }
1490
1491 pub fn tcx(&self) -> TyCtxt<'tcx> {
1492 self.tcx
1493 }
1494
1495 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1500 self.node_id_to_def_id
1501 .items()
1502 .filter(|(_, v)| v.key() == def_id)
1503 .map(|(k, _)| *k)
1504 .get_only()
1505 .unwrap()
1506 }
1507}
1508
1509impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1510 pub fn new(
1511 tcx: TyCtxt<'tcx>,
1512 attrs: &[ast::Attribute],
1513 crate_span: Span,
1514 current_crate_outer_attr_insert_span: Span,
1515 arenas: &'ra ResolverArenas<'ra>,
1516 ) -> Resolver<'ra, 'tcx> {
1517 let root_def_id = CRATE_DEF_ID.to_def_id();
1518 let graph_root = arenas.new_module(
1519 None,
1520 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1521 ExpnId::root(),
1522 crate_span,
1523 attr::contains_name(attrs, sym::no_implicit_prelude),
1524 );
1525 let local_modules = vec![graph_root];
1526 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1527 let empty_module = arenas.new_module(
1528 None,
1529 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1530 ExpnId::root(),
1531 DUMMY_SP,
1532 true,
1533 );
1534
1535 let mut node_id_to_def_id = NodeMap::default();
1536 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1537
1538 crate_feed.def_kind(DefKind::Mod);
1539 let crate_feed = crate_feed.downgrade();
1540 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1541
1542 let mut invocation_parents = FxHashMap::default();
1543 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1544
1545 let mut extern_prelude: FxIndexMap<_, _> = tcx
1546 .sess
1547 .opts
1548 .externs
1549 .iter()
1550 .filter_map(|(name, entry)| {
1551 if entry.add_prelude
1554 && let name = Symbol::intern(name)
1555 && name.can_be_raw()
1556 {
1557 let ident = Macros20NormalizedIdent::with_dummy_span(name);
1558 Some((ident, ExternPreludeEntry::flag()))
1559 } else {
1560 None
1561 }
1562 })
1563 .collect();
1564
1565 if !attr::contains_name(attrs, sym::no_core) {
1566 let ident = Macros20NormalizedIdent::with_dummy_span(sym::core);
1567 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1568 if !attr::contains_name(attrs, sym::no_std) {
1569 let ident = Macros20NormalizedIdent::with_dummy_span(sym::std);
1570 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1571 }
1572 }
1573
1574 let registered_tools = tcx.registered_tools(());
1575 let edition = tcx.sess.edition();
1576
1577 let mut resolver = Resolver {
1578 tcx,
1579
1580 expn_that_defined: Default::default(),
1581
1582 graph_root,
1585 assert_speculative: false, prelude: None,
1587 extern_prelude,
1588
1589 field_names: Default::default(),
1590 field_defaults: Default::default(),
1591 field_visibility_spans: FxHashMap::default(),
1592
1593 pat_span_map: Default::default(),
1594 partial_res_map: Default::default(),
1595 import_res_map: Default::default(),
1596 import_use_map: Default::default(),
1597 label_res_map: Default::default(),
1598 lifetimes_res_map: Default::default(),
1599 extra_lifetime_params_map: Default::default(),
1600 extern_crate_map: Default::default(),
1601 module_children: Default::default(),
1602 ambig_module_children: Default::default(),
1603 trait_map: NodeMap::default(),
1604 empty_module,
1605 local_modules,
1606 local_module_map,
1607 extern_module_map: Default::default(),
1608 block_map: Default::default(),
1609 decl_parent_modules: FxHashMap::default(),
1610 ast_transform_scopes: FxHashMap::default(),
1611
1612 glob_map: Default::default(),
1613 used_imports: FxHashSet::default(),
1614 maybe_unused_trait_imports: Default::default(),
1615 inaccessible_ctor_reexport: Default::default(),
1616
1617 arenas,
1618 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1619 builtin_type_decls: PrimTy::ALL
1620 .iter()
1621 .map(|prim_ty| {
1622 let res = Res::PrimTy(*prim_ty);
1623 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1624 (prim_ty.name(), decl)
1625 })
1626 .collect(),
1627 builtin_attr_decls: BUILTIN_ATTRIBUTES
1628 .iter()
1629 .map(|builtin_attr| {
1630 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1631 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1632 (builtin_attr.name, decl)
1633 })
1634 .collect(),
1635 registered_tool_decls: registered_tools
1636 .iter()
1637 .map(|ident| {
1638 let res = Res::ToolMod;
1639 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1640 (*ident, decl)
1641 })
1642 .collect(),
1643 macro_names: FxHashSet::default(),
1644 builtin_macros: Default::default(),
1645 registered_tools,
1646 macro_use_prelude: Default::default(),
1647 local_macro_map: Default::default(),
1648 extern_macro_map: Default::default(),
1649 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1650 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1651 non_macro_attr: arenas
1652 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1653 invocation_parent_scopes: Default::default(),
1654 output_macro_rules_scopes: Default::default(),
1655 macro_rules_scopes: Default::default(),
1656 helper_attrs: Default::default(),
1657 derive_data: Default::default(),
1658 local_macro_def_scopes: FxHashMap::default(),
1659 name_already_seen: FxHashMap::default(),
1660 struct_constructors: Default::default(),
1661 unused_macros: Default::default(),
1662 unused_macro_rules: Default::default(),
1663 proc_macro_stubs: Default::default(),
1664 single_segment_macro_resolutions: Default::default(),
1665 multi_segment_macro_resolutions: Default::default(),
1666 builtin_attrs: Default::default(),
1667 containers_deriving_copy: Default::default(),
1668 lint_buffer: LintBuffer::default(),
1669 node_id_to_def_id,
1670 disambiguator: DisambiguatorState::new(),
1671 placeholder_field_indices: Default::default(),
1672 invocation_parents,
1673 item_generics_num_lifetimes: Default::default(),
1674 trait_impls: Default::default(),
1675 confused_type_with_std_module: Default::default(),
1676 lifetime_elision_allowed: Default::default(),
1677 stripped_cfg_items: Default::default(),
1678 effective_visibilities: Default::default(),
1679 doc_link_resolutions: Default::default(),
1680 doc_link_traits_in_scope: Default::default(),
1681 all_macro_rules: Default::default(),
1682 delegation_fn_sigs: Default::default(),
1683 glob_delegation_invoc_ids: Default::default(),
1684 impl_unexpanded_invocations: Default::default(),
1685 impl_binding_keys: Default::default(),
1686 current_crate_outer_attr_insert_span,
1687 mods_with_parse_errors: Default::default(),
1688 impl_trait_names: Default::default(),
1689 delegation_infos: Default::default(),
1690 ..
1691 };
1692
1693 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1694 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1695 resolver.feed_visibility(crate_feed, Visibility::Public);
1696
1697 resolver
1698 }
1699
1700 fn new_local_module(
1701 &mut self,
1702 parent: Option<Module<'ra>>,
1703 kind: ModuleKind,
1704 expn_id: ExpnId,
1705 span: Span,
1706 no_implicit_prelude: bool,
1707 ) -> Module<'ra> {
1708 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1709 self.local_modules.push(module);
1710 if let Some(def_id) = module.opt_def_id() {
1711 self.local_module_map.insert(def_id.expect_local(), module);
1712 }
1713 module
1714 }
1715
1716 fn new_extern_module(
1717 &self,
1718 parent: Option<Module<'ra>>,
1719 kind: ModuleKind,
1720 expn_id: ExpnId,
1721 span: Span,
1722 no_implicit_prelude: bool,
1723 ) -> Module<'ra> {
1724 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1725 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1726 module
1727 }
1728
1729 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1730 let mac = self.arenas.alloc_macro(macro_data);
1731 self.local_macro_map.insert(def_id, mac);
1732 mac
1733 }
1734
1735 fn next_node_id(&mut self) -> NodeId {
1736 let start = self.next_node_id;
1737 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1738 self.next_node_id = ast::NodeId::from_u32(next);
1739 start
1740 }
1741
1742 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1743 let start = self.next_node_id;
1744 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1745 self.next_node_id = ast::NodeId::from_usize(end);
1746 start..self.next_node_id
1747 }
1748
1749 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1750 &mut self.lint_buffer
1751 }
1752
1753 pub fn arenas() -> ResolverArenas<'ra> {
1754 Default::default()
1755 }
1756
1757 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1758 let feed = feed.upgrade(self.tcx);
1759 feed.visibility(vis.to_def_id());
1760 self.visibilities_for_hashing.push((feed.def_id(), vis));
1761 }
1762
1763 pub fn into_outputs(self) -> ResolverOutputs {
1764 let proc_macros = self.proc_macros;
1765 let expn_that_defined = self.expn_that_defined;
1766 let extern_crate_map = self.extern_crate_map;
1767 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1768 let glob_map = self.glob_map;
1769 let main_def = self.main_def;
1770 let confused_type_with_std_module = self.confused_type_with_std_module;
1771 let effective_visibilities = self.effective_visibilities;
1772
1773 let stripped_cfg_items = self
1774 .stripped_cfg_items
1775 .into_iter()
1776 .filter_map(|item| {
1777 let parent_module =
1778 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1779 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1780 })
1781 .collect();
1782
1783 let global_ctxt = ResolverGlobalCtxt {
1784 expn_that_defined,
1785 visibilities_for_hashing: self.visibilities_for_hashing,
1786 effective_visibilities,
1787 extern_crate_map,
1788 module_children: self.module_children,
1789 ambig_module_children: self.ambig_module_children,
1790 glob_map,
1791 maybe_unused_trait_imports,
1792 main_def,
1793 trait_impls: self.trait_impls,
1794 proc_macros,
1795 confused_type_with_std_module,
1796 doc_link_resolutions: self.doc_link_resolutions,
1797 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1798 all_macro_rules: self.all_macro_rules,
1799 stripped_cfg_items,
1800 };
1801 let ast_lowering = ty::ResolverAstLowering {
1802 partial_res_map: self.partial_res_map,
1803 import_res_map: self.import_res_map,
1804 label_res_map: self.label_res_map,
1805 lifetimes_res_map: self.lifetimes_res_map,
1806 extra_lifetime_params_map: self.extra_lifetime_params_map,
1807 next_node_id: self.next_node_id,
1808 node_id_to_def_id: self
1809 .node_id_to_def_id
1810 .into_items()
1811 .map(|(k, f)| (k, f.key()))
1812 .collect(),
1813 trait_map: self.trait_map,
1814 lifetime_elision_allowed: self.lifetime_elision_allowed,
1815 lint_buffer: Steal::new(self.lint_buffer),
1816 delegation_fn_sigs: self.delegation_fn_sigs,
1817 delegation_infos: self.delegation_infos,
1818 };
1819 ResolverOutputs { global_ctxt, ast_lowering }
1820 }
1821
1822 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1823 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1824 }
1825
1826 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1827 CStore::from_tcx(self.tcx)
1828 }
1829
1830 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1831 CStore::from_tcx_mut(self.tcx)
1832 }
1833
1834 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1835 match macro_kind {
1836 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1837 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1838 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1839 }
1840 }
1841
1842 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1847 CmResolver::new(self, !self.assert_speculative)
1848 }
1849
1850 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1852 f(self, TypeNS);
1853 f(self, ValueNS);
1854 f(self, MacroNS);
1855 }
1856
1857 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1858 mut self: CmResolver<'r, 'ra, 'tcx>,
1859 mut f: F,
1860 ) {
1861 f(&mut self, TypeNS);
1862 f(&mut self, ValueNS);
1863 f(&mut self, MacroNS);
1864 }
1865
1866 fn is_builtin_macro(&self, res: Res) -> bool {
1867 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1868 }
1869
1870 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1871 loop {
1872 match ctxt.outer_expn_data().macro_def_id {
1873 Some(def_id) => return def_id,
1874 None => ctxt.remove_mark(),
1875 };
1876 }
1877 }
1878
1879 pub fn resolve_crate(&mut self, krate: &Crate) {
1881 self.tcx.sess.time("resolve_crate", || {
1882 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1883 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1884 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1885 });
1886 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1887 self.tcx
1888 .sess
1889 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1890 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1891 self.tcx.sess.time("resolve_main", || self.resolve_main());
1892 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1893 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1894 self.tcx
1895 .sess
1896 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1897 });
1898
1899 self.tcx.untracked().cstore.freeze();
1901 }
1902
1903 fn traits_in_scope(
1904 &mut self,
1905 current_trait: Option<Module<'ra>>,
1906 parent_scope: &ParentScope<'ra>,
1907 ctxt: SyntaxContext,
1908 assoc_item: Option<(Symbol, Namespace)>,
1909 ) -> Vec<TraitCandidate> {
1910 let mut found_traits = Vec::new();
1911
1912 if let Some(module) = current_trait {
1913 if self.trait_may_have_item(Some(module), assoc_item) {
1914 let def_id = module.def_id();
1915 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1916 }
1917 }
1918
1919 let scope_set = ScopeSet::All(TypeNS);
1920 self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1921 match scope {
1922 Scope::ModuleNonGlobs(module, _) => {
1923 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1924 }
1925 Scope::ModuleGlobs(..) => {
1926 }
1928 Scope::StdLibPrelude => {
1929 if let Some(module) = this.prelude {
1930 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1931 }
1932 }
1933 Scope::ExternPreludeItems
1934 | Scope::ExternPreludeFlags
1935 | Scope::ToolPrelude
1936 | Scope::BuiltinTypes => {}
1937 _ => unreachable!(),
1938 }
1939 ControlFlow::<()>::Continue(())
1940 });
1941
1942 found_traits
1943 }
1944
1945 fn traits_in_module(
1946 &mut self,
1947 module: Module<'ra>,
1948 assoc_item: Option<(Symbol, Namespace)>,
1949 found_traits: &mut Vec<TraitCandidate>,
1950 ) {
1951 module.ensure_traits(self);
1952 let traits = module.traits.borrow();
1953 for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1954 if self.trait_may_have_item(trait_module, assoc_item) {
1955 let def_id = trait_binding.res().def_id();
1956 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1957 found_traits.push(TraitCandidate { def_id, import_ids });
1958 }
1959 }
1960 }
1961
1962 fn trait_may_have_item(
1968 &self,
1969 trait_module: Option<Module<'ra>>,
1970 assoc_item: Option<(Symbol, Namespace)>,
1971 ) -> bool {
1972 match (trait_module, assoc_item) {
1973 (Some(trait_module), Some((name, ns))) => self
1974 .resolutions(trait_module)
1975 .borrow()
1976 .iter()
1977 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1978 _ => true,
1979 }
1980 }
1981
1982 fn find_transitive_imports(
1983 &mut self,
1984 mut kind: &DeclKind<'_>,
1985 trait_name: Ident,
1986 ) -> SmallVec<[LocalDefId; 1]> {
1987 let mut import_ids = smallvec![];
1988 while let DeclKind::Import { import, source_decl, .. } = kind {
1989 if let Some(node_id) = import.id() {
1990 let def_id = self.local_def_id(node_id);
1991 self.maybe_unused_trait_imports.insert(def_id);
1992 import_ids.push(def_id);
1993 }
1994 self.add_to_glob_map(*import, trait_name);
1995 kind = &source_decl.kind;
1996 }
1997 import_ids
1998 }
1999
2000 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2001 if module.populate_on_access.get() {
2002 module.populate_on_access.set(false);
2003 self.build_reduced_graph_external(module);
2004 }
2005 &module.0.0.lazy_resolutions
2006 }
2007
2008 fn resolution(
2009 &self,
2010 module: Module<'ra>,
2011 key: BindingKey,
2012 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2013 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2014 }
2015
2016 fn resolution_or_default(
2017 &self,
2018 module: Module<'ra>,
2019 key: BindingKey,
2020 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2021 self.resolutions(module)
2022 .borrow_mut_unchecked()
2023 .entry(key)
2024 .or_insert_with(|| self.arenas.alloc_name_resolution())
2025 }
2026
2027 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2029 for ambiguity_error in &self.ambiguity_errors {
2030 if ambiguity_error.kind == ambi.kind
2032 && ambiguity_error.ident == ambi.ident
2033 && ambiguity_error.ident.span == ambi.ident.span
2034 && ambiguity_error.b1.span == ambi.b1.span
2035 && ambiguity_error.b2.span == ambi.b2.span
2036 {
2037 return true;
2038 }
2039 }
2040 false
2041 }
2042
2043 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2044 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity);
2045 }
2046
2047 fn record_use_inner(
2048 &mut self,
2049 ident: Ident,
2050 used_decl: Decl<'ra>,
2051 used: Used,
2052 warn_ambiguity: bool,
2053 ) {
2054 if let Some(b2) = used_decl.ambiguity {
2055 let ambiguity_error = AmbiguityError {
2056 kind: AmbiguityKind::GlobVsGlob,
2057 ident,
2058 b1: used_decl,
2059 b2,
2060 scope1: Scope::ModuleGlobs(self.empty_module, None),
2061 scope2: Scope::ModuleGlobs(self.empty_module, None),
2062 warning: warn_ambiguity,
2063 };
2064 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2065 self.ambiguity_errors.push(ambiguity_error);
2067 }
2068 }
2069 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2070 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2071 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2074 let empty_module = self.empty_module;
2075 let arenas = self.arenas;
2076 self.cm()
2077 .maybe_resolve_ident_in_module(
2078 ModuleOrUniformRoot::Module(prelude),
2079 ident,
2080 MacroNS,
2081 &ParentScope::module(empty_module, arenas),
2082 None,
2083 )
2084 .is_ok()
2085 });
2086 if !found_in_stdlib_prelude {
2087 self.lint_buffer().buffer_lint(
2088 PRIVATE_MACRO_USE,
2089 import.root_id,
2090 ident.span,
2091 errors::MacroIsPrivate { ident },
2092 );
2093 }
2094 }
2095 if used == Used::Scope
2098 && let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident))
2099 && entry.item_decl == Some((used_decl, false))
2100 {
2101 return;
2102 }
2103 let old_used = self.import_use_map.entry(import).or_insert(used);
2104 if *old_used < used {
2105 *old_used = used;
2106 }
2107 if let Some(id) = import.id() {
2108 self.used_imports.insert(id);
2109 }
2110 self.add_to_glob_map(import, ident);
2111 self.record_use_inner(
2112 ident,
2113 source_decl,
2114 Used::Other,
2115 warn_ambiguity || source_decl.warn_ambiguity,
2116 );
2117 }
2118 }
2119
2120 #[inline]
2121 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2122 if let ImportKind::Glob { id, .. } = import.kind {
2123 let def_id = self.local_def_id(id);
2124 self.glob_map.entry(def_id).or_default().insert(ident.name);
2125 }
2126 }
2127
2128 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2129 debug!("resolve_crate_root({:?})", ident);
2130 let mut ctxt = ident.span.ctxt();
2131 let mark = if ident.name == kw::DollarCrate {
2132 ctxt = ctxt.normalize_to_macro_rules();
2139 debug!(
2140 "resolve_crate_root: marks={:?}",
2141 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2142 );
2143 let mut iter = ctxt.marks().into_iter().rev().peekable();
2144 let mut result = None;
2145 while let Some(&(mark, transparency)) = iter.peek() {
2147 if transparency == Transparency::Opaque {
2148 result = Some(mark);
2149 iter.next();
2150 } else {
2151 break;
2152 }
2153 }
2154 debug!(
2155 "resolve_crate_root: found opaque mark {:?} {:?}",
2156 result,
2157 result.map(|r| r.expn_data())
2158 );
2159 for (mark, transparency) in iter {
2161 if transparency == Transparency::SemiOpaque {
2162 result = Some(mark);
2163 } else {
2164 break;
2165 }
2166 }
2167 debug!(
2168 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2169 result,
2170 result.map(|r| r.expn_data())
2171 );
2172 result
2173 } else {
2174 debug!("resolve_crate_root: not DollarCrate");
2175 ctxt = ctxt.normalize_to_macros_2_0();
2176 ctxt.adjust(ExpnId::root())
2177 };
2178 let module = match mark {
2179 Some(def) => self.expn_def_scope(def),
2180 None => {
2181 debug!(
2182 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2183 ident, ident.span
2184 );
2185 return self.graph_root;
2186 }
2187 };
2188 let module = self.expect_module(
2189 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2190 );
2191 debug!(
2192 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2193 ident,
2194 module,
2195 module.kind.name(),
2196 ident.span
2197 );
2198 module
2199 }
2200
2201 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2202 let mut module = self.expect_module(module.nearest_parent_mod());
2203 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2204 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2205 module = self.expect_module(parent.nearest_parent_mod());
2206 }
2207 module
2208 }
2209
2210 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2211 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2212 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2213 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2214 }
2215 }
2216
2217 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2218 debug!("(recording pat) recording {:?} for {:?}", node, span);
2219 self.pat_span_map.insert(node, span);
2220 }
2221
2222 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2223 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2224 }
2225
2226 fn set_decl_parent_module(&mut self, decl: Decl<'ra>, module: Module<'ra>) {
2227 if let Some(old_module) = self.decl_parent_modules.insert(decl, module) {
2228 if module != old_module {
2229 span_bug!(decl.span, "parent module is reset for a name declaration");
2230 }
2231 }
2232 }
2233
2234 fn disambiguate_macro_rules_vs_modularized(
2235 &self,
2236 macro_rules: Decl<'ra>,
2237 modularized: Decl<'ra>,
2238 ) -> bool {
2239 let macro_rules = &self.decl_parent_modules[¯o_rules];
2247 let modularized = &self.decl_parent_modules[&modularized];
2248 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2249 && modularized.is_ancestor_of(*macro_rules)
2250 }
2251
2252 fn extern_prelude_get_item<'r>(
2253 mut self: CmResolver<'r, 'ra, 'tcx>,
2254 ident: Ident,
2255 finalize: bool,
2256 ) -> Option<Decl<'ra>> {
2257 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2258 entry.and_then(|entry| entry.item_decl).map(|(binding, _)| {
2259 if finalize {
2260 self.get_mut().record_use(ident, binding, Used::Scope);
2261 }
2262 binding
2263 })
2264 }
2265
2266 fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<Decl<'ra>> {
2267 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2268 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2269 let (pending_decl, finalized) = flag_decl.get();
2270 let decl = match pending_decl {
2271 PendingDecl::Ready(decl) => {
2272 if finalize && !finalized {
2273 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2274 }
2275 decl
2276 }
2277 PendingDecl::Pending => {
2278 debug_assert!(!finalized);
2279 let crate_id = if finalize {
2280 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2281 } else {
2282 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2283 };
2284 crate_id.map(|crate_id| {
2285 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2286 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2287 })
2288 }
2289 };
2290 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized));
2291 decl.or_else(|| finalize.then_some(self.dummy_decl))
2292 })
2293 }
2294
2295 fn resolve_rustdoc_path(
2300 &mut self,
2301 path_str: &str,
2302 ns: Namespace,
2303 parent_scope: ParentScope<'ra>,
2304 ) -> Option<Res> {
2305 let segments: Result<Vec<_>, ()> = path_str
2306 .split("::")
2307 .enumerate()
2308 .map(|(i, s)| {
2309 let sym = if s.is_empty() {
2310 if i == 0 {
2311 kw::PathRoot
2313 } else {
2314 return Err(()); }
2316 } else {
2317 Symbol::intern(s)
2318 };
2319 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2320 })
2321 .collect();
2322 let Ok(segments) = segments else { return None };
2323
2324 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2325 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2326 PathResult::NonModule(path_res) => {
2327 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2328 }
2329 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2330 None
2331 }
2332 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2333 }
2334 }
2335
2336 fn def_span(&self, def_id: DefId) -> Span {
2338 match def_id.as_local() {
2339 Some(def_id) => self.tcx.source_span(def_id),
2340 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2342 }
2343 }
2344
2345 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2346 match def_id.as_local() {
2347 Some(def_id) => self.field_names.get(&def_id).cloned(),
2348 None if matches!(
2349 self.tcx.def_kind(def_id),
2350 DefKind::Struct | DefKind::Union | DefKind::Variant
2351 ) =>
2352 {
2353 Some(
2354 self.tcx
2355 .associated_item_def_ids(def_id)
2356 .iter()
2357 .map(|&def_id| {
2358 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2359 })
2360 .collect(),
2361 )
2362 }
2363 _ => None,
2364 }
2365 }
2366
2367 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2368 match def_id.as_local() {
2369 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2370 None if matches!(
2371 self.tcx.def_kind(def_id),
2372 DefKind::Struct | DefKind::Union | DefKind::Variant
2373 ) =>
2374 {
2375 Some(
2376 self.tcx
2377 .associated_item_def_ids(def_id)
2378 .iter()
2379 .filter_map(|&def_id| {
2380 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2381 })
2382 .collect(),
2383 )
2384 }
2385 _ => None,
2386 }
2387 }
2388
2389 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2393 let ExprKind::Path(None, path) = &expr.kind else {
2394 return None;
2395 };
2396 if path.segments.last().unwrap().args.is_some() {
2399 return None;
2400 }
2401
2402 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2403
2404 if def_id.is_local() {
2408 return None;
2409 }
2410
2411 find_attr!(
2412 self.tcx.get_all_attrs(def_id),
2414 AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2415 )
2416 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2417 }
2418
2419 fn resolve_main(&mut self) {
2420 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2421 if !any_exe {
2423 return;
2424 }
2425
2426 let module = self.graph_root;
2427 let ident = Ident::with_dummy_span(sym::main);
2428 let parent_scope = &ParentScope::module(module, self.arenas);
2429
2430 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2431 ModuleOrUniformRoot::Module(module),
2432 ident,
2433 ValueNS,
2434 parent_scope,
2435 None,
2436 ) else {
2437 return;
2438 };
2439
2440 let res = name_binding.res();
2441 let is_import = name_binding.is_import();
2442 let span = name_binding.span;
2443 if let Res::Def(DefKind::Fn, _) = res {
2444 self.record_use(ident, name_binding, Used::Other);
2445 }
2446 self.main_def = Some(MainDefinition { res, is_import, span });
2447 }
2448}
2449
2450fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2451 let mut result = String::new();
2452 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2453 if i > 0 {
2454 result.push_str("::");
2455 }
2456 if Ident::with_dummy_span(name).is_raw_guess() {
2457 result.push_str("r#");
2458 }
2459 result.push_str(name.as_str());
2460 }
2461 result
2462}
2463
2464fn path_names_to_string(path: &Path) -> String {
2465 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2466}
2467
2468fn module_to_string(mut module: Module<'_>) -> Option<String> {
2470 let mut names = Vec::new();
2471 loop {
2472 if let ModuleKind::Def(.., name) = module.kind {
2473 if let Some(parent) = module.parent {
2474 names.push(name.unwrap());
2476 module = parent
2477 } else {
2478 break;
2479 }
2480 } else {
2481 names.push(sym::opaque_module_name_placeholder);
2482 let Some(parent) = module.parent else {
2483 return None;
2484 };
2485 module = parent;
2486 }
2487 }
2488 if names.is_empty() {
2489 return None;
2490 }
2491 Some(names_to_string(names.iter().rev().copied()))
2492}
2493
2494#[derive(Copy, Clone, PartialEq, Debug)]
2495enum Stage {
2496 Early,
2500 Late,
2503}
2504
2505#[derive(Copy, Clone, Debug)]
2507struct Finalize {
2508 node_id: NodeId,
2510 path_span: Span,
2513 root_span: Span,
2516 report_private: bool = true,
2519 used: Used = Used::Other,
2521 stage: Stage = Stage::Early,
2523}
2524
2525impl Finalize {
2526 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2527 Finalize::with_root_span(node_id, path_span, path_span)
2528 }
2529
2530 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2531 Finalize { node_id, path_span, root_span, .. }
2532 }
2533}
2534
2535pub fn provide(providers: &mut Providers) {
2536 providers.registered_tools = macros::registered_tools;
2537}
2538
2539type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2545
2546use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2550
2551mod ref_mut {
2554 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2555 use std::fmt;
2556 use std::ops::Deref;
2557
2558 use crate::Resolver;
2559
2560 pub(crate) struct RefOrMut<'a, T> {
2562 p: &'a mut T,
2563 mutable: bool,
2564 }
2565
2566 impl<'a, T> Deref for RefOrMut<'a, T> {
2567 type Target = T;
2568
2569 fn deref(&self) -> &Self::Target {
2570 self.p
2571 }
2572 }
2573
2574 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2575 fn as_ref(&self) -> &T {
2576 self.p
2577 }
2578 }
2579
2580 impl<'a, T> RefOrMut<'a, T> {
2581 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2582 RefOrMut { p, mutable }
2583 }
2584
2585 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2587 RefOrMut { p: self.p, mutable: self.mutable }
2588 }
2589
2590 #[track_caller]
2595 pub(crate) fn get_mut(&mut self) -> &mut T {
2596 match self.mutable {
2597 false => panic!("Can't mutably borrow speculative resolver"),
2598 true => self.p,
2599 }
2600 }
2601
2602 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2605 self.p
2606 }
2607 }
2608
2609 #[derive(Default)]
2611 pub(crate) struct CmCell<T>(Cell<T>);
2612
2613 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2615 f.debug_tuple("CmCell").field(&self.get()).finish()
2616 }
2617 }
2618
2619 impl<T: Copy> Clone for CmCell<T> {
2620 fn clone(&self) -> CmCell<T> {
2621 CmCell::new(self.get())
2622 }
2623 }
2624
2625 impl<T: Copy> CmCell<T> {
2626 pub(crate) const fn get(&self) -> T {
2627 self.0.get()
2628 }
2629
2630 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2631 where
2632 T: Copy,
2633 {
2634 let old = self.get();
2635 self.set_unchecked(f(old));
2636 }
2637 }
2638
2639 impl<T> CmCell<T> {
2640 pub(crate) const fn new(value: T) -> CmCell<T> {
2641 CmCell(Cell::new(value))
2642 }
2643
2644 pub(crate) fn set_unchecked(&self, val: T) {
2645 self.0.set(val);
2646 }
2647
2648 pub(crate) fn into_inner(self) -> T {
2649 self.0.into_inner()
2650 }
2651 }
2652
2653 #[derive(Default)]
2655 pub(crate) struct CmRefCell<T>(RefCell<T>);
2656
2657 impl<T> CmRefCell<T> {
2658 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2659 CmRefCell(RefCell::new(value))
2660 }
2661
2662 #[track_caller]
2663 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2664 self.0.borrow_mut()
2665 }
2666
2667 #[track_caller]
2668 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2669 if r.assert_speculative {
2670 panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2671 }
2672 self.borrow_mut_unchecked()
2673 }
2674
2675 #[track_caller]
2676 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2677 self.0.try_borrow_mut()
2678 }
2679
2680 #[track_caller]
2681 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2682 self.0.borrow()
2683 }
2684 }
2685
2686 impl<T: Default> CmRefCell<T> {
2687 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2688 if r.assert_speculative {
2689 panic!("Not allowed to mutate a CmRefCell during speculative resolution");
2690 }
2691 self.0.take()
2692 }
2693 }
2694}