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 write!(f, "{:?}", self.res())
785 }
786}
787
788#[derive(Clone, Copy, Debug)]
790struct NameBindingData<'ra> {
791 kind: NameBindingKind<'ra>,
792 ambiguity: Option<(NameBinding<'ra>, AmbiguityKind)>,
793 warn_ambiguity: bool,
796 expansion: LocalExpnId,
797 span: Span,
798 vis: Visibility<DefId>,
799}
800
801type NameBinding<'ra> = Interned<'ra, NameBindingData<'ra>>;
804
805impl std::hash::Hash for NameBindingData<'_> {
810 fn hash<H>(&self, _: &mut H)
811 where
812 H: std::hash::Hasher,
813 {
814 unreachable!()
815 }
816}
817
818#[derive(Clone, Copy, Debug)]
819enum NameBindingKind<'ra> {
820 Res(Res),
821 Import { binding: NameBinding<'ra>, import: Import<'ra> },
822}
823
824impl<'ra> NameBindingKind<'ra> {
825 fn is_import(&self) -> bool {
827 matches!(*self, NameBindingKind::Import { .. })
828 }
829}
830
831#[derive(Debug)]
832struct PrivacyError<'ra> {
833 ident: Ident,
834 binding: NameBinding<'ra>,
835 dedup_span: Span,
836 outermost_res: Option<(Res, Ident)>,
837 parent_scope: ParentScope<'ra>,
838 single_nested: bool,
840 source: Option<ast::Expr>,
841}
842
843#[derive(Debug)]
844struct UseError<'a> {
845 err: Diag<'a>,
846 candidates: Vec<ImportSuggestion>,
848 def_id: DefId,
850 instead: bool,
852 suggestion: Option<(Span, &'static str, String, Applicability)>,
854 path: Vec<Segment>,
857 is_call: bool,
859}
860
861#[derive(Clone, Copy, PartialEq, Debug)]
862enum AmbiguityKind {
863 BuiltinAttr,
864 DeriveHelper,
865 MacroRulesVsModularized,
866 GlobVsOuter,
867 GlobVsGlob,
868 GlobVsExpanded,
869 MoreExpandedVsOuter,
870}
871
872impl AmbiguityKind {
873 fn descr(self) -> &'static str {
874 match self {
875 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
876 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
877 AmbiguityKind::MacroRulesVsModularized => {
878 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
879 }
880 AmbiguityKind::GlobVsOuter => {
881 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
882 }
883 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
884 AmbiguityKind::GlobVsExpanded => {
885 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
886 }
887 AmbiguityKind::MoreExpandedVsOuter => {
888 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
889 }
890 }
891 }
892}
893
894#[derive(Clone, Copy, PartialEq)]
896enum AmbiguityErrorMisc {
897 SuggestCrate,
898 SuggestSelf,
899 FromPrelude,
900 None,
901}
902
903struct AmbiguityError<'ra> {
904 kind: AmbiguityKind,
905 ident: Ident,
906 b1: NameBinding<'ra>,
907 b2: NameBinding<'ra>,
908 misc1: AmbiguityErrorMisc,
909 misc2: AmbiguityErrorMisc,
910 warning: bool,
911}
912
913impl<'ra> NameBindingData<'ra> {
914 fn res(&self) -> Res {
915 match self.kind {
916 NameBindingKind::Res(res) => res,
917 NameBindingKind::Import { binding, .. } => binding.res(),
918 }
919 }
920
921 fn import_source(&self) -> NameBinding<'ra> {
922 match self.kind {
923 NameBindingKind::Import { binding, .. } => binding,
924 _ => unreachable!(),
925 }
926 }
927
928 fn is_ambiguity_recursive(&self) -> bool {
929 self.ambiguity.is_some()
930 || match self.kind {
931 NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(),
932 _ => false,
933 }
934 }
935
936 fn warn_ambiguity_recursive(&self) -> bool {
937 self.warn_ambiguity
938 || match self.kind {
939 NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(),
940 _ => false,
941 }
942 }
943
944 fn is_possibly_imported_variant(&self) -> bool {
945 match self.kind {
946 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
947 NameBindingKind::Res(Res::Def(
948 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
949 _,
950 )) => true,
951 NameBindingKind::Res(..) => false,
952 }
953 }
954
955 fn is_extern_crate(&self) -> bool {
956 match self.kind {
957 NameBindingKind::Import { import, .. } => {
958 matches!(import.kind, ImportKind::ExternCrate { .. })
959 }
960 NameBindingKind::Res(Res::Def(_, def_id)) => def_id.is_crate_root(),
961 _ => false,
962 }
963 }
964
965 fn is_import(&self) -> bool {
966 matches!(self.kind, NameBindingKind::Import { .. })
967 }
968
969 fn is_import_user_facing(&self) -> bool {
972 matches!(self.kind, NameBindingKind::Import { import, .. }
973 if !matches!(import.kind, ImportKind::MacroExport))
974 }
975
976 fn is_glob_import(&self) -> bool {
977 match self.kind {
978 NameBindingKind::Import { import, .. } => import.is_glob(),
979 _ => false,
980 }
981 }
982
983 fn is_assoc_item(&self) -> bool {
984 matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
985 }
986
987 fn macro_kinds(&self) -> Option<MacroKinds> {
988 self.res().macro_kinds()
989 }
990
991 fn may_appear_after(
998 &self,
999 invoc_parent_expansion: LocalExpnId,
1000 binding: NameBinding<'_>,
1001 ) -> bool {
1002 let self_parent_expansion = self.expansion;
1006 let other_parent_expansion = binding.expansion;
1007 let certainly_before_other_or_simultaneously =
1008 other_parent_expansion.is_descendant_of(self_parent_expansion);
1009 let certainly_before_invoc_or_simultaneously =
1010 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1011 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1012 }
1013
1014 fn determined(&self) -> bool {
1018 match &self.kind {
1019 NameBindingKind::Import { binding, import, .. } if import.is_glob() => {
1020 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1021 && binding.determined()
1022 }
1023 _ => true,
1024 }
1025 }
1026}
1027
1028#[derive(Default, Clone)]
1029struct ExternPreludeEntry<'ra> {
1030 item_binding: Option<NameBinding<'ra>>,
1032 flag_binding: Cell<Option<NameBinding<'ra>>>,
1034 only_item: bool,
1037 introduced_by_item: bool,
1040}
1041
1042struct DeriveData {
1043 resolutions: Vec<DeriveResolution>,
1044 helper_attrs: Vec<(usize, Ident)>,
1045 has_derive_copy: bool,
1046}
1047
1048struct MacroData {
1049 ext: Arc<SyntaxExtension>,
1050 nrules: usize,
1051 macro_rules: bool,
1052}
1053
1054impl MacroData {
1055 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1056 MacroData { ext, nrules: 0, macro_rules: false }
1057 }
1058}
1059
1060pub struct ResolverOutputs {
1061 pub global_ctxt: ResolverGlobalCtxt,
1062 pub ast_lowering: ResolverAstLowering,
1063}
1064
1065pub struct Resolver<'ra, 'tcx> {
1069 tcx: TyCtxt<'tcx>,
1070
1071 expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1073
1074 graph_root: Module<'ra>,
1075
1076 assert_speculative: bool,
1078
1079 prelude: Option<Module<'ra>> = None,
1080 extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1081
1082 field_names: LocalDefIdMap<Vec<Ident>>,
1084 field_defaults: LocalDefIdMap<Vec<Symbol>>,
1085
1086 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1089
1090 determined_imports: Vec<Import<'ra>> = Vec::new(),
1092
1093 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1095
1096 pat_span_map: NodeMap<Span>,
1099
1100 partial_res_map: NodeMap<PartialRes>,
1102 import_res_map: NodeMap<PerNS<Option<Res>>>,
1104 import_use_map: FxHashMap<Import<'ra>, Used>,
1106 label_res_map: NodeMap<NodeId>,
1108 lifetimes_res_map: NodeMap<LifetimeRes>,
1110 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1112
1113 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1115 module_children: LocalDefIdMap<Vec<ModChild>>,
1116 trait_map: NodeMap<Vec<TraitCandidate>>,
1117
1118 block_map: NodeMap<Module<'ra>>,
1133 empty_module: Module<'ra>,
1137 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1139 extern_module_map: RefCell<FxIndexMap<DefId, Module<'ra>>>,
1141 binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1142
1143 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1145 glob_error: Option<ErrorGuaranteed> = None,
1146 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1147 used_imports: FxHashSet<NodeId>,
1148 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1149
1150 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1152 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1154 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1156 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1158
1159 arenas: &'ra ResolverArenas<'ra>,
1160 dummy_binding: NameBinding<'ra>,
1161 builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1162 builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1163 registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1164 macro_names: FxHashSet<Ident>,
1165 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1166 registered_tools: &'tcx RegisteredTools,
1167 macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1168 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1170 extern_macro_map: RefCell<FxHashMap<DefId, &'ra MacroData>>,
1172 dummy_ext_bang: Arc<SyntaxExtension>,
1173 dummy_ext_derive: Arc<SyntaxExtension>,
1174 non_macro_attr: &'ra MacroData,
1175 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1176 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1177 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1178 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1180 proc_macro_stubs: FxHashSet<LocalDefId>,
1181 single_segment_macro_resolutions:
1184 RefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1185 multi_segment_macro_resolutions:
1186 RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1187 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1188 containers_deriving_copy: FxHashSet<LocalExpnId>,
1192 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1195 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1198 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1200 helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1202 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1205
1206 name_already_seen: FxHashMap<Symbol, Span>,
1208
1209 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1210
1211 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1212
1213 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1217
1218 lint_buffer: LintBuffer,
1219
1220 next_node_id: NodeId = CRATE_NODE_ID,
1221
1222 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1223
1224 disambiguator: DisambiguatorState,
1225
1226 placeholder_field_indices: FxHashMap<NodeId, usize>,
1228 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1232
1233 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1234 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1236 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1237
1238 main_def: Option<MainDefinition> = None,
1239 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1240 proc_macros: Vec<LocalDefId> = Vec::new(),
1243 confused_type_with_std_module: FxIndexMap<Span, Span>,
1244 lifetime_elision_allowed: FxHashSet<NodeId>,
1246
1247 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1249
1250 effective_visibilities: EffectiveVisibilities,
1251 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1252 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1253 all_macro_rules: UnordSet<Symbol>,
1254
1255 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1257 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1260 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1263
1264 current_crate_outer_attr_insert_span: Span,
1267
1268 mods_with_parse_errors: FxHashSet<DefId>,
1269
1270 impl_trait_names: FxHashMap<NodeId, Symbol>,
1274}
1275
1276#[derive(Default)]
1279pub struct ResolverArenas<'ra> {
1280 modules: TypedArena<ModuleData<'ra>>,
1281 local_modules: RefCell<Vec<Module<'ra>>>,
1282 imports: TypedArena<ImportData<'ra>>,
1283 name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1284 ast_paths: TypedArena<ast::Path>,
1285 macros: TypedArena<MacroData>,
1286 dropless: DroplessArena,
1287}
1288
1289impl<'ra> ResolverArenas<'ra> {
1290 fn new_res_binding(
1291 &'ra self,
1292 res: Res,
1293 vis: Visibility<DefId>,
1294 span: Span,
1295 expansion: LocalExpnId,
1296 ) -> NameBinding<'ra> {
1297 self.alloc_name_binding(NameBindingData {
1298 kind: NameBindingKind::Res(res),
1299 ambiguity: None,
1300 warn_ambiguity: false,
1301 vis,
1302 span,
1303 expansion,
1304 })
1305 }
1306
1307 fn new_pub_res_binding(
1308 &'ra self,
1309 res: Res,
1310 span: Span,
1311 expn_id: LocalExpnId,
1312 ) -> NameBinding<'ra> {
1313 self.new_res_binding(res, Visibility::Public, span, expn_id)
1314 }
1315
1316 fn new_module(
1317 &'ra self,
1318 parent: Option<Module<'ra>>,
1319 kind: ModuleKind,
1320 expn_id: ExpnId,
1321 span: Span,
1322 no_implicit_prelude: bool,
1323 ) -> Module<'ra> {
1324 let (def_id, self_binding) = match kind {
1325 ModuleKind::Def(def_kind, def_id, _) => (
1326 Some(def_id),
1327 Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT)),
1328 ),
1329 ModuleKind::Block => (None, None),
1330 };
1331 let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1332 parent,
1333 kind,
1334 expn_id,
1335 span,
1336 no_implicit_prelude,
1337 self_binding,
1338 ))));
1339 if def_id.is_none_or(|def_id| def_id.is_local()) {
1340 self.local_modules.borrow_mut().push(module);
1341 }
1342 module
1343 }
1344 fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1345 self.local_modules.borrow()
1346 }
1347 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1348 Interned::new_unchecked(self.dropless.alloc(name_binding))
1349 }
1350 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1351 Interned::new_unchecked(self.imports.alloc(import))
1352 }
1353 fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1354 self.name_resolutions.alloc(Default::default())
1355 }
1356 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1357 self.dropless.alloc(Cell::new(scope))
1358 }
1359 fn alloc_macro_rules_binding(
1360 &'ra self,
1361 binding: MacroRulesBinding<'ra>,
1362 ) -> &'ra MacroRulesBinding<'ra> {
1363 self.dropless.alloc(binding)
1364 }
1365 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1366 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1367 }
1368 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1369 self.macros.alloc(macro_data)
1370 }
1371 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1372 self.dropless.alloc_from_iter(spans)
1373 }
1374}
1375
1376impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1377 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1378 self
1379 }
1380}
1381
1382impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1383 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1384 self
1385 }
1386}
1387
1388impl<'tcx> Resolver<'_, 'tcx> {
1389 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1390 self.opt_feed(node).map(|f| f.key())
1391 }
1392
1393 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1394 self.feed(node).key()
1395 }
1396
1397 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1398 self.node_id_to_def_id.get(&node).copied()
1399 }
1400
1401 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1402 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1403 }
1404
1405 fn local_def_kind(&self, node: NodeId) -> DefKind {
1406 self.tcx.def_kind(self.local_def_id(node))
1407 }
1408
1409 fn create_def(
1411 &mut self,
1412 parent: LocalDefId,
1413 node_id: ast::NodeId,
1414 name: Option<Symbol>,
1415 def_kind: DefKind,
1416 expn_id: ExpnId,
1417 span: Span,
1418 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1419 assert!(
1420 !self.node_id_to_def_id.contains_key(&node_id),
1421 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1422 node_id,
1423 name,
1424 def_kind,
1425 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1426 );
1427
1428 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1430 let def_id = feed.def_id();
1431
1432 if expn_id != ExpnId::root() {
1434 self.expn_that_defined.insert(def_id, expn_id);
1435 }
1436
1437 debug_assert_eq!(span.data_untracked().parent, None);
1439 let _id = self.tcx.untracked().source_span.push(span);
1440 debug_assert_eq!(_id, def_id);
1441
1442 if node_id != ast::DUMMY_NODE_ID {
1446 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1447 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1448 }
1449
1450 feed
1451 }
1452
1453 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1454 if let Some(def_id) = def_id.as_local() {
1455 self.item_generics_num_lifetimes[&def_id]
1456 } else {
1457 self.tcx.generics_of(def_id).own_counts().lifetimes
1458 }
1459 }
1460
1461 pub fn tcx(&self) -> TyCtxt<'tcx> {
1462 self.tcx
1463 }
1464
1465 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1470 self.node_id_to_def_id
1471 .items()
1472 .filter(|(_, v)| v.key() == def_id)
1473 .map(|(k, _)| *k)
1474 .get_only()
1475 .unwrap()
1476 }
1477}
1478
1479impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1480 pub fn new(
1481 tcx: TyCtxt<'tcx>,
1482 attrs: &[ast::Attribute],
1483 crate_span: Span,
1484 current_crate_outer_attr_insert_span: Span,
1485 arenas: &'ra ResolverArenas<'ra>,
1486 ) -> Resolver<'ra, 'tcx> {
1487 let root_def_id = CRATE_DEF_ID.to_def_id();
1488 let mut local_module_map = FxIndexMap::default();
1489 let graph_root = arenas.new_module(
1490 None,
1491 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1492 ExpnId::root(),
1493 crate_span,
1494 attr::contains_name(attrs, sym::no_implicit_prelude),
1495 );
1496 local_module_map.insert(CRATE_DEF_ID, graph_root);
1497 let empty_module = arenas.new_module(
1498 None,
1499 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1500 ExpnId::root(),
1501 DUMMY_SP,
1502 true,
1503 );
1504
1505 let mut node_id_to_def_id = NodeMap::default();
1506 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1507
1508 crate_feed.def_kind(DefKind::Mod);
1509 let crate_feed = crate_feed.downgrade();
1510 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1511
1512 let mut invocation_parents = FxHashMap::default();
1513 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1514
1515 let mut extern_prelude: FxIndexMap<_, _> = tcx
1516 .sess
1517 .opts
1518 .externs
1519 .iter()
1520 .filter_map(|(name, entry)| {
1521 if entry.add_prelude
1524 && let name = Symbol::intern(name)
1525 && name.can_be_raw()
1526 {
1527 Some((Macros20NormalizedIdent::with_dummy_span(name), Default::default()))
1528 } else {
1529 None
1530 }
1531 })
1532 .collect();
1533
1534 if !attr::contains_name(attrs, sym::no_core) {
1535 extern_prelude
1536 .insert(Macros20NormalizedIdent::with_dummy_span(sym::core), Default::default());
1537 if !attr::contains_name(attrs, sym::no_std) {
1538 extern_prelude
1539 .insert(Macros20NormalizedIdent::with_dummy_span(sym::std), Default::default());
1540 }
1541 }
1542
1543 let registered_tools = tcx.registered_tools(());
1544 let edition = tcx.sess.edition();
1545
1546 let mut resolver = Resolver {
1547 tcx,
1548
1549 expn_that_defined: Default::default(),
1550
1551 graph_root,
1554 assert_speculative: false, prelude: None,
1556 extern_prelude,
1557
1558 field_names: Default::default(),
1559 field_defaults: Default::default(),
1560 field_visibility_spans: FxHashMap::default(),
1561
1562 pat_span_map: Default::default(),
1563 partial_res_map: Default::default(),
1564 import_res_map: Default::default(),
1565 import_use_map: Default::default(),
1566 label_res_map: Default::default(),
1567 lifetimes_res_map: Default::default(),
1568 extra_lifetime_params_map: Default::default(),
1569 extern_crate_map: Default::default(),
1570 module_children: Default::default(),
1571 trait_map: NodeMap::default(),
1572 empty_module,
1573 local_module_map,
1574 extern_module_map: Default::default(),
1575 block_map: Default::default(),
1576 binding_parent_modules: FxHashMap::default(),
1577 ast_transform_scopes: FxHashMap::default(),
1578
1579 glob_map: Default::default(),
1580 used_imports: FxHashSet::default(),
1581 maybe_unused_trait_imports: Default::default(),
1582
1583 arenas,
1584 dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1585 builtin_types_bindings: PrimTy::ALL
1586 .iter()
1587 .map(|prim_ty| {
1588 let res = Res::PrimTy(*prim_ty);
1589 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1590 (prim_ty.name(), binding)
1591 })
1592 .collect(),
1593 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1594 .iter()
1595 .map(|builtin_attr| {
1596 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1597 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1598 (builtin_attr.name, binding)
1599 })
1600 .collect(),
1601 registered_tool_bindings: registered_tools
1602 .iter()
1603 .map(|ident| {
1604 let res = Res::ToolMod;
1605 let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1606 (*ident, binding)
1607 })
1608 .collect(),
1609 macro_names: FxHashSet::default(),
1610 builtin_macros: Default::default(),
1611 registered_tools,
1612 macro_use_prelude: Default::default(),
1613 local_macro_map: Default::default(),
1614 extern_macro_map: Default::default(),
1615 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1616 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1617 non_macro_attr: arenas
1618 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1619 invocation_parent_scopes: Default::default(),
1620 output_macro_rules_scopes: Default::default(),
1621 macro_rules_scopes: Default::default(),
1622 helper_attrs: Default::default(),
1623 derive_data: Default::default(),
1624 local_macro_def_scopes: FxHashMap::default(),
1625 name_already_seen: FxHashMap::default(),
1626 struct_constructors: Default::default(),
1627 unused_macros: Default::default(),
1628 unused_macro_rules: Default::default(),
1629 proc_macro_stubs: Default::default(),
1630 single_segment_macro_resolutions: Default::default(),
1631 multi_segment_macro_resolutions: Default::default(),
1632 builtin_attrs: Default::default(),
1633 containers_deriving_copy: Default::default(),
1634 lint_buffer: LintBuffer::default(),
1635 node_id_to_def_id,
1636 disambiguator: DisambiguatorState::new(),
1637 placeholder_field_indices: Default::default(),
1638 invocation_parents,
1639 legacy_const_generic_args: Default::default(),
1640 item_generics_num_lifetimes: Default::default(),
1641 trait_impls: Default::default(),
1642 confused_type_with_std_module: Default::default(),
1643 lifetime_elision_allowed: Default::default(),
1644 stripped_cfg_items: Default::default(),
1645 effective_visibilities: Default::default(),
1646 doc_link_resolutions: Default::default(),
1647 doc_link_traits_in_scope: Default::default(),
1648 all_macro_rules: Default::default(),
1649 delegation_fn_sigs: Default::default(),
1650 glob_delegation_invoc_ids: Default::default(),
1651 impl_unexpanded_invocations: Default::default(),
1652 impl_binding_keys: Default::default(),
1653 current_crate_outer_attr_insert_span,
1654 mods_with_parse_errors: Default::default(),
1655 impl_trait_names: Default::default(),
1656 ..
1657 };
1658
1659 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1660 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1661 resolver.feed_visibility(crate_feed, Visibility::Public);
1662
1663 resolver
1664 }
1665
1666 fn new_local_module(
1667 &mut self,
1668 parent: Option<Module<'ra>>,
1669 kind: ModuleKind,
1670 expn_id: ExpnId,
1671 span: Span,
1672 no_implicit_prelude: bool,
1673 ) -> Module<'ra> {
1674 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1675 if let Some(def_id) = module.opt_def_id() {
1676 self.local_module_map.insert(def_id.expect_local(), module);
1677 }
1678 module
1679 }
1680
1681 fn new_extern_module(
1682 &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.extern_module_map.borrow_mut().insert(module.def_id(), module);
1691 module
1692 }
1693
1694 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1695 let mac = self.arenas.alloc_macro(macro_data);
1696 self.local_macro_map.insert(def_id, mac);
1697 mac
1698 }
1699
1700 fn next_node_id(&mut self) -> NodeId {
1701 let start = self.next_node_id;
1702 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1703 self.next_node_id = ast::NodeId::from_u32(next);
1704 start
1705 }
1706
1707 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1708 let start = self.next_node_id;
1709 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1710 self.next_node_id = ast::NodeId::from_usize(end);
1711 start..self.next_node_id
1712 }
1713
1714 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1715 &mut self.lint_buffer
1716 }
1717
1718 pub fn arenas() -> ResolverArenas<'ra> {
1719 Default::default()
1720 }
1721
1722 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1723 let feed = feed.upgrade(self.tcx);
1724 feed.visibility(vis.to_def_id());
1725 self.visibilities_for_hashing.push((feed.def_id(), vis));
1726 }
1727
1728 pub fn into_outputs(self) -> ResolverOutputs {
1729 let proc_macros = self.proc_macros;
1730 let expn_that_defined = self.expn_that_defined;
1731 let extern_crate_map = self.extern_crate_map;
1732 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1733 let glob_map = self.glob_map;
1734 let main_def = self.main_def;
1735 let confused_type_with_std_module = self.confused_type_with_std_module;
1736 let effective_visibilities = self.effective_visibilities;
1737
1738 let stripped_cfg_items = self
1739 .stripped_cfg_items
1740 .into_iter()
1741 .filter_map(|item| {
1742 let parent_module =
1743 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1744 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1745 })
1746 .collect();
1747
1748 let global_ctxt = ResolverGlobalCtxt {
1749 expn_that_defined,
1750 visibilities_for_hashing: self.visibilities_for_hashing,
1751 effective_visibilities,
1752 extern_crate_map,
1753 module_children: self.module_children,
1754 glob_map,
1755 maybe_unused_trait_imports,
1756 main_def,
1757 trait_impls: self.trait_impls,
1758 proc_macros,
1759 confused_type_with_std_module,
1760 doc_link_resolutions: self.doc_link_resolutions,
1761 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1762 all_macro_rules: self.all_macro_rules,
1763 stripped_cfg_items,
1764 };
1765 let ast_lowering = ty::ResolverAstLowering {
1766 legacy_const_generic_args: self.legacy_const_generic_args,
1767 partial_res_map: self.partial_res_map,
1768 import_res_map: self.import_res_map,
1769 label_res_map: self.label_res_map,
1770 lifetimes_res_map: self.lifetimes_res_map,
1771 extra_lifetime_params_map: self.extra_lifetime_params_map,
1772 next_node_id: self.next_node_id,
1773 node_id_to_def_id: self
1774 .node_id_to_def_id
1775 .into_items()
1776 .map(|(k, f)| (k, f.key()))
1777 .collect(),
1778 disambiguator: self.disambiguator,
1779 trait_map: self.trait_map,
1780 lifetime_elision_allowed: self.lifetime_elision_allowed,
1781 lint_buffer: Steal::new(self.lint_buffer),
1782 delegation_fn_sigs: self.delegation_fn_sigs,
1783 };
1784 ResolverOutputs { global_ctxt, ast_lowering }
1785 }
1786
1787 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1788 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1789 }
1790
1791 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1792 CStore::from_tcx(self.tcx)
1793 }
1794
1795 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1796 CStore::from_tcx_mut(self.tcx)
1797 }
1798
1799 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1800 match macro_kind {
1801 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1802 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1803 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1804 }
1805 }
1806
1807 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1812 CmResolver::new(self, !self.assert_speculative)
1813 }
1814
1815 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1817 f(self, TypeNS);
1818 f(self, ValueNS);
1819 f(self, MacroNS);
1820 }
1821
1822 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1823 mut self: CmResolver<'r, 'ra, 'tcx>,
1824 mut f: F,
1825 ) {
1826 f(&mut self, TypeNS);
1827 f(&mut self, ValueNS);
1828 f(&mut self, MacroNS);
1829 }
1830
1831 fn is_builtin_macro(&self, res: Res) -> bool {
1832 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1833 }
1834
1835 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1836 loop {
1837 match ctxt.outer_expn_data().macro_def_id {
1838 Some(def_id) => return def_id,
1839 None => ctxt.remove_mark(),
1840 };
1841 }
1842 }
1843
1844 pub fn resolve_crate(&mut self, krate: &Crate) {
1846 self.tcx.sess.time("resolve_crate", || {
1847 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1848 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1849 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1850 });
1851 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1852 self.tcx
1853 .sess
1854 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1855 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1856 self.tcx.sess.time("resolve_main", || self.resolve_main());
1857 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1858 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1859 self.tcx
1860 .sess
1861 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1862 });
1863
1864 self.tcx.untracked().cstore.freeze();
1866 }
1867
1868 fn traits_in_scope(
1869 &mut self,
1870 current_trait: Option<Module<'ra>>,
1871 parent_scope: &ParentScope<'ra>,
1872 ctxt: SyntaxContext,
1873 assoc_item: Option<(Symbol, Namespace)>,
1874 ) -> Vec<TraitCandidate> {
1875 let mut found_traits = Vec::new();
1876
1877 if let Some(module) = current_trait {
1878 if self.trait_may_have_item(Some(module), assoc_item) {
1879 let def_id = module.def_id();
1880 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1881 }
1882 }
1883
1884 self.cm().visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1885 match scope {
1886 Scope::Module(module, _) => {
1887 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1888 }
1889 Scope::StdLibPrelude => {
1890 if let Some(module) = this.prelude {
1891 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1892 }
1893 }
1894 Scope::ExternPreludeItems
1895 | Scope::ExternPreludeFlags
1896 | Scope::ToolPrelude
1897 | Scope::BuiltinTypes => {}
1898 _ => unreachable!(),
1899 }
1900 None::<()>
1901 });
1902
1903 found_traits
1904 }
1905
1906 fn traits_in_module(
1907 &mut self,
1908 module: Module<'ra>,
1909 assoc_item: Option<(Symbol, Namespace)>,
1910 found_traits: &mut Vec<TraitCandidate>,
1911 ) {
1912 module.ensure_traits(self);
1913 let traits = module.traits.borrow();
1914 for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1915 if self.trait_may_have_item(trait_module, assoc_item) {
1916 let def_id = trait_binding.res().def_id();
1917 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1918 found_traits.push(TraitCandidate { def_id, import_ids });
1919 }
1920 }
1921 }
1922
1923 fn trait_may_have_item(
1929 &self,
1930 trait_module: Option<Module<'ra>>,
1931 assoc_item: Option<(Symbol, Namespace)>,
1932 ) -> bool {
1933 match (trait_module, assoc_item) {
1934 (Some(trait_module), Some((name, ns))) => self
1935 .resolutions(trait_module)
1936 .borrow()
1937 .iter()
1938 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1939 _ => true,
1940 }
1941 }
1942
1943 fn find_transitive_imports(
1944 &mut self,
1945 mut kind: &NameBindingKind<'_>,
1946 trait_name: Ident,
1947 ) -> SmallVec<[LocalDefId; 1]> {
1948 let mut import_ids = smallvec![];
1949 while let NameBindingKind::Import { import, binding, .. } = kind {
1950 if let Some(node_id) = import.id() {
1951 let def_id = self.local_def_id(node_id);
1952 self.maybe_unused_trait_imports.insert(def_id);
1953 import_ids.push(def_id);
1954 }
1955 self.add_to_glob_map(*import, trait_name);
1956 kind = &binding.kind;
1957 }
1958 import_ids
1959 }
1960
1961 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1962 if module.populate_on_access.get() {
1963 module.populate_on_access.set(false);
1964 self.build_reduced_graph_external(module);
1965 }
1966 &module.0.0.lazy_resolutions
1967 }
1968
1969 fn resolution(
1970 &self,
1971 module: Module<'ra>,
1972 key: BindingKey,
1973 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
1974 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
1975 }
1976
1977 fn resolution_or_default(
1978 &self,
1979 module: Module<'ra>,
1980 key: BindingKey,
1981 ) -> &'ra RefCell<NameResolution<'ra>> {
1982 self.resolutions(module)
1983 .borrow_mut()
1984 .entry(key)
1985 .or_insert_with(|| self.arenas.alloc_name_resolution())
1986 }
1987
1988 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1990 for ambiguity_error in &self.ambiguity_errors {
1991 if ambiguity_error.kind == ambi.kind
1993 && ambiguity_error.ident == ambi.ident
1994 && ambiguity_error.ident.span == ambi.ident.span
1995 && ambiguity_error.b1.span == ambi.b1.span
1996 && ambiguity_error.b2.span == ambi.b2.span
1997 && ambiguity_error.misc1 == ambi.misc1
1998 && ambiguity_error.misc2 == ambi.misc2
1999 {
2000 return true;
2001 }
2002 }
2003 false
2004 }
2005
2006 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2007 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2008 }
2009
2010 fn record_use_inner(
2011 &mut self,
2012 ident: Ident,
2013 used_binding: NameBinding<'ra>,
2014 used: Used,
2015 warn_ambiguity: bool,
2016 ) {
2017 if let Some((b2, kind)) = used_binding.ambiguity {
2018 let ambiguity_error = AmbiguityError {
2019 kind,
2020 ident,
2021 b1: used_binding,
2022 b2,
2023 misc1: AmbiguityErrorMisc::None,
2024 misc2: AmbiguityErrorMisc::None,
2025 warning: warn_ambiguity,
2026 };
2027 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2028 self.ambiguity_errors.push(ambiguity_error);
2030 }
2031 }
2032 if let NameBindingKind::Import { import, binding } = used_binding.kind {
2033 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2034 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2037 let empty_module = self.empty_module;
2038 let arenas = self.arenas;
2039 self.cm()
2040 .maybe_resolve_ident_in_module(
2041 ModuleOrUniformRoot::Module(prelude),
2042 ident,
2043 MacroNS,
2044 &ParentScope::module(empty_module, arenas),
2045 None,
2046 )
2047 .is_ok()
2048 });
2049 if !found_in_stdlib_prelude {
2050 self.lint_buffer().buffer_lint(
2051 PRIVATE_MACRO_USE,
2052 import.root_id,
2053 ident.span,
2054 BuiltinLintDiag::MacroIsPrivate(ident),
2055 );
2056 }
2057 }
2058 if used == Used::Scope {
2061 if let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident)) {
2062 if !entry.introduced_by_item && entry.item_binding == Some(used_binding) {
2063 return;
2064 }
2065 }
2066 }
2067 let old_used = self.import_use_map.entry(import).or_insert(used);
2068 if *old_used < used {
2069 *old_used = used;
2070 }
2071 if let Some(id) = import.id() {
2072 self.used_imports.insert(id);
2073 }
2074 self.add_to_glob_map(import, ident);
2075 self.record_use_inner(
2076 ident,
2077 binding,
2078 Used::Other,
2079 warn_ambiguity || binding.warn_ambiguity,
2080 );
2081 }
2082 }
2083
2084 #[inline]
2085 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2086 if let ImportKind::Glob { id, .. } = import.kind {
2087 let def_id = self.local_def_id(id);
2088 self.glob_map.entry(def_id).or_default().insert(ident.name);
2089 }
2090 }
2091
2092 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2093 debug!("resolve_crate_root({:?})", ident);
2094 let mut ctxt = ident.span.ctxt();
2095 let mark = if ident.name == kw::DollarCrate {
2096 ctxt = ctxt.normalize_to_macro_rules();
2103 debug!(
2104 "resolve_crate_root: marks={:?}",
2105 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2106 );
2107 let mut iter = ctxt.marks().into_iter().rev().peekable();
2108 let mut result = None;
2109 while let Some(&(mark, transparency)) = iter.peek() {
2111 if transparency == Transparency::Opaque {
2112 result = Some(mark);
2113 iter.next();
2114 } else {
2115 break;
2116 }
2117 }
2118 debug!(
2119 "resolve_crate_root: found opaque mark {:?} {:?}",
2120 result,
2121 result.map(|r| r.expn_data())
2122 );
2123 for (mark, transparency) in iter {
2125 if transparency == Transparency::SemiOpaque {
2126 result = Some(mark);
2127 } else {
2128 break;
2129 }
2130 }
2131 debug!(
2132 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2133 result,
2134 result.map(|r| r.expn_data())
2135 );
2136 result
2137 } else {
2138 debug!("resolve_crate_root: not DollarCrate");
2139 ctxt = ctxt.normalize_to_macros_2_0();
2140 ctxt.adjust(ExpnId::root())
2141 };
2142 let module = match mark {
2143 Some(def) => self.expn_def_scope(def),
2144 None => {
2145 debug!(
2146 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2147 ident, ident.span
2148 );
2149 return self.graph_root;
2150 }
2151 };
2152 let module = self.expect_module(
2153 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2154 );
2155 debug!(
2156 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2157 ident,
2158 module,
2159 module.kind.name(),
2160 ident.span
2161 );
2162 module
2163 }
2164
2165 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2166 let mut module = self.expect_module(module.nearest_parent_mod());
2167 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2168 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2169 module = self.expect_module(parent.nearest_parent_mod());
2170 }
2171 module
2172 }
2173
2174 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2175 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2176 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2177 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2178 }
2179 }
2180
2181 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2182 debug!("(recording pat) recording {:?} for {:?}", node, span);
2183 self.pat_span_map.insert(node, span);
2184 }
2185
2186 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2187 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2188 }
2189
2190 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2191 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2192 if module != old_module {
2193 span_bug!(binding.span, "parent module is reset for binding");
2194 }
2195 }
2196 }
2197
2198 fn disambiguate_macro_rules_vs_modularized(
2199 &self,
2200 macro_rules: NameBinding<'ra>,
2201 modularized: NameBinding<'ra>,
2202 ) -> bool {
2203 match (
2207 self.binding_parent_modules.get(¯o_rules),
2208 self.binding_parent_modules.get(&modularized),
2209 ) {
2210 (Some(macro_rules), Some(modularized)) => {
2211 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2212 && modularized.is_ancestor_of(*macro_rules)
2213 }
2214 _ => false,
2215 }
2216 }
2217
2218 fn extern_prelude_get_item<'r>(
2219 mut self: CmResolver<'r, 'ra, 'tcx>,
2220 ident: Ident,
2221 finalize: bool,
2222 ) -> Option<NameBinding<'ra>> {
2223 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2224 entry.and_then(|entry| entry.item_binding).map(|binding| {
2225 if finalize {
2226 self.get_mut().record_use(ident, binding, Used::Scope);
2227 }
2228 binding
2229 })
2230 }
2231
2232 fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2233 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2234 entry.and_then(|entry| match entry.flag_binding.get() {
2235 Some(binding) => {
2236 if finalize {
2237 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2238 }
2239 Some(binding)
2240 }
2241 None if entry.only_item => None,
2242 None => {
2243 let crate_id = if finalize {
2244 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2245 } else {
2246 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2247 };
2248 match crate_id {
2249 Some(crate_id) => {
2250 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2251 let binding =
2252 self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
2253 entry.flag_binding.set(Some(binding));
2254 Some(binding)
2255 }
2256 None => finalize.then_some(self.dummy_binding),
2257 }
2258 }
2259 })
2260 }
2261
2262 fn resolve_rustdoc_path(
2267 &mut self,
2268 path_str: &str,
2269 ns: Namespace,
2270 parent_scope: ParentScope<'ra>,
2271 ) -> Option<Res> {
2272 let segments: Result<Vec<_>, ()> = path_str
2273 .split("::")
2274 .enumerate()
2275 .map(|(i, s)| {
2276 let sym = if s.is_empty() {
2277 if i == 0 {
2278 kw::PathRoot
2280 } else {
2281 return Err(()); }
2283 } else {
2284 Symbol::intern(s)
2285 };
2286 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2287 })
2288 .collect();
2289 let Ok(segments) = segments else { return None };
2290
2291 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2292 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2293 PathResult::NonModule(path_res) => {
2294 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2295 }
2296 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2297 None
2298 }
2299 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2300 }
2301 }
2302
2303 fn def_span(&self, def_id: DefId) -> Span {
2305 match def_id.as_local() {
2306 Some(def_id) => self.tcx.source_span(def_id),
2307 None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2309 }
2310 }
2311
2312 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2313 match def_id.as_local() {
2314 Some(def_id) => self.field_names.get(&def_id).cloned(),
2315 None => Some(
2316 self.tcx
2317 .associated_item_def_ids(def_id)
2318 .iter()
2319 .map(|&def_id| {
2320 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2321 })
2322 .collect(),
2323 ),
2324 }
2325 }
2326
2327 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2328 match def_id.as_local() {
2329 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2330 None => Some(
2331 self.tcx
2332 .associated_item_def_ids(def_id)
2333 .iter()
2334 .filter_map(|&def_id| {
2335 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2336 })
2337 .collect(),
2338 ),
2339 }
2340 }
2341
2342 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2346 if let ExprKind::Path(None, path) = &expr.kind {
2347 if path.segments.last().unwrap().args.is_some() {
2350 return None;
2351 }
2352
2353 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2354 if let Res::Def(def::DefKind::Fn, def_id) = res {
2355 if def_id.is_local() {
2359 return None;
2360 }
2361
2362 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2363 return v.clone();
2364 }
2365
2366 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2367 let mut ret = Vec::new();
2368 for meta in attr.meta_item_list()? {
2369 match meta.lit()?.kind {
2370 LitKind::Int(a, _) => ret.push(a.get() as usize),
2371 _ => panic!("invalid arg index"),
2372 }
2373 }
2374 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2376 return Some(ret);
2377 }
2378 }
2379 None
2380 }
2381
2382 fn resolve_main(&mut self) {
2383 let module = self.graph_root;
2384 let ident = Ident::with_dummy_span(sym::main);
2385 let parent_scope = &ParentScope::module(module, self.arenas);
2386
2387 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2388 ModuleOrUniformRoot::Module(module),
2389 ident,
2390 ValueNS,
2391 parent_scope,
2392 None,
2393 ) else {
2394 return;
2395 };
2396
2397 let res = name_binding.res();
2398 let is_import = name_binding.is_import();
2399 let span = name_binding.span;
2400 if let Res::Def(DefKind::Fn, _) = res {
2401 self.record_use(ident, name_binding, Used::Other);
2402 }
2403 self.main_def = Some(MainDefinition { res, is_import, span });
2404 }
2405}
2406
2407fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2408 let mut result = String::new();
2409 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2410 if i > 0 {
2411 result.push_str("::");
2412 }
2413 if Ident::with_dummy_span(name).is_raw_guess() {
2414 result.push_str("r#");
2415 }
2416 result.push_str(name.as_str());
2417 }
2418 result
2419}
2420
2421fn path_names_to_string(path: &Path) -> String {
2422 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2423}
2424
2425fn module_to_string(mut module: Module<'_>) -> Option<String> {
2427 let mut names = Vec::new();
2428 loop {
2429 if let ModuleKind::Def(.., name) = module.kind {
2430 if let Some(parent) = module.parent {
2431 names.push(name.unwrap());
2433 module = parent
2434 } else {
2435 break;
2436 }
2437 } else {
2438 names.push(sym::opaque_module_name_placeholder);
2439 let Some(parent) = module.parent else {
2440 return None;
2441 };
2442 module = parent;
2443 }
2444 }
2445 if names.is_empty() {
2446 return None;
2447 }
2448 Some(names_to_string(names.iter().rev().copied()))
2449}
2450
2451#[derive(Copy, Clone, Debug)]
2452struct Finalize {
2453 node_id: NodeId,
2455 path_span: Span,
2458 root_span: Span,
2461 report_private: bool,
2464 used: Used,
2466}
2467
2468impl Finalize {
2469 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2470 Finalize::with_root_span(node_id, path_span, path_span)
2471 }
2472
2473 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2474 Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2475 }
2476}
2477
2478pub fn provide(providers: &mut Providers) {
2479 providers.registered_tools = macros::registered_tools;
2480}
2481
2482mod ref_mut {
2483 use std::ops::Deref;
2484
2485 pub(crate) struct RefOrMut<'a, T> {
2487 p: &'a mut T,
2488 mutable: bool,
2489 }
2490
2491 impl<'a, T> Deref for RefOrMut<'a, T> {
2492 type Target = T;
2493
2494 fn deref(&self) -> &Self::Target {
2495 self.p
2496 }
2497 }
2498
2499 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2500 fn as_ref(&self) -> &T {
2501 self.p
2502 }
2503 }
2504
2505 impl<'a, T> RefOrMut<'a, T> {
2506 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2507 RefOrMut { p, mutable }
2508 }
2509
2510 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2512 RefOrMut { p: self.p, mutable: self.mutable }
2513 }
2514
2515 #[track_caller]
2520 pub(crate) fn get_mut(&mut self) -> &mut T {
2521 match self.mutable {
2522 false => panic!("Can't mutably borrow speculative resolver"),
2523 true => self.p,
2524 }
2525 }
2526
2527 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2530 self.p
2531 }
2532 }
2533}
2534
2535type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;