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>>, Option<Span>)>,
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 impl_trait_names: FxHashMap<NodeId, Symbol>,
1232}
1233
1234#[derive(Default)]
1237pub struct ResolverArenas<'ra> {
1238 modules: TypedArena<ModuleData<'ra>>,
1239 local_modules: RefCell<Vec<Module<'ra>>>,
1240 imports: TypedArena<ImportData<'ra>>,
1241 name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1242 ast_paths: TypedArena<ast::Path>,
1243 dropless: DroplessArena,
1244}
1245
1246impl<'ra> ResolverArenas<'ra> {
1247 fn new_module(
1248 &'ra self,
1249 parent: Option<Module<'ra>>,
1250 kind: ModuleKind,
1251 expn_id: ExpnId,
1252 span: Span,
1253 no_implicit_prelude: bool,
1254 module_map: &mut FxIndexMap<DefId, Module<'ra>>,
1255 module_self_bindings: &mut FxHashMap<Module<'ra>, NameBinding<'ra>>,
1256 ) -> Module<'ra> {
1257 let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1258 parent,
1259 kind,
1260 expn_id,
1261 span,
1262 no_implicit_prelude,
1263 ))));
1264 let def_id = module.opt_def_id();
1265 if def_id.is_none_or(|def_id| def_id.is_local()) {
1266 self.local_modules.borrow_mut().push(module);
1267 }
1268 if let Some(def_id) = def_id {
1269 module_map.insert(def_id, module);
1270 let vis = ty::Visibility::<DefId>::Public;
1271 let binding = (module, vis, module.span, LocalExpnId::ROOT).to_name_binding(self);
1272 module_self_bindings.insert(module, binding);
1273 }
1274 module
1275 }
1276 fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1277 self.local_modules.borrow()
1278 }
1279 fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1280 Interned::new_unchecked(self.dropless.alloc(name_binding))
1281 }
1282 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1283 Interned::new_unchecked(self.imports.alloc(import))
1284 }
1285 fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1286 self.name_resolutions.alloc(Default::default())
1287 }
1288 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1289 Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1290 }
1291 fn alloc_macro_rules_binding(
1292 &'ra self,
1293 binding: MacroRulesBinding<'ra>,
1294 ) -> &'ra MacroRulesBinding<'ra> {
1295 self.dropless.alloc(binding)
1296 }
1297 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1298 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1299 }
1300 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1301 self.dropless.alloc_from_iter(spans)
1302 }
1303}
1304
1305impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1306 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1307 self
1308 }
1309}
1310
1311impl<'tcx> Resolver<'_, 'tcx> {
1312 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1313 self.opt_feed(node).map(|f| f.key())
1314 }
1315
1316 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1317 self.feed(node).key()
1318 }
1319
1320 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1321 self.node_id_to_def_id.get(&node).copied()
1322 }
1323
1324 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1325 self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1326 }
1327
1328 fn local_def_kind(&self, node: NodeId) -> DefKind {
1329 self.tcx.def_kind(self.local_def_id(node))
1330 }
1331
1332 fn create_def(
1334 &mut self,
1335 parent: LocalDefId,
1336 node_id: ast::NodeId,
1337 name: Option<Symbol>,
1338 def_kind: DefKind,
1339 expn_id: ExpnId,
1340 span: Span,
1341 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1342 assert!(
1343 !self.node_id_to_def_id.contains_key(&node_id),
1344 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1345 node_id,
1346 name,
1347 def_kind,
1348 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1349 );
1350
1351 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1353 let def_id = feed.def_id();
1354
1355 if expn_id != ExpnId::root() {
1357 self.expn_that_defined.insert(def_id, expn_id);
1358 }
1359
1360 debug_assert_eq!(span.data_untracked().parent, None);
1362 let _id = self.tcx.untracked().source_span.push(span);
1363 debug_assert_eq!(_id, def_id);
1364
1365 if node_id != ast::DUMMY_NODE_ID {
1369 debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1370 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1371 }
1372
1373 feed
1374 }
1375
1376 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1377 if let Some(def_id) = def_id.as_local() {
1378 self.item_generics_num_lifetimes[&def_id]
1379 } else {
1380 self.tcx.generics_of(def_id).own_counts().lifetimes
1381 }
1382 }
1383
1384 pub fn tcx(&self) -> TyCtxt<'tcx> {
1385 self.tcx
1386 }
1387
1388 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1393 self.node_id_to_def_id
1394 .items()
1395 .filter(|(_, v)| v.key() == def_id)
1396 .map(|(k, _)| *k)
1397 .get_only()
1398 .unwrap()
1399 }
1400}
1401
1402impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1403 pub fn new(
1404 tcx: TyCtxt<'tcx>,
1405 attrs: &[ast::Attribute],
1406 crate_span: Span,
1407 current_crate_outer_attr_insert_span: Span,
1408 arenas: &'ra ResolverArenas<'ra>,
1409 ) -> Resolver<'ra, 'tcx> {
1410 let root_def_id = CRATE_DEF_ID.to_def_id();
1411 let mut module_map = FxIndexMap::default();
1412 let mut module_self_bindings = FxHashMap::default();
1413 let graph_root = arenas.new_module(
1414 None,
1415 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1416 ExpnId::root(),
1417 crate_span,
1418 attr::contains_name(attrs, sym::no_implicit_prelude),
1419 &mut module_map,
1420 &mut module_self_bindings,
1421 );
1422 let empty_module = arenas.new_module(
1423 None,
1424 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1425 ExpnId::root(),
1426 DUMMY_SP,
1427 true,
1428 &mut Default::default(),
1429 &mut Default::default(),
1430 );
1431
1432 let mut node_id_to_def_id = NodeMap::default();
1433 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1434
1435 crate_feed.def_kind(DefKind::Mod);
1436 let crate_feed = crate_feed.downgrade();
1437 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1438
1439 let mut invocation_parents = FxHashMap::default();
1440 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1441
1442 let mut extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'_>> = tcx
1443 .sess
1444 .opts
1445 .externs
1446 .iter()
1447 .filter(|(_, entry)| entry.add_prelude)
1448 .map(|(name, _)| (Ident::from_str(name), Default::default()))
1449 .collect();
1450
1451 if !attr::contains_name(attrs, sym::no_core) {
1452 extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1453 if !attr::contains_name(attrs, sym::no_std) {
1454 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1455 }
1456 }
1457
1458 let registered_tools = tcx.registered_tools(());
1459
1460 let pub_vis = ty::Visibility::<DefId>::Public;
1461 let edition = tcx.sess.edition();
1462
1463 let mut resolver = Resolver {
1464 tcx,
1465
1466 expn_that_defined: Default::default(),
1467
1468 graph_root,
1471 prelude: None,
1472 extern_prelude,
1473
1474 field_names: Default::default(),
1475 field_visibility_spans: FxHashMap::default(),
1476
1477 determined_imports: Vec::new(),
1478 indeterminate_imports: Vec::new(),
1479
1480 pat_span_map: Default::default(),
1481 partial_res_map: Default::default(),
1482 import_res_map: Default::default(),
1483 import_use_map: Default::default(),
1484 label_res_map: Default::default(),
1485 lifetimes_res_map: Default::default(),
1486 extra_lifetime_params_map: Default::default(),
1487 extern_crate_map: Default::default(),
1488 module_children: Default::default(),
1489 trait_map: NodeMap::default(),
1490 underscore_disambiguator: 0,
1491 empty_module,
1492 module_map,
1493 block_map: Default::default(),
1494 binding_parent_modules: FxHashMap::default(),
1495 ast_transform_scopes: FxHashMap::default(),
1496
1497 glob_map: Default::default(),
1498 glob_error: None,
1499 visibilities_for_hashing: Default::default(),
1500 used_imports: FxHashSet::default(),
1501 maybe_unused_trait_imports: Default::default(),
1502
1503 privacy_errors: Vec::new(),
1504 ambiguity_errors: Vec::new(),
1505 use_injections: Vec::new(),
1506 macro_expanded_macro_export_errors: BTreeSet::new(),
1507
1508 arenas,
1509 dummy_binding: (Res::Err, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas),
1510 builtin_types_bindings: PrimTy::ALL
1511 .iter()
1512 .map(|prim_ty| {
1513 let binding = (Res::PrimTy(*prim_ty), pub_vis, DUMMY_SP, LocalExpnId::ROOT)
1514 .to_name_binding(arenas);
1515 (prim_ty.name(), binding)
1516 })
1517 .collect(),
1518 builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1519 .iter()
1520 .map(|builtin_attr| {
1521 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1522 let binding =
1523 (res, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas);
1524 (builtin_attr.name, binding)
1525 })
1526 .collect(),
1527 registered_tool_bindings: registered_tools
1528 .iter()
1529 .map(|ident| {
1530 let binding = (Res::ToolMod, pub_vis, ident.span, LocalExpnId::ROOT)
1531 .to_name_binding(arenas);
1532 (*ident, binding)
1533 })
1534 .collect(),
1535 module_self_bindings,
1536
1537 used_extern_options: Default::default(),
1538 macro_names: FxHashSet::default(),
1539 builtin_macros: Default::default(),
1540 registered_tools,
1541 macro_use_prelude: Default::default(),
1542 macro_map: FxHashMap::default(),
1543 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1544 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1545 non_macro_attr: MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition))),
1546 invocation_parent_scopes: Default::default(),
1547 output_macro_rules_scopes: Default::default(),
1548 macro_rules_scopes: Default::default(),
1549 helper_attrs: Default::default(),
1550 derive_data: Default::default(),
1551 local_macro_def_scopes: FxHashMap::default(),
1552 name_already_seen: FxHashMap::default(),
1553 potentially_unused_imports: Vec::new(),
1554 potentially_unnecessary_qualifications: Default::default(),
1555 struct_constructors: Default::default(),
1556 unused_macros: Default::default(),
1557 unused_macro_rules: Default::default(),
1558 proc_macro_stubs: Default::default(),
1559 single_segment_macro_resolutions: Default::default(),
1560 multi_segment_macro_resolutions: Default::default(),
1561 builtin_attrs: Default::default(),
1562 containers_deriving_copy: Default::default(),
1563 lint_buffer: LintBuffer::default(),
1564 next_node_id: CRATE_NODE_ID,
1565 node_id_to_def_id,
1566 disambiguator: DisambiguatorState::new(),
1567 placeholder_field_indices: Default::default(),
1568 invocation_parents,
1569 legacy_const_generic_args: Default::default(),
1570 item_generics_num_lifetimes: Default::default(),
1571 main_def: Default::default(),
1572 trait_impls: Default::default(),
1573 proc_macros: Default::default(),
1574 confused_type_with_std_module: Default::default(),
1575 lifetime_elision_allowed: Default::default(),
1576 stripped_cfg_items: Default::default(),
1577 effective_visibilities: Default::default(),
1578 doc_link_resolutions: Default::default(),
1579 doc_link_traits_in_scope: Default::default(),
1580 all_macro_rules: Default::default(),
1581 delegation_fn_sigs: Default::default(),
1582 glob_delegation_invoc_ids: Default::default(),
1583 impl_unexpanded_invocations: Default::default(),
1584 impl_binding_keys: Default::default(),
1585 current_crate_outer_attr_insert_span,
1586 mods_with_parse_errors: Default::default(),
1587 impl_trait_names: Default::default(),
1588 };
1589
1590 let root_parent_scope = ParentScope::module(graph_root, &resolver);
1591 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1592 resolver.feed_visibility(crate_feed, ty::Visibility::Public);
1593
1594 resolver
1595 }
1596
1597 fn new_module(
1598 &mut self,
1599 parent: Option<Module<'ra>>,
1600 kind: ModuleKind,
1601 expn_id: ExpnId,
1602 span: Span,
1603 no_implicit_prelude: bool,
1604 ) -> Module<'ra> {
1605 let module_map = &mut self.module_map;
1606 let module_self_bindings = &mut self.module_self_bindings;
1607 self.arenas.new_module(
1608 parent,
1609 kind,
1610 expn_id,
1611 span,
1612 no_implicit_prelude,
1613 module_map,
1614 module_self_bindings,
1615 )
1616 }
1617
1618 fn next_node_id(&mut self) -> NodeId {
1619 let start = self.next_node_id;
1620 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1621 self.next_node_id = ast::NodeId::from_u32(next);
1622 start
1623 }
1624
1625 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1626 let start = self.next_node_id;
1627 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1628 self.next_node_id = ast::NodeId::from_usize(end);
1629 start..self.next_node_id
1630 }
1631
1632 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1633 &mut self.lint_buffer
1634 }
1635
1636 pub fn arenas() -> ResolverArenas<'ra> {
1637 Default::default()
1638 }
1639
1640 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: ty::Visibility) {
1641 let feed = feed.upgrade(self.tcx);
1642 feed.visibility(vis.to_def_id());
1643 self.visibilities_for_hashing.push((feed.def_id(), vis));
1644 }
1645
1646 pub fn into_outputs(self) -> ResolverOutputs {
1647 let proc_macros = self.proc_macros;
1648 let expn_that_defined = self.expn_that_defined;
1649 let extern_crate_map = self.extern_crate_map;
1650 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1651 let glob_map = self.glob_map;
1652 let main_def = self.main_def;
1653 let confused_type_with_std_module = self.confused_type_with_std_module;
1654 let effective_visibilities = self.effective_visibilities;
1655
1656 let stripped_cfg_items = Steal::new(
1657 self.stripped_cfg_items
1658 .into_iter()
1659 .filter_map(|item| {
1660 let parent_module =
1661 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1662 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1663 })
1664 .collect(),
1665 );
1666
1667 let global_ctxt = ResolverGlobalCtxt {
1668 expn_that_defined,
1669 visibilities_for_hashing: self.visibilities_for_hashing,
1670 effective_visibilities,
1671 extern_crate_map,
1672 module_children: self.module_children,
1673 glob_map,
1674 maybe_unused_trait_imports,
1675 main_def,
1676 trait_impls: self.trait_impls,
1677 proc_macros,
1678 confused_type_with_std_module,
1679 doc_link_resolutions: self.doc_link_resolutions,
1680 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1681 all_macro_rules: self.all_macro_rules,
1682 stripped_cfg_items,
1683 };
1684 let ast_lowering = ty::ResolverAstLowering {
1685 legacy_const_generic_args: self.legacy_const_generic_args,
1686 partial_res_map: self.partial_res_map,
1687 import_res_map: self.import_res_map,
1688 label_res_map: self.label_res_map,
1689 lifetimes_res_map: self.lifetimes_res_map,
1690 extra_lifetime_params_map: self.extra_lifetime_params_map,
1691 next_node_id: self.next_node_id,
1692 node_id_to_def_id: self
1693 .node_id_to_def_id
1694 .into_items()
1695 .map(|(k, f)| (k, f.key()))
1696 .collect(),
1697 disambiguator: self.disambiguator,
1698 trait_map: self.trait_map,
1699 lifetime_elision_allowed: self.lifetime_elision_allowed,
1700 lint_buffer: Steal::new(self.lint_buffer),
1701 delegation_fn_sigs: self.delegation_fn_sigs,
1702 };
1703 ResolverOutputs { global_ctxt, ast_lowering }
1704 }
1705
1706 fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1707 StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1708 }
1709
1710 fn crate_loader<T>(&mut self, f: impl FnOnce(&mut CrateLoader<'_, '_>) -> T) -> T {
1711 f(&mut CrateLoader::new(
1712 self.tcx,
1713 &mut CStore::from_tcx_mut(self.tcx),
1714 &mut self.used_extern_options,
1715 ))
1716 }
1717
1718 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1719 CStore::from_tcx(self.tcx)
1720 }
1721
1722 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1723 match macro_kind {
1724 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1725 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1726 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1727 }
1728 }
1729
1730 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1732 f(self, TypeNS);
1733 f(self, ValueNS);
1734 f(self, MacroNS);
1735 }
1736
1737 fn is_builtin_macro(&mut self, res: Res) -> bool {
1738 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1739 }
1740
1741 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1742 loop {
1743 match ctxt.outer_expn_data().macro_def_id {
1744 Some(def_id) => return def_id,
1745 None => ctxt.remove_mark(),
1746 };
1747 }
1748 }
1749
1750 pub fn resolve_crate(&mut self, krate: &Crate) {
1752 self.tcx.sess.time("resolve_crate", || {
1753 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1754 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1755 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1756 });
1757 self.tcx.sess.time("check_hidden_glob_reexports", || {
1758 self.check_hidden_glob_reexports(exported_ambiguities)
1759 });
1760 self.tcx
1761 .sess
1762 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1763 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1764 self.tcx.sess.time("resolve_main", || self.resolve_main());
1765 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1766 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1767 self.tcx
1768 .sess
1769 .time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate)));
1770 });
1771
1772 self.tcx.untracked().cstore.freeze();
1774 }
1775
1776 fn traits_in_scope(
1777 &mut self,
1778 current_trait: Option<Module<'ra>>,
1779 parent_scope: &ParentScope<'ra>,
1780 ctxt: SyntaxContext,
1781 assoc_item: Option<(Symbol, Namespace)>,
1782 ) -> Vec<TraitCandidate> {
1783 let mut found_traits = Vec::new();
1784
1785 if let Some(module) = current_trait {
1786 if self.trait_may_have_item(Some(module), assoc_item) {
1787 let def_id = module.def_id();
1788 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1789 }
1790 }
1791
1792 self.visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1793 match scope {
1794 Scope::Module(module, _) => {
1795 this.traits_in_module(module, assoc_item, &mut found_traits);
1796 }
1797 Scope::StdLibPrelude => {
1798 if let Some(module) = this.prelude {
1799 this.traits_in_module(module, assoc_item, &mut found_traits);
1800 }
1801 }
1802 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1803 _ => unreachable!(),
1804 }
1805 None::<()>
1806 });
1807
1808 found_traits
1809 }
1810
1811 fn traits_in_module(
1812 &mut self,
1813 module: Module<'ra>,
1814 assoc_item: Option<(Symbol, Namespace)>,
1815 found_traits: &mut Vec<TraitCandidate>,
1816 ) {
1817 module.ensure_traits(self);
1818 let traits = module.traits.borrow();
1819 for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1820 if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1821 let def_id = trait_binding.res().def_id();
1822 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1823 found_traits.push(TraitCandidate { def_id, import_ids });
1824 }
1825 }
1826 }
1827
1828 fn trait_may_have_item(
1834 &mut self,
1835 trait_module: Option<Module<'ra>>,
1836 assoc_item: Option<(Symbol, Namespace)>,
1837 ) -> bool {
1838 match (trait_module, assoc_item) {
1839 (Some(trait_module), Some((name, ns))) => self
1840 .resolutions(trait_module)
1841 .borrow()
1842 .iter()
1843 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1844 _ => true,
1845 }
1846 }
1847
1848 fn find_transitive_imports(
1849 &mut self,
1850 mut kind: &NameBindingKind<'_>,
1851 trait_name: Ident,
1852 ) -> SmallVec<[LocalDefId; 1]> {
1853 let mut import_ids = smallvec![];
1854 while let NameBindingKind::Import { import, binding, .. } = kind {
1855 if let Some(node_id) = import.id() {
1856 let def_id = self.local_def_id(node_id);
1857 self.maybe_unused_trait_imports.insert(def_id);
1858 import_ids.push(def_id);
1859 }
1860 self.add_to_glob_map(*import, trait_name);
1861 kind = &binding.kind;
1862 }
1863 import_ids
1864 }
1865
1866 fn new_disambiguated_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1867 let ident = ident.normalize_to_macros_2_0();
1868 let disambiguator = if ident.name == kw::Underscore {
1869 self.underscore_disambiguator += 1;
1870 self.underscore_disambiguator
1871 } else {
1872 0
1873 };
1874 BindingKey { ident, ns, disambiguator }
1875 }
1876
1877 fn resolutions(&mut self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1878 if module.populate_on_access.get() {
1879 module.populate_on_access.set(false);
1880 self.build_reduced_graph_external(module);
1881 }
1882 &module.0.0.lazy_resolutions
1883 }
1884
1885 fn resolution(
1886 &mut self,
1887 module: Module<'ra>,
1888 key: BindingKey,
1889 ) -> &'ra RefCell<NameResolution<'ra>> {
1890 *self
1891 .resolutions(module)
1892 .borrow_mut()
1893 .entry(key)
1894 .or_insert_with(|| self.arenas.alloc_name_resolution())
1895 }
1896
1897 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1899 for ambiguity_error in &self.ambiguity_errors {
1900 if ambiguity_error.kind == ambi.kind
1902 && ambiguity_error.ident == ambi.ident
1903 && ambiguity_error.ident.span == ambi.ident.span
1904 && ambiguity_error.b1.span == ambi.b1.span
1905 && ambiguity_error.b2.span == ambi.b2.span
1906 && ambiguity_error.misc1 == ambi.misc1
1907 && ambiguity_error.misc2 == ambi.misc2
1908 {
1909 return true;
1910 }
1911 }
1912 false
1913 }
1914
1915 fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
1916 self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
1917 }
1918
1919 fn record_use_inner(
1920 &mut self,
1921 ident: Ident,
1922 used_binding: NameBinding<'ra>,
1923 used: Used,
1924 warn_ambiguity: bool,
1925 ) {
1926 if let Some((b2, kind)) = used_binding.ambiguity {
1927 let ambiguity_error = AmbiguityError {
1928 kind,
1929 ident,
1930 b1: used_binding,
1931 b2,
1932 misc1: AmbiguityErrorMisc::None,
1933 misc2: AmbiguityErrorMisc::None,
1934 warning: warn_ambiguity,
1935 };
1936 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
1937 self.ambiguity_errors.push(ambiguity_error);
1939 }
1940 }
1941 if let NameBindingKind::Import { import, binding } = used_binding.kind {
1942 if let ImportKind::MacroUse { warn_private: true } = import.kind {
1943 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
1946 self.maybe_resolve_ident_in_module(
1947 ModuleOrUniformRoot::Module(prelude),
1948 ident,
1949 MacroNS,
1950 &ParentScope::module(self.empty_module, self),
1951 None,
1952 )
1953 .is_ok()
1954 });
1955 if !found_in_stdlib_prelude {
1956 self.lint_buffer().buffer_lint(
1957 PRIVATE_MACRO_USE,
1958 import.root_id,
1959 ident.span,
1960 BuiltinLintDiag::MacroIsPrivate(ident),
1961 );
1962 }
1963 }
1964 if used == Used::Scope {
1967 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1968 if !entry.introduced_by_item && entry.binding == Some(used_binding) {
1969 return;
1970 }
1971 }
1972 }
1973 let old_used = self.import_use_map.entry(import).or_insert(used);
1974 if *old_used < used {
1975 *old_used = used;
1976 }
1977 if let Some(id) = import.id() {
1978 self.used_imports.insert(id);
1979 }
1980 self.add_to_glob_map(import, ident);
1981 self.record_use_inner(
1982 ident,
1983 binding,
1984 Used::Other,
1985 warn_ambiguity || binding.warn_ambiguity,
1986 );
1987 }
1988 }
1989
1990 #[inline]
1991 fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
1992 if let ImportKind::Glob { id, .. } = import.kind {
1993 let def_id = self.local_def_id(id);
1994 self.glob_map.entry(def_id).or_default().insert(ident.name);
1995 }
1996 }
1997
1998 fn resolve_crate_root(&mut self, ident: Ident) -> Module<'ra> {
1999 debug!("resolve_crate_root({:?})", ident);
2000 let mut ctxt = ident.span.ctxt();
2001 let mark = if ident.name == kw::DollarCrate {
2002 ctxt = ctxt.normalize_to_macro_rules();
2009 debug!(
2010 "resolve_crate_root: marks={:?}",
2011 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2012 );
2013 let mut iter = ctxt.marks().into_iter().rev().peekable();
2014 let mut result = None;
2015 while let Some(&(mark, transparency)) = iter.peek() {
2017 if transparency == Transparency::Opaque {
2018 result = Some(mark);
2019 iter.next();
2020 } else {
2021 break;
2022 }
2023 }
2024 debug!(
2025 "resolve_crate_root: found opaque mark {:?} {:?}",
2026 result,
2027 result.map(|r| r.expn_data())
2028 );
2029 for (mark, transparency) in iter {
2031 if transparency == Transparency::SemiOpaque {
2032 result = Some(mark);
2033 } else {
2034 break;
2035 }
2036 }
2037 debug!(
2038 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2039 result,
2040 result.map(|r| r.expn_data())
2041 );
2042 result
2043 } else {
2044 debug!("resolve_crate_root: not DollarCrate");
2045 ctxt = ctxt.normalize_to_macros_2_0();
2046 ctxt.adjust(ExpnId::root())
2047 };
2048 let module = match mark {
2049 Some(def) => self.expn_def_scope(def),
2050 None => {
2051 debug!(
2052 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2053 ident, ident.span
2054 );
2055 return self.graph_root;
2056 }
2057 };
2058 let module = self.expect_module(
2059 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2060 );
2061 debug!(
2062 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2063 ident,
2064 module,
2065 module.kind.name(),
2066 ident.span
2067 );
2068 module
2069 }
2070
2071 fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2072 let mut module = self.expect_module(module.nearest_parent_mod());
2073 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2074 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2075 module = self.expect_module(parent.nearest_parent_mod());
2076 }
2077 module
2078 }
2079
2080 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2081 debug!("(recording res) recording {:?} for {}", resolution, node_id);
2082 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2083 panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2084 }
2085 }
2086
2087 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2088 debug!("(recording pat) recording {:?} for {:?}", node, span);
2089 self.pat_span_map.insert(node, span);
2090 }
2091
2092 fn is_accessible_from(
2093 &self,
2094 vis: ty::Visibility<impl Into<DefId>>,
2095 module: Module<'ra>,
2096 ) -> bool {
2097 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2098 }
2099
2100 fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2101 if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2102 if module != old_module {
2103 span_bug!(binding.span, "parent module is reset for binding");
2104 }
2105 }
2106 }
2107
2108 fn disambiguate_macro_rules_vs_modularized(
2109 &self,
2110 macro_rules: NameBinding<'ra>,
2111 modularized: NameBinding<'ra>,
2112 ) -> bool {
2113 match (
2117 self.binding_parent_modules.get(¯o_rules),
2118 self.binding_parent_modules.get(&modularized),
2119 ) {
2120 (Some(macro_rules), Some(modularized)) => {
2121 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2122 && modularized.is_ancestor_of(*macro_rules)
2123 }
2124 _ => false,
2125 }
2126 }
2127
2128 fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2129 if ident.is_path_segment_keyword() {
2130 return None;
2132 }
2133
2134 let norm_ident = ident.normalize_to_macros_2_0();
2135 let binding = self.extern_prelude.get(&norm_ident).cloned().and_then(|entry| {
2136 Some(if let Some(binding) = entry.binding {
2137 if finalize {
2138 if !entry.is_import() {
2139 self.crate_loader(|c| c.process_path_extern(ident.name, ident.span));
2140 } else if entry.introduced_by_item {
2141 self.record_use(ident, binding, Used::Other);
2142 }
2143 }
2144 binding
2145 } else {
2146 let crate_id = if finalize {
2147 let Some(crate_id) =
2148 self.crate_loader(|c| c.process_path_extern(ident.name, ident.span))
2149 else {
2150 return Some(self.dummy_binding);
2151 };
2152 crate_id
2153 } else {
2154 self.crate_loader(|c| c.maybe_process_path_extern(ident.name))?
2155 };
2156 let crate_root = self.expect_module(crate_id.as_def_id());
2157 let vis = ty::Visibility::<DefId>::Public;
2158 (crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas)
2159 })
2160 });
2161
2162 if let Some(entry) = self.extern_prelude.get_mut(&norm_ident) {
2163 entry.binding = binding;
2164 }
2165
2166 binding
2167 }
2168
2169 fn resolve_rustdoc_path(
2174 &mut self,
2175 path_str: &str,
2176 ns: Namespace,
2177 parent_scope: ParentScope<'ra>,
2178 ) -> Option<Res> {
2179 let segments: Result<Vec<_>, ()> = path_str
2180 .split("::")
2181 .enumerate()
2182 .map(|(i, s)| {
2183 let sym = if s.is_empty() {
2184 if i == 0 {
2185 kw::PathRoot
2187 } else {
2188 return Err(()); }
2190 } else {
2191 Symbol::intern(s)
2192 };
2193 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2194 })
2195 .collect();
2196 let Ok(segments) = segments else { return None };
2197
2198 match self.maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2199 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2200 PathResult::NonModule(path_res) => {
2201 path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2202 }
2203 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2204 None
2205 }
2206 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2207 }
2208 }
2209
2210 fn def_span(&self, def_id: DefId) -> Span {
2212 match def_id.as_local() {
2213 Some(def_id) => self.tcx.source_span(def_id),
2214 None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2216 }
2217 }
2218
2219 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2220 match def_id.as_local() {
2221 Some(def_id) => self.field_names.get(&def_id).cloned(),
2222 None => Some(
2223 self.tcx
2224 .associated_item_def_ids(def_id)
2225 .iter()
2226 .map(|&def_id| {
2227 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2228 })
2229 .collect(),
2230 ),
2231 }
2232 }
2233
2234 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2238 if let ExprKind::Path(None, path) = &expr.kind {
2239 if path.segments.last().unwrap().args.is_some() {
2242 return None;
2243 }
2244
2245 let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2246 if let Res::Def(def::DefKind::Fn, def_id) = res {
2247 if def_id.is_local() {
2251 return None;
2252 }
2253
2254 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2255 return v.clone();
2256 }
2257
2258 let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2259 let mut ret = Vec::new();
2260 for meta in attr.meta_item_list()? {
2261 match meta.lit()?.kind {
2262 LitKind::Int(a, _) => ret.push(a.get() as usize),
2263 _ => panic!("invalid arg index"),
2264 }
2265 }
2266 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2268 return Some(ret);
2269 }
2270 }
2271 None
2272 }
2273
2274 fn resolve_main(&mut self) {
2275 let module = self.graph_root;
2276 let ident = Ident::with_dummy_span(sym::main);
2277 let parent_scope = &ParentScope::module(module, self);
2278
2279 let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2280 ModuleOrUniformRoot::Module(module),
2281 ident,
2282 ValueNS,
2283 parent_scope,
2284 None,
2285 ) else {
2286 return;
2287 };
2288
2289 let res = name_binding.res();
2290 let is_import = name_binding.is_import();
2291 let span = name_binding.span;
2292 if let Res::Def(DefKind::Fn, _) = res {
2293 self.record_use(ident, name_binding, Used::Other);
2294 }
2295 self.main_def = Some(MainDefinition { res, is_import, span });
2296 }
2297}
2298
2299fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2300 let mut result = String::new();
2301 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2302 if i > 0 {
2303 result.push_str("::");
2304 }
2305 if Ident::with_dummy_span(name).is_raw_guess() {
2306 result.push_str("r#");
2307 }
2308 result.push_str(name.as_str());
2309 }
2310 result
2311}
2312
2313fn path_names_to_string(path: &Path) -> String {
2314 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2315}
2316
2317fn module_to_string(mut module: Module<'_>) -> Option<String> {
2319 let mut names = Vec::new();
2320 loop {
2321 if let ModuleKind::Def(.., name) = module.kind {
2322 if let Some(parent) = module.parent {
2323 names.push(name.unwrap());
2325 module = parent
2326 } else {
2327 break;
2328 }
2329 } else {
2330 names.push(sym::opaque_module_name_placeholder);
2331 let Some(parent) = module.parent else {
2332 return None;
2333 };
2334 module = parent;
2335 }
2336 }
2337 if names.is_empty() {
2338 return None;
2339 }
2340 Some(names_to_string(names.iter().rev().copied()))
2341}
2342
2343#[derive(Copy, Clone, Debug)]
2344struct Finalize {
2345 node_id: NodeId,
2347 path_span: Span,
2350 root_span: Span,
2353 report_private: bool,
2356 used: Used,
2358}
2359
2360impl Finalize {
2361 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2362 Finalize::with_root_span(node_id, path_span, path_span)
2363 }
2364
2365 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2366 Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2367 }
2368}
2369
2370pub fn provide(providers: &mut Providers) {
2371 providers.registered_tools = macros::registered_tools;
2372}