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