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