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