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