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(rustc_attrs)]
23#![feature(rustdoc_internals)]
24#![recursion_limit = "256"]
25use std::cell::{Cell, Ref, RefCell};
28use std::collections::BTreeSet;
29use std::fmt;
30use std::sync::Arc;
31
32use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
33use effective_visibilities::EffectiveVisibilitiesVisitor;
34use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
35use imports::{Import, ImportData, ImportKind, NameResolution};
36use late::{
37 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
38 UnnecessaryQualification,
39};
40use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
41use rustc_arena::{DroplessArena, TypedArena};
42use rustc_ast::node_id::NodeMap;
43use rustc_ast::{
44 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
45 LitKind, NodeId, Path, attr,
46};
47use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
48use rustc_data_structures::intern::Interned;
49use rustc_data_structures::steal::Steal;
50use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
51use rustc_data_structures::unord::{UnordMap, UnordSet};
52use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed};
53use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
54use rustc_feature::BUILTIN_ATTRIBUTES;
55use rustc_hir::attrs::StrippedCfgItem;
56use rustc_hir::def::Namespace::{self, *};
57use rustc_hir::def::{
58 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
59 PerNS,
60};
61use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
62use rustc_hir::definitions::DisambiguatorState;
63use rustc_hir::{PrimTy, TraitCandidate};
64use rustc_index::bit_set::DenseBitSet;
65use rustc_metadata::creader::CStore;
66use rustc_middle::metadata::ModChild;
67use rustc_middle::middle::privacy::EffectiveVisibilities;
68use rustc_middle::query::Providers;
69use rustc_middle::span_bug;
70use rustc_middle::ty::{
71 self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
72 ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
73};
74use rustc_query_system::ich::StableHashingContext;
75use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
76use rustc_session::lint::{BuiltinLintDiag, LintBuffer};
77use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
78use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
79use smallvec::{SmallVec, smallvec};
80use tracing::debug;
81
82type Res = def::Res<NodeId>;
83
84mod build_reduced_graph;
85mod check_unused;
86mod def_collector;
87mod diagnostics;
88mod effective_visibilities;
89mod errors;
90mod ident;
91mod imports;
92mod late;
93mod macros;
94pub mod rustdoc;
95
96pub use macros::registered_tools_ast;
97
98rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
99
100#[derive(Debug)]
101enum Weak {
102 Yes,
103 No,
104}
105
106#[derive(Copy, Clone, PartialEq, Debug)]
107enum Determinacy {
108 Determined,
109 Undetermined,
110}
111
112impl Determinacy {
113 fn determined(determined: bool) -> Determinacy {
114 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
115 }
116}
117
118#[derive(Clone, Copy, Debug)]
120enum Scope<'ra> {
121 DeriveHelpers(LocalExpnId),
123 DeriveHelpersCompat,
127 MacroRules(MacroRulesScopeRef<'ra>),
129 Module(Module<'ra>, Option<NodeId>),
133 MacroUsePrelude,
135 BuiltinAttrs,
137 ExternPreludeItems,
139 ExternPreludeFlags,
141 ToolPrelude,
143 StdLibPrelude,
145 BuiltinTypes,
147}
148
149#[derive(Clone, Copy, Debug)]
152enum ScopeSet<'ra> {
153 All(Namespace),
155 ModuleAndExternPrelude(Namespace, Module<'ra>),
157 ExternPrelude,
159 Macro(MacroKind),
161 Late(Namespace, Module<'ra>, Option<NodeId>),
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: BTreeSet<Span>,
237 target: BTreeSet<Span>,
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> = RefCell<FxIndexMap<BindingKey, &'ra RefCell<NameResolution<'ra>>>>;
576
577struct ModuleData<'ra> {
589 parent: Option<Module<'ra>>,
591 kind: ModuleKind,
593
594 lazy_resolutions: Resolutions<'ra>,
597 populate_on_access: Cell<bool>,
599 underscore_disambiguator: Cell<u32>,
601
602 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
604
605 no_implicit_prelude: bool,
607
608 glob_importers: RefCell<Vec<Import<'ra>>>,
609 globs: RefCell<Vec<Import<'ra>>>,
610
611 traits:
613 RefCell<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: Cell::new(is_foreign),
662 underscore_disambiguator: Cell::new(0),
663 unexpanded_invocations: Default::default(),
664 no_implicit_prelude,
665 glob_importers: RefCell::new(Vec::new()),
666 globs: RefCell::new(Vec::new()),
667 traits: RefCell::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();
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
1031#[derive(Default, Clone)]
1032struct ExternPreludeEntry<'ra> {
1033 item_binding: Option<NameBinding<'ra>>,
1035 flag_binding: Cell<Option<NameBinding<'ra>>>,
1037 only_item: bool,
1040 introduced_by_item: bool,
1043}
1044
1045struct DeriveData {
1046 resolutions: Vec<DeriveResolution>,
1047 helper_attrs: Vec<(usize, Ident)>,
1048 has_derive_copy: bool,
1049}
1050
1051struct MacroData {
1052 ext: Arc<SyntaxExtension>,
1053 nrules: usize,
1054 macro_rules: bool,
1055}
1056
1057impl MacroData {
1058 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1059 MacroData { ext, nrules: 0, macro_rules: false }
1060 }
1061}
1062
1063pub struct ResolverOutputs {
1064 pub global_ctxt: ResolverGlobalCtxt,
1065 pub ast_lowering: ResolverAstLowering,
1066}
1067
1068pub struct Resolver<'ra, 'tcx> {
1072 tcx: TyCtxt<'tcx>,
1073
1074 expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1076
1077 graph_root: Module<'ra>,
1078
1079 assert_speculative: bool,
1081
1082 prelude: Option<Module<'ra>> = None,
1083 extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1084
1085 field_names: LocalDefIdMap<Vec<Ident>>,
1087 field_defaults: LocalDefIdMap<Vec<Symbol>>,
1088
1089 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1092
1093 determined_imports: Vec<Import<'ra>> = Vec::new(),
1095
1096 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1098
1099 pat_span_map: NodeMap<Span>,
1102
1103 partial_res_map: NodeMap<PartialRes>,
1105 import_res_map: NodeMap<PerNS<Option<Res>>>,
1107 import_use_map: FxHashMap<Import<'ra>, Used>,
1109 label_res_map: NodeMap<NodeId>,
1111 lifetimes_res_map: NodeMap<LifetimeRes>,
1113 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1115
1116 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1118 module_children: LocalDefIdMap<Vec<ModChild>>,
1119 trait_map: NodeMap<Vec<TraitCandidate>>,
1120
1121 block_map: NodeMap<Module<'ra>>,
1136 empty_module: Module<'ra>,
1140 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1142 extern_module_map: RefCell<FxIndexMap<DefId, Module<'ra>>>,
1144 binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1145
1146 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1148 glob_error: Option<ErrorGuaranteed> = None,
1149 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1150 used_imports: FxHashSet<NodeId>,
1151 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1152
1153 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1155 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1157 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1159 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1161
1162 arenas: &'ra ResolverArenas<'ra>,
1163 dummy_binding: NameBinding<'ra>,
1164 builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1165 builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1166 registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1167 macro_names: FxHashSet<Ident>,
1168 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1169 registered_tools: &'tcx RegisteredTools,
1170 macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1171 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1173 extern_macro_map: RefCell<FxHashMap<DefId, &'ra MacroData>>,
1175 dummy_ext_bang: Arc<SyntaxExtension>,
1176 dummy_ext_derive: Arc<SyntaxExtension>,
1177 non_macro_attr: &'ra MacroData,
1178 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1179 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1180 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1181 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1183 proc_macro_stubs: FxHashSet<LocalDefId>,
1184 single_segment_macro_resolutions:
1187 RefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1188 multi_segment_macro_resolutions:
1189 RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1190 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1191 containers_deriving_copy: FxHashSet<LocalExpnId>,
1195 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1198 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1201 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1203 helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1205 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1208
1209 name_already_seen: FxHashMap<Symbol, Span>,
1211
1212 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1213
1214 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1215
1216 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1220
1221 lint_buffer: LintBuffer,
1222
1223 next_node_id: NodeId = CRATE_NODE_ID,
1224
1225 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1226
1227 disambiguator: DisambiguatorState,
1228
1229 placeholder_field_indices: FxHashMap<NodeId, usize>,
1231 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1235
1236 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1237 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1239 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1240
1241 main_def: Option<MainDefinition> = None,
1242 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1243 proc_macros: Vec<LocalDefId> = Vec::new(),
1246 confused_type_with_std_module: FxIndexMap<Span, Span>,
1247 lifetime_elision_allowed: FxHashSet<NodeId>,
1249
1250 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1252
1253 effective_visibilities: EffectiveVisibilities,
1254 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1255 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1256 all_macro_rules: UnordSet<Symbol>,
1257
1258 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1260 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1263 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1266
1267 current_crate_outer_attr_insert_span: Span,
1270
1271 mods_with_parse_errors: FxHashSet<DefId>,
1272
1273 all_crate_macros_already_registered: bool = false,
1276
1277 impl_trait_names: FxHashMap<NodeId, Symbol>,
1281}
1282
1283#[derive(Default)]
1286pub struct ResolverArenas<'ra> {
1287 modules: TypedArena<ModuleData<'ra>>,
1288 local_modules: RefCell<Vec<Module<'ra>>>,
1289 imports: TypedArena<ImportData<'ra>>,
1290 name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1291 ast_paths: TypedArena<ast::Path>,
1292 macros: TypedArena<MacroData>,
1293 dropless: DroplessArena,
1294}
1295
1296impl<'ra> ResolverArenas<'ra> {
1297 fn new_res_binding(
1298 &'ra self,
1299 res: Res,
1300 vis: Visibility<DefId>,
1301 span: Span,
1302 expansion: LocalExpnId,
1303 ) -> NameBinding<'ra> {
1304 self.alloc_name_binding(NameBindingData {
1305 kind: NameBindingKind::Res(res),
1306 ambiguity: None,
1307 warn_ambiguity: false,
1308 vis,
1309 span,
1310 expansion,
1311 })
1312 }
1313
1314 fn new_pub_res_binding(
1315 &'ra self,
1316 res: Res,
1317 span: Span,
1318 expn_id: LocalExpnId,
1319 ) -> NameBinding<'ra> {
1320 self.new_res_binding(res, Visibility::Public, span, expn_id)
1321 }
1322
1323 fn new_module(
1324 &'ra self,
1325 parent: Option<Module<'ra>>,
1326 kind: ModuleKind,
1327 expn_id: ExpnId,
1328 span: Span,
1329 no_implicit_prelude: bool,
1330 ) -> Module<'ra> {
1331 let (def_id, self_binding) = match kind {
1332 ModuleKind::Def(def_kind, def_id, _) => (
1333 Some(def_id),
1334 Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT)),
1335 ),
1336 ModuleKind::Block => (None, None),
1337 };
1338 let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1339 parent,
1340 kind,
1341 expn_id,
1342 span,
1343 no_implicit_prelude,
1344 self_binding,
1345 ))));
1346 if def_id.is_none_or(|def_id| def_id.is_local()) {
1347 self.local_modules.borrow_mut().push(module);
1348 }
1349 module
1350 }
1351 fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1352 self.local_modules.borrow()
1353 }
1354 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1355 Interned::new_unchecked(self.dropless.alloc(name_binding))
1356 }
1357 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1358 Interned::new_unchecked(self.imports.alloc(import))
1359 }
1360 fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1361 self.name_resolutions.alloc(Default::default())
1362 }
1363 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1364 self.dropless.alloc(Cell::new(scope))
1365 }
1366 fn alloc_macro_rules_binding(
1367 &'ra self,
1368 binding: MacroRulesBinding<'ra>,
1369 ) -> &'ra MacroRulesBinding<'ra> {
1370 self.dropless.alloc(binding)
1371 }
1372 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1373 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1374 }
1375 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1376 self.macros.alloc(macro_data)
1377 }
1378 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1379 self.dropless.alloc_from_iter(spans)
1380 }
1381}
1382
1383impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1384 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1385 self
1386 }
1387}
1388
1389impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1390 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1391 self
1392 }
1393}
1394
1395impl<'tcx> Resolver<'_, 'tcx> {
1396 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1397 self.opt_feed(node).map(|f| f.key())
1398 }
1399
1400 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1401 self.feed(node).key()
1402 }
1403
1404 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1405 self.node_id_to_def_id.get(&node).copied()
1406 }
1407
1408 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1409 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1410 }
1411
1412 fn local_def_kind(&self, node: NodeId) -> DefKind {
1413 self.tcx.def_kind(self.local_def_id(node))
1414 }
1415
1416 fn create_def(
1418 &mut self,
1419 parent: LocalDefId,
1420 node_id: ast::NodeId,
1421 name: Option<Symbol>,
1422 def_kind: DefKind,
1423 expn_id: ExpnId,
1424 span: Span,
1425 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1426 assert!(
1427 !self.node_id_to_def_id.contains_key(&node_id),
1428 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1429 node_id,
1430 name,
1431 def_kind,
1432 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1433 );
1434
1435 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1437 let def_id = feed.def_id();
1438
1439 if expn_id != ExpnId::root() {
1441 self.expn_that_defined.insert(def_id, expn_id);
1442 }
1443
1444 debug_assert_eq!(span.data_untracked().parent, None);
1446 let _id = self.tcx.untracked().source_span.push(span);
1447 debug_assert_eq!(_id, def_id);
1448
1449 if node_id != ast::DUMMY_NODE_ID {
1453 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1454 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1455 }
1456
1457 feed
1458 }
1459
1460 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1461 if let Some(def_id) = def_id.as_local() {
1462 self.item_generics_num_lifetimes[&def_id]
1463 } else {
1464 self.tcx.generics_of(def_id).own_counts().lifetimes
1465 }
1466 }
1467
1468 pub fn tcx(&self) -> TyCtxt<'tcx> {
1469 self.tcx
1470 }
1471
1472 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1477 self.node_id_to_def_id
1478 .items()
1479 .filter(|(_, v)| v.key() == def_id)
1480 .map(|(k, _)| *k)
1481 .get_only()
1482 .unwrap()
1483 }
1484}
1485
1486impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1487 pub fn new(
1488 tcx: TyCtxt<'tcx>,
1489 attrs: &[ast::Attribute],
1490 crate_span: Span,
1491 current_crate_outer_attr_insert_span: Span,
1492 arenas: &'ra ResolverArenas<'ra>,
1493 ) -> Resolver<'ra, 'tcx> {
1494 let root_def_id = CRATE_DEF_ID.to_def_id();
1495 let mut local_module_map = FxIndexMap::default();
1496 let graph_root = arenas.new_module(
1497 None,
1498 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1499 ExpnId::root(),
1500 crate_span,
1501 attr::contains_name(attrs, sym::no_implicit_prelude),
1502 );
1503 local_module_map.insert(CRATE_DEF_ID, graph_root);
1504 let empty_module = arenas.new_module(
1505 None,
1506 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1507 ExpnId::root(),
1508 DUMMY_SP,
1509 true,
1510 );
1511
1512 let mut node_id_to_def_id = NodeMap::default();
1513 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1514
1515 crate_feed.def_kind(DefKind::Mod);
1516 let crate_feed = crate_feed.downgrade();
1517 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1518
1519 let mut invocation_parents = FxHashMap::default();
1520 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1521
1522 let mut extern_prelude: FxIndexMap<_, _> = tcx
1523 .sess
1524 .opts
1525 .externs
1526 .iter()
1527 .filter_map(|(name, entry)| {
1528 if entry.add_prelude
1531 && let name = Symbol::intern(name)
1532 && name.can_be_raw()
1533 {
1534 Some((Macros20NormalizedIdent::with_dummy_span(name), Default::default()))
1535 } else {
1536 None
1537 }
1538 })
1539 .collect();
1540
1541 if !attr::contains_name(attrs, sym::no_core) {
1542 extern_prelude
1543 .insert(Macros20NormalizedIdent::with_dummy_span(sym::core), Default::default());
1544 if !attr::contains_name(attrs, sym::no_std) {
1545 extern_prelude
1546 .insert(Macros20NormalizedIdent::with_dummy_span(sym::std), Default::default());
1547 }
1548 }
1549
1550 let registered_tools = tcx.registered_tools(());
1551 let edition = tcx.sess.edition();
1552
1553 let mut resolver = Resolver {
1554 tcx,
1555
1556 expn_that_defined: Default::default(),
1557
1558 graph_root,
1561 assert_speculative: false, prelude: None,
1563 extern_prelude,
1564
1565 field_names: Default::default(),
1566 field_defaults: Default::default(),
1567 field_visibility_spans: FxHashMap::default(),
1568
1569 pat_span_map: Default::default(),
1570 partial_res_map: Default::default(),
1571 import_res_map: Default::default(),
1572 import_use_map: Default::default(),
1573 label_res_map: Default::default(),
1574 lifetimes_res_map: Default::default(),
1575 extra_lifetime_params_map: Default::default(),
1576 extern_crate_map: Default::default(),
1577 module_children: Default::default(),
1578 trait_map: NodeMap::default(),
1579 empty_module,
1580 local_module_map,
1581 extern_module_map: Default::default(),
1582 block_map: Default::default(),
1583 binding_parent_modules: FxHashMap::default(),
1584 ast_transform_scopes: FxHashMap::default(),
1585
1586 glob_map: Default::default(),
1587 used_imports: FxHashSet::default(),
1588 maybe_unused_trait_imports: Default::default(),
1589
1590 arenas,
1591 dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1592 builtin_types_bindings: PrimTy::ALL
1593 .iter()
1594 .map(|prim_ty| {
1595 let res = Res::PrimTy(*prim_ty);
1596 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1597 (prim_ty.name(), binding)
1598 })
1599 .collect(),
1600 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1601 .iter()
1602 .map(|builtin_attr| {
1603 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1604 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1605 (builtin_attr.name, binding)
1606 })
1607 .collect(),
1608 registered_tool_bindings: registered_tools
1609 .iter()
1610 .map(|ident| {
1611 let res = Res::ToolMod;
1612 let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1613 (*ident, binding)
1614 })
1615 .collect(),
1616 macro_names: FxHashSet::default(),
1617 builtin_macros: Default::default(),
1618 registered_tools,
1619 macro_use_prelude: Default::default(),
1620 local_macro_map: Default::default(),
1621 extern_macro_map: Default::default(),
1622 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1623 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1624 non_macro_attr: arenas
1625 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1626 invocation_parent_scopes: Default::default(),
1627 output_macro_rules_scopes: Default::default(),
1628 macro_rules_scopes: Default::default(),
1629 helper_attrs: Default::default(),
1630 derive_data: Default::default(),
1631 local_macro_def_scopes: FxHashMap::default(),
1632 name_already_seen: FxHashMap::default(),
1633 struct_constructors: Default::default(),
1634 unused_macros: Default::default(),
1635 unused_macro_rules: Default::default(),
1636 proc_macro_stubs: Default::default(),
1637 single_segment_macro_resolutions: Default::default(),
1638 multi_segment_macro_resolutions: Default::default(),
1639 builtin_attrs: Default::default(),
1640 containers_deriving_copy: Default::default(),
1641 lint_buffer: LintBuffer::default(),
1642 node_id_to_def_id,
1643 disambiguator: DisambiguatorState::new(),
1644 placeholder_field_indices: Default::default(),
1645 invocation_parents,
1646 legacy_const_generic_args: Default::default(),
1647 item_generics_num_lifetimes: Default::default(),
1648 trait_impls: Default::default(),
1649 confused_type_with_std_module: Default::default(),
1650 lifetime_elision_allowed: Default::default(),
1651 stripped_cfg_items: Default::default(),
1652 effective_visibilities: Default::default(),
1653 doc_link_resolutions: Default::default(),
1654 doc_link_traits_in_scope: Default::default(),
1655 all_macro_rules: Default::default(),
1656 delegation_fn_sigs: Default::default(),
1657 glob_delegation_invoc_ids: Default::default(),
1658 impl_unexpanded_invocations: Default::default(),
1659 impl_binding_keys: Default::default(),
1660 current_crate_outer_attr_insert_span,
1661 mods_with_parse_errors: Default::default(),
1662 impl_trait_names: Default::default(),
1663 ..
1664 };
1665
1666 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1667 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1668 resolver.feed_visibility(crate_feed, Visibility::Public);
1669
1670 resolver
1671 }
1672
1673 fn new_local_module(
1674 &mut self,
1675 parent: Option<Module<'ra>>,
1676 kind: ModuleKind,
1677 expn_id: ExpnId,
1678 span: Span,
1679 no_implicit_prelude: bool,
1680 ) -> Module<'ra> {
1681 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1682 if let Some(def_id) = module.opt_def_id() {
1683 self.local_module_map.insert(def_id.expect_local(), module);
1684 }
1685 module
1686 }
1687
1688 fn new_extern_module(
1689 &self,
1690 parent: Option<Module<'ra>>,
1691 kind: ModuleKind,
1692 expn_id: ExpnId,
1693 span: Span,
1694 no_implicit_prelude: bool,
1695 ) -> Module<'ra> {
1696 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1697 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1698 module
1699 }
1700
1701 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1702 let mac = self.arenas.alloc_macro(macro_data);
1703 self.local_macro_map.insert(def_id, mac);
1704 mac
1705 }
1706
1707 fn next_node_id(&mut self) -> NodeId {
1708 let start = self.next_node_id;
1709 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1710 self.next_node_id = ast::NodeId::from_u32(next);
1711 start
1712 }
1713
1714 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1715 let start = self.next_node_id;
1716 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1717 self.next_node_id = ast::NodeId::from_usize(end);
1718 start..self.next_node_id
1719 }
1720
1721 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1722 &mut self.lint_buffer
1723 }
1724
1725 pub fn arenas() -> ResolverArenas<'ra> {
1726 Default::default()
1727 }
1728
1729 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1730 let feed = feed.upgrade(self.tcx);
1731 feed.visibility(vis.to_def_id());
1732 self.visibilities_for_hashing.push((feed.def_id(), vis));
1733 }
1734
1735 pub fn into_outputs(self) -> ResolverOutputs {
1736 let proc_macros = self.proc_macros;
1737 let expn_that_defined = self.expn_that_defined;
1738 let extern_crate_map = self.extern_crate_map;
1739 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1740 let glob_map = self.glob_map;
1741 let main_def = self.main_def;
1742 let confused_type_with_std_module = self.confused_type_with_std_module;
1743 let effective_visibilities = self.effective_visibilities;
1744
1745 let stripped_cfg_items = self
1746 .stripped_cfg_items
1747 .into_iter()
1748 .filter_map(|item| {
1749 let parent_module =
1750 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1751 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1752 })
1753 .collect();
1754
1755 let global_ctxt = ResolverGlobalCtxt {
1756 expn_that_defined,
1757 visibilities_for_hashing: self.visibilities_for_hashing,
1758 effective_visibilities,
1759 extern_crate_map,
1760 module_children: self.module_children,
1761 glob_map,
1762 maybe_unused_trait_imports,
1763 main_def,
1764 trait_impls: self.trait_impls,
1765 proc_macros,
1766 confused_type_with_std_module,
1767 doc_link_resolutions: self.doc_link_resolutions,
1768 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1769 all_macro_rules: self.all_macro_rules,
1770 stripped_cfg_items,
1771 };
1772 let ast_lowering = ty::ResolverAstLowering {
1773 legacy_const_generic_args: self.legacy_const_generic_args,
1774 partial_res_map: self.partial_res_map,
1775 import_res_map: self.import_res_map,
1776 label_res_map: self.label_res_map,
1777 lifetimes_res_map: self.lifetimes_res_map,
1778 extra_lifetime_params_map: self.extra_lifetime_params_map,
1779 next_node_id: self.next_node_id,
1780 node_id_to_def_id: self
1781 .node_id_to_def_id
1782 .into_items()
1783 .map(|(k, f)| (k, f.key()))
1784 .collect(),
1785 disambiguator: self.disambiguator,
1786 trait_map: self.trait_map,
1787 lifetime_elision_allowed: self.lifetime_elision_allowed,
1788 lint_buffer: Steal::new(self.lint_buffer),
1789 delegation_fn_sigs: self.delegation_fn_sigs,
1790 };
1791 ResolverOutputs { global_ctxt, ast_lowering }
1792 }
1793
1794 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1795 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1796 }
1797
1798 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1799 CStore::from_tcx(self.tcx)
1800 }
1801
1802 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1803 CStore::from_tcx_mut(self.tcx)
1804 }
1805
1806 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1807 match macro_kind {
1808 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1809 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1810 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1811 }
1812 }
1813
1814 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1819 CmResolver::new(self, !self.assert_speculative)
1820 }
1821
1822 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1824 f(self, TypeNS);
1825 f(self, ValueNS);
1826 f(self, MacroNS);
1827 }
1828
1829 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1830 mut self: CmResolver<'r, 'ra, 'tcx>,
1831 mut f: F,
1832 ) {
1833 f(&mut self, TypeNS);
1834 f(&mut self, ValueNS);
1835 f(&mut self, MacroNS);
1836 }
1837
1838 fn is_builtin_macro(&self, res: Res) -> bool {
1839 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1840 }
1841
1842 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1843 loop {
1844 match ctxt.outer_expn_data().macro_def_id {
1845 Some(def_id) => return def_id,
1846 None => ctxt.remove_mark(),
1847 };
1848 }
1849 }
1850
1851 pub fn resolve_crate(&mut self, krate: &Crate) {
1853 self.tcx.sess.time("resolve_crate", || {
1854 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1855 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1856 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1857 });
1858 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1859 self.tcx
1860 .sess
1861 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1862 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1863 self.tcx.sess.time("resolve_main", || self.resolve_main());
1864 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1865 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1866 self.tcx
1867 .sess
1868 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1869 });
1870
1871 self.tcx.untracked().cstore.freeze();
1873 }
1874
1875 fn traits_in_scope(
1876 &mut self,
1877 current_trait: Option<Module<'ra>>,
1878 parent_scope: &ParentScope<'ra>,
1879 ctxt: SyntaxContext,
1880 assoc_item: Option<(Symbol, Namespace)>,
1881 ) -> Vec<TraitCandidate> {
1882 let mut found_traits = Vec::new();
1883
1884 if let Some(module) = current_trait {
1885 if self.trait_may_have_item(Some(module), assoc_item) {
1886 let def_id = module.def_id();
1887 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1888 }
1889 }
1890
1891 self.cm().visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1892 match scope {
1893 Scope::Module(module, _) => {
1894 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1895 }
1896 Scope::StdLibPrelude => {
1897 if let Some(module) = this.prelude {
1898 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1899 }
1900 }
1901 Scope::ExternPreludeItems
1902 | Scope::ExternPreludeFlags
1903 | Scope::ToolPrelude
1904 | Scope::BuiltinTypes => {}
1905 _ => unreachable!(),
1906 }
1907 None::<()>
1908 });
1909
1910 found_traits
1911 }
1912
1913 fn traits_in_module(
1914 &mut self,
1915 module: Module<'ra>,
1916 assoc_item: Option<(Symbol, Namespace)>,
1917 found_traits: &mut Vec<TraitCandidate>,
1918 ) {
1919 module.ensure_traits(self);
1920 let traits = module.traits.borrow();
1921 for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1922 if self.trait_may_have_item(trait_module, assoc_item) {
1923 let def_id = trait_binding.res().def_id();
1924 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1925 found_traits.push(TraitCandidate { def_id, import_ids });
1926 }
1927 }
1928 }
1929
1930 fn trait_may_have_item(
1936 &self,
1937 trait_module: Option<Module<'ra>>,
1938 assoc_item: Option<(Symbol, Namespace)>,
1939 ) -> bool {
1940 match (trait_module, assoc_item) {
1941 (Some(trait_module), Some((name, ns))) => self
1942 .resolutions(trait_module)
1943 .borrow()
1944 .iter()
1945 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1946 _ => true,
1947 }
1948 }
1949
1950 fn find_transitive_imports(
1951 &mut self,
1952 mut kind: &NameBindingKind<'_>,
1953 trait_name: Ident,
1954 ) -> SmallVec<[LocalDefId; 1]> {
1955 let mut import_ids = smallvec![];
1956 while let NameBindingKind::Import { import, binding, .. } = kind {
1957 if let Some(node_id) = import.id() {
1958 let def_id = self.local_def_id(node_id);
1959 self.maybe_unused_trait_imports.insert(def_id);
1960 import_ids.push(def_id);
1961 }
1962 self.add_to_glob_map(*import, trait_name);
1963 kind = &binding.kind;
1964 }
1965 import_ids
1966 }
1967
1968 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1969 if module.populate_on_access.get() {
1970 module.populate_on_access.set(false);
1971 self.build_reduced_graph_external(module);
1972 }
1973 &module.0.0.lazy_resolutions
1974 }
1975
1976 fn resolution(
1977 &self,
1978 module: Module<'ra>,
1979 key: BindingKey,
1980 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
1981 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
1982 }
1983
1984 fn resolution_or_default(
1985 &self,
1986 module: Module<'ra>,
1987 key: BindingKey,
1988 ) -> &'ra RefCell<NameResolution<'ra>> {
1989 self.resolutions(module)
1990 .borrow_mut()
1991 .entry(key)
1992 .or_insert_with(|| self.arenas.alloc_name_resolution())
1993 }
1994
1995 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1997 for ambiguity_error in &self.ambiguity_errors {
1998 if ambiguity_error.kind == ambi.kind
2000 && ambiguity_error.ident == ambi.ident
2001 && ambiguity_error.ident.span == ambi.ident.span
2002 && ambiguity_error.b1.span == ambi.b1.span
2003 && ambiguity_error.b2.span == ambi.b2.span
2004 && ambiguity_error.misc1 == ambi.misc1
2005 && ambiguity_error.misc2 == ambi.misc2
2006 {
2007 return true;
2008 }
2009 }
2010 false
2011 }
2012
2013 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2014 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2015 }
2016
2017 fn record_use_inner(
2018 &mut self,
2019 ident: Ident,
2020 used_binding: NameBinding<'ra>,
2021 used: Used,
2022 warn_ambiguity: bool,
2023 ) {
2024 if let Some((b2, kind)) = used_binding.ambiguity {
2025 let ambiguity_error = AmbiguityError {
2026 kind,
2027 ident,
2028 b1: used_binding,
2029 b2,
2030 misc1: AmbiguityErrorMisc::None,
2031 misc2: AmbiguityErrorMisc::None,
2032 warning: warn_ambiguity,
2033 };
2034 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2035 self.ambiguity_errors.push(ambiguity_error);
2037 }
2038 }
2039 if let NameBindingKind::Import { import, binding } = used_binding.kind {
2040 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2041 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2044 let empty_module = self.empty_module;
2045 let arenas = self.arenas;
2046 self.cm()
2047 .maybe_resolve_ident_in_module(
2048 ModuleOrUniformRoot::Module(prelude),
2049 ident,
2050 MacroNS,
2051 &ParentScope::module(empty_module, arenas),
2052 None,
2053 )
2054 .is_ok()
2055 });
2056 if !found_in_stdlib_prelude {
2057 self.lint_buffer().buffer_lint(
2058 PRIVATE_MACRO_USE,
2059 import.root_id,
2060 ident.span,
2061 BuiltinLintDiag::MacroIsPrivate(ident),
2062 );
2063 }
2064 }
2065 if used == Used::Scope {
2068 if let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident)) {
2069 if !entry.introduced_by_item && entry.item_binding == Some(used_binding) {
2070 return;
2071 }
2072 }
2073 }
2074 let old_used = self.import_use_map.entry(import).or_insert(used);
2075 if *old_used < used {
2076 *old_used = used;
2077 }
2078 if let Some(id) = import.id() {
2079 self.used_imports.insert(id);
2080 }
2081 self.add_to_glob_map(import, ident);
2082 self.record_use_inner(
2083 ident,
2084 binding,
2085 Used::Other,
2086 warn_ambiguity || binding.warn_ambiguity,
2087 );
2088 }
2089 }
2090
2091 #[inline]
2092 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2093 if let ImportKind::Glob { id, .. } = import.kind {
2094 let def_id = self.local_def_id(id);
2095 self.glob_map.entry(def_id).or_default().insert(ident.name);
2096 }
2097 }
2098
2099 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2100 debug!("resolve_crate_root({:?})", ident);
2101 let mut ctxt = ident.span.ctxt();
2102 let mark = if ident.name == kw::DollarCrate {
2103 ctxt = ctxt.normalize_to_macro_rules();
2110 debug!(
2111 "resolve_crate_root: marks={:?}",
2112 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2113 );
2114 let mut iter = ctxt.marks().into_iter().rev().peekable();
2115 let mut result = None;
2116 while let Some(&(mark, transparency)) = iter.peek() {
2118 if transparency == Transparency::Opaque {
2119 result = Some(mark);
2120 iter.next();
2121 } else {
2122 break;
2123 }
2124 }
2125 debug!(
2126 "resolve_crate_root: found opaque mark {:?} {:?}",
2127 result,
2128 result.map(|r| r.expn_data())
2129 );
2130 for (mark, transparency) in iter {
2132 if transparency == Transparency::SemiOpaque {
2133 result = Some(mark);
2134 } else {
2135 break;
2136 }
2137 }
2138 debug!(
2139 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2140 result,
2141 result.map(|r| r.expn_data())
2142 );
2143 result
2144 } else {
2145 debug!("resolve_crate_root: not DollarCrate");
2146 ctxt = ctxt.normalize_to_macros_2_0();
2147 ctxt.adjust(ExpnId::root())
2148 };
2149 let module = match mark {
2150 Some(def) => self.expn_def_scope(def),
2151 None => {
2152 debug!(
2153 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2154 ident, ident.span
2155 );
2156 return self.graph_root;
2157 }
2158 };
2159 let module = self.expect_module(
2160 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2161 );
2162 debug!(
2163 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2164 ident,
2165 module,
2166 module.kind.name(),
2167 ident.span
2168 );
2169 module
2170 }
2171
2172 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2173 let mut module = self.expect_module(module.nearest_parent_mod());
2174 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2175 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2176 module = self.expect_module(parent.nearest_parent_mod());
2177 }
2178 module
2179 }
2180
2181 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2182 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2183 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2184 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2185 }
2186 }
2187
2188 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2189 debug!("(recording pat) recording {:?} for {:?}", node, span);
2190 self.pat_span_map.insert(node, span);
2191 }
2192
2193 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2194 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2195 }
2196
2197 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2198 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2199 if module != old_module {
2200 span_bug!(binding.span, "parent module is reset for binding");
2201 }
2202 }
2203 }
2204
2205 fn disambiguate_macro_rules_vs_modularized(
2206 &self,
2207 macro_rules: NameBinding<'ra>,
2208 modularized: NameBinding<'ra>,
2209 ) -> bool {
2210 match (
2214 self.binding_parent_modules.get(¯o_rules),
2215 self.binding_parent_modules.get(&modularized),
2216 ) {
2217 (Some(macro_rules), Some(modularized)) => {
2218 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2219 && modularized.is_ancestor_of(*macro_rules)
2220 }
2221 _ => false,
2222 }
2223 }
2224
2225 fn extern_prelude_get_item<'r>(
2226 mut self: CmResolver<'r, 'ra, 'tcx>,
2227 ident: Ident,
2228 finalize: bool,
2229 ) -> Option<NameBinding<'ra>> {
2230 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2231 entry.and_then(|entry| entry.item_binding).map(|binding| {
2232 if finalize {
2233 self.get_mut().record_use(ident, binding, Used::Scope);
2234 }
2235 binding
2236 })
2237 }
2238
2239 fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2240 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2241 entry.and_then(|entry| match entry.flag_binding.get() {
2242 Some(binding) => {
2243 if finalize {
2244 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2245 }
2246 Some(binding)
2247 }
2248 None if entry.only_item => None,
2249 None => {
2250 let crate_id = if finalize {
2251 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2252 } else {
2253 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2254 };
2255 match crate_id {
2256 Some(crate_id) => {
2257 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2258 let binding =
2259 self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
2260 entry.flag_binding.set(Some(binding));
2261 Some(binding)
2262 }
2263 None => finalize.then_some(self.dummy_binding),
2264 }
2265 }
2266 })
2267 }
2268
2269 fn resolve_rustdoc_path(
2274 &mut self,
2275 path_str: &str,
2276 ns: Namespace,
2277 parent_scope: ParentScope<'ra>,
2278 ) -> Option<Res> {
2279 let segments: Result<Vec<_>, ()> = path_str
2280 .split("::")
2281 .enumerate()
2282 .map(|(i, s)| {
2283 let sym = if s.is_empty() {
2284 if i == 0 {
2285 kw::PathRoot
2287 } else {
2288 return Err(()); }
2290 } else {
2291 Symbol::intern(s)
2292 };
2293 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2294 })
2295 .collect();
2296 let Ok(segments) = segments else { return None };
2297
2298 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2299 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2300 PathResult::NonModule(path_res) => {
2301 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2302 }
2303 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2304 None
2305 }
2306 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2307 }
2308 }
2309
2310 fn def_span(&self, def_id: DefId) -> Span {
2312 match def_id.as_local() {
2313 Some(def_id) => self.tcx.source_span(def_id),
2314 None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2316 }
2317 }
2318
2319 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2320 match def_id.as_local() {
2321 Some(def_id) => self.field_names.get(&def_id).cloned(),
2322 None => Some(
2323 self.tcx
2324 .associated_item_def_ids(def_id)
2325 .iter()
2326 .map(|&def_id| {
2327 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2328 })
2329 .collect(),
2330 ),
2331 }
2332 }
2333
2334 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2335 match def_id.as_local() {
2336 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2337 None => Some(
2338 self.tcx
2339 .associated_item_def_ids(def_id)
2340 .iter()
2341 .filter_map(|&def_id| {
2342 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2343 })
2344 .collect(),
2345 ),
2346 }
2347 }
2348
2349 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2353 if let ExprKind::Path(None, path) = &expr.kind {
2354 if path.segments.last().unwrap().args.is_some() {
2357 return None;
2358 }
2359
2360 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2361 if let Res::Def(def::DefKind::Fn, def_id) = res {
2362 if def_id.is_local() {
2366 return None;
2367 }
2368
2369 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2370 return v.clone();
2371 }
2372
2373 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2374 let mut ret = Vec::new();
2375 for meta in attr.meta_item_list()? {
2376 match meta.lit()?.kind {
2377 LitKind::Int(a, _) => ret.push(a.get() as usize),
2378 _ => panic!("invalid arg index"),
2379 }
2380 }
2381 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2383 return Some(ret);
2384 }
2385 }
2386 None
2387 }
2388
2389 fn resolve_main(&mut self) {
2390 let module = self.graph_root;
2391 let ident = Ident::with_dummy_span(sym::main);
2392 let parent_scope = &ParentScope::module(module, self.arenas);
2393
2394 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2395 ModuleOrUniformRoot::Module(module),
2396 ident,
2397 ValueNS,
2398 parent_scope,
2399 None,
2400 ) else {
2401 return;
2402 };
2403
2404 let res = name_binding.res();
2405 let is_import = name_binding.is_import();
2406 let span = name_binding.span;
2407 if let Res::Def(DefKind::Fn, _) = res {
2408 self.record_use(ident, name_binding, Used::Other);
2409 }
2410 self.main_def = Some(MainDefinition { res, is_import, span });
2411 }
2412}
2413
2414fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2415 let mut result = String::new();
2416 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2417 if i > 0 {
2418 result.push_str("::");
2419 }
2420 if Ident::with_dummy_span(name).is_raw_guess() {
2421 result.push_str("r#");
2422 }
2423 result.push_str(name.as_str());
2424 }
2425 result
2426}
2427
2428fn path_names_to_string(path: &Path) -> String {
2429 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2430}
2431
2432fn module_to_string(mut module: Module<'_>) -> Option<String> {
2434 let mut names = Vec::new();
2435 loop {
2436 if let ModuleKind::Def(.., name) = module.kind {
2437 if let Some(parent) = module.parent {
2438 names.push(name.unwrap());
2440 module = parent
2441 } else {
2442 break;
2443 }
2444 } else {
2445 names.push(sym::opaque_module_name_placeholder);
2446 let Some(parent) = module.parent else {
2447 return None;
2448 };
2449 module = parent;
2450 }
2451 }
2452 if names.is_empty() {
2453 return None;
2454 }
2455 Some(names_to_string(names.iter().rev().copied()))
2456}
2457
2458#[derive(Copy, Clone, Debug)]
2459struct Finalize {
2460 node_id: NodeId,
2462 path_span: Span,
2465 root_span: Span,
2468 report_private: bool,
2471 used: Used,
2473}
2474
2475impl Finalize {
2476 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2477 Finalize::with_root_span(node_id, path_span, path_span)
2478 }
2479
2480 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2481 Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2482 }
2483}
2484
2485pub fn provide(providers: &mut Providers) {
2486 providers.registered_tools = macros::registered_tools;
2487}
2488
2489mod ref_mut {
2490 use std::ops::Deref;
2491
2492 pub(crate) struct RefOrMut<'a, T> {
2494 p: &'a mut T,
2495 mutable: bool,
2496 }
2497
2498 impl<'a, T> Deref for RefOrMut<'a, T> {
2499 type Target = T;
2500
2501 fn deref(&self) -> &Self::Target {
2502 self.p
2503 }
2504 }
2505
2506 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2507 fn as_ref(&self) -> &T {
2508 self.p
2509 }
2510 }
2511
2512 impl<'a, T> RefOrMut<'a, T> {
2513 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2514 RefOrMut { p, mutable }
2515 }
2516
2517 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2519 RefOrMut { p: self.p, mutable: self.mutable }
2520 }
2521
2522 #[track_caller]
2527 pub(crate) fn get_mut(&mut self) -> &mut T {
2528 match self.mutable {
2529 false => panic!("Can't mutably borrow speculative resolver"),
2530 true => self.p,
2531 }
2532 }
2533
2534 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2537 self.p
2538 }
2539 }
2540}
2541
2542type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;