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