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