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, LintBuffer};
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::BuiltinLintDiag;
76use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
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}
162
163#[derive(Clone, Copy, Debug)]
168struct ParentScope<'ra> {
169 module: Module<'ra>,
170 expansion: LocalExpnId,
171 macro_rules: MacroRulesScopeRef<'ra>,
172 derives: &'ra [ast::Path],
173}
174
175impl<'ra> ParentScope<'ra> {
176 fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
179 ParentScope {
180 module,
181 expansion: LocalExpnId::ROOT,
182 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
183 derives: &[],
184 }
185 }
186}
187
188#[derive(Copy, Debug, Clone)]
189struct InvocationParent {
190 parent_def: LocalDefId,
191 impl_trait_context: ImplTraitContext,
192 in_attr: bool,
193}
194
195impl InvocationParent {
196 const ROOT: Self = Self {
197 parent_def: CRATE_DEF_ID,
198 impl_trait_context: ImplTraitContext::Existential,
199 in_attr: false,
200 };
201}
202
203#[derive(Copy, Debug, Clone)]
204enum ImplTraitContext {
205 Existential,
206 Universal,
207 InBinding,
208}
209
210#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
225enum Used {
226 Scope,
227 Other,
228}
229
230#[derive(Debug)]
231struct BindingError {
232 name: Ident,
233 origin: BTreeSet<Span>,
234 target: BTreeSet<Span>,
235 could_be_path: bool,
236}
237
238#[derive(Debug)]
239enum ResolutionError<'ra> {
240 GenericParamsFromOuterItem(Res, HasGenericParams, DefKind),
242 NameAlreadyUsedInParameterList(Ident, Span),
245 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
247 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
249 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
251 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
253 VariableBoundWithDifferentMode(Ident, Span),
255 IdentifierBoundMoreThanOnceInParameterList(Ident),
257 IdentifierBoundMoreThanOnceInSamePattern(Ident),
259 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
261 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
263 SelfImportCanOnlyAppearOnceInTheList,
265 SelfImportOnlyInImportListWithNonEmptyPrefix,
267 FailedToResolve {
269 segment: Option<Symbol>,
270 label: String,
271 suggestion: Option<Suggestion>,
272 module: Option<ModuleOrUniformRoot<'ra>>,
273 },
274 CannotCaptureDynamicEnvironmentInFnItem,
276 AttemptToUseNonConstantValueInConstant {
278 ident: Ident,
279 suggestion: &'static str,
280 current: &'static str,
281 type_span: Option<Span>,
282 },
283 BindingShadowsSomethingUnacceptable {
285 shadowing_binding: PatternSource,
286 name: Symbol,
287 participle: &'static str,
288 article: &'static str,
289 shadowed_binding: Res,
290 shadowed_binding_span: Span,
291 },
292 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
294 ParamInTyOfConstParam { name: Symbol },
298 ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
302 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
306 ForwardDeclaredSelf(ForwardGenericParamBanReason),
308 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
310 TraitImplMismatch {
312 name: Ident,
313 kind: &'static str,
314 trait_path: String,
315 trait_item_span: Span,
316 code: ErrCode,
317 },
318 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
320 InvalidAsmSym,
322 LowercaseSelf,
324 BindingInNeverPattern,
326}
327
328enum VisResolutionError<'a> {
329 Relative2018(Span, &'a ast::Path),
330 AncestorOnly(Span),
331 FailedToResolve(Span, String, Option<Suggestion>),
332 ExpectedFound(Span, String, Res),
333 Indeterminate(Span),
334 ModuleOnly(Span),
335}
336
337#[derive(Clone, Copy, Debug)]
340struct Segment {
341 ident: Ident,
342 id: Option<NodeId>,
343 has_generic_args: bool,
346 has_lifetime_args: bool,
348 args_span: Span,
349}
350
351impl Segment {
352 fn from_path(path: &Path) -> Vec<Segment> {
353 path.segments.iter().map(|s| s.into()).collect()
354 }
355
356 fn from_ident(ident: Ident) -> Segment {
357 Segment {
358 ident,
359 id: None,
360 has_generic_args: false,
361 has_lifetime_args: false,
362 args_span: DUMMY_SP,
363 }
364 }
365
366 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
367 Segment {
368 ident,
369 id: Some(id),
370 has_generic_args: false,
371 has_lifetime_args: false,
372 args_span: DUMMY_SP,
373 }
374 }
375
376 fn names_to_string(segments: &[Segment]) -> String {
377 names_to_string(segments.iter().map(|seg| seg.ident.name))
378 }
379}
380
381impl<'a> From<&'a ast::PathSegment> for Segment {
382 fn from(seg: &'a ast::PathSegment) -> Segment {
383 let has_generic_args = seg.args.is_some();
384 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
385 match args {
386 GenericArgs::AngleBracketed(args) => {
387 let found_lifetimes = args
388 .args
389 .iter()
390 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
391 (args.span, found_lifetimes)
392 }
393 GenericArgs::Parenthesized(args) => (args.span, true),
394 GenericArgs::ParenthesizedElided(span) => (*span, true),
395 }
396 } else {
397 (DUMMY_SP, false)
398 };
399 Segment {
400 ident: seg.ident,
401 id: Some(seg.id),
402 has_generic_args,
403 has_lifetime_args,
404 args_span,
405 }
406 }
407}
408
409#[derive(Debug, Copy, Clone)]
415enum LexicalScopeBinding<'ra> {
416 Item(NameBinding<'ra>),
417 Res(Res),
418}
419
420impl<'ra> LexicalScopeBinding<'ra> {
421 fn res(self) -> Res {
422 match self {
423 LexicalScopeBinding::Item(binding) => binding.res(),
424 LexicalScopeBinding::Res(res) => res,
425 }
426 }
427}
428
429#[derive(Copy, Clone, PartialEq, Debug)]
430enum ModuleOrUniformRoot<'ra> {
431 Module(Module<'ra>),
433
434 ModuleAndExternPrelude(Module<'ra>),
438
439 ExternPrelude,
442
443 CurrentScope,
447}
448
449#[derive(Debug)]
450enum PathResult<'ra> {
451 Module(ModuleOrUniformRoot<'ra>),
452 NonModule(PartialRes),
453 Indeterminate,
454 Failed {
455 span: Span,
456 label: String,
457 suggestion: Option<Suggestion>,
458 is_error_from_last_segment: bool,
459 module: Option<ModuleOrUniformRoot<'ra>>,
473 segment_name: Symbol,
475 error_implied_by_parse_error: bool,
476 },
477}
478
479impl<'ra> PathResult<'ra> {
480 fn failed(
481 ident: Ident,
482 is_error_from_last_segment: bool,
483 finalize: bool,
484 error_implied_by_parse_error: bool,
485 module: Option<ModuleOrUniformRoot<'ra>>,
486 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
487 ) -> PathResult<'ra> {
488 let (label, suggestion) =
489 if finalize { label_and_suggestion() } else { (String::new(), None) };
490 PathResult::Failed {
491 span: ident.span,
492 segment_name: ident.name,
493 label,
494 suggestion,
495 is_error_from_last_segment,
496 module,
497 error_implied_by_parse_error,
498 }
499 }
500}
501
502#[derive(Debug)]
503enum ModuleKind {
504 Block,
517 Def(DefKind, DefId, Option<Symbol>),
527}
528
529impl ModuleKind {
530 fn name(&self) -> Option<Symbol> {
532 match *self {
533 ModuleKind::Block => None,
534 ModuleKind::Def(.., name) => name,
535 }
536 }
537}
538
539#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
544struct BindingKey {
545 ident: Macros20NormalizedIdent,
548 ns: Namespace,
549 disambiguator: u32,
555}
556
557impl BindingKey {
558 fn new(ident: Ident, ns: Namespace) -> Self {
559 BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator: 0 }
560 }
561
562 fn new_disambiguated(
563 ident: Ident,
564 ns: Namespace,
565 disambiguator: impl FnOnce() -> u32,
566 ) -> BindingKey {
567 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
568 BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator }
569 }
570}
571
572type Resolutions<'ra> = RefCell<FxIndexMap<BindingKey, &'ra RefCell<NameResolution<'ra>>>>;
573
574struct ModuleData<'ra> {
586 parent: Option<Module<'ra>>,
588 kind: ModuleKind,
590
591 lazy_resolutions: Resolutions<'ra>,
594 populate_on_access: Cell<bool>,
596 underscore_disambiguator: Cell<u32>,
598
599 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
601
602 no_implicit_prelude: bool,
604
605 glob_importers: RefCell<Vec<Import<'ra>>>,
606 globs: RefCell<Vec<Import<'ra>>>,
607
608 traits:
610 RefCell<Option<Box<[(Macros20NormalizedIdent, NameBinding<'ra>, Option<Module<'ra>>)]>>>,
611
612 span: Span,
614
615 expansion: ExpnId,
616
617 self_binding: Option<NameBinding<'ra>>,
620}
621
622#[derive(Clone, Copy, PartialEq, Eq, Hash)]
625#[rustc_pass_by_value]
626struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
627
628impl std::hash::Hash for ModuleData<'_> {
633 fn hash<H>(&self, _: &mut H)
634 where
635 H: std::hash::Hasher,
636 {
637 unreachable!()
638 }
639}
640
641impl<'ra> ModuleData<'ra> {
642 fn new(
643 parent: Option<Module<'ra>>,
644 kind: ModuleKind,
645 expansion: ExpnId,
646 span: Span,
647 no_implicit_prelude: bool,
648 self_binding: Option<NameBinding<'ra>>,
649 ) -> Self {
650 let is_foreign = match kind {
651 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
652 ModuleKind::Block => false,
653 };
654 ModuleData {
655 parent,
656 kind,
657 lazy_resolutions: Default::default(),
658 populate_on_access: Cell::new(is_foreign),
659 underscore_disambiguator: Cell::new(0),
660 unexpanded_invocations: Default::default(),
661 no_implicit_prelude,
662 glob_importers: RefCell::new(Vec::new()),
663 globs: RefCell::new(Vec::new()),
664 traits: RefCell::new(None),
665 span,
666 expansion,
667 self_binding,
668 }
669 }
670}
671
672impl<'ra> Module<'ra> {
673 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
674 self,
675 resolver: &R,
676 mut f: impl FnMut(&R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
677 ) {
678 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
679 if let Some(binding) = name_resolution.borrow().best_binding() {
680 f(resolver, key.ident, key.ns, binding);
681 }
682 }
683 }
684
685 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
686 self,
687 resolver: &mut R,
688 mut f: impl FnMut(&mut R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
689 ) {
690 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
691 if let Some(binding) = name_resolution.borrow().best_binding() {
692 f(resolver, key.ident, key.ns, binding);
693 }
694 }
695 }
696
697 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
699 let mut traits = self.traits.borrow_mut();
700 if traits.is_none() {
701 let mut collected_traits = Vec::new();
702 self.for_each_child(resolver, |r, name, ns, binding| {
703 if ns != TypeNS {
704 return;
705 }
706 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
707 collected_traits.push((name, binding, r.as_ref().get_module(def_id)))
708 }
709 });
710 *traits = Some(collected_traits.into_boxed_slice());
711 }
712 }
713
714 fn res(self) -> Option<Res> {
715 match self.kind {
716 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
717 _ => None,
718 }
719 }
720
721 fn def_id(self) -> DefId {
722 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
723 }
724
725 fn opt_def_id(self) -> Option<DefId> {
726 match self.kind {
727 ModuleKind::Def(_, def_id, _) => Some(def_id),
728 _ => None,
729 }
730 }
731
732 fn is_normal(self) -> bool {
734 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
735 }
736
737 fn is_trait(self) -> bool {
738 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
739 }
740
741 fn nearest_item_scope(self) -> Module<'ra> {
742 match self.kind {
743 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
744 self.parent.expect("enum or trait module without a parent")
745 }
746 _ => self,
747 }
748 }
749
750 fn nearest_parent_mod(self) -> DefId {
753 match self.kind {
754 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
755 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
756 }
757 }
758
759 fn is_ancestor_of(self, mut other: Self) -> bool {
760 while self != other {
761 if let Some(parent) = other.parent {
762 other = parent;
763 } else {
764 return false;
765 }
766 }
767 true
768 }
769}
770
771impl<'ra> std::ops::Deref for Module<'ra> {
772 type Target = ModuleData<'ra>;
773
774 fn deref(&self) -> &Self::Target {
775 &self.0
776 }
777}
778
779impl<'ra> fmt::Debug for Module<'ra> {
780 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781 match self.kind {
782 ModuleKind::Block => write!(f, "block"),
783 ModuleKind::Def(..) => write!(f, "{:?}", self.res()),
784 }
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 all_crate_macros_already_registered: bool = false,
1273
1274 impl_trait_names: FxHashMap<NodeId, Symbol>,
1278}
1279
1280#[derive(Default)]
1283pub struct ResolverArenas<'ra> {
1284 modules: TypedArena<ModuleData<'ra>>,
1285 local_modules: RefCell<Vec<Module<'ra>>>,
1286 imports: TypedArena<ImportData<'ra>>,
1287 name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1288 ast_paths: TypedArena<ast::Path>,
1289 macros: TypedArena<MacroData>,
1290 dropless: DroplessArena,
1291}
1292
1293impl<'ra> ResolverArenas<'ra> {
1294 fn new_res_binding(
1295 &'ra self,
1296 res: Res,
1297 vis: Visibility<DefId>,
1298 span: Span,
1299 expansion: LocalExpnId,
1300 ) -> NameBinding<'ra> {
1301 self.alloc_name_binding(NameBindingData {
1302 kind: NameBindingKind::Res(res),
1303 ambiguity: None,
1304 warn_ambiguity: false,
1305 vis,
1306 span,
1307 expansion,
1308 })
1309 }
1310
1311 fn new_pub_res_binding(
1312 &'ra self,
1313 res: Res,
1314 span: Span,
1315 expn_id: LocalExpnId,
1316 ) -> NameBinding<'ra> {
1317 self.new_res_binding(res, Visibility::Public, span, expn_id)
1318 }
1319
1320 fn new_module(
1321 &'ra self,
1322 parent: Option<Module<'ra>>,
1323 kind: ModuleKind,
1324 expn_id: ExpnId,
1325 span: Span,
1326 no_implicit_prelude: bool,
1327 ) -> Module<'ra> {
1328 let (def_id, self_binding) = match kind {
1329 ModuleKind::Def(def_kind, def_id, _) => (
1330 Some(def_id),
1331 Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT)),
1332 ),
1333 ModuleKind::Block => (None, None),
1334 };
1335 let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1336 parent,
1337 kind,
1338 expn_id,
1339 span,
1340 no_implicit_prelude,
1341 self_binding,
1342 ))));
1343 if def_id.is_none_or(|def_id| def_id.is_local()) {
1344 self.local_modules.borrow_mut().push(module);
1345 }
1346 module
1347 }
1348 fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1349 self.local_modules.borrow()
1350 }
1351 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1352 Interned::new_unchecked(self.dropless.alloc(name_binding))
1353 }
1354 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1355 Interned::new_unchecked(self.imports.alloc(import))
1356 }
1357 fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1358 self.name_resolutions.alloc(Default::default())
1359 }
1360 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1361 self.dropless.alloc(Cell::new(scope))
1362 }
1363 fn alloc_macro_rules_binding(
1364 &'ra self,
1365 binding: MacroRulesBinding<'ra>,
1366 ) -> &'ra MacroRulesBinding<'ra> {
1367 self.dropless.alloc(binding)
1368 }
1369 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1370 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1371 }
1372 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1373 self.macros.alloc(macro_data)
1374 }
1375 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1376 self.dropless.alloc_from_iter(spans)
1377 }
1378}
1379
1380impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1381 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1382 self
1383 }
1384}
1385
1386impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1387 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1388 self
1389 }
1390}
1391
1392impl<'tcx> Resolver<'_, 'tcx> {
1393 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1394 self.opt_feed(node).map(|f| f.key())
1395 }
1396
1397 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1398 self.feed(node).key()
1399 }
1400
1401 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1402 self.node_id_to_def_id.get(&node).copied()
1403 }
1404
1405 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1406 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1407 }
1408
1409 fn local_def_kind(&self, node: NodeId) -> DefKind {
1410 self.tcx.def_kind(self.local_def_id(node))
1411 }
1412
1413 fn create_def(
1415 &mut self,
1416 parent: LocalDefId,
1417 node_id: ast::NodeId,
1418 name: Option<Symbol>,
1419 def_kind: DefKind,
1420 expn_id: ExpnId,
1421 span: Span,
1422 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1423 assert!(
1424 !self.node_id_to_def_id.contains_key(&node_id),
1425 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1426 node_id,
1427 name,
1428 def_kind,
1429 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1430 );
1431
1432 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1434 let def_id = feed.def_id();
1435
1436 if expn_id != ExpnId::root() {
1438 self.expn_that_defined.insert(def_id, expn_id);
1439 }
1440
1441 debug_assert_eq!(span.data_untracked().parent, None);
1443 let _id = self.tcx.untracked().source_span.push(span);
1444 debug_assert_eq!(_id, def_id);
1445
1446 if node_id != ast::DUMMY_NODE_ID {
1450 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1451 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1452 }
1453
1454 feed
1455 }
1456
1457 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1458 if let Some(def_id) = def_id.as_local() {
1459 self.item_generics_num_lifetimes[&def_id]
1460 } else {
1461 self.tcx.generics_of(def_id).own_counts().lifetimes
1462 }
1463 }
1464
1465 pub fn tcx(&self) -> TyCtxt<'tcx> {
1466 self.tcx
1467 }
1468
1469 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1474 self.node_id_to_def_id
1475 .items()
1476 .filter(|(_, v)| v.key() == def_id)
1477 .map(|(k, _)| *k)
1478 .get_only()
1479 .unwrap()
1480 }
1481}
1482
1483impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1484 pub fn new(
1485 tcx: TyCtxt<'tcx>,
1486 attrs: &[ast::Attribute],
1487 crate_span: Span,
1488 current_crate_outer_attr_insert_span: Span,
1489 arenas: &'ra ResolverArenas<'ra>,
1490 ) -> Resolver<'ra, 'tcx> {
1491 let root_def_id = CRATE_DEF_ID.to_def_id();
1492 let mut local_module_map = FxIndexMap::default();
1493 let graph_root = arenas.new_module(
1494 None,
1495 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1496 ExpnId::root(),
1497 crate_span,
1498 attr::contains_name(attrs, sym::no_implicit_prelude),
1499 );
1500 local_module_map.insert(CRATE_DEF_ID, graph_root);
1501 let empty_module = arenas.new_module(
1502 None,
1503 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1504 ExpnId::root(),
1505 DUMMY_SP,
1506 true,
1507 );
1508
1509 let mut node_id_to_def_id = NodeMap::default();
1510 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1511
1512 crate_feed.def_kind(DefKind::Mod);
1513 let crate_feed = crate_feed.downgrade();
1514 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1515
1516 let mut invocation_parents = FxHashMap::default();
1517 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1518
1519 let mut extern_prelude: FxIndexMap<_, _> = tcx
1520 .sess
1521 .opts
1522 .externs
1523 .iter()
1524 .filter_map(|(name, entry)| {
1525 if entry.add_prelude
1528 && let name = Symbol::intern(name)
1529 && name.can_be_raw()
1530 {
1531 Some((Macros20NormalizedIdent::with_dummy_span(name), Default::default()))
1532 } else {
1533 None
1534 }
1535 })
1536 .collect();
1537
1538 if !attr::contains_name(attrs, sym::no_core) {
1539 extern_prelude
1540 .insert(Macros20NormalizedIdent::with_dummy_span(sym::core), Default::default());
1541 if !attr::contains_name(attrs, sym::no_std) {
1542 extern_prelude
1543 .insert(Macros20NormalizedIdent::with_dummy_span(sym::std), Default::default());
1544 }
1545 }
1546
1547 let registered_tools = tcx.registered_tools(());
1548 let edition = tcx.sess.edition();
1549
1550 let mut resolver = Resolver {
1551 tcx,
1552
1553 expn_that_defined: Default::default(),
1554
1555 graph_root,
1558 assert_speculative: false, prelude: None,
1560 extern_prelude,
1561
1562 field_names: Default::default(),
1563 field_defaults: Default::default(),
1564 field_visibility_spans: FxHashMap::default(),
1565
1566 pat_span_map: Default::default(),
1567 partial_res_map: Default::default(),
1568 import_res_map: Default::default(),
1569 import_use_map: Default::default(),
1570 label_res_map: Default::default(),
1571 lifetimes_res_map: Default::default(),
1572 extra_lifetime_params_map: Default::default(),
1573 extern_crate_map: Default::default(),
1574 module_children: Default::default(),
1575 trait_map: NodeMap::default(),
1576 empty_module,
1577 local_module_map,
1578 extern_module_map: Default::default(),
1579 block_map: Default::default(),
1580 binding_parent_modules: FxHashMap::default(),
1581 ast_transform_scopes: FxHashMap::default(),
1582
1583 glob_map: Default::default(),
1584 used_imports: FxHashSet::default(),
1585 maybe_unused_trait_imports: Default::default(),
1586
1587 arenas,
1588 dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1589 builtin_types_bindings: PrimTy::ALL
1590 .iter()
1591 .map(|prim_ty| {
1592 let res = Res::PrimTy(*prim_ty);
1593 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1594 (prim_ty.name(), binding)
1595 })
1596 .collect(),
1597 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1598 .iter()
1599 .map(|builtin_attr| {
1600 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1601 let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1602 (builtin_attr.name, binding)
1603 })
1604 .collect(),
1605 registered_tool_bindings: registered_tools
1606 .iter()
1607 .map(|ident| {
1608 let res = Res::ToolMod;
1609 let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1610 (*ident, binding)
1611 })
1612 .collect(),
1613 macro_names: FxHashSet::default(),
1614 builtin_macros: Default::default(),
1615 registered_tools,
1616 macro_use_prelude: Default::default(),
1617 local_macro_map: Default::default(),
1618 extern_macro_map: Default::default(),
1619 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1620 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1621 non_macro_attr: arenas
1622 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1623 invocation_parent_scopes: Default::default(),
1624 output_macro_rules_scopes: Default::default(),
1625 macro_rules_scopes: Default::default(),
1626 helper_attrs: Default::default(),
1627 derive_data: Default::default(),
1628 local_macro_def_scopes: FxHashMap::default(),
1629 name_already_seen: FxHashMap::default(),
1630 struct_constructors: Default::default(),
1631 unused_macros: Default::default(),
1632 unused_macro_rules: Default::default(),
1633 proc_macro_stubs: Default::default(),
1634 single_segment_macro_resolutions: Default::default(),
1635 multi_segment_macro_resolutions: Default::default(),
1636 builtin_attrs: Default::default(),
1637 containers_deriving_copy: Default::default(),
1638 lint_buffer: LintBuffer::default(),
1639 node_id_to_def_id,
1640 disambiguator: DisambiguatorState::new(),
1641 placeholder_field_indices: Default::default(),
1642 invocation_parents,
1643 legacy_const_generic_args: Default::default(),
1644 item_generics_num_lifetimes: Default::default(),
1645 trait_impls: Default::default(),
1646 confused_type_with_std_module: Default::default(),
1647 lifetime_elision_allowed: Default::default(),
1648 stripped_cfg_items: Default::default(),
1649 effective_visibilities: Default::default(),
1650 doc_link_resolutions: Default::default(),
1651 doc_link_traits_in_scope: Default::default(),
1652 all_macro_rules: Default::default(),
1653 delegation_fn_sigs: Default::default(),
1654 glob_delegation_invoc_ids: Default::default(),
1655 impl_unexpanded_invocations: Default::default(),
1656 impl_binding_keys: Default::default(),
1657 current_crate_outer_attr_insert_span,
1658 mods_with_parse_errors: Default::default(),
1659 impl_trait_names: Default::default(),
1660 ..
1661 };
1662
1663 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1664 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1665 resolver.feed_visibility(crate_feed, Visibility::Public);
1666
1667 resolver
1668 }
1669
1670 fn new_local_module(
1671 &mut self,
1672 parent: Option<Module<'ra>>,
1673 kind: ModuleKind,
1674 expn_id: ExpnId,
1675 span: Span,
1676 no_implicit_prelude: bool,
1677 ) -> Module<'ra> {
1678 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1679 if let Some(def_id) = module.opt_def_id() {
1680 self.local_module_map.insert(def_id.expect_local(), module);
1681 }
1682 module
1683 }
1684
1685 fn new_extern_module(
1686 &self,
1687 parent: Option<Module<'ra>>,
1688 kind: ModuleKind,
1689 expn_id: ExpnId,
1690 span: Span,
1691 no_implicit_prelude: bool,
1692 ) -> Module<'ra> {
1693 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1694 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1695 module
1696 }
1697
1698 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1699 let mac = self.arenas.alloc_macro(macro_data);
1700 self.local_macro_map.insert(def_id, mac);
1701 mac
1702 }
1703
1704 fn next_node_id(&mut self) -> NodeId {
1705 let start = self.next_node_id;
1706 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1707 self.next_node_id = ast::NodeId::from_u32(next);
1708 start
1709 }
1710
1711 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1712 let start = self.next_node_id;
1713 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1714 self.next_node_id = ast::NodeId::from_usize(end);
1715 start..self.next_node_id
1716 }
1717
1718 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1719 &mut self.lint_buffer
1720 }
1721
1722 pub fn arenas() -> ResolverArenas<'ra> {
1723 Default::default()
1724 }
1725
1726 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1727 let feed = feed.upgrade(self.tcx);
1728 feed.visibility(vis.to_def_id());
1729 self.visibilities_for_hashing.push((feed.def_id(), vis));
1730 }
1731
1732 pub fn into_outputs(self) -> ResolverOutputs {
1733 let proc_macros = self.proc_macros;
1734 let expn_that_defined = self.expn_that_defined;
1735 let extern_crate_map = self.extern_crate_map;
1736 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1737 let glob_map = self.glob_map;
1738 let main_def = self.main_def;
1739 let confused_type_with_std_module = self.confused_type_with_std_module;
1740 let effective_visibilities = self.effective_visibilities;
1741
1742 let stripped_cfg_items = self
1743 .stripped_cfg_items
1744 .into_iter()
1745 .filter_map(|item| {
1746 let parent_module =
1747 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1748 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1749 })
1750 .collect();
1751
1752 let global_ctxt = ResolverGlobalCtxt {
1753 expn_that_defined,
1754 visibilities_for_hashing: self.visibilities_for_hashing,
1755 effective_visibilities,
1756 extern_crate_map,
1757 module_children: self.module_children,
1758 glob_map,
1759 maybe_unused_trait_imports,
1760 main_def,
1761 trait_impls: self.trait_impls,
1762 proc_macros,
1763 confused_type_with_std_module,
1764 doc_link_resolutions: self.doc_link_resolutions,
1765 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1766 all_macro_rules: self.all_macro_rules,
1767 stripped_cfg_items,
1768 };
1769 let ast_lowering = ty::ResolverAstLowering {
1770 legacy_const_generic_args: self.legacy_const_generic_args,
1771 partial_res_map: self.partial_res_map,
1772 import_res_map: self.import_res_map,
1773 label_res_map: self.label_res_map,
1774 lifetimes_res_map: self.lifetimes_res_map,
1775 extra_lifetime_params_map: self.extra_lifetime_params_map,
1776 next_node_id: self.next_node_id,
1777 node_id_to_def_id: self
1778 .node_id_to_def_id
1779 .into_items()
1780 .map(|(k, f)| (k, f.key()))
1781 .collect(),
1782 disambiguator: self.disambiguator,
1783 trait_map: self.trait_map,
1784 lifetime_elision_allowed: self.lifetime_elision_allowed,
1785 lint_buffer: Steal::new(self.lint_buffer),
1786 delegation_fn_sigs: self.delegation_fn_sigs,
1787 };
1788 ResolverOutputs { global_ctxt, ast_lowering }
1789 }
1790
1791 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1792 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1793 }
1794
1795 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1796 CStore::from_tcx(self.tcx)
1797 }
1798
1799 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1800 CStore::from_tcx_mut(self.tcx)
1801 }
1802
1803 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1804 match macro_kind {
1805 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1806 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1807 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1808 }
1809 }
1810
1811 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1816 CmResolver::new(self, !self.assert_speculative)
1817 }
1818
1819 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1821 f(self, TypeNS);
1822 f(self, ValueNS);
1823 f(self, MacroNS);
1824 }
1825
1826 fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1827 mut self: CmResolver<'r, 'ra, 'tcx>,
1828 mut f: F,
1829 ) {
1830 f(&mut self, TypeNS);
1831 f(&mut self, ValueNS);
1832 f(&mut self, MacroNS);
1833 }
1834
1835 fn is_builtin_macro(&self, res: Res) -> bool {
1836 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1837 }
1838
1839 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1840 loop {
1841 match ctxt.outer_expn_data().macro_def_id {
1842 Some(def_id) => return def_id,
1843 None => ctxt.remove_mark(),
1844 };
1845 }
1846 }
1847
1848 pub fn resolve_crate(&mut self, krate: &Crate) {
1850 self.tcx.sess.time("resolve_crate", || {
1851 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1852 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1853 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1854 });
1855 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1856 self.tcx
1857 .sess
1858 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1859 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1860 self.tcx.sess.time("resolve_main", || self.resolve_main());
1861 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1862 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1863 self.tcx
1864 .sess
1865 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1866 });
1867
1868 self.tcx.untracked().cstore.freeze();
1870 }
1871
1872 fn traits_in_scope(
1873 &mut self,
1874 current_trait: Option<Module<'ra>>,
1875 parent_scope: &ParentScope<'ra>,
1876 ctxt: SyntaxContext,
1877 assoc_item: Option<(Symbol, Namespace)>,
1878 ) -> Vec<TraitCandidate> {
1879 let mut found_traits = Vec::new();
1880
1881 if let Some(module) = current_trait {
1882 if self.trait_may_have_item(Some(module), assoc_item) {
1883 let def_id = module.def_id();
1884 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1885 }
1886 }
1887
1888 let scope_set = ScopeSet::All(TypeNS);
1889 self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1890 match scope {
1891 Scope::Module(module, _) => {
1892 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1893 }
1894 Scope::StdLibPrelude => {
1895 if let Some(module) = this.prelude {
1896 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1897 }
1898 }
1899 Scope::ExternPreludeItems
1900 | Scope::ExternPreludeFlags
1901 | Scope::ToolPrelude
1902 | Scope::BuiltinTypes => {}
1903 _ => unreachable!(),
1904 }
1905 None::<()>
1906 });
1907
1908 found_traits
1909 }
1910
1911 fn traits_in_module(
1912 &mut self,
1913 module: Module<'ra>,
1914 assoc_item: Option<(Symbol, Namespace)>,
1915 found_traits: &mut Vec<TraitCandidate>,
1916 ) {
1917 module.ensure_traits(self);
1918 let traits = module.traits.borrow();
1919 for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1920 if self.trait_may_have_item(trait_module, assoc_item) {
1921 let def_id = trait_binding.res().def_id();
1922 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1923 found_traits.push(TraitCandidate { def_id, import_ids });
1924 }
1925 }
1926 }
1927
1928 fn trait_may_have_item(
1934 &self,
1935 trait_module: Option<Module<'ra>>,
1936 assoc_item: Option<(Symbol, Namespace)>,
1937 ) -> bool {
1938 match (trait_module, assoc_item) {
1939 (Some(trait_module), Some((name, ns))) => self
1940 .resolutions(trait_module)
1941 .borrow()
1942 .iter()
1943 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1944 _ => true,
1945 }
1946 }
1947
1948 fn find_transitive_imports(
1949 &mut self,
1950 mut kind: &NameBindingKind<'_>,
1951 trait_name: Ident,
1952 ) -> SmallVec<[LocalDefId; 1]> {
1953 let mut import_ids = smallvec![];
1954 while let NameBindingKind::Import { import, binding, .. } = kind {
1955 if let Some(node_id) = import.id() {
1956 let def_id = self.local_def_id(node_id);
1957 self.maybe_unused_trait_imports.insert(def_id);
1958 import_ids.push(def_id);
1959 }
1960 self.add_to_glob_map(*import, trait_name);
1961 kind = &binding.kind;
1962 }
1963 import_ids
1964 }
1965
1966 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1967 if module.populate_on_access.get() {
1968 module.populate_on_access.set(false);
1969 self.build_reduced_graph_external(module);
1970 }
1971 &module.0.0.lazy_resolutions
1972 }
1973
1974 fn resolution(
1975 &self,
1976 module: Module<'ra>,
1977 key: BindingKey,
1978 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
1979 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
1980 }
1981
1982 fn resolution_or_default(
1983 &self,
1984 module: Module<'ra>,
1985 key: BindingKey,
1986 ) -> &'ra RefCell<NameResolution<'ra>> {
1987 self.resolutions(module)
1988 .borrow_mut()
1989 .entry(key)
1990 .or_insert_with(|| self.arenas.alloc_name_resolution())
1991 }
1992
1993 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1995 for ambiguity_error in &self.ambiguity_errors {
1996 if ambiguity_error.kind == ambi.kind
1998 && ambiguity_error.ident == ambi.ident
1999 && ambiguity_error.ident.span == ambi.ident.span
2000 && ambiguity_error.b1.span == ambi.b1.span
2001 && ambiguity_error.b2.span == ambi.b2.span
2002 && ambiguity_error.misc1 == ambi.misc1
2003 && ambiguity_error.misc2 == ambi.misc2
2004 {
2005 return true;
2006 }
2007 }
2008 false
2009 }
2010
2011 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2012 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2013 }
2014
2015 fn record_use_inner(
2016 &mut self,
2017 ident: Ident,
2018 used_binding: NameBinding<'ra>,
2019 used: Used,
2020 warn_ambiguity: bool,
2021 ) {
2022 if let Some((b2, kind)) = used_binding.ambiguity {
2023 let ambiguity_error = AmbiguityError {
2024 kind,
2025 ident,
2026 b1: used_binding,
2027 b2,
2028 misc1: AmbiguityErrorMisc::None,
2029 misc2: AmbiguityErrorMisc::None,
2030 warning: warn_ambiguity,
2031 };
2032 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2033 self.ambiguity_errors.push(ambiguity_error);
2035 }
2036 }
2037 if let NameBindingKind::Import { import, binding } = used_binding.kind {
2038 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2039 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2042 let empty_module = self.empty_module;
2043 let arenas = self.arenas;
2044 self.cm()
2045 .maybe_resolve_ident_in_module(
2046 ModuleOrUniformRoot::Module(prelude),
2047 ident,
2048 MacroNS,
2049 &ParentScope::module(empty_module, arenas),
2050 None,
2051 )
2052 .is_ok()
2053 });
2054 if !found_in_stdlib_prelude {
2055 self.lint_buffer().buffer_lint(
2056 PRIVATE_MACRO_USE,
2057 import.root_id,
2058 ident.span,
2059 BuiltinLintDiag::MacroIsPrivate(ident),
2060 );
2061 }
2062 }
2063 if used == Used::Scope {
2066 if let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident)) {
2067 if !entry.introduced_by_item && entry.item_binding == Some(used_binding) {
2068 return;
2069 }
2070 }
2071 }
2072 let old_used = self.import_use_map.entry(import).or_insert(used);
2073 if *old_used < used {
2074 *old_used = used;
2075 }
2076 if let Some(id) = import.id() {
2077 self.used_imports.insert(id);
2078 }
2079 self.add_to_glob_map(import, ident);
2080 self.record_use_inner(
2081 ident,
2082 binding,
2083 Used::Other,
2084 warn_ambiguity || binding.warn_ambiguity,
2085 );
2086 }
2087 }
2088
2089 #[inline]
2090 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2091 if let ImportKind::Glob { id, .. } = import.kind {
2092 let def_id = self.local_def_id(id);
2093 self.glob_map.entry(def_id).or_default().insert(ident.name);
2094 }
2095 }
2096
2097 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2098 debug!("resolve_crate_root({:?})", ident);
2099 let mut ctxt = ident.span.ctxt();
2100 let mark = if ident.name == kw::DollarCrate {
2101 ctxt = ctxt.normalize_to_macro_rules();
2108 debug!(
2109 "resolve_crate_root: marks={:?}",
2110 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2111 );
2112 let mut iter = ctxt.marks().into_iter().rev().peekable();
2113 let mut result = None;
2114 while let Some(&(mark, transparency)) = iter.peek() {
2116 if transparency == Transparency::Opaque {
2117 result = Some(mark);
2118 iter.next();
2119 } else {
2120 break;
2121 }
2122 }
2123 debug!(
2124 "resolve_crate_root: found opaque mark {:?} {:?}",
2125 result,
2126 result.map(|r| r.expn_data())
2127 );
2128 for (mark, transparency) in iter {
2130 if transparency == Transparency::SemiOpaque {
2131 result = Some(mark);
2132 } else {
2133 break;
2134 }
2135 }
2136 debug!(
2137 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2138 result,
2139 result.map(|r| r.expn_data())
2140 );
2141 result
2142 } else {
2143 debug!("resolve_crate_root: not DollarCrate");
2144 ctxt = ctxt.normalize_to_macros_2_0();
2145 ctxt.adjust(ExpnId::root())
2146 };
2147 let module = match mark {
2148 Some(def) => self.expn_def_scope(def),
2149 None => {
2150 debug!(
2151 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2152 ident, ident.span
2153 );
2154 return self.graph_root;
2155 }
2156 };
2157 let module = self.expect_module(
2158 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2159 );
2160 debug!(
2161 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2162 ident,
2163 module,
2164 module.kind.name(),
2165 ident.span
2166 );
2167 module
2168 }
2169
2170 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2171 let mut module = self.expect_module(module.nearest_parent_mod());
2172 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2173 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2174 module = self.expect_module(parent.nearest_parent_mod());
2175 }
2176 module
2177 }
2178
2179 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2180 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2181 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2182 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2183 }
2184 }
2185
2186 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2187 debug!("(recording pat) recording {:?} for {:?}", node, span);
2188 self.pat_span_map.insert(node, span);
2189 }
2190
2191 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2192 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2193 }
2194
2195 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2196 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2197 if module != old_module {
2198 span_bug!(binding.span, "parent module is reset for binding");
2199 }
2200 }
2201 }
2202
2203 fn disambiguate_macro_rules_vs_modularized(
2204 &self,
2205 macro_rules: NameBinding<'ra>,
2206 modularized: NameBinding<'ra>,
2207 ) -> bool {
2208 match (
2212 self.binding_parent_modules.get(¯o_rules),
2213 self.binding_parent_modules.get(&modularized),
2214 ) {
2215 (Some(macro_rules), Some(modularized)) => {
2216 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2217 && modularized.is_ancestor_of(*macro_rules)
2218 }
2219 _ => false,
2220 }
2221 }
2222
2223 fn extern_prelude_get_item<'r>(
2224 mut self: CmResolver<'r, 'ra, 'tcx>,
2225 ident: Ident,
2226 finalize: bool,
2227 ) -> Option<NameBinding<'ra>> {
2228 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2229 entry.and_then(|entry| entry.item_binding).map(|binding| {
2230 if finalize {
2231 self.get_mut().record_use(ident, binding, Used::Scope);
2232 }
2233 binding
2234 })
2235 }
2236
2237 fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2238 let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2239 entry.and_then(|entry| match entry.flag_binding.get() {
2240 Some(binding) => {
2241 if finalize {
2242 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2243 }
2244 Some(binding)
2245 }
2246 None if entry.only_item => None,
2247 None => {
2248 let crate_id = if finalize {
2249 self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2250 } else {
2251 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2252 };
2253 match crate_id {
2254 Some(crate_id) => {
2255 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2256 let binding =
2257 self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
2258 entry.flag_binding.set(Some(binding));
2259 Some(binding)
2260 }
2261 None => finalize.then_some(self.dummy_binding),
2262 }
2263 }
2264 })
2265 }
2266
2267 fn resolve_rustdoc_path(
2272 &mut self,
2273 path_str: &str,
2274 ns: Namespace,
2275 parent_scope: ParentScope<'ra>,
2276 ) -> Option<Res> {
2277 let segments: Result<Vec<_>, ()> = path_str
2278 .split("::")
2279 .enumerate()
2280 .map(|(i, s)| {
2281 let sym = if s.is_empty() {
2282 if i == 0 {
2283 kw::PathRoot
2285 } else {
2286 return Err(()); }
2288 } else {
2289 Symbol::intern(s)
2290 };
2291 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2292 })
2293 .collect();
2294 let Ok(segments) = segments else { return None };
2295
2296 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2297 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2298 PathResult::NonModule(path_res) => {
2299 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2300 }
2301 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2302 None
2303 }
2304 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2305 }
2306 }
2307
2308 fn def_span(&self, def_id: DefId) -> Span {
2310 match def_id.as_local() {
2311 Some(def_id) => self.tcx.source_span(def_id),
2312 None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2314 }
2315 }
2316
2317 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2318 match def_id.as_local() {
2319 Some(def_id) => self.field_names.get(&def_id).cloned(),
2320 None => Some(
2321 self.tcx
2322 .associated_item_def_ids(def_id)
2323 .iter()
2324 .map(|&def_id| {
2325 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2326 })
2327 .collect(),
2328 ),
2329 }
2330 }
2331
2332 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2333 match def_id.as_local() {
2334 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2335 None => Some(
2336 self.tcx
2337 .associated_item_def_ids(def_id)
2338 .iter()
2339 .filter_map(|&def_id| {
2340 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2341 })
2342 .collect(),
2343 ),
2344 }
2345 }
2346
2347 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2351 if let ExprKind::Path(None, path) = &expr.kind {
2352 if path.segments.last().unwrap().args.is_some() {
2355 return None;
2356 }
2357
2358 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2359 if let Res::Def(def::DefKind::Fn, def_id) = res {
2360 if def_id.is_local() {
2364 return None;
2365 }
2366
2367 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2368 return v.clone();
2369 }
2370
2371 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2372 let mut ret = Vec::new();
2373 for meta in attr.meta_item_list()? {
2374 match meta.lit()?.kind {
2375 LitKind::Int(a, _) => ret.push(a.get() as usize),
2376 _ => panic!("invalid arg index"),
2377 }
2378 }
2379 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2381 return Some(ret);
2382 }
2383 }
2384 None
2385 }
2386
2387 fn resolve_main(&mut self) {
2388 let module = self.graph_root;
2389 let ident = Ident::with_dummy_span(sym::main);
2390 let parent_scope = &ParentScope::module(module, self.arenas);
2391
2392 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2393 ModuleOrUniformRoot::Module(module),
2394 ident,
2395 ValueNS,
2396 parent_scope,
2397 None,
2398 ) else {
2399 return;
2400 };
2401
2402 let res = name_binding.res();
2403 let is_import = name_binding.is_import();
2404 let span = name_binding.span;
2405 if let Res::Def(DefKind::Fn, _) = res {
2406 self.record_use(ident, name_binding, Used::Other);
2407 }
2408 self.main_def = Some(MainDefinition { res, is_import, span });
2409 }
2410}
2411
2412fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2413 let mut result = String::new();
2414 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2415 if i > 0 {
2416 result.push_str("::");
2417 }
2418 if Ident::with_dummy_span(name).is_raw_guess() {
2419 result.push_str("r#");
2420 }
2421 result.push_str(name.as_str());
2422 }
2423 result
2424}
2425
2426fn path_names_to_string(path: &Path) -> String {
2427 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2428}
2429
2430fn module_to_string(mut module: Module<'_>) -> Option<String> {
2432 let mut names = Vec::new();
2433 loop {
2434 if let ModuleKind::Def(.., name) = module.kind {
2435 if let Some(parent) = module.parent {
2436 names.push(name.unwrap());
2438 module = parent
2439 } else {
2440 break;
2441 }
2442 } else {
2443 names.push(sym::opaque_module_name_placeholder);
2444 let Some(parent) = module.parent else {
2445 return None;
2446 };
2447 module = parent;
2448 }
2449 }
2450 if names.is_empty() {
2451 return None;
2452 }
2453 Some(names_to_string(names.iter().rev().copied()))
2454}
2455
2456#[derive(Copy, Clone, PartialEq, Debug)]
2457enum Stage {
2458 Early,
2462 Late,
2465}
2466
2467#[derive(Copy, Clone, Debug)]
2468struct Finalize {
2469 node_id: NodeId,
2471 path_span: Span,
2474 root_span: Span,
2477 report_private: bool = true,
2480 used: Used = Used::Other,
2482 stage: Stage = Stage::Early,
2484}
2485
2486impl Finalize {
2487 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2488 Finalize::with_root_span(node_id, path_span, path_span)
2489 }
2490
2491 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2492 Finalize { node_id, path_span, root_span, .. }
2493 }
2494}
2495
2496pub fn provide(providers: &mut Providers) {
2497 providers.registered_tools = macros::registered_tools;
2498}
2499
2500mod ref_mut {
2501 use std::ops::Deref;
2502
2503 pub(crate) struct RefOrMut<'a, T> {
2505 p: &'a mut T,
2506 mutable: bool,
2507 }
2508
2509 impl<'a, T> Deref for RefOrMut<'a, T> {
2510 type Target = T;
2511
2512 fn deref(&self) -> &Self::Target {
2513 self.p
2514 }
2515 }
2516
2517 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2518 fn as_ref(&self) -> &T {
2519 self.p
2520 }
2521 }
2522
2523 impl<'a, T> RefOrMut<'a, T> {
2524 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2525 RefOrMut { p, mutable }
2526 }
2527
2528 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2530 RefOrMut { p: self.p, mutable: self.mutable }
2531 }
2532
2533 #[track_caller]
2538 pub(crate) fn get_mut(&mut self) -> &mut T {
2539 match self.mutable {
2540 false => panic!("Can't mutably borrow speculative resolver"),
2541 true => self.p,
2542 }
2543 }
2544
2545 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2548 self.p
2549 }
2550 }
2551}
2552
2553type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;