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(assert_matches)]
16#![feature(box_patterns)]
17#![feature(if_let_guard)]
18#![feature(iter_intersperse)]
19#![feature(rustc_attrs)]
20#![feature(rustdoc_internals)]
21#![recursion_limit = "256"]
22use std::cell::{Cell, RefCell};
25use std::collections::BTreeSet;
26use std::fmt;
27use std::sync::Arc;
28
29use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
30use effective_visibilities::EffectiveVisibilitiesVisitor;
31use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
32use imports::{Import, ImportData, ImportKind, NameResolution};
33use late::{
34 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
35 UnnecessaryQualification,
36};
37use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
38use rustc_arena::{DroplessArena, TypedArena};
39use rustc_ast::expand::StrippedCfgItem;
40use rustc_ast::node_id::NodeMap;
41use rustc_ast::{
42 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
43 LitKind, NodeId, Path, attr,
44};
45use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
46use rustc_data_structures::intern::Interned;
47use rustc_data_structures::steal::Steal;
48use rustc_data_structures::sync::FreezeReadGuard;
49use rustc_data_structures::unord::UnordMap;
50use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed};
51use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
52use rustc_feature::BUILTIN_ATTRIBUTES;
53use rustc_hir::def::Namespace::{self, *};
54use rustc_hir::def::{
55 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS,
56};
57use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
58use rustc_hir::definitions::DisambiguatorState;
59use rustc_hir::{PrimTy, TraitCandidate};
60use rustc_metadata::creader::{CStore, CrateLoader};
61use rustc_middle::metadata::ModChild;
62use rustc_middle::middle::privacy::EffectiveVisibilities;
63use rustc_middle::query::Providers;
64use rustc_middle::span_bug;
65use rustc_middle::ty::{
66 self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverGlobalCtxt,
67 ResolverOutputs, TyCtxt, TyCtxtFeed,
68};
69use rustc_query_system::ich::StableHashingContext;
70use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
71use rustc_session::lint::{BuiltinLintDiag, LintBuffer};
72use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
73use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
74use smallvec::{SmallVec, smallvec};
75use tracing::debug;
76
77type Res = def::Res<NodeId>;
78
79mod build_reduced_graph;
80mod check_unused;
81mod def_collector;
82mod diagnostics;
83mod effective_visibilities;
84mod errors;
85mod ident;
86mod imports;
87mod late;
88mod macros;
89pub mod rustdoc;
90
91pub use macros::registered_tools_ast;
92
93rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
94
95#[derive(Debug)]
96enum Weak {
97 Yes,
98 No,
99}
100
101#[derive(Copy, Clone, PartialEq, Debug)]
102enum Determinacy {
103 Determined,
104 Undetermined,
105}
106
107impl Determinacy {
108 fn determined(determined: bool) -> Determinacy {
109 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
110 }
111}
112
113#[derive(Clone, Copy, Debug)]
117enum Scope<'ra> {
118 DeriveHelpers(LocalExpnId),
119 DeriveHelpersCompat,
120 MacroRules(MacroRulesScopeRef<'ra>),
121 CrateRoot,
122 Module(Module<'ra>, Option<NodeId>),
125 MacroUsePrelude,
126 BuiltinAttrs,
127 ExternPrelude,
128 ToolPrelude,
129 StdLibPrelude,
130 BuiltinTypes,
131}
132
133#[derive(Clone, Copy, Debug)]
138enum ScopeSet<'ra> {
139 All(Namespace),
141 AbsolutePath(Namespace),
143 Macro(MacroKind),
145 Late(Namespace, Module<'ra>, Option<NodeId>),
148}
149
150#[derive(Clone, Copy, Debug)]
155struct ParentScope<'ra> {
156 module: Module<'ra>,
157 expansion: LocalExpnId,
158 macro_rules: MacroRulesScopeRef<'ra>,
159 derives: &'ra [ast::Path],
160}
161
162impl<'ra> ParentScope<'ra> {
163 fn module(module: Module<'ra>, resolver: &Resolver<'ra, '_>) -> ParentScope<'ra> {
166 ParentScope {
167 module,
168 expansion: LocalExpnId::ROOT,
169 macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
170 derives: &[],
171 }
172 }
173}
174
175#[derive(Copy, Debug, Clone)]
176struct InvocationParent {
177 parent_def: LocalDefId,
178 impl_trait_context: ImplTraitContext,
179 in_attr: bool,
180}
181
182impl InvocationParent {
183 const ROOT: Self = Self {
184 parent_def: CRATE_DEF_ID,
185 impl_trait_context: ImplTraitContext::Existential,
186 in_attr: false,
187 };
188}
189
190#[derive(Copy, Debug, Clone)]
191enum ImplTraitContext {
192 Existential,
193 Universal,
194 InBinding,
195}
196
197#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
212enum Used {
213 Scope,
214 Other,
215}
216
217#[derive(Debug)]
218struct BindingError {
219 name: Ident,
220 origin: BTreeSet<Span>,
221 target: BTreeSet<Span>,
222 could_be_path: bool,
223}
224
225#[derive(Debug)]
226enum ResolutionError<'ra> {
227 GenericParamsFromOuterItem(Res, HasGenericParams, DefKind),
229 NameAlreadyUsedInParameterList(Ident, Span),
232 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
234 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
236 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
238 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
240 VariableBoundWithDifferentMode(Ident, Span),
242 IdentifierBoundMoreThanOnceInParameterList(Ident),
244 IdentifierBoundMoreThanOnceInSamePattern(Ident),
246 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
248 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
250 SelfImportCanOnlyAppearOnceInTheList,
252 SelfImportOnlyInImportListWithNonEmptyPrefix,
254 FailedToResolve {
256 segment: Option<Symbol>,
257 label: String,
258 suggestion: Option<Suggestion>,
259 module: Option<ModuleOrUniformRoot<'ra>>,
260 },
261 CannotCaptureDynamicEnvironmentInFnItem,
263 AttemptToUseNonConstantValueInConstant {
265 ident: Ident,
266 suggestion: &'static str,
267 current: &'static str,
268 type_span: Option<Span>,
269 },
270 BindingShadowsSomethingUnacceptable {
272 shadowing_binding: PatternSource,
273 name: Symbol,
274 participle: &'static str,
275 article: &'static str,
276 shadowed_binding: Res,
277 shadowed_binding_span: Span,
278 },
279 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
281 ParamInTyOfConstParam { name: Symbol },
285 ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
289 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
293 ForwardDeclaredSelf(ForwardGenericParamBanReason),
295 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
297 TraitImplMismatch {
299 name: Ident,
300 kind: &'static str,
301 trait_path: String,
302 trait_item_span: Span,
303 code: ErrCode,
304 },
305 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
307 InvalidAsmSym,
309 LowercaseSelf,
311 BindingInNeverPattern,
313}
314
315enum VisResolutionError<'a> {
316 Relative2018(Span, &'a ast::Path),
317 AncestorOnly(Span),
318 FailedToResolve(Span, String, Option<Suggestion>),
319 ExpectedFound(Span, String, Res),
320 Indeterminate(Span),
321 ModuleOnly(Span),
322}
323
324#[derive(Clone, Copy, Debug)]
327struct Segment {
328 ident: Ident,
329 id: Option<NodeId>,
330 has_generic_args: bool,
333 has_lifetime_args: bool,
335 args_span: Span,
336}
337
338impl Segment {
339 fn from_path(path: &Path) -> Vec<Segment> {
340 path.segments.iter().map(|s| s.into()).collect()
341 }
342
343 fn from_ident(ident: Ident) -> Segment {
344 Segment {
345 ident,
346 id: None,
347 has_generic_args: false,
348 has_lifetime_args: false,
349 args_span: DUMMY_SP,
350 }
351 }
352
353 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
354 Segment {
355 ident,
356 id: Some(id),
357 has_generic_args: false,
358 has_lifetime_args: false,
359 args_span: DUMMY_SP,
360 }
361 }
362
363 fn names_to_string(segments: &[Segment]) -> String {
364 names_to_string(segments.iter().map(|seg| seg.ident.name))
365 }
366}
367
368impl<'a> From<&'a ast::PathSegment> for Segment {
369 fn from(seg: &'a ast::PathSegment) -> Segment {
370 let has_generic_args = seg.args.is_some();
371 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
372 match args {
373 GenericArgs::AngleBracketed(args) => {
374 let found_lifetimes = args
375 .args
376 .iter()
377 .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
378 (args.span, found_lifetimes)
379 }
380 GenericArgs::Parenthesized(args) => (args.span, true),
381 GenericArgs::ParenthesizedElided(span) => (*span, true),
382 }
383 } else {
384 (DUMMY_SP, false)
385 };
386 Segment {
387 ident: seg.ident,
388 id: Some(seg.id),
389 has_generic_args,
390 has_lifetime_args,
391 args_span,
392 }
393 }
394}
395
396#[derive(Debug, Copy, Clone)]
402enum LexicalScopeBinding<'ra> {
403 Item(NameBinding<'ra>),
404 Res(Res),
405}
406
407impl<'ra> LexicalScopeBinding<'ra> {
408 fn res(self) -> Res {
409 match self {
410 LexicalScopeBinding::Item(binding) => binding.res(),
411 LexicalScopeBinding::Res(res) => res,
412 }
413 }
414}
415
416#[derive(Copy, Clone, PartialEq, Debug)]
417enum ModuleOrUniformRoot<'ra> {
418 Module(Module<'ra>),
420
421 CrateRootAndExternPrelude,
423
424 ExternPrelude,
427
428 CurrentScope,
432}
433
434#[derive(Debug)]
435enum PathResult<'ra> {
436 Module(ModuleOrUniformRoot<'ra>),
437 NonModule(PartialRes),
438 Indeterminate,
439 Failed {
440 span: Span,
441 label: String,
442 suggestion: Option<Suggestion>,
443 is_error_from_last_segment: bool,
444 module: Option<ModuleOrUniformRoot<'ra>>,
458 segment_name: Symbol,
460 error_implied_by_parse_error: bool,
461 },
462}
463
464impl<'ra> PathResult<'ra> {
465 fn failed(
466 ident: Ident,
467 is_error_from_last_segment: bool,
468 finalize: bool,
469 error_implied_by_parse_error: bool,
470 module: Option<ModuleOrUniformRoot<'ra>>,
471 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
472 ) -> PathResult<'ra> {
473 let (label, suggestion) =
474 if finalize { label_and_suggestion() } else { (String::new(), None) };
475 PathResult::Failed {
476 span: ident.span,
477 segment_name: ident.name,
478 label,
479 suggestion,
480 is_error_from_last_segment,
481 module,
482 error_implied_by_parse_error,
483 }
484 }
485}
486
487#[derive(Debug)]
488enum ModuleKind {
489 Block,
502 Def(DefKind, DefId, Option<Symbol>),
512}
513
514impl ModuleKind {
515 fn name(&self) -> Option<Symbol> {
517 match *self {
518 ModuleKind::Block => None,
519 ModuleKind::Def(.., name) => name,
520 }
521 }
522}
523
524#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
529struct BindingKey {
530 ident: Ident,
533 ns: Namespace,
534 disambiguator: u32,
537}
538
539impl BindingKey {
540 fn new(ident: Ident, ns: Namespace) -> Self {
541 let ident = ident.normalize_to_macros_2_0();
542 BindingKey { ident, ns, disambiguator: 0 }
543 }
544}
545
546type Resolutions<'ra> = RefCell<FxIndexMap<BindingKey, &'ra RefCell<NameResolution<'ra>>>>;
547
548struct ModuleData<'ra> {
560 parent: Option<Module<'ra>>,
562 kind: ModuleKind,
564
565 lazy_resolutions: Resolutions<'ra>,
568 populate_on_access: Cell<bool>,
570
571 unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
573
574 no_implicit_prelude: bool,
576
577 glob_importers: RefCell<Vec<Import<'ra>>>,
578 globs: RefCell<Vec<Import<'ra>>>,
579
580 traits: RefCell<Option<Box<[(Ident, NameBinding<'ra>)]>>>,
582
583 span: Span,
585
586 expansion: ExpnId,
587}
588
589#[derive(Clone, Copy, PartialEq, Eq, Hash)]
592#[rustc_pass_by_value]
593struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
594
595impl std::hash::Hash for ModuleData<'_> {
600 fn hash<H>(&self, _: &mut H)
601 where
602 H: std::hash::Hasher,
603 {
604 unreachable!()
605 }
606}
607
608impl<'ra> ModuleData<'ra> {
609 fn new(
610 parent: Option<Module<'ra>>,
611 kind: ModuleKind,
612 expansion: ExpnId,
613 span: Span,
614 no_implicit_prelude: bool,
615 ) -> Self {
616 let is_foreign = match kind {
617 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
618 ModuleKind::Block => false,
619 };
620 ModuleData {
621 parent,
622 kind,
623 lazy_resolutions: Default::default(),
624 populate_on_access: Cell::new(is_foreign),
625 unexpanded_invocations: Default::default(),
626 no_implicit_prelude,
627 glob_importers: RefCell::new(Vec::new()),
628 globs: RefCell::new(Vec::new()),
629 traits: RefCell::new(None),
630 span,
631 expansion,
632 }
633 }
634}
635
636impl<'ra> Module<'ra> {
637 fn for_each_child<'tcx, R, F>(self, resolver: &mut R, mut f: F)
638 where
639 R: AsMut<Resolver<'ra, 'tcx>>,
640 F: FnMut(&mut R, Ident, Namespace, NameBinding<'ra>),
641 {
642 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
643 if let Some(binding) = name_resolution.borrow().binding {
644 f(resolver, key.ident, key.ns, binding);
645 }
646 }
647 }
648
649 fn ensure_traits<'tcx, R>(self, resolver: &mut R)
651 where
652 R: AsMut<Resolver<'ra, 'tcx>>,
653 {
654 let mut traits = self.traits.borrow_mut();
655 if traits.is_none() {
656 let mut collected_traits = Vec::new();
657 self.for_each_child(resolver, |_, name, ns, binding| {
658 if ns != TypeNS {
659 return;
660 }
661 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
662 collected_traits.push((name, binding))
663 }
664 });
665 *traits = Some(collected_traits.into_boxed_slice());
666 }
667 }
668
669 fn res(self) -> Option<Res> {
670 match self.kind {
671 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
672 _ => None,
673 }
674 }
675
676 fn def_id(self) -> DefId {
678 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
679 }
680
681 fn opt_def_id(self) -> Option<DefId> {
682 match self.kind {
683 ModuleKind::Def(_, def_id, _) => Some(def_id),
684 _ => None,
685 }
686 }
687
688 fn is_normal(self) -> bool {
690 matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
691 }
692
693 fn is_trait(self) -> bool {
694 matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
695 }
696
697 fn nearest_item_scope(self) -> Module<'ra> {
698 match self.kind {
699 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
700 self.parent.expect("enum or trait module without a parent")
701 }
702 _ => self,
703 }
704 }
705
706 fn nearest_parent_mod(self) -> DefId {
709 match self.kind {
710 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
711 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
712 }
713 }
714
715 fn is_ancestor_of(self, mut other: Self) -> bool {
716 while self != other {
717 if let Some(parent) = other.parent {
718 other = parent;
719 } else {
720 return false;
721 }
722 }
723 true
724 }
725}
726
727impl<'ra> std::ops::Deref for Module<'ra> {
728 type Target = ModuleData<'ra>;
729
730 fn deref(&self) -> &Self::Target {
731 &self.0
732 }
733}
734
735impl<'ra> fmt::Debug for Module<'ra> {
736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737 write!(f, "{:?}", self.res())
738 }
739}
740
741#[derive(Clone, Copy, Debug)]
743struct NameBindingData<'ra> {
744 kind: NameBindingKind<'ra>,
745 ambiguity: Option<(NameBinding<'ra>, AmbiguityKind)>,
746 warn_ambiguity: bool,
749 expansion: LocalExpnId,
750 span: Span,
751 vis: ty::Visibility<DefId>,
752}
753
754type NameBinding<'ra> = Interned<'ra, NameBindingData<'ra>>;
757
758impl std::hash::Hash for NameBindingData<'_> {
763 fn hash<H>(&self, _: &mut H)
764 where
765 H: std::hash::Hasher,
766 {
767 unreachable!()
768 }
769}
770
771trait ToNameBinding<'ra> {
772 fn to_name_binding(self, arenas: &'ra ResolverArenas<'ra>) -> NameBinding<'ra>;
773}
774
775impl<'ra> ToNameBinding<'ra> for NameBinding<'ra> {
776 fn to_name_binding(self, _: &'ra ResolverArenas<'ra>) -> NameBinding<'ra> {
777 self
778 }
779}
780
781#[derive(Clone, Copy, Debug)]
782enum NameBindingKind<'ra> {
783 Res(Res),
784 Module(Module<'ra>),
785 Import { binding: NameBinding<'ra>, import: Import<'ra> },
786}
787
788impl<'ra> NameBindingKind<'ra> {
789 fn is_import(&self) -> bool {
791 matches!(*self, NameBindingKind::Import { .. })
792 }
793}
794
795#[derive(Debug)]
796struct PrivacyError<'ra> {
797 ident: Ident,
798 binding: NameBinding<'ra>,
799 dedup_span: Span,
800 outermost_res: Option<(Res, Ident)>,
801 parent_scope: ParentScope<'ra>,
802 single_nested: bool,
804}
805
806#[derive(Debug)]
807struct UseError<'a> {
808 err: Diag<'a>,
809 candidates: Vec<ImportSuggestion>,
811 def_id: DefId,
813 instead: bool,
815 suggestion: Option<(Span, &'static str, String, Applicability)>,
817 path: Vec<Segment>,
820 is_call: bool,
822}
823
824#[derive(Clone, Copy, PartialEq, Debug)]
825enum AmbiguityKind {
826 BuiltinAttr,
827 DeriveHelper,
828 MacroRulesVsModularized,
829 GlobVsOuter,
830 GlobVsGlob,
831 GlobVsExpanded,
832 MoreExpandedVsOuter,
833}
834
835impl AmbiguityKind {
836 fn descr(self) -> &'static str {
837 match self {
838 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
839 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
840 AmbiguityKind::MacroRulesVsModularized => {
841 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
842 }
843 AmbiguityKind::GlobVsOuter => {
844 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
845 }
846 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
847 AmbiguityKind::GlobVsExpanded => {
848 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
849 }
850 AmbiguityKind::MoreExpandedVsOuter => {
851 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
852 }
853 }
854 }
855}
856
857#[derive(Clone, Copy, PartialEq)]
859enum AmbiguityErrorMisc {
860 SuggestCrate,
861 SuggestSelf,
862 FromPrelude,
863 None,
864}
865
866struct AmbiguityError<'ra> {
867 kind: AmbiguityKind,
868 ident: Ident,
869 b1: NameBinding<'ra>,
870 b2: NameBinding<'ra>,
871 misc1: AmbiguityErrorMisc,
872 misc2: AmbiguityErrorMisc,
873 warning: bool,
874}
875
876impl<'ra> NameBindingData<'ra> {
877 fn module(&self) -> Option<Module<'ra>> {
878 match self.kind {
879 NameBindingKind::Module(module) => Some(module),
880 NameBindingKind::Import { binding, .. } => binding.module(),
881 _ => None,
882 }
883 }
884
885 fn res(&self) -> Res {
886 match self.kind {
887 NameBindingKind::Res(res) => res,
888 NameBindingKind::Module(module) => module.res().unwrap(),
889 NameBindingKind::Import { binding, .. } => binding.res(),
890 }
891 }
892
893 fn is_ambiguity_recursive(&self) -> bool {
894 self.ambiguity.is_some()
895 || match self.kind {
896 NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(),
897 _ => false,
898 }
899 }
900
901 fn warn_ambiguity_recursive(&self) -> bool {
902 self.warn_ambiguity
903 || match self.kind {
904 NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(),
905 _ => false,
906 }
907 }
908
909 fn is_possibly_imported_variant(&self) -> bool {
910 match self.kind {
911 NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
912 NameBindingKind::Res(Res::Def(
913 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
914 _,
915 )) => true,
916 NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
917 }
918 }
919
920 fn is_extern_crate(&self) -> bool {
921 match self.kind {
922 NameBindingKind::Import { import, .. } => {
923 matches!(import.kind, ImportKind::ExternCrate { .. })
924 }
925 NameBindingKind::Module(module)
926 if let ModuleKind::Def(DefKind::Mod, def_id, _) = module.kind =>
927 {
928 def_id.is_crate_root()
929 }
930 _ => false,
931 }
932 }
933
934 fn is_import(&self) -> bool {
935 matches!(self.kind, NameBindingKind::Import { .. })
936 }
937
938 fn is_import_user_facing(&self) -> bool {
941 matches!(self.kind, NameBindingKind::Import { import, .. }
942 if !matches!(import.kind, ImportKind::MacroExport))
943 }
944
945 fn is_glob_import(&self) -> bool {
946 match self.kind {
947 NameBindingKind::Import { import, .. } => import.is_glob(),
948 _ => false,
949 }
950 }
951
952 fn is_assoc_item(&self) -> bool {
953 matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
954 }
955
956 fn macro_kind(&self) -> Option<MacroKind> {
957 self.res().macro_kind()
958 }
959
960 fn may_appear_after(
967 &self,
968 invoc_parent_expansion: LocalExpnId,
969 binding: NameBinding<'_>,
970 ) -> bool {
971 let self_parent_expansion = self.expansion;
975 let other_parent_expansion = binding.expansion;
976 let certainly_before_other_or_simultaneously =
977 other_parent_expansion.is_descendant_of(self_parent_expansion);
978 let certainly_before_invoc_or_simultaneously =
979 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
980 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
981 }
982
983 fn determined(&self) -> bool {
987 match &self.kind {
988 NameBindingKind::Import { binding, import, .. } if import.is_glob() => {
989 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
990 && binding.determined()
991 }
992 _ => true,
993 }
994 }
995}
996
997#[derive(Default, Clone)]
998struct ExternPreludeEntry<'ra> {
999 binding: Option<NameBinding<'ra>>,
1000 introduced_by_item: bool,
1001}
1002
1003impl ExternPreludeEntry<'_> {
1004 fn is_import(&self) -> bool {
1005 self.binding.is_some_and(|binding| binding.is_import())
1006 }
1007}
1008
1009struct DeriveData {
1010 resolutions: Vec<DeriveResolution>,
1011 helper_attrs: Vec<(usize, Ident)>,
1012 has_derive_copy: bool,
1013}
1014
1015struct MacroData {
1016 ext: Arc<SyntaxExtension>,
1017 rule_spans: Vec<(usize, Span)>,
1018 macro_rules: bool,
1019}
1020
1021impl MacroData {
1022 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1023 MacroData { ext, rule_spans: Vec::new(), macro_rules: false }
1024 }
1025}
1026
1027pub struct Resolver<'ra, 'tcx> {
1031 tcx: TyCtxt<'tcx>,
1032
1033 expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
1035
1036 graph_root: Module<'ra>,
1037
1038 prelude: Option<Module<'ra>>,
1039 extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'ra>>,
1040
1041 field_names: LocalDefIdMap<Vec<Ident>>,
1043
1044 field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1047
1048 determined_imports: Vec<Import<'ra>>,
1050
1051 indeterminate_imports: Vec<Import<'ra>>,
1053
1054 pat_span_map: NodeMap<Span>,
1057
1058 partial_res_map: NodeMap<PartialRes>,
1060 import_res_map: NodeMap<PerNS<Option<Res>>>,
1062 import_use_map: FxHashMap<Import<'ra>, Used>,
1064 label_res_map: NodeMap<NodeId>,
1066 lifetimes_res_map: NodeMap<LifetimeRes>,
1068 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1070
1071 extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1073 module_children: LocalDefIdMap<Vec<ModChild>>,
1074 trait_map: NodeMap<Vec<TraitCandidate>>,
1075
1076 block_map: NodeMap<Module<'ra>>,
1091 empty_module: Module<'ra>,
1095 module_map: FxIndexMap<DefId, Module<'ra>>,
1096 binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1097
1098 underscore_disambiguator: u32,
1099
1100 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1102 glob_error: Option<ErrorGuaranteed>,
1103 visibilities_for_hashing: Vec<(LocalDefId, ty::Visibility)>,
1104 used_imports: FxHashSet<NodeId>,
1105 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1106
1107 privacy_errors: Vec<PrivacyError<'ra>>,
1109 ambiguity_errors: Vec<AmbiguityError<'ra>>,
1111 use_injections: Vec<UseError<'tcx>>,
1113 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
1115
1116 arenas: &'ra ResolverArenas<'ra>,
1117 dummy_binding: NameBinding<'ra>,
1118 builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1119 builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1120 registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1121 module_self_bindings: FxHashMap<Module<'ra>, NameBinding<'ra>>,
1124
1125 used_extern_options: FxHashSet<Symbol>,
1126 macro_names: FxHashSet<Ident>,
1127 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1128 registered_tools: &'tcx RegisteredTools,
1129 macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1130 macro_map: FxHashMap<DefId, MacroData>,
1131 dummy_ext_bang: Arc<SyntaxExtension>,
1132 dummy_ext_derive: Arc<SyntaxExtension>,
1133 non_macro_attr: MacroData,
1134 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1135 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1136 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1137 unused_macro_rules: FxIndexMap<NodeId, UnordMap<usize, (Ident, Span)>>,
1139 proc_macro_stubs: FxHashSet<LocalDefId>,
1140 single_segment_macro_resolutions:
1142 Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>)>,
1143 multi_segment_macro_resolutions:
1144 Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>,
1145 builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1146 containers_deriving_copy: FxHashSet<LocalExpnId>,
1150 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1153 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1156 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1158 helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1160 derive_data: FxHashMap<LocalExpnId, DeriveData>,
1163
1164 name_already_seen: FxHashMap<Symbol, Span>,
1166
1167 potentially_unused_imports: Vec<Import<'ra>>,
1168
1169 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>>,
1170
1171 struct_constructors: LocalDefIdMap<(Res, ty::Visibility<DefId>, Vec<ty::Visibility<DefId>>)>,
1175
1176 lint_buffer: LintBuffer,
1177
1178 next_node_id: NodeId,
1179
1180 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1181
1182 disambiguator: DisambiguatorState,
1183
1184 placeholder_field_indices: FxHashMap<NodeId, usize>,
1186 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1190
1191 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1192 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1194 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1195
1196 main_def: Option<MainDefinition>,
1197 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1198 proc_macros: Vec<LocalDefId>,
1201 confused_type_with_std_module: FxIndexMap<Span, Span>,
1202 lifetime_elision_allowed: FxHashSet<NodeId>,
1204
1205 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>>,
1207
1208 effective_visibilities: EffectiveVisibilities,
1209 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1210 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1211 all_macro_rules: FxHashSet<Symbol>,
1212
1213 glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1215 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1218 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1221
1222 current_crate_outer_attr_insert_span: Span,
1225
1226 mods_with_parse_errors: FxHashSet<DefId>,
1227}
1228
1229#[derive(Default)]
1232pub struct ResolverArenas<'ra> {
1233 modules: TypedArena<ModuleData<'ra>>,
1234 local_modules: RefCell<Vec<Module<'ra>>>,
1235 imports: TypedArena<ImportData<'ra>>,
1236 name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1237 ast_paths: TypedArena<ast::Path>,
1238 dropless: DroplessArena,
1239}
1240
1241impl<'ra> ResolverArenas<'ra> {
1242 fn new_module(
1243 &'ra self,
1244 parent: Option<Module<'ra>>,
1245 kind: ModuleKind,
1246 expn_id: ExpnId,
1247 span: Span,
1248 no_implicit_prelude: bool,
1249 module_map: &mut FxIndexMap<DefId, Module<'ra>>,
1250 module_self_bindings: &mut FxHashMap<Module<'ra>, NameBinding<'ra>>,
1251 ) -> Module<'ra> {
1252 let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1253 parent,
1254 kind,
1255 expn_id,
1256 span,
1257 no_implicit_prelude,
1258 ))));
1259 let def_id = module.opt_def_id();
1260 if def_id.is_none_or(|def_id| def_id.is_local()) {
1261 self.local_modules.borrow_mut().push(module);
1262 }
1263 if let Some(def_id) = def_id {
1264 module_map.insert(def_id, module);
1265 let vis = ty::Visibility::<DefId>::Public;
1266 let binding = (module, vis, module.span, LocalExpnId::ROOT).to_name_binding(self);
1267 module_self_bindings.insert(module, binding);
1268 }
1269 module
1270 }
1271 fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1272 self.local_modules.borrow()
1273 }
1274 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1275 Interned::new_unchecked(self.dropless.alloc(name_binding))
1276 }
1277 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1278 Interned::new_unchecked(self.imports.alloc(import))
1279 }
1280 fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1281 self.name_resolutions.alloc(Default::default())
1282 }
1283 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1284 Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1285 }
1286 fn alloc_macro_rules_binding(
1287 &'ra self,
1288 binding: MacroRulesBinding<'ra>,
1289 ) -> &'ra MacroRulesBinding<'ra> {
1290 self.dropless.alloc(binding)
1291 }
1292 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1293 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1294 }
1295 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1296 self.dropless.alloc_from_iter(spans)
1297 }
1298}
1299
1300impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1301 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1302 self
1303 }
1304}
1305
1306impl<'tcx> Resolver<'_, 'tcx> {
1307 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1308 self.opt_feed(node).map(|f| f.key())
1309 }
1310
1311 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1312 self.feed(node).key()
1313 }
1314
1315 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1316 self.node_id_to_def_id.get(&node).copied()
1317 }
1318
1319 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1320 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1321 }
1322
1323 fn local_def_kind(&self, node: NodeId) -> DefKind {
1324 self.tcx.def_kind(self.local_def_id(node))
1325 }
1326
1327 fn create_def(
1329 &mut self,
1330 parent: LocalDefId,
1331 node_id: ast::NodeId,
1332 name: Option<Symbol>,
1333 def_kind: DefKind,
1334 expn_id: ExpnId,
1335 span: Span,
1336 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1337 assert!(
1338 !self.node_id_to_def_id.contains_key(&node_id),
1339 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1340 node_id,
1341 name,
1342 def_kind,
1343 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1344 );
1345
1346 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1348 let def_id = feed.def_id();
1349
1350 if expn_id != ExpnId::root() {
1352 self.expn_that_defined.insert(def_id, expn_id);
1353 }
1354
1355 debug_assert_eq!(span.data_untracked().parent, None);
1357 let _id = self.tcx.untracked().source_span.push(span);
1358 debug_assert_eq!(_id, def_id);
1359
1360 if node_id != ast::DUMMY_NODE_ID {
1364 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1365 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1366 }
1367
1368 feed
1369 }
1370
1371 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1372 if let Some(def_id) = def_id.as_local() {
1373 self.item_generics_num_lifetimes[&def_id]
1374 } else {
1375 self.tcx.generics_of(def_id).own_counts().lifetimes
1376 }
1377 }
1378
1379 pub fn tcx(&self) -> TyCtxt<'tcx> {
1380 self.tcx
1381 }
1382
1383 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1388 self.node_id_to_def_id
1389 .items()
1390 .filter(|(_, v)| v.key() == def_id)
1391 .map(|(k, _)| *k)
1392 .get_only()
1393 .unwrap()
1394 }
1395}
1396
1397impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1398 pub fn new(
1399 tcx: TyCtxt<'tcx>,
1400 attrs: &[ast::Attribute],
1401 crate_span: Span,
1402 current_crate_outer_attr_insert_span: Span,
1403 arenas: &'ra ResolverArenas<'ra>,
1404 ) -> Resolver<'ra, 'tcx> {
1405 let root_def_id = CRATE_DEF_ID.to_def_id();
1406 let mut module_map = FxIndexMap::default();
1407 let mut module_self_bindings = FxHashMap::default();
1408 let graph_root = arenas.new_module(
1409 None,
1410 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1411 ExpnId::root(),
1412 crate_span,
1413 attr::contains_name(attrs, sym::no_implicit_prelude),
1414 &mut module_map,
1415 &mut module_self_bindings,
1416 );
1417 let empty_module = arenas.new_module(
1418 None,
1419 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1420 ExpnId::root(),
1421 DUMMY_SP,
1422 true,
1423 &mut Default::default(),
1424 &mut Default::default(),
1425 );
1426
1427 let mut node_id_to_def_id = NodeMap::default();
1428 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1429
1430 crate_feed.def_kind(DefKind::Mod);
1431 let crate_feed = crate_feed.downgrade();
1432 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1433
1434 let mut invocation_parents = FxHashMap::default();
1435 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1436
1437 let mut extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'_>> = tcx
1438 .sess
1439 .opts
1440 .externs
1441 .iter()
1442 .filter(|(_, entry)| entry.add_prelude)
1443 .map(|(name, _)| (Ident::from_str(name), Default::default()))
1444 .collect();
1445
1446 if !attr::contains_name(attrs, sym::no_core) {
1447 extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1448 if !attr::contains_name(attrs, sym::no_std) {
1449 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1450 }
1451 }
1452
1453 let registered_tools = tcx.registered_tools(());
1454
1455 let pub_vis = ty::Visibility::<DefId>::Public;
1456 let edition = tcx.sess.edition();
1457
1458 let mut resolver = Resolver {
1459 tcx,
1460
1461 expn_that_defined: Default::default(),
1462
1463 graph_root,
1466 prelude: None,
1467 extern_prelude,
1468
1469 field_names: Default::default(),
1470 field_visibility_spans: FxHashMap::default(),
1471
1472 determined_imports: Vec::new(),
1473 indeterminate_imports: Vec::new(),
1474
1475 pat_span_map: Default::default(),
1476 partial_res_map: Default::default(),
1477 import_res_map: Default::default(),
1478 import_use_map: Default::default(),
1479 label_res_map: Default::default(),
1480 lifetimes_res_map: Default::default(),
1481 extra_lifetime_params_map: Default::default(),
1482 extern_crate_map: Default::default(),
1483 module_children: Default::default(),
1484 trait_map: NodeMap::default(),
1485 underscore_disambiguator: 0,
1486 empty_module,
1487 module_map,
1488 block_map: Default::default(),
1489 binding_parent_modules: FxHashMap::default(),
1490 ast_transform_scopes: FxHashMap::default(),
1491
1492 glob_map: Default::default(),
1493 glob_error: None,
1494 visibilities_for_hashing: Default::default(),
1495 used_imports: FxHashSet::default(),
1496 maybe_unused_trait_imports: Default::default(),
1497
1498 privacy_errors: Vec::new(),
1499 ambiguity_errors: Vec::new(),
1500 use_injections: Vec::new(),
1501 macro_expanded_macro_export_errors: BTreeSet::new(),
1502
1503 arenas,
1504 dummy_binding: (Res::Err, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas),
1505 builtin_types_bindings: PrimTy::ALL
1506 .iter()
1507 .map(|prim_ty| {
1508 let binding = (Res::PrimTy(*prim_ty), pub_vis, DUMMY_SP, LocalExpnId::ROOT)
1509 .to_name_binding(arenas);
1510 (prim_ty.name(), binding)
1511 })
1512 .collect(),
1513 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1514 .iter()
1515 .map(|builtin_attr| {
1516 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1517 let binding =
1518 (res, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas);
1519 (builtin_attr.name, binding)
1520 })
1521 .collect(),
1522 registered_tool_bindings: registered_tools
1523 .iter()
1524 .map(|ident| {
1525 let binding = (Res::ToolMod, pub_vis, ident.span, LocalExpnId::ROOT)
1526 .to_name_binding(arenas);
1527 (*ident, binding)
1528 })
1529 .collect(),
1530 module_self_bindings,
1531
1532 used_extern_options: Default::default(),
1533 macro_names: FxHashSet::default(),
1534 builtin_macros: Default::default(),
1535 registered_tools,
1536 macro_use_prelude: Default::default(),
1537 macro_map: FxHashMap::default(),
1538 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1539 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1540 non_macro_attr: MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition))),
1541 invocation_parent_scopes: Default::default(),
1542 output_macro_rules_scopes: Default::default(),
1543 macro_rules_scopes: Default::default(),
1544 helper_attrs: Default::default(),
1545 derive_data: Default::default(),
1546 local_macro_def_scopes: FxHashMap::default(),
1547 name_already_seen: FxHashMap::default(),
1548 potentially_unused_imports: Vec::new(),
1549 potentially_unnecessary_qualifications: Default::default(),
1550 struct_constructors: Default::default(),
1551 unused_macros: Default::default(),
1552 unused_macro_rules: Default::default(),
1553 proc_macro_stubs: Default::default(),
1554 single_segment_macro_resolutions: Default::default(),
1555 multi_segment_macro_resolutions: Default::default(),
1556 builtin_attrs: Default::default(),
1557 containers_deriving_copy: Default::default(),
1558 lint_buffer: LintBuffer::default(),
1559 next_node_id: CRATE_NODE_ID,
1560 node_id_to_def_id,
1561 disambiguator: DisambiguatorState::new(),
1562 placeholder_field_indices: Default::default(),
1563 invocation_parents,
1564 legacy_const_generic_args: Default::default(),
1565 item_generics_num_lifetimes: Default::default(),
1566 main_def: Default::default(),
1567 trait_impls: Default::default(),
1568 proc_macros: Default::default(),
1569 confused_type_with_std_module: Default::default(),
1570 lifetime_elision_allowed: Default::default(),
1571 stripped_cfg_items: Default::default(),
1572 effective_visibilities: Default::default(),
1573 doc_link_resolutions: Default::default(),
1574 doc_link_traits_in_scope: Default::default(),
1575 all_macro_rules: Default::default(),
1576 delegation_fn_sigs: Default::default(),
1577 glob_delegation_invoc_ids: Default::default(),
1578 impl_unexpanded_invocations: Default::default(),
1579 impl_binding_keys: Default::default(),
1580 current_crate_outer_attr_insert_span,
1581 mods_with_parse_errors: Default::default(),
1582 };
1583
1584 let root_parent_scope = ParentScope::module(graph_root, &resolver);
1585 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1586 resolver.feed_visibility(crate_feed, ty::Visibility::Public);
1587
1588 resolver
1589 }
1590
1591 fn new_module(
1592 &mut self,
1593 parent: Option<Module<'ra>>,
1594 kind: ModuleKind,
1595 expn_id: ExpnId,
1596 span: Span,
1597 no_implicit_prelude: bool,
1598 ) -> Module<'ra> {
1599 let module_map = &mut self.module_map;
1600 let module_self_bindings = &mut self.module_self_bindings;
1601 self.arenas.new_module(
1602 parent,
1603 kind,
1604 expn_id,
1605 span,
1606 no_implicit_prelude,
1607 module_map,
1608 module_self_bindings,
1609 )
1610 }
1611
1612 fn next_node_id(&mut self) -> NodeId {
1613 let start = self.next_node_id;
1614 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1615 self.next_node_id = ast::NodeId::from_u32(next);
1616 start
1617 }
1618
1619 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1620 let start = self.next_node_id;
1621 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1622 self.next_node_id = ast::NodeId::from_usize(end);
1623 start..self.next_node_id
1624 }
1625
1626 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1627 &mut self.lint_buffer
1628 }
1629
1630 pub fn arenas() -> ResolverArenas<'ra> {
1631 Default::default()
1632 }
1633
1634 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: ty::Visibility) {
1635 let feed = feed.upgrade(self.tcx);
1636 feed.visibility(vis.to_def_id());
1637 self.visibilities_for_hashing.push((feed.def_id(), vis));
1638 }
1639
1640 pub fn into_outputs(self) -> ResolverOutputs {
1641 let proc_macros = self.proc_macros;
1642 let expn_that_defined = self.expn_that_defined;
1643 let extern_crate_map = self.extern_crate_map;
1644 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1645 let glob_map = self.glob_map;
1646 let main_def = self.main_def;
1647 let confused_type_with_std_module = self.confused_type_with_std_module;
1648 let effective_visibilities = self.effective_visibilities;
1649
1650 let stripped_cfg_items = Steal::new(
1651 self.stripped_cfg_items
1652 .into_iter()
1653 .filter_map(|item| {
1654 let parent_module =
1655 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1656 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1657 })
1658 .collect(),
1659 );
1660
1661 let global_ctxt = ResolverGlobalCtxt {
1662 expn_that_defined,
1663 visibilities_for_hashing: self.visibilities_for_hashing,
1664 effective_visibilities,
1665 extern_crate_map,
1666 module_children: self.module_children,
1667 glob_map,
1668 maybe_unused_trait_imports,
1669 main_def,
1670 trait_impls: self.trait_impls,
1671 proc_macros,
1672 confused_type_with_std_module,
1673 doc_link_resolutions: self.doc_link_resolutions,
1674 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1675 all_macro_rules: self.all_macro_rules,
1676 stripped_cfg_items,
1677 };
1678 let ast_lowering = ty::ResolverAstLowering {
1679 legacy_const_generic_args: self.legacy_const_generic_args,
1680 partial_res_map: self.partial_res_map,
1681 import_res_map: self.import_res_map,
1682 label_res_map: self.label_res_map,
1683 lifetimes_res_map: self.lifetimes_res_map,
1684 extra_lifetime_params_map: self.extra_lifetime_params_map,
1685 next_node_id: self.next_node_id,
1686 node_id_to_def_id: self
1687 .node_id_to_def_id
1688 .into_items()
1689 .map(|(k, f)| (k, f.key()))
1690 .collect(),
1691 disambiguator: self.disambiguator,
1692 trait_map: self.trait_map,
1693 lifetime_elision_allowed: self.lifetime_elision_allowed,
1694 lint_buffer: Steal::new(self.lint_buffer),
1695 delegation_fn_sigs: self.delegation_fn_sigs,
1696 };
1697 ResolverOutputs { global_ctxt, ast_lowering }
1698 }
1699
1700 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1701 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1702 }
1703
1704 fn crate_loader<T>(&mut self, f: impl FnOnce(&mut CrateLoader<'_, '_>) -> T) -> T {
1705 f(&mut CrateLoader::new(
1706 self.tcx,
1707 &mut CStore::from_tcx_mut(self.tcx),
1708 &mut self.used_extern_options,
1709 ))
1710 }
1711
1712 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1713 CStore::from_tcx(self.tcx)
1714 }
1715
1716 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1717 match macro_kind {
1718 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1719 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1720 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1721 }
1722 }
1723
1724 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1726 f(self, TypeNS);
1727 f(self, ValueNS);
1728 f(self, MacroNS);
1729 }
1730
1731 fn is_builtin_macro(&mut self, res: Res) -> bool {
1732 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1733 }
1734
1735 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1736 loop {
1737 match ctxt.outer_expn_data().macro_def_id {
1738 Some(def_id) => return def_id,
1739 None => ctxt.remove_mark(),
1740 };
1741 }
1742 }
1743
1744 pub fn resolve_crate(&mut self, krate: &Crate) {
1746 self.tcx.sess.time("resolve_crate", || {
1747 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1748 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1749 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1750 });
1751 self.tcx.sess.time("check_hidden_glob_reexports", || {
1752 self.check_hidden_glob_reexports(exported_ambiguities)
1753 });
1754 self.tcx
1755 .sess
1756 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1757 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1758 self.tcx.sess.time("resolve_main", || self.resolve_main());
1759 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1760 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1761 self.tcx
1762 .sess
1763 .time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate)));
1764 });
1765
1766 self.tcx.untracked().cstore.freeze();
1768 }
1769
1770 fn traits_in_scope(
1771 &mut self,
1772 current_trait: Option<Module<'ra>>,
1773 parent_scope: &ParentScope<'ra>,
1774 ctxt: SyntaxContext,
1775 assoc_item: Option<(Symbol, Namespace)>,
1776 ) -> Vec<TraitCandidate> {
1777 let mut found_traits = Vec::new();
1778
1779 if let Some(module) = current_trait {
1780 if self.trait_may_have_item(Some(module), assoc_item) {
1781 let def_id = module.def_id();
1782 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1783 }
1784 }
1785
1786 self.visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1787 match scope {
1788 Scope::Module(module, _) => {
1789 this.traits_in_module(module, assoc_item, &mut found_traits);
1790 }
1791 Scope::StdLibPrelude => {
1792 if let Some(module) = this.prelude {
1793 this.traits_in_module(module, assoc_item, &mut found_traits);
1794 }
1795 }
1796 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1797 _ => unreachable!(),
1798 }
1799 None::<()>
1800 });
1801
1802 found_traits
1803 }
1804
1805 fn traits_in_module(
1806 &mut self,
1807 module: Module<'ra>,
1808 assoc_item: Option<(Symbol, Namespace)>,
1809 found_traits: &mut Vec<TraitCandidate>,
1810 ) {
1811 module.ensure_traits(self);
1812 let traits = module.traits.borrow();
1813 for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1814 if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1815 let def_id = trait_binding.res().def_id();
1816 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1817 found_traits.push(TraitCandidate { def_id, import_ids });
1818 }
1819 }
1820 }
1821
1822 fn trait_may_have_item(
1828 &mut self,
1829 trait_module: Option<Module<'ra>>,
1830 assoc_item: Option<(Symbol, Namespace)>,
1831 ) -> bool {
1832 match (trait_module, assoc_item) {
1833 (Some(trait_module), Some((name, ns))) => self
1834 .resolutions(trait_module)
1835 .borrow()
1836 .iter()
1837 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1838 _ => true,
1839 }
1840 }
1841
1842 fn find_transitive_imports(
1843 &mut self,
1844 mut kind: &NameBindingKind<'_>,
1845 trait_name: Ident,
1846 ) -> SmallVec<[LocalDefId; 1]> {
1847 let mut import_ids = smallvec![];
1848 while let NameBindingKind::Import { import, binding, .. } = kind {
1849 if let Some(node_id) = import.id() {
1850 let def_id = self.local_def_id(node_id);
1851 self.maybe_unused_trait_imports.insert(def_id);
1852 import_ids.push(def_id);
1853 }
1854 self.add_to_glob_map(*import, trait_name);
1855 kind = &binding.kind;
1856 }
1857 import_ids
1858 }
1859
1860 fn new_disambiguated_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1861 let ident = ident.normalize_to_macros_2_0();
1862 let disambiguator = if ident.name == kw::Underscore {
1863 self.underscore_disambiguator += 1;
1864 self.underscore_disambiguator
1865 } else {
1866 0
1867 };
1868 BindingKey { ident, ns, disambiguator }
1869 }
1870
1871 fn resolutions(&mut self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1872 if module.populate_on_access.get() {
1873 module.populate_on_access.set(false);
1874 self.build_reduced_graph_external(module);
1875 }
1876 &module.0.0.lazy_resolutions
1877 }
1878
1879 fn resolution(
1880 &mut self,
1881 module: Module<'ra>,
1882 key: BindingKey,
1883 ) -> &'ra RefCell<NameResolution<'ra>> {
1884 *self
1885 .resolutions(module)
1886 .borrow_mut()
1887 .entry(key)
1888 .or_insert_with(|| self.arenas.alloc_name_resolution())
1889 }
1890
1891 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1893 for ambiguity_error in &self.ambiguity_errors {
1894 if ambiguity_error.kind == ambi.kind
1896 && ambiguity_error.ident == ambi.ident
1897 && ambiguity_error.ident.span == ambi.ident.span
1898 && ambiguity_error.b1.span == ambi.b1.span
1899 && ambiguity_error.b2.span == ambi.b2.span
1900 && ambiguity_error.misc1 == ambi.misc1
1901 && ambiguity_error.misc2 == ambi.misc2
1902 {
1903 return true;
1904 }
1905 }
1906 false
1907 }
1908
1909 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
1910 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
1911 }
1912
1913 fn record_use_inner(
1914 &mut self,
1915 ident: Ident,
1916 used_binding: NameBinding<'ra>,
1917 used: Used,
1918 warn_ambiguity: bool,
1919 ) {
1920 if let Some((b2, kind)) = used_binding.ambiguity {
1921 let ambiguity_error = AmbiguityError {
1922 kind,
1923 ident,
1924 b1: used_binding,
1925 b2,
1926 misc1: AmbiguityErrorMisc::None,
1927 misc2: AmbiguityErrorMisc::None,
1928 warning: warn_ambiguity,
1929 };
1930 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
1931 self.ambiguity_errors.push(ambiguity_error);
1933 }
1934 }
1935 if let NameBindingKind::Import { import, binding } = used_binding.kind {
1936 if let ImportKind::MacroUse { warn_private: true } = import.kind {
1937 self.lint_buffer().buffer_lint(
1938 PRIVATE_MACRO_USE,
1939 import.root_id,
1940 ident.span,
1941 BuiltinLintDiag::MacroIsPrivate(ident),
1942 );
1943 }
1944 if used == Used::Scope {
1947 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1948 if !entry.introduced_by_item && entry.binding == Some(used_binding) {
1949 return;
1950 }
1951 }
1952 }
1953 let old_used = self.import_use_map.entry(import).or_insert(used);
1954 if *old_used < used {
1955 *old_used = used;
1956 }
1957 if let Some(id) = import.id() {
1958 self.used_imports.insert(id);
1959 }
1960 self.add_to_glob_map(import, ident);
1961 self.record_use_inner(
1962 ident,
1963 binding,
1964 Used::Other,
1965 warn_ambiguity || binding.warn_ambiguity,
1966 );
1967 }
1968 }
1969
1970 #[inline]
1971 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
1972 if let ImportKind::Glob { id, .. } = import.kind {
1973 let def_id = self.local_def_id(id);
1974 self.glob_map.entry(def_id).or_default().insert(ident.name);
1975 }
1976 }
1977
1978 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'ra> {
1979 debug!("resolve_crate_root({:?})", ident);
1980 let mut ctxt = ident.span.ctxt();
1981 let mark = if ident.name == kw::DollarCrate {
1982 ctxt = ctxt.normalize_to_macro_rules();
1989 debug!(
1990 "resolve_crate_root: marks={:?}",
1991 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1992 );
1993 let mut iter = ctxt.marks().into_iter().rev().peekable();
1994 let mut result = None;
1995 while let Some(&(mark, transparency)) = iter.peek() {
1997 if transparency == Transparency::Opaque {
1998 result = Some(mark);
1999 iter.next();
2000 } else {
2001 break;
2002 }
2003 }
2004 debug!(
2005 "resolve_crate_root: found opaque mark {:?} {:?}",
2006 result,
2007 result.map(|r| r.expn_data())
2008 );
2009 for (mark, transparency) in iter {
2011 if transparency == Transparency::SemiOpaque {
2012 result = Some(mark);
2013 } else {
2014 break;
2015 }
2016 }
2017 debug!(
2018 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2019 result,
2020 result.map(|r| r.expn_data())
2021 );
2022 result
2023 } else {
2024 debug!("resolve_crate_root: not DollarCrate");
2025 ctxt = ctxt.normalize_to_macros_2_0();
2026 ctxt.adjust(ExpnId::root())
2027 };
2028 let module = match mark {
2029 Some(def) => self.expn_def_scope(def),
2030 None => {
2031 debug!(
2032 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2033 ident, ident.span
2034 );
2035 return self.graph_root;
2036 }
2037 };
2038 let module = self.expect_module(
2039 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2040 );
2041 debug!(
2042 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2043 ident,
2044 module,
2045 module.kind.name(),
2046 ident.span
2047 );
2048 module
2049 }
2050
2051 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2052 let mut module = self.expect_module(module.nearest_parent_mod());
2053 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2054 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2055 module = self.expect_module(parent.nearest_parent_mod());
2056 }
2057 module
2058 }
2059
2060 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2061 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2062 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2063 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2064 }
2065 }
2066
2067 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2068 debug!("(recording pat) recording {:?} for {:?}", node, span);
2069 self.pat_span_map.insert(node, span);
2070 }
2071
2072 fn is_accessible_from(
2073 &self,
2074 vis: ty::Visibility<impl Into<DefId>>,
2075 module: Module<'ra>,
2076 ) -> bool {
2077 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2078 }
2079
2080 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2081 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2082 if module != old_module {
2083 span_bug!(binding.span, "parent module is reset for binding");
2084 }
2085 }
2086 }
2087
2088 fn disambiguate_macro_rules_vs_modularized(
2089 &self,
2090 macro_rules: NameBinding<'ra>,
2091 modularized: NameBinding<'ra>,
2092 ) -> bool {
2093 match (
2097 self.binding_parent_modules.get(¯o_rules),
2098 self.binding_parent_modules.get(&modularized),
2099 ) {
2100 (Some(macro_rules), Some(modularized)) => {
2101 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2102 && modularized.is_ancestor_of(*macro_rules)
2103 }
2104 _ => false,
2105 }
2106 }
2107
2108 fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2109 if ident.is_path_segment_keyword() {
2110 return None;
2112 }
2113
2114 let norm_ident = ident.normalize_to_macros_2_0();
2115 let binding = self.extern_prelude.get(&norm_ident).cloned().and_then(|entry| {
2116 Some(if let Some(binding) = entry.binding {
2117 if finalize {
2118 if !entry.is_import() {
2119 self.crate_loader(|c| c.process_path_extern(ident.name, ident.span));
2120 } else if entry.introduced_by_item {
2121 self.record_use(ident, binding, Used::Other);
2122 }
2123 }
2124 binding
2125 } else {
2126 let crate_id = if finalize {
2127 let Some(crate_id) =
2128 self.crate_loader(|c| c.process_path_extern(ident.name, ident.span))
2129 else {
2130 return Some(self.dummy_binding);
2131 };
2132 crate_id
2133 } else {
2134 self.crate_loader(|c| c.maybe_process_path_extern(ident.name))?
2135 };
2136 let crate_root = self.expect_module(crate_id.as_def_id());
2137 let vis = ty::Visibility::<DefId>::Public;
2138 (crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas)
2139 })
2140 });
2141
2142 if let Some(entry) = self.extern_prelude.get_mut(&norm_ident) {
2143 entry.binding = binding;
2144 }
2145
2146 binding
2147 }
2148
2149 fn resolve_rustdoc_path(
2154 &mut self,
2155 path_str: &str,
2156 ns: Namespace,
2157 parent_scope: ParentScope<'ra>,
2158 ) -> Option<Res> {
2159 let segments: Result<Vec<_>, ()> = path_str
2160 .split("::")
2161 .enumerate()
2162 .map(|(i, s)| {
2163 let sym = if s.is_empty() {
2164 if i == 0 {
2165 kw::PathRoot
2167 } else {
2168 return Err(()); }
2170 } else {
2171 Symbol::intern(s)
2172 };
2173 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2174 })
2175 .collect();
2176 let Ok(segments) = segments else { return None };
2177
2178 match self.maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2179 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2180 PathResult::NonModule(path_res) => {
2181 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2182 }
2183 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2184 None
2185 }
2186 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2187 }
2188 }
2189
2190 fn def_span(&self, def_id: DefId) -> Span {
2192 match def_id.as_local() {
2193 Some(def_id) => self.tcx.source_span(def_id),
2194 None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2196 }
2197 }
2198
2199 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2200 match def_id.as_local() {
2201 Some(def_id) => self.field_names.get(&def_id).cloned(),
2202 None => Some(
2203 self.tcx
2204 .associated_item_def_ids(def_id)
2205 .iter()
2206 .map(|&def_id| {
2207 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2208 })
2209 .collect(),
2210 ),
2211 }
2212 }
2213
2214 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2218 if let ExprKind::Path(None, path) = &expr.kind {
2219 if path.segments.last().unwrap().args.is_some() {
2222 return None;
2223 }
2224
2225 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2226 if let Res::Def(def::DefKind::Fn, def_id) = res {
2227 if def_id.is_local() {
2231 return None;
2232 }
2233
2234 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2235 return v.clone();
2236 }
2237
2238 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2239 let mut ret = Vec::new();
2240 for meta in attr.meta_item_list()? {
2241 match meta.lit()?.kind {
2242 LitKind::Int(a, _) => ret.push(a.get() as usize),
2243 _ => panic!("invalid arg index"),
2244 }
2245 }
2246 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2248 return Some(ret);
2249 }
2250 }
2251 None
2252 }
2253
2254 fn resolve_main(&mut self) {
2255 let module = self.graph_root;
2256 let ident = Ident::with_dummy_span(sym::main);
2257 let parent_scope = &ParentScope::module(module, self);
2258
2259 let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2260 ModuleOrUniformRoot::Module(module),
2261 ident,
2262 ValueNS,
2263 parent_scope,
2264 None,
2265 ) else {
2266 return;
2267 };
2268
2269 let res = name_binding.res();
2270 let is_import = name_binding.is_import();
2271 let span = name_binding.span;
2272 if let Res::Def(DefKind::Fn, _) = res {
2273 self.record_use(ident, name_binding, Used::Other);
2274 }
2275 self.main_def = Some(MainDefinition { res, is_import, span });
2276 }
2277}
2278
2279fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2280 let mut result = String::new();
2281 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2282 if i > 0 {
2283 result.push_str("::");
2284 }
2285 if Ident::with_dummy_span(name).is_raw_guess() {
2286 result.push_str("r#");
2287 }
2288 result.push_str(name.as_str());
2289 }
2290 result
2291}
2292
2293fn path_names_to_string(path: &Path) -> String {
2294 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2295}
2296
2297fn module_to_string(mut module: Module<'_>) -> Option<String> {
2299 let mut names = Vec::new();
2300 loop {
2301 if let ModuleKind::Def(.., name) = module.kind {
2302 if let Some(parent) = module.parent {
2303 names.push(name.unwrap());
2305 module = parent
2306 } else {
2307 break;
2308 }
2309 } else {
2310 names.push(sym::opaque_module_name_placeholder);
2311 let Some(parent) = module.parent else {
2312 return None;
2313 };
2314 module = parent;
2315 }
2316 }
2317 if names.is_empty() {
2318 return None;
2319 }
2320 Some(names_to_string(names.iter().rev().copied()))
2321}
2322
2323#[derive(Copy, Clone, Debug)]
2324struct Finalize {
2325 node_id: NodeId,
2327 path_span: Span,
2330 root_span: Span,
2333 report_private: bool,
2336 used: Used,
2338}
2339
2340impl Finalize {
2341 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2342 Finalize::with_root_span(node_id, path_span, path_span)
2343 }
2344
2345 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2346 Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2347 }
2348}
2349
2350pub fn provide(providers: &mut Providers) {
2351 providers.registered_tools = macros::registered_tools;
2352}