1#![allow(internal_features)]
11#![feature(arbitrary_self_types)]
12#![feature(const_default)]
13#![feature(const_trait_impl)]
14#![feature(control_flow_into_value)]
15#![feature(default_field_values)]
16#![feature(deref_patterns)]
17#![feature(iter_intersperse)]
18#![feature(option_into_flat_iter)]
19#![feature(rustc_attrs)]
20#![feature(trim_prefix_suffix)]
21#![recursion_limit = "256"]
22use std::cell::Ref;
25use std::collections::BTreeSet;
26use std::ops::ControlFlow;
27use std::sync::Arc;
28use std::{fmt, mem};
29
30use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
31use effective_visibilities::EffectiveVisibilitiesVisitor;
32use hygiene::Macros20NormalizedSyntaxContext;
33use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
34use late::{
35 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
36 UnnecessaryQualification,
37};
38pub use macros::registered_tools_ast;
39use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
40use rustc_arena::{DroplessArena, TypedArena};
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::{
43 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
44 GenericArg, GenericArgs, Generics, NodeId, Path, attr,
45};
46use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
47use rustc_data_structures::intern::Interned;
48use rustc_data_structures::steal::Steal;
49use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, WorkerLocal};
50use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
51use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
52use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
53use rustc_feature::{BUILTIN_ATTRIBUTES, Features};
54use rustc_hir::attrs::StrippedCfgItem;
55use rustc_hir::def::Namespace::{self, *};
56use rustc_hir::def::{
57 self, CtorOf, DefKind, DocLinkResMap, MacroKinds, NonMacroAttrKind, PartialRes, PerNS,
58};
59use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
60use rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};
61use rustc_hir::{PrimTy, TraitCandidate, find_attr};
62use rustc_index::bit_set::DenseBitSet;
63use rustc_metadata::creader::CStore;
64use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
65use rustc_middle::middle::privacy::EffectiveVisibilities;
66use rustc_middle::query::Providers;
67use rustc_middle::ty::{
68 self, DelegationInfo, MainDefinition, PerOwnerResolverData, RegisteredTools,
69 ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
70};
71use rustc_middle::{bug, span_bug};
72use rustc_session::config::CrateType;
73use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
74use rustc_span::def_id::{LocalModId, ModId};
75use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
76use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
77use smallvec::{SmallVec, smallvec};
78use tracing::{debug, instrument};
79
80use crate::diagnostics::impls::{
81 ImportSuggestion, LabelSuggestion, OnUnknownData, StructCtor, Suggestion,
82};
83use crate::imports::NameResolutionRef;
84use crate::ref_mut::{CmCell, CmRefCell};
85
86mod build_reduced_graph;
87mod check_unused;
88mod def_collector;
89mod diagnostics;
90mod effective_visibilities;
91mod ident;
92mod imports;
93mod late;
94mod macros;
95pub mod rustdoc;
96
97type Res = def::Res<NodeId>;
98
99#[derive(#[automatically_derived]
impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Determinacy {
#[inline]
fn clone(&self) -> Determinacy { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Determinacy {
#[inline]
fn eq(&self, other: &Determinacy) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Determinacy {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Determinacy::Determined => "Determined",
Determinacy::Undetermined => "Undetermined",
})
}
}Debug)]
100enum Determinacy {
101 Determined,
102 Undetermined,
103}
104
105impl Determinacy {
106 fn determined(determined: bool) -> Determinacy {
107 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
108 }
109}
110
111#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Scope<'ra> {
#[inline]
fn clone(&self) -> Scope<'ra> {
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Scope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for Scope<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Scope::DeriveHelpers(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DeriveHelpers", &__self_0),
Scope::DeriveHelpersCompat =>
::core::fmt::Formatter::write_str(f, "DeriveHelpersCompat"),
Scope::MacroRules(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MacroRules", &__self_0),
Scope::ModuleNonGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleNonGlobs", __self_0, &__self_1),
Scope::ModuleGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleGlobs", __self_0, &__self_1),
Scope::MacroUsePrelude =>
::core::fmt::Formatter::write_str(f, "MacroUsePrelude"),
Scope::BuiltinAttrs =>
::core::fmt::Formatter::write_str(f, "BuiltinAttrs"),
Scope::ExternPreludeItems =>
::core::fmt::Formatter::write_str(f, "ExternPreludeItems"),
Scope::ExternPreludeFlags =>
::core::fmt::Formatter::write_str(f, "ExternPreludeFlags"),
Scope::ToolPrelude =>
::core::fmt::Formatter::write_str(f, "ToolPrelude"),
Scope::StdLibPrelude =>
::core::fmt::Formatter::write_str(f, "StdLibPrelude"),
Scope::BuiltinTypes =>
::core::fmt::Formatter::write_str(f, "BuiltinTypes"),
}
}
}Debug)]
113enum Scope<'ra> {
114 DeriveHelpers(LocalExpnId),
116 DeriveHelpersCompat,
120 MacroRules(MacroRulesScopeRef<'ra>),
122 ModuleNonGlobs(Module<'ra>, Option<NodeId>),
126 ModuleGlobs(Module<'ra>, Option<NodeId>),
130 MacroUsePrelude,
132 BuiltinAttrs,
134 ExternPreludeItems,
136 ExternPreludeFlags,
138 ToolPrelude,
140 StdLibPrelude,
142 BuiltinTypes,
144}
145
146#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ScopeSet<'ra> {
#[inline]
fn clone(&self) -> ScopeSet<'ra> {
let _: ::core::clone::AssertParamIsClone<Namespace>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<MacroKind>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ScopeSet<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ScopeSet<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ScopeSet::All(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
&__self_0),
ScopeSet::Module(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Module",
__self_0, &__self_1),
ScopeSet::ModuleAndExternPrelude(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleAndExternPrelude", __self_0, &__self_1),
ScopeSet::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
ScopeSet::Macro(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Macro",
&__self_0),
}
}
}Debug)]
149enum ScopeSet<'ra> {
150 All(Namespace),
152 Module(Namespace, Module<'ra>),
154 ModuleAndExternPrelude(Namespace, Module<'ra>),
156 ExternPrelude,
158 Macro(MacroKind),
160}
161
162#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
#[inline]
fn clone(&self) -> ParentScope<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
let _: ::core::clone::AssertParamIsClone<&'ra [ast::Path]>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ParentScope<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "ParentScope",
"module", &self.module, "expansion", &self.expansion,
"macro_rules", &self.macro_rules, "derives", &&self.derives)
}
}Debug)]
167struct ParentScope<'ra> {
168 module: Module<'ra>,
169 expansion: LocalExpnId,
170 macro_rules: MacroRulesScopeRef<'ra>,
171 derives: &'ra [ast::Path],
172}
173
174impl<'ra> ParentScope<'ra> {
175 fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
178 ParentScope {
179 module: module.to_module(),
180 expansion: LocalExpnId::ROOT,
181 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
182 derives: &[],
183 }
184 }
185}
186
187#[derive(#[automatically_derived]
impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InvocationParent {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"InvocationParent", "parent_def", &self.parent_def,
"impl_trait_context", &self.impl_trait_context, "in_attr",
&self.in_attr, "owner", &&self.owner)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InvocationParent {
#[inline]
fn clone(&self) -> InvocationParent {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<NodeId>;
*self
}
}Clone)]
188struct InvocationParent {
189 parent_def: LocalDefId,
190 impl_trait_context: ImplTraitContext,
191 in_attr: bool,
192 owner: NodeId,
193}
194
195impl InvocationParent {
196 const ROOT: Self = Self {
197 parent_def: CRATE_DEF_ID,
198 impl_trait_context: ImplTraitContext::Existential,
199 in_attr: false,
200 owner: CRATE_NODE_ID,
201 };
202}
203
204#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ImplTraitContext::Existential => "Existential",
ImplTraitContext::Universal => "Universal",
ImplTraitContext::InBinding => "InBinding",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
#[inline]
fn clone(&self) -> ImplTraitContext { *self }
}Clone)]
205enum ImplTraitContext {
206 Existential,
207 Universal,
208 InBinding,
209}
210
211#[derive(#[automatically_derived]
impl ::core::clone::Clone for Used {
#[inline]
fn clone(&self) -> Used { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Used { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Used {
#[inline]
fn eq(&self, other: &Used) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Used {
#[inline]
fn partial_cmp(&self, other: &Used)
-> ::core::option::Option<::core::cmp::Ordering> {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
}
}PartialOrd, #[automatically_derived]
impl ::core::fmt::Debug for Used {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Used::Scope => "Scope", Used::Other => "Other", })
}
}Debug)]
226enum Used {
227 Scope,
228 Other,
229}
230
231#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BindingError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "BindingError",
"name", &self.name, "origin", &self.origin, "target",
&self.target, "could_be_path", &&self.could_be_path)
}
}Debug)]
232struct BindingError {
233 name: Ident,
234 origin: Vec<(Span, ast::Pat)>,
235 target: Vec<ast::Pat>,
236 could_be_path: bool,
237}
238
239#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ResolutionError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ResolutionError::GenericParamsFromOuterItem {
outer_res: __self_0,
has_generic_params: __self_1,
def_kind: __self_2,
inner_item: __self_3,
current_self_ty: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"GenericParamsFromOuterItem", "outer_res", __self_0,
"has_generic_params", __self_1, "def_kind", __self_2,
"inner_item", __self_3, "current_self_ty", &__self_4),
ResolutionError::NameAlreadyUsedInParameterList(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NameAlreadyUsedInParameterList", __self_0, &__self_1),
ResolutionError::MethodNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::TypeNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::ConstNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::VariableNotBoundInPattern(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableNotBoundInPattern", __self_0, &__self_1),
ResolutionError::VariableBoundWithDifferentMode(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableBoundWithDifferentMode", __self_0, &__self_1),
ResolutionError::IdentifierBoundMoreThanOnceInParameterList(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInParameterList", &__self_0),
ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
ResolutionError::UndeclaredLabel {
name: __self_0, suggestion: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UndeclaredLabel", "name", __self_0, "suggestion",
&__self_1),
ResolutionError::FailedToResolve {
segment: __self_0,
label: __self_1,
suggestion: __self_2,
module: __self_3,
message: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"FailedToResolve", "segment", __self_0, "label", __self_1,
"suggestion", __self_2, "module", __self_3, "message",
&__self_4),
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem =>
::core::fmt::Formatter::write_str(f,
"CannotCaptureDynamicEnvironmentInFnItem"),
ResolutionError::AttemptToUseNonConstantValueInConstant {
ident: __self_0,
suggestion: __self_1,
current: __self_2,
type_span: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"AttemptToUseNonConstantValueInConstant", "ident", __self_0,
"suggestion", __self_1, "current", __self_2, "type_span",
&__self_3),
ResolutionError::BindingShadowsSomethingUnacceptable {
shadowing_binding: __self_0,
name: __self_1,
participle: __self_2,
article: __self_3,
shadowed_binding: __self_4,
shadowed_binding_span: __self_5 } => {
let names: &'static _ =
&["shadowing_binding", "name", "participle", "article",
"shadowed_binding", "shadowed_binding_span"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
&__self_5];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"BindingShadowsSomethingUnacceptable", names, values)
}
ResolutionError::ForwardDeclaredGenericParam(__self_0, __self_1)
=>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ForwardDeclaredGenericParam", __self_0, &__self_1),
ResolutionError::ParamInTyOfConstParam { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ParamInTyOfConstParam", "name", &__self_0),
ResolutionError::ParamInNonTrivialAnonConst {
is_gca: __self_0, name: __self_1, param_kind: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ParamInNonTrivialAnonConst", "is_gca", __self_0, "name",
__self_1, "param_kind", &__self_2),
ResolutionError::ParamInEnumDiscriminant {
name: __self_0, param_kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ParamInEnumDiscriminant", "name", __self_0, "param_kind",
&__self_1),
ResolutionError::ForwardDeclaredSelf(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ForwardDeclaredSelf", &__self_0),
ResolutionError::UnreachableLabel {
name: __self_0,
definition_span: __self_1,
suggestion: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"UnreachableLabel", "name", __self_0, "definition_span",
__self_1, "suggestion", &__self_2),
ResolutionError::TraitImplMismatch {
name: __self_0,
kind: __self_1,
trait_path: __self_2,
trait_item_span: __self_3,
code: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"TraitImplMismatch", "name", __self_0, "kind", __self_1,
"trait_path", __self_2, "trait_item_span", __self_3, "code",
&__self_4),
ResolutionError::TraitImplDuplicate {
name: __self_0, trait_item_span: __self_1, old_span: __self_2
} =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TraitImplDuplicate", "name", __self_0, "trait_item_span",
__self_1, "old_span", &__self_2),
ResolutionError::InvalidAsmSym =>
::core::fmt::Formatter::write_str(f, "InvalidAsmSym"),
ResolutionError::LowercaseSelf =>
::core::fmt::Formatter::write_str(f, "LowercaseSelf"),
ResolutionError::BindingInNeverPattern =>
::core::fmt::Formatter::write_str(f, "BindingInNeverPattern"),
}
}
}Debug)]
240enum ResolutionError<'ra> {
241 GenericParamsFromOuterItem {
243 outer_res: Res,
244 has_generic_params: HasGenericParams,
245 def_kind: DefKind,
246 inner_item: Option<(Span, Span, ast::ItemKind)>,
248 current_self_ty: Option<String>,
249 },
250 NameAlreadyUsedInParameterList(Ident, Span),
253 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
255 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
257 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
259 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
261 VariableBoundWithDifferentMode(Ident, Span),
263 IdentifierBoundMoreThanOnceInParameterList(Ident),
265 IdentifierBoundMoreThanOnceInSamePattern(Ident),
267 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
269 FailedToResolve {
271 segment: Symbol,
272 label: String,
273 suggestion: Option<Suggestion>,
274 module: Option<ModuleOrUniformRoot<'ra>>,
275 message: String,
276 },
277 CannotCaptureDynamicEnvironmentInFnItem,
279 AttemptToUseNonConstantValueInConstant {
281 ident: Ident,
282 suggestion: &'static str,
283 current: &'static str,
284 type_span: Option<Span>,
285 },
286 BindingShadowsSomethingUnacceptable {
288 shadowing_binding: PatternSource,
289 name: Symbol,
290 participle: &'static str,
291 article: &'static str,
292 shadowed_binding: Res,
293 shadowed_binding_span: Span,
294 },
295 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
297 ParamInTyOfConstParam { name: Symbol },
301 ParamInNonTrivialAnonConst {
305 is_gca: bool,
306 name: Symbol,
307 param_kind: ParamKindInNonTrivialAnonConst,
308 },
309 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
313 ForwardDeclaredSelf(ForwardGenericParamBanReason),
315 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
317 TraitImplMismatch {
319 name: Ident,
320 kind: &'static str,
321 trait_path: String,
322 trait_item_span: Span,
323 code: ErrCode,
324 },
325 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
327 InvalidAsmSym,
329 LowercaseSelf,
331 BindingInNeverPattern,
333}
334
335#[derive(#[automatically_derived]
impl ::core::fmt::Debug for VisResolutionError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
VisResolutionError::Relative2018(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Relative2018", __self_0, &__self_1),
VisResolutionError::AncestorOnly(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AncestorOnly", &__self_0),
VisResolutionError::FailedToResolve(__self_0, __self_1, __self_2,
__self_3, __self_4) =>
::core::fmt::Formatter::debug_tuple_field5_finish(f,
"FailedToResolve", __self_0, __self_1, __self_2, __self_3,
&__self_4),
VisResolutionError::ExpectedFound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"ExpectedFound", __self_0, __self_1, &__self_2),
VisResolutionError::Indeterminate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Indeterminate", &__self_0),
VisResolutionError::ModuleOnly(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ModuleOnly", &__self_0),
}
}
}Debug)]
336enum VisResolutionError {
337 Relative2018(Span, ast::Path),
338 AncestorOnly(Span),
339 FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),
340 ExpectedFound(Span, String, Res),
341 Indeterminate(Span),
342 ModuleOnly(Span),
343}
344
345#[derive(#[automatically_derived]
impl ::core::clone::Clone for Segment {
#[inline]
fn clone(&self) -> Segment {
let _: ::core::clone::AssertParamIsClone<Ident>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Segment { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Segment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f, "Segment",
"ident", &self.ident, "id", &self.id, "has_generic_args",
&self.has_generic_args, "has_lifetime_args",
&self.has_lifetime_args, "args_span", &&self.args_span)
}
}Debug)]
348struct Segment {
349 ident: Ident,
350 id: Option<NodeId>,
351 has_generic_args: bool,
353 has_lifetime_args: bool,
355 args_span: Span,
356}
357
358impl Segment {
359 fn from_path(path: &Path) -> Vec<Segment> {
360 path.segments.iter().map(|s| s.into()).collect()
361 }
362
363 fn from_ident(ident: Ident) -> Segment {
364 Segment {
365 ident,
366 id: None,
367 has_generic_args: false,
368 has_lifetime_args: false,
369 args_span: DUMMY_SP,
370 }
371 }
372
373 fn names_to_string(segments: &[Segment]) -> String {
374 names_to_string(segments.iter().map(|seg| seg.ident.name))
375 }
376}
377
378impl<'a> From<&'a ast::PathSegment> for Segment {
379 fn from(seg: &'a ast::PathSegment) -> Segment {
380 let has_generic_args = seg.args.is_some();
381 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
382 match args {
383 GenericArgs::AngleBracketed(args) => {
384 let found_lifetimes = args
385 .args
386 .iter()
387 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
388 (args.span, found_lifetimes)
389 }
390 GenericArgs::Parenthesized(args) => (args.span, true),
391 GenericArgs::ParenthesizedElided(span) => (*span, true),
392 }
393 } else {
394 (DUMMY_SP, false)
395 };
396 Segment {
397 ident: seg.ident,
398 id: Some(seg.id),
399 has_generic_args,
400 has_lifetime_args,
401 args_span,
402 }
403 }
404}
405
406#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for LateDecl<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LateDecl::Decl(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Decl",
&__self_0),
LateDecl::RibDef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "RibDef",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LateDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for LateDecl<'ra> {
#[inline]
fn clone(&self) -> LateDecl<'ra> {
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Res>;
*self
}
}Clone)]
408enum LateDecl<'ra> {
409 Decl(Decl<'ra>),
411 RibDef(Res),
414}
415
416impl<'ra> LateDecl<'ra> {
417 fn res(self) -> Res {
418 match self {
419 LateDecl::Decl(binding) => binding.res(),
420 LateDecl::RibDef(res) => res,
421 }
422 }
423}
424
425#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ModuleOrUniformRoot<'ra> {
#[inline]
fn clone(&self) -> ModuleOrUniformRoot<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ModuleOrUniformRoot<'ra> {
#[inline]
fn eq(&self, other: &ModuleOrUniformRoot<'ra>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ModuleOrUniformRoot::Module(__self_0),
ModuleOrUniformRoot::Module(__arg1_0)) =>
__self_0 == __arg1_0,
(ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0),
ModuleOrUniformRoot::ModuleAndExternPrelude(__arg1_0)) =>
__self_0 == __arg1_0,
(ModuleOrUniformRoot::OpenModule(__self_0),
ModuleOrUniformRoot::OpenModule(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ModuleOrUniformRoot<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleOrUniformRoot::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ModuleAndExternPrelude", &__self_0),
ModuleOrUniformRoot::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
ModuleOrUniformRoot::CurrentScope =>
::core::fmt::Formatter::write_str(f, "CurrentScope"),
ModuleOrUniformRoot::OpenModule(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OpenModule", &__self_0),
}
}
}Debug)]
426enum ModuleOrUniformRoot<'ra> {
427 Module(Module<'ra>),
429
430 ModuleAndExternPrelude(Module<'ra>),
434
435 ExternPrelude,
438
439 CurrentScope,
443
444 OpenModule(Symbol),
448}
449
450#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PathResult::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
PathResult::NonModule(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonModule", &__self_0),
PathResult::Indeterminate =>
::core::fmt::Formatter::write_str(f, "Indeterminate"),
PathResult::Failed {
span: __self_0,
label: __self_1,
suggestion: __self_2,
is_error_from_last_segment: __self_3,
module: __self_4,
segment: __self_5,
error_implied_by_parse_error: __self_6,
message: __self_7,
note: __self_8 } => {
let names: &'static _ =
&["span", "label", "suggestion",
"is_error_from_last_segment", "module", "segment",
"error_implied_by_parse_error", "message", "note"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, __self_6, __self_7, &__self_8];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Failed", names, values)
}
}
}
}Debug)]
451enum PathResult<'ra> {
452 Module(ModuleOrUniformRoot<'ra>),
453 NonModule(PartialRes),
454 Indeterminate,
455 Failed {
456 span: Span,
457 label: String,
458 suggestion: Option<Suggestion>,
459 is_error_from_last_segment: bool,
460 module: Option<ModuleOrUniformRoot<'ra>>,
474 segment: Ident,
476 error_implied_by_parse_error: bool,
477 message: String,
478 note: Option<String>,
479 },
480}
481
482impl<'ra> PathResult<'ra> {
483 fn failed(
484 ident: Ident,
485 is_error_from_last_segment: bool,
486 finalize: bool,
487 error_implied_by_parse_error: bool,
488 module: Option<ModuleOrUniformRoot<'ra>>,
489 label_and_suggestion_and_note: impl FnOnce() -> (
490 String,
491 String,
492 Option<Suggestion>,
493 Option<String>,
494 ),
495 ) -> PathResult<'ra> {
496 let (message, label, suggestion, note) = if finalize {
497 label_and_suggestion_and_note()
498 } else {
499 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in this scope",
ident))
})format!("cannot find `{ident}` in this scope"), String::new(), None, None)
501 };
502 PathResult::Failed {
503 span: ident.span,
504 segment: ident,
505 label,
506 suggestion,
507 is_error_from_last_segment,
508 module,
509 error_implied_by_parse_error,
510 message,
511 note,
512 }
513 }
514}
515
516#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleKind::Block =>
::core::fmt::Formatter::write_str(f, "Block"),
ModuleKind::Def(__self_0, __self_1, __self_2, __self_3) =>
::core::fmt::Formatter::debug_tuple_field4_finish(f, "Def",
__self_0, __self_1, __self_2, &__self_3),
}
}
}Debug)]
517enum ModuleKind {
518 Block,
531 Def(DefKind, DefId, NodeId, Option<Symbol>),
541}
542
543impl ModuleKind {
544 fn opt_def_id(&self) -> Option<DefId> {
545 match self {
546 ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
547 _ => None,
548 }
549 }
550
551 fn def_id(&self) -> DefId {
552 self.opt_def_id().expect("`Module::def_id` is called on a block module")
553 }
554
555 fn is_local(&self) -> bool {
556 match self {
557 ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
558 ModuleKind::Block => true,
559 }
560 }
561}
562
563#[derive(#[automatically_derived]
impl ::core::clone::Clone for IdentKey {
#[inline]
fn clone(&self) -> IdentKey {
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _:
::core::clone::AssertParamIsClone<Macros20NormalizedSyntaxContext>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IdentKey { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for IdentKey {
#[inline]
fn eq(&self, other: &IdentKey) -> bool {
self.name == other.name && self.ctxt == other.ctxt
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IdentKey {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Symbol>;
let _: ::core::cmp::AssertParamIsEq<Macros20NormalizedSyntaxContext>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for IdentKey {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.name, state);
::core::hash::Hash::hash(&self.ctxt, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for IdentKey {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "IdentKey",
"name", &self.name, "ctxt", &&self.ctxt)
}
}Debug)]
574struct IdentKey {
575 name: Symbol,
576 ctxt: Macros20NormalizedSyntaxContext,
577}
578
579impl IdentKey {
580 #[inline]
581 fn new(ident: Ident) -> IdentKey {
582 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
583 }
584
585 #[inline]
586 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
587 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
588 (IdentKey { name: ident.name, ctxt }, def)
589 }
590
591 #[inline]
592 fn with_root_ctxt(name: Symbol) -> Self {
593 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
594 IdentKey { name, ctxt }
595 }
596
597 #[inline]
598 fn orig(self, orig_ident_span: Span) -> Ident {
599 Ident::new(self.name, orig_ident_span)
600 }
601}
602
603#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingKey {
#[inline]
fn clone(&self) -> BindingKey {
let _: ::core::clone::AssertParamIsClone<IdentKey>;
let _: ::core::clone::AssertParamIsClone<Namespace>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for BindingKey {
#[inline]
fn eq(&self, other: &BindingKey) -> bool {
self.disambiguator == other.disambiguator && self.ident == other.ident
&& self.ns == other.ns
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BindingKey {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<IdentKey>;
let _: ::core::cmp::AssertParamIsEq<Namespace>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for BindingKey {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.ident, state);
::core::hash::Hash::hash(&self.ns, state);
::core::hash::Hash::hash(&self.disambiguator, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for BindingKey {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "BindingKey",
"ident", &self.ident, "ns", &self.ns, "disambiguator",
&&self.disambiguator)
}
}Debug)]
608struct BindingKey {
609 ident: IdentKey,
612 ns: Namespace,
613 disambiguator: u32,
619}
620
621impl BindingKey {
622 fn new(ident: IdentKey, ns: Namespace) -> Self {
623 BindingKey { ident, ns, disambiguator: 0 }
624 }
625
626 fn new_disambiguated(
627 ident: IdentKey,
628 ns: Namespace,
629 disambiguator: impl FnOnce() -> u32,
630 ) -> BindingKey {
631 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
632 BindingKey { ident, ns, disambiguator }
633 }
634}
635
636type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, NameResolutionRef<'ra>>>;
637
638struct ModuleData<'ra> {
650 parent: Option<Module<'ra>>,
652 kind: ModuleKind,
654
655 lazy_resolutions: Resolutions<'ra>,
658 populate_on_access: CacheCell<bool>,
660 underscore_disambiguator: CmCell<u32>,
662
663 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
665
666 no_implicit_prelude: bool,
668
669 glob_importers: CmRefCell<Vec<Import<'ra>>>,
670 globs: CmRefCell<Vec<Import<'ra>>>,
671
672 traits: CmRefCell<
674 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
675 >,
676
677 span: Span,
679
680 expansion: ExpnId,
681
682 self_decl: Option<Decl<'ra>>,
685}
686
687#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Module<'ra> {
#[inline]
fn clone(&self) -> Module<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Module<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for Module<'ra> {
#[inline]
fn eq(&self, other: &Module<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for Module<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
}
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for Module<'ra> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
690#[rustc_pass_by_value]
691struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
692
693#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for LocalModule<'ra> {
#[inline]
fn clone(&self) -> LocalModule<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LocalModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for LocalModule<'ra> {
#[inline]
fn eq(&self, other: &LocalModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for LocalModule<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
}
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for LocalModule<'ra> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
695#[rustc_pass_by_value]
696struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
697
698#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ExternModule<'ra> {
#[inline]
fn clone(&self) -> ExternModule<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ExternModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ExternModule<'ra> {
#[inline]
fn eq(&self, other: &ExternModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for ExternModule<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
}
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for ExternModule<'ra> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
700#[rustc_pass_by_value]
701struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
702
703impl<'ra> ModuleData<'ra> {
704 fn new(
705 parent: Option<Module<'ra>>,
706 kind: ModuleKind,
707 expansion: ExpnId,
708 span: Span,
709 no_implicit_prelude: bool,
710 vis: Visibility<ModId>,
711 arenas: &'ra ResolverArenas<'ra>,
712 ) -> Self {
713 let is_foreign = !kind.is_local();
714 let self_decl = match kind {
715 ModuleKind::Def(def_kind, def_id, ..) => {
716 let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
717 Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
718 }
719 ModuleKind::Block => None,
720 };
721 ModuleData {
722 parent,
723 kind,
724 lazy_resolutions: Default::default(),
725 populate_on_access: CacheCell::new(is_foreign),
726 underscore_disambiguator: CmCell::new(0),
727 unexpanded_invocations: Default::default(),
728 no_implicit_prelude,
729 glob_importers: CmRefCell::new(Vec::new()),
730 globs: CmRefCell::new(Vec::new()),
731 traits: CmRefCell::new(None),
732 span,
733 expansion,
734 self_decl,
735 }
736 }
737
738 fn name(&self) -> Option<Symbol> {
740 match self.kind {
741 ModuleKind::Block => None,
742 ModuleKind::Def(.., name) => name,
743 }
744 }
745
746 fn opt_def_id(&self) -> Option<DefId> {
747 self.kind.opt_def_id()
748 }
749
750 fn def_id(&self) -> DefId {
751 self.kind.def_id()
752 }
753
754 fn is_local(&self) -> bool {
755 self.kind.is_local()
756 }
757
758 fn has_unexpanded_invocations(&self) -> bool {
759 !self.unexpanded_invocations.borrow().is_empty()
760 }
761
762 fn res(&self) -> Option<Res> {
763 match self.kind {
764 ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
765 _ => None,
766 }
767 }
768
769 fn def_kind(&self) -> Option<DefKind> {
770 match self.kind {
771 ModuleKind::Def(def_kind, ..) => Some(def_kind),
772 ModuleKind::Block => None,
773 }
774 }
775}
776
777impl<'ra> Module<'ra> {
778 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
779 self,
780 resolver: &R,
781 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
782 ) {
783 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
784 let name_resolution = name_resolution.borrow();
785 if let Some(decl) = name_resolution.best_decl() {
786 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
787 }
788 }
789 }
790
791 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
792 self,
793 resolver: &mut R,
794 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
795 ) {
796 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
797 let name_resolution = name_resolution.borrow();
798 if let Some(decl) = name_resolution.best_decl() {
799 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
800 }
801 }
802 }
803
804 fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {
806 let mut traits = self.traits.borrow_mut(resolver.as_ref());
807 if traits.is_none() {
808 let mut collected_traits = Vec::new();
809 self.for_each_child(resolver, |r, ident, _, ns, mut decl| {
810 if ns != TypeNS {
811 return;
812 }
813
814 let ambiguous = decl.is_ambiguity_recursive();
815 let mut try_record_trait = |decl: Decl<'ra>| {
816 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = decl.res() {
817 collected_traits.push((
818 ident.name,
819 decl,
820 r.as_ref().get_module(def_id),
821 ambiguous,
822 ));
823 true
824 } else {
825 false
826 }
827 };
828 while !try_record_trait(decl)
832 && let Some((_, ambig_decl)) = decl.descent_to_ambiguity()
833 {
834 decl = ambig_decl;
835 }
836 });
837 *traits = Some(collected_traits.into_boxed_slice());
838 }
839 }
840
841 fn is_normal(self) -> bool {
843 self.def_kind() == Some(DefKind::Mod)
844 }
845
846 fn is_trait(self) -> bool {
847 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind() {
Some(DefKind::Trait) => true,
_ => false,
}matches!(self.def_kind(), Some(DefKind::Trait))
848 }
849
850 fn nearest_item_scope(self) -> Module<'ra> {
851 match self.def_kind() {
852 Some(DefKind::Enum | DefKind::Trait) => {
853 self.parent.expect("enum or trait module without a parent")
854 }
855 _ => self,
856 }
857 }
858
859 fn nearest_parent_mod(self) -> ModId {
862 match self.kind {
863 ModuleKind::Def(DefKind::Mod, def_id, _, _) => ModId::new_unchecked(def_id),
864 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
865 }
866 }
867
868 fn nearest_parent_mod_node_id(self) -> NodeId {
871 match self.kind {
872 ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
873 _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
874 }
875 }
876
877 fn is_ancestor_of(self, mut other: Self) -> bool {
878 while self != other {
879 if let Some(parent) = other.parent {
880 other = parent;
881 } else {
882 return false;
883 }
884 }
885 true
886 }
887
888 #[track_caller]
889 fn expect_local(self) -> LocalModule<'ra> {
890 match self.kind {
891 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
892 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected extern module: {0:?}", self))span_bug!(self.span, "unexpected extern module: {self:?}")
893 }
894 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
895 }
896 }
897
898 #[track_caller]
899 fn expect_extern(self) -> ExternModule<'ra> {
900 match self.kind {
901 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
902 ModuleKind::Def(..) | ModuleKind::Block => {
903 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected local module: {0:?}", self))span_bug!(self.span, "unexpected local module: {self:?}")
904 }
905 }
906 }
907}
908
909impl<'ra> LocalModule<'ra> {
910 fn new(
911 parent: Option<LocalModule<'ra>>,
912 kind: ModuleKind,
913 vis: Visibility<ModId>,
914 expn_id: ExpnId,
915 span: Span,
916 no_implicit_prelude: bool,
917 arenas: &'ra ResolverArenas<'ra>,
918 ) -> LocalModule<'ra> {
919 if !kind.is_local() {
::core::panicking::panic("assertion failed: kind.is_local()")
};assert!(kind.is_local());
920 let parent = parent.map(|m| m.to_module());
921 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
922 LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
924 }
925
926 fn to_module(self) -> Module<'ra> {
927 Module(self.0)
928 }
929}
930
931impl<'ra> ExternModule<'ra> {
932 fn new(
933 parent: Option<ExternModule<'ra>>,
934 kind: ModuleKind,
935 vis: Visibility<ModId>,
936 expn_id: ExpnId,
937 span: Span,
938 no_implicit_prelude: bool,
939 arenas: &'ra ResolverArenas<'ra>,
940 ) -> ExternModule<'ra> {
941 if !!kind.is_local() {
::core::panicking::panic("assertion failed: !kind.is_local()")
};assert!(!kind.is_local());
942 let parent = parent.map(|m| m.to_module());
943 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
944 ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
946 }
947
948 fn to_module(self) -> Module<'ra> {
949 Module(self.0)
950 }
951}
952
953impl<'ra> std::ops::Deref for Module<'ra> {
954 type Target = ModuleData<'ra>;
955
956 fn deref(&self) -> &Self::Target {
957 &self.0
958 }
959}
960
961impl<'ra> std::ops::Deref for LocalModule<'ra> {
962 type Target = ModuleData<'ra>;
963
964 fn deref(&self) -> &Self::Target {
965 &self.0
966 }
967}
968
969impl<'ra> std::ops::Deref for ExternModule<'ra> {
970 type Target = ModuleData<'ra>;
971
972 fn deref(&self) -> &Self::Target {
973 &self.0
974 }
975}
976
977impl<'ra> fmt::Debug for Module<'ra> {
978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
979 match self.res() {
980 None => f.write_fmt(format_args!("block"))write!(f, "block"),
981 Some(res) => f.write_fmt(format_args!("{0:?}", res))write!(f, "{:?}", res),
982 }
983 }
984}
985
986impl<'ra> fmt::Debug for LocalModule<'ra> {
987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
988 self.to_module().fmt(f)
989 }
990}
991
992#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclData<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["kind", "ambiguity", "expansion", "span", "initial_vis",
"ambiguity_vis_max", "ambiguity_vis_min", "parent_module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.ambiguity, &self.expansion, &self.span,
&self.initial_vis, &self.ambiguity_vis_max,
&self.ambiguity_vis_min, &&self.parent_module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DeclData",
names, values)
}
}Debug)]
994struct DeclData<'ra> {
995 kind: DeclKind<'ra>,
996 ambiguity: CmCell<Option<(Decl<'ra>, bool )>>,
997 expansion: LocalExpnId,
998 span: Span,
999 initial_vis: Visibility<ModId>,
1000 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
1003 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
1006 parent_module: Option<Module<'ra>>,
1007}
1008
1009type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
1012
1013#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclKind<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DeclKind::Def(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
&__self_0),
DeclKind::Import { source_decl: __self_0, import: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Import", "source_decl", __self_0, "import", &__self_1),
}
}
}Debug)]
1015enum DeclKind<'ra> {
1016 Def(Res),
1019 Import { source_decl: Decl<'ra>, import: Import<'ra> },
1021}
1022
1023impl<'ra> DeclKind<'ra> {
1024 fn is_import(&self) -> bool {
1026 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
1027 }
1028}
1029
1030#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PrivacyError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["ident", "decl", "dedup_span", "outermost_res", "parent_scope",
"single_nested", "source"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.ident, &self.decl, &self.dedup_span, &self.outermost_res,
&self.parent_scope, &self.single_nested, &&self.source];
::core::fmt::Formatter::debug_struct_fields_finish(f, "PrivacyError",
names, values)
}
}Debug)]
1031struct PrivacyError<'ra> {
1032 ident: Ident,
1033 decl: Decl<'ra>,
1034 dedup_span: Span,
1035 outermost_res: Option<(Res, Ident)>,
1036 parent_scope: ParentScope<'ra>,
1037 single_nested: bool,
1039 source: Option<ast::Expr>,
1040}
1041
1042#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for UseError<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["err", "candidates", "node_id", "instead", "suggestion", "path",
"is_call"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.err, &self.candidates, &self.node_id, &self.instead,
&self.suggestion, &self.path, &&self.is_call];
::core::fmt::Formatter::debug_struct_fields_finish(f, "UseError",
names, values)
}
}Debug)]
1043struct UseError<'a> {
1044 err: Diag<'a>,
1045 candidates: Vec<ImportSuggestion>,
1047 node_id: NodeId,
1049 instead: bool,
1051 suggestion: Option<(Span, &'static str, String, Applicability)>,
1053 path: Vec<Segment>,
1056 is_call: bool,
1058}
1059
1060#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DelayedVisResolutionError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DelayedVisResolutionError", "vis", &self.vis, "parent_scope",
&self.parent_scope, "error", &&self.error)
}
}Debug)]
1061struct DelayedVisResolutionError<'ra> {
1062 vis: ast::Visibility,
1063 parent_scope: ParentScope<'ra>,
1064 error: VisResolutionError,
1065}
1066
1067#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityKind {
#[inline]
fn clone(&self) -> AmbiguityKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityKind {
#[inline]
fn eq(&self, other: &AmbiguityKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AmbiguityKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AmbiguityKind::BuiltinAttr => "BuiltinAttr",
AmbiguityKind::DeriveHelper => "DeriveHelper",
AmbiguityKind::MacroRulesVsModularized =>
"MacroRulesVsModularized",
AmbiguityKind::GlobVsOuter => "GlobVsOuter",
AmbiguityKind::GlobVsGlob => "GlobVsGlob",
AmbiguityKind::GlobVsExpanded => "GlobVsExpanded",
AmbiguityKind::MoreExpandedVsOuter => "MoreExpandedVsOuter",
})
}
}Debug)]
1068enum AmbiguityKind {
1069 BuiltinAttr,
1070 DeriveHelper,
1071 MacroRulesVsModularized,
1072 GlobVsOuter,
1073 GlobVsGlob,
1074 GlobVsExpanded,
1075 MoreExpandedVsOuter,
1076}
1077
1078impl AmbiguityKind {
1079 fn descr(self) -> &'static str {
1080 match self {
1081 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1082 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1083 AmbiguityKind::MacroRulesVsModularized => {
1084 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1085 }
1086 AmbiguityKind::GlobVsOuter => {
1087 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1088 }
1089 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1090 AmbiguityKind::GlobVsExpanded => {
1091 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1092 }
1093 AmbiguityKind::MoreExpandedVsOuter => {
1094 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1095 }
1096 }
1097 }
1098}
1099
1100#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityWarning {
#[inline]
fn clone(&self) -> AmbiguityWarning { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityWarning { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityWarning {
#[inline]
fn eq(&self, other: &AmbiguityWarning) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1101enum AmbiguityWarning {
1102 GlobImport,
1103 PanicImport,
1104}
1105
1106struct AmbiguityError<'ra> {
1107 kind: AmbiguityKind,
1108 ambig_vis: Option<(Visibility, Visibility)>,
1109 ident: Ident,
1110 b1: Decl<'ra>,
1111 b2: Decl<'ra>,
1112 scope1: Scope<'ra>,
1113 scope2: Scope<'ra>,
1114 warning: Option<AmbiguityWarning>,
1115}
1116
1117impl<'ra> DeclData<'ra> {
1118 fn vis(&self) -> Visibility<ModId> {
1119 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1121 }
1122
1123 fn min_vis(&self) -> Visibility<ModId> {
1124 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1126 }
1127
1128 fn res(&self) -> Res {
1129 match self.kind {
1130 DeclKind::Def(res) => res,
1131 DeclKind::Import { source_decl, .. } => source_decl.res(),
1132 }
1133 }
1134
1135 fn import_source(&self) -> Decl<'ra> {
1136 match self.kind {
1137 DeclKind::Import { source_decl, .. } => source_decl,
1138 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1139 }
1140 }
1141
1142 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1143 match self.ambiguity.get() {
1144 Some((ambig_binding, _)) => Some((self, ambig_binding)),
1145 None => match self.kind {
1146 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1147 _ => None,
1148 },
1149 }
1150 }
1151
1152 fn is_ambiguity_recursive(&self) -> bool {
1153 self.ambiguity.get().is_some()
1154 || match self.kind {
1155 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1156 _ => false,
1157 }
1158 }
1159
1160 fn is_possibly_imported_variant(&self) -> bool {
1161 match self.kind {
1162 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1163 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1164 true
1165 }
1166 DeclKind::Def(..) => false,
1167 }
1168 }
1169
1170 fn is_extern_crate(&self) -> bool {
1171 match self.kind {
1172 DeclKind::Import { import, .. } => {
1173 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1174 }
1175 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1176 _ => false,
1177 }
1178 }
1179
1180 fn is_import(&self) -> bool {
1181 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1182 }
1183
1184 fn is_import_user_facing(&self) -> bool {
1187 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { import, .. } if
!#[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroExport => true,
_ => false,
} => true,
_ => false,
}matches!(self.kind, DeclKind::Import { import, .. }
1188 if !matches!(import.kind, ImportKind::MacroExport))
1189 }
1190
1191 fn is_glob_import(&self) -> bool {
1192 match self.kind {
1193 DeclKind::Import { import, .. } => import.is_glob(),
1194 _ => false,
1195 }
1196 }
1197
1198 fn is_assoc_item(&self) -> bool {
1199 #[allow(non_exhaustive_omitted_patterns)] match self.res() {
Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy,
_) => true,
_ => false,
}matches!(
1200 self.res(),
1201 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
1202 )
1203 }
1204
1205 fn macro_kinds(&self) -> Option<MacroKinds> {
1206 self.res().macro_kinds()
1207 }
1208
1209 fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {
1210 let mut reexport_chain = SmallVec::new();
1211 let mut next_binding = self;
1212 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1213 reexport_chain.push(import.simplify());
1214 next_binding = source_decl;
1215 }
1216 reexport_chain
1217 }
1218
1219 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1226 let self_parent_expansion = self.expansion;
1230 let other_parent_expansion = decl.expansion;
1231 let certainly_before_other_or_simultaneously =
1232 other_parent_expansion.is_descendant_of(self_parent_expansion);
1233 let certainly_before_invoc_or_simultaneously =
1234 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1235 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1236 }
1237
1238 fn determined(&self) -> bool {
1244 match &self.kind {
1245 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1246 !import.parent_scope.module.has_unexpanded_invocations() && source_decl.determined()
1247 }
1248 _ => true,
1249 }
1250 }
1251}
1252
1253#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ExternPreludeEntry<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ExternPreludeEntry", "item_decl", &self.item_decl, "flag_decl",
&&self.flag_decl)
}
}Debug)]
1254struct ExternPreludeEntry<'ra> {
1255 item_decl: Option<(Decl<'ra>, Span, bool)>,
1259 flag_decl: Option<
1261 CacheCell<(
1262 PendingDecl<'ra>,
1263 bool,
1264 bool,
1265 )>,
1266 >,
1267}
1268
1269impl ExternPreludeEntry<'_> {
1270 fn introduced_by_item(&self) -> bool {
1271 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1272 }
1273
1274 fn flag() -> Self {
1275 ExternPreludeEntry {
1276 item_decl: None,
1277 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1278 }
1279 }
1280
1281 fn open_flag() -> Self {
1282 ExternPreludeEntry {
1283 item_decl: None,
1284 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
1285 }
1286 }
1287
1288 fn span(&self) -> Span {
1289 match self.item_decl {
1290 Some((_, span, _)) => span,
1291 None => DUMMY_SP,
1292 }
1293 }
1294}
1295
1296struct DeriveData {
1297 resolutions: Vec<DeriveResolution>,
1298 helper_attrs: Vec<(usize, IdentKey, Span)>,
1299 has_derive_copy: bool,
1302 has_derive_ord: bool,
1303}
1304
1305pub struct ResolverOutputs<'tcx> {
1306 pub global_ctxt: ResolverGlobalCtxt,
1307 pub ast_lowering: ResolverAstLowering<'tcx>,
1308}
1309
1310#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DelegationFnSig {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"DelegationFnSig", "has_self", &&self.has_self)
}
}Debug)]
1311struct DelegationFnSig {
1312 pub has_self: bool,
1313}
1314
1315pub struct Resolver<'ra, 'tcx> {
1319 tcx: TyCtxt<'tcx>,
1320
1321 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1323
1324 graph_root: LocalModule<'ra>,
1325
1326 assert_speculative: bool,
1328
1329 prelude: Option<Module<'ra>> = None,
1330 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1331
1332 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1334 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1335
1336 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1339
1340 determined_imports: Vec<Import<'ra>> = Vec::new(),
1342
1343 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1345
1346 pat_span_map: NodeMap<Span> = Default::default(),
1349
1350 partial_res_map: NodeMap<PartialRes> = Default::default(),
1352 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1354
1355 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1357 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1358 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1359
1360 block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1375 empty_module: LocalModule<'ra>,
1379 local_modules: Vec<LocalModule<'ra>>,
1381 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1383 extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,
1385
1386 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1388 glob_error: Option<ErrorGuaranteed> = None,
1389 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1390 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1391 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1392
1393 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1395 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1397 issue_145575_hack_applied: bool = false,
1398 delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),
1400 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1402
1403 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1404 dummy_decl: Decl<'ra>,
1405 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1406 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1407 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1408 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1409 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1410 registered_tools: &'tcx RegisteredTools,
1411 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1412 local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),
1414 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
1416 dummy_ext_bang: &'ra Arc<SyntaxExtension>,
1417 dummy_ext_derive: &'ra Arc<SyntaxExtension>,
1418 non_macro_attr: &'ra Arc<SyntaxExtension>,
1419 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1420 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1421 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1422 unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,
1424 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1425 single_segment_macro_resolutions:
1427 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1428 multi_segment_macro_resolutions:
1429 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1430 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1431 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1435 containers_deriving_ord: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1436 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1439 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1442 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1444 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1446 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1449
1450 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1452
1453 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1454
1455 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1456
1457 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1461
1462 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1465
1466 lint_buffer: LintBuffer,
1467
1468 next_node_id: NodeId = CRATE_NODE_ID,
1469
1470 owners: NodeMap<PerOwnerResolverData<'tcx>>,
1472
1473 current_owner: PerOwnerResolverData<'tcx>,
1475
1476 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1477
1478 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1480 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1484
1485 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1487 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1489 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1490 delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,
1491
1492 main_def: Option<MainDefinition> = None,
1493 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1494 proc_macros: Vec<LocalDefId> = Vec::new(),
1497 confused_type_with_std_module: FxIndexMap<Span, Span>,
1498
1499 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1501
1502 effective_visibilities: EffectiveVisibilities,
1503 macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
1504
1505 doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap>,
1506 doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>>,
1507 all_macro_rules: UnordSet<Symbol> = Default::default(),
1508
1509 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1511 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1514 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1517
1518 current_crate_outer_attr_insert_span: Span,
1521
1522 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1523
1524 all_crate_macros_already_registered: bool = false,
1527
1528 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1532
1533 on_unknown_data: FxHashMap<LocalDefId, OnUnknownData> = default::fx_hash_map(),
1535 features: &'tcx Features,
1536}
1537
1538#[derive(#[automatically_derived]
impl<'ra> ::core::default::Default for ResolverArenas<'ra> {
#[inline]
fn default() -> ResolverArenas<'ra> {
ResolverArenas {
modules: ::core::default::Default::default(),
imports: ::core::default::Default::default(),
name_resolutions: ::core::default::Default::default(),
ast_paths: ::core::default::Default::default(),
macros: ::core::default::Default::default(),
dropless: ::core::default::Default::default(),
}
}
}Default)]
1541pub struct ResolverArenas<'ra> {
1542 modules: TypedArena<ModuleData<'ra>>,
1543 imports: TypedArena<ImportData<'ra>>,
1544 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1545 ast_paths: TypedArena<ast::Path>,
1546 macros: TypedArena<Arc<SyntaxExtension>>,
1547 dropless: DroplessArena,
1548}
1549
1550impl<'ra> ResolverArenas<'ra> {
1551 fn new_def_decl(
1552 &'ra self,
1553 res: Res,
1554 vis: Visibility<ModId>,
1555 span: Span,
1556 expansion: LocalExpnId,
1557 parent_module: Option<Module<'ra>>,
1558 ) -> Decl<'ra> {
1559 self.alloc_decl(DeclData {
1560 kind: DeclKind::Def(res),
1561 ambiguity: CmCell::new(None),
1562 initial_vis: vis,
1563 ambiguity_vis_max: CmCell::new(None),
1564 ambiguity_vis_min: CmCell::new(None),
1565 span,
1566 expansion,
1567 parent_module,
1568 })
1569 }
1570
1571 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1572 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1573 }
1574
1575 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1576 Interned::new_unchecked(self.dropless.alloc(data))
1578 }
1579 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1580 Interned::new_unchecked(self.imports.alloc(import))
1582 }
1583 fn alloc_name_resolution(&'ra self, resolution: NameResolution<'ra>) -> NameResolutionRef<'ra> {
1584 Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution)))
1586 }
1587 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1588 self.dropless.alloc(CacheCell::new(scope))
1589 }
1590 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1591 self.dropless.alloc(decl)
1592 }
1593 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1594 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1595 }
1596 fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
1597 self.macros.alloc(Arc::new(ext))
1598 }
1599 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1600 self.dropless.alloc_from_iter(spans)
1601 }
1602}
1603
1604impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1605 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1606 self
1607 }
1608}
1609
1610impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1611 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1612 self
1613 }
1614}
1615
1616impl<'tcx> Resolver<'_, 'tcx> {
1617 fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
1621 self.owners[&owner].def_id
1622 }
1623
1624 fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
1628 self.owners[&owner].node_id_to_def_id[&id]
1629 }
1630
1631 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1633 self.current_owner.node_id_to_def_id.get(&node).copied()
1634 }
1635
1636 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1638 self.opt_local_def_id(node).unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
node));
}panic!("no entry for node id: `{node:?}`"))
1639 }
1640
1641 fn create_def(
1643 &mut self,
1644 parent: LocalDefId,
1645 node_id: ast::NodeId,
1646 name: Option<Symbol>,
1647 def_kind: DefKind,
1648 expn_id: ExpnId,
1649 span: Span,
1650 is_owner: bool,
1651 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1652 if !!self.current_owner.node_id_to_def_id.contains_key(&node_id) {
{
::core::panicking::panic_fmt(format_args!("adding a def for node-id {0:?}, name {1:?}, data {2:?} but a previous def exists: {3:?}",
node_id, name, def_kind,
self.tcx.definitions_untracked().def_key(self.current_owner.node_id_to_def_id[&node_id])));
}
};assert!(
1653 !self.current_owner.node_id_to_def_id.contains_key(&node_id),
1654 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1655 node_id,
1656 name,
1657 def_kind,
1658 self.tcx
1659 .definitions_untracked()
1660 .def_key(self.current_owner.node_id_to_def_id[&node_id]),
1661 );
1662
1663 let disambiguator = self.disambiguators.get_or_create(parent);
1664
1665 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1667 let def_id = feed.def_id();
1668
1669 if expn_id != ExpnId::root() {
1671 self.expn_that_defined.insert(def_id, expn_id);
1672 }
1673
1674 if true {
{
match (&span.data_untracked().parent, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(span.data_untracked().parent, None);
1676 let _id = self.tcx.untracked().source_span.push(span);
1677 if true {
{
match (&_id, &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(_id, def_id);
1678
1679 if node_id != ast::DUMMY_NODE_ID && !is_owner {
1683 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:1683",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1683u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
def_id, node_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1684 self.current_owner.node_id_to_def_id.insert(node_id, def_id);
1685 }
1686
1687 feed
1688 }
1689
1690 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1691 if let Some(def_id) = def_id.as_local() {
1692 self.item_generics_num_lifetimes[&def_id]
1693 } else {
1694 self.tcx.generics_of(def_id).own_counts().lifetimes
1695 }
1696 }
1697
1698 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1699 if let Some(def_id) = def_id.as_local() {
1700 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1701 } else {
1702 let required = self
1703 .tcx
1704 .generics_of(def_id)
1705 .own_params
1706 .iter()
1707 .filter_map(|param| match param.kind {
1708 ty::GenericParamDefKind::Lifetime => Some("'_"),
1709 ty::GenericParamDefKind::Type { has_default, .. }
1710 | ty::GenericParamDefKind::Const { has_default } => {
1711 if has_default {
1712 None
1713 } else {
1714 Some("_")
1715 }
1716 }
1717 })
1718 .collect::<Vec<_>>();
1719
1720 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1721 }
1722 }
1723
1724 pub fn tcx(&self) -> TyCtxt<'tcx> {
1725 self.tcx
1726 }
1727
1728 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1735 self.owners
1736 .items()
1737 .flat_map(|(_, data)| {
1738 data.node_id_to_def_id
1739 .items()
1740 .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
1741 })
1742 .filter(|(_, v)| **v == def_id)
1743 .map(|(k, _)| *k)
1744 .get_only()
1745 .unwrap()
1746 }
1747}
1748
1749impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1750 pub fn new(
1751 tcx: TyCtxt<'tcx>,
1752 attrs: &[ast::Attribute],
1753 crate_span: Span,
1754 current_crate_outer_attr_insert_span: Span,
1755 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1756 ) -> Resolver<'ra, 'tcx> {
1757 let root_def_id = CRATE_DEF_ID.to_def_id();
1758 let graph_root = LocalModule::new(
1759 None,
1760 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1761 Visibility::Public,
1762 ExpnId::root(),
1763 crate_span,
1764 attr::contains_name(attrs, sym::no_implicit_prelude),
1765 arenas,
1766 );
1767 let local_modules = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[graph_root]))vec![graph_root];
1768 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1769 let empty_module = LocalModule::new(
1770 None,
1771 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1772 Visibility::Public,
1773 ExpnId::root(),
1774 DUMMY_SP,
1775 true,
1776 arenas,
1777 );
1778
1779 let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
1780 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1781
1782 crate_feed.def_kind(DefKind::Mod);
1783 let mut owners = NodeMap::default();
1784 owners.insert(CRATE_NODE_ID, owner_data);
1785
1786 let mut invocation_parents = FxHashMap::default();
1787 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1788
1789 let extern_prelude = build_extern_prelude(tcx, attrs);
1790 let registered_tools = tcx.registered_tools(());
1791 let edition = tcx.sess.edition();
1792
1793 let mut resolver = Resolver {
1794 tcx,
1795
1796 graph_root,
1799 assert_speculative: false, extern_prelude,
1801
1802 empty_module,
1803 local_modules,
1804 local_module_map,
1805 extern_module_map: Default::default(),
1806
1807 glob_map: Default::default(),
1808 maybe_unused_trait_imports: Default::default(),
1809
1810 arenas,
1811 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1812 builtin_type_decls: PrimTy::ALL
1813 .iter()
1814 .map(|prim_ty| {
1815 let res = Res::PrimTy(*prim_ty);
1816 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1817 (prim_ty.name(), decl)
1818 })
1819 .collect(),
1820 builtin_attr_decls: BUILTIN_ATTRIBUTES
1821 .iter()
1822 .map(|builtin_attr| {
1823 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));
1824 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1825 (*builtin_attr, decl)
1826 })
1827 .collect(),
1828 registered_tool_decls: registered_tools
1829 .iter()
1830 .map(|&ident| {
1831 let res = Res::ToolMod;
1832 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1833 (IdentKey::new(ident), decl)
1834 })
1835 .collect(),
1836 registered_tools,
1837 macro_use_prelude: Default::default(),
1838 extern_macro_map: Default::default(),
1839 dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
1840 dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
1841 non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
1842 unused_macros: Default::default(),
1843 unused_macro_rules: Default::default(),
1844 single_segment_macro_resolutions: Default::default(),
1845 multi_segment_macro_resolutions: Default::default(),
1846 lint_buffer: LintBuffer::default(),
1847 owners,
1848 current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
1849 invocation_parents,
1850 trait_impls: Default::default(),
1851 confused_type_with_std_module: Default::default(),
1852 stripped_cfg_items: Default::default(),
1853 effective_visibilities: Default::default(),
1854 macro_reachable_adts: Default::default(),
1855 doc_link_resolutions: Default::default(),
1856 doc_link_traits_in_scope: Default::default(),
1857 current_crate_outer_attr_insert_span,
1858 disambiguators: Default::default(),
1859 delegation_infos: Default::default(),
1860 features: tcx.features(),
1861 ..
1862 };
1863
1864 if let Some(directive) = OnUnknownData::from_attrs(&resolver, attrs) {
1865 resolver.on_unknown_data.insert(CRATE_DEF_ID, directive);
1866 }
1867
1868 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1869 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1870 resolver.feed_visibility(crate_feed, Visibility::Public);
1871
1872 resolver
1873 }
1874
1875 fn new_local_module(
1876 &mut self,
1877 parent: Option<LocalModule<'ra>>,
1878 kind: ModuleKind,
1879 expn_id: ExpnId,
1880 span: Span,
1881 no_implicit_prelude: bool,
1882 ) -> LocalModule<'ra> {
1883 let vis =
1884 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1885 let module =
1886 LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
1887 self.local_modules.push(module);
1888 if let Some(def_id) = module.opt_def_id() {
1889 self.local_module_map.insert(def_id.expect_local(), module);
1890 }
1891 module
1892 }
1893
1894 fn new_extern_module(
1895 &self,
1896 parent: Option<ExternModule<'ra>>,
1897 kind: ModuleKind,
1898 expn_id: ExpnId,
1899 span: Span,
1900 no_implicit_prelude: bool,
1901 ) -> ExternModule<'ra> {
1902 let def_id = kind.def_id();
1903 let module = ExternModule::new(
1904 parent,
1905 kind,
1906 self.tcx.visibility(def_id),
1907 expn_id,
1908 span,
1909 no_implicit_prelude,
1910 self.arenas,
1911 );
1912 self.extern_module_map.borrow_mut().insert(def_id, module);
1913 module
1914 }
1915
1916 fn next_node_id(&mut self) -> NodeId {
1917 let start = self.next_node_id;
1918 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1919 self.next_node_id = ast::NodeId::from_u32(next);
1920 start
1921 }
1922
1923 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1924 let start = self.next_node_id;
1925 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1926 self.next_node_id = ast::NodeId::from_usize(end);
1927 start..self.next_node_id
1928 }
1929
1930 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1931 &mut self.lint_buffer
1932 }
1933
1934 pub fn arenas() -> ResolverArenas<'ra> {
1935 Default::default()
1936 }
1937
1938 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1939 feed.visibility(vis.to_mod_id());
1940 self.visibilities_for_hashing.push((feed.def_id(), vis));
1941 }
1942
1943 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1944 let proc_macros = self.proc_macros;
1945 let expn_that_defined = self.expn_that_defined;
1946 let extern_crate_map = self.extern_crate_map;
1947 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1948 let glob_map = self.glob_map;
1949 let main_def = self.main_def;
1950 let confused_type_with_std_module = self.confused_type_with_std_module;
1951 let effective_visibilities = self.effective_visibilities;
1952
1953 let stripped_cfg_items = self
1954 .stripped_cfg_items
1955 .into_iter()
1956 .filter_map(|item| {
1957 let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
1958 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1959 })
1960 .collect();
1961 let disambiguators = self
1962 .disambiguators
1963 .into_items()
1964 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
1965 .collect();
1966
1967 let global_ctxt = ResolverGlobalCtxt {
1968 expn_that_defined,
1969 visibilities_for_hashing: self.visibilities_for_hashing,
1970 effective_visibilities,
1971 macro_reachable_adts: self.macro_reachable_adts,
1972 extern_crate_map,
1973 module_children: self.module_children,
1974 ambig_module_children: self.ambig_module_children,
1975 glob_map,
1976 maybe_unused_trait_imports,
1977 main_def,
1978 trait_impls: self.trait_impls,
1979 proc_macros,
1980 confused_type_with_std_module,
1981 doc_link_resolutions: self.doc_link_resolutions,
1982 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1983 all_macro_rules: self.all_macro_rules,
1984 stripped_cfg_items,
1985 delegation_infos: self.delegation_infos,
1986 };
1987 let ast_lowering = ty::ResolverAstLowering {
1988 partial_res_map: self.partial_res_map,
1989 next_node_id: self.next_node_id,
1990 owners: self.owners,
1991 lint_buffer: Steal::new(self.lint_buffer),
1992 disambiguators,
1993 };
1994 ResolverOutputs { global_ctxt, ast_lowering }
1995 }
1996
1997 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1998 CStore::from_tcx(self.tcx)
1999 }
2000
2001 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
2002 CStore::from_tcx_mut(self.tcx)
2003 }
2004
2005 fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
2006 match macro_kind {
2007 MacroKind::Bang => self.dummy_ext_bang,
2008 MacroKind::Derive => self.dummy_ext_derive,
2009 MacroKind::Attr => self.non_macro_attr,
2010 }
2011 }
2012
2013 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
2018 CmResolver::new(self, !self.assert_speculative)
2019 }
2020
2021 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2023 f(self, TypeNS);
2024 f(self, ValueNS);
2025 f(self, MacroNS);
2026 }
2027
2028 fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
2029 mut self: CmResolver<'r, 'ra, 'tcx>,
2030 mut f: F,
2031 ) {
2032 f(self.reborrow(), TypeNS);
2033 f(self.reborrow(), ValueNS);
2034 f(self, MacroNS);
2035 }
2036
2037 fn is_builtin_macro(&self, res: Res) -> bool {
2038 self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
2039 }
2040
2041 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2042 self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
2043 }
2044
2045 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2046 loop {
2047 match ctxt.outer_expn_data().macro_def_id {
2048 Some(def_id) => return def_id,
2049 None => ctxt.remove_mark(),
2050 };
2051 }
2052 }
2053
2054 pub fn resolve_crate(&mut self, krate: &Crate) {
2056 self.tcx.sess.time("resolve_crate", || {
2057 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2058 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2059 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2060 });
2061 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2062 self.tcx
2063 .sess
2064 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2065 let (use_items, use_injections) =
2066 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2067 self.tcx.sess.time("resolve_main", || self.resolve_main());
2068 self.tcx.sess.time("resolve_check_unused", || self.check_unused(use_items));
2069 self.tcx
2070 .sess
2071 .time("resolve_report_errors", || self.report_errors(krate, use_injections));
2072 self.tcx
2073 .sess
2074 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2075 });
2076
2077 self.tcx.untracked().freeze_cstore();
2079 }
2080
2081 fn traits_in_scope(
2082 &mut self,
2083 current_trait: Option<Module<'ra>>,
2084 parent_scope: &ParentScope<'ra>,
2085 sp: Span,
2086 assoc_item: Option<(Symbol, Namespace)>,
2087 ) -> &'tcx [TraitCandidate<'tcx>] {
2088 let mut found_traits = Vec::new();
2089
2090 if let Some(module) = current_trait {
2091 if self.trait_may_have_item(Some(module), assoc_item) {
2092 let def_id = module.def_id();
2093 found_traits.push(TraitCandidate {
2094 def_id,
2095 import_ids: &[],
2096 lint_ambiguous: false,
2097 });
2098 }
2099 }
2100
2101 let scope_set = ScopeSet::All(TypeNS);
2102 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2103 self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2104 match scope {
2105 Scope::ModuleNonGlobs(module, _) => {
2106 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2107 }
2108 Scope::ModuleGlobs(..) => {
2109 }
2111 Scope::StdLibPrelude => {
2112 if let Some(module) = this.prelude {
2113 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2114 }
2115 }
2116 Scope::ExternPreludeItems
2117 | Scope::ExternPreludeFlags
2118 | Scope::ToolPrelude
2119 | Scope::BuiltinTypes => {}
2120 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2121 }
2122 ControlFlow::<()>::Continue(())
2123 });
2124
2125 self.tcx.hir_arena.alloc_slice(&found_traits)
2126 }
2127
2128 fn traits_in_module(
2129 &mut self,
2130 module: Module<'ra>,
2131 assoc_item: Option<(Symbol, Namespace)>,
2132 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2133 ) {
2134 module.ensure_traits(self);
2135 let traits = module.traits.borrow();
2136 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2137 traits.as_ref().unwrap().iter()
2138 {
2139 if self.trait_may_have_item(trait_module, assoc_item) {
2140 let def_id = trait_binding.res().def_id();
2141 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2142 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2143 }
2144 }
2145 }
2146
2147 fn trait_may_have_item(
2153 &self,
2154 trait_module: Option<Module<'ra>>,
2155 assoc_item: Option<(Symbol, Namespace)>,
2156 ) -> bool {
2157 match (trait_module, assoc_item) {
2158 (Some(trait_module), Some((name, ns))) => self
2159 .resolutions(trait_module)
2160 .borrow()
2161 .iter()
2162 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2163 _ => true,
2164 }
2165 }
2166
2167 fn find_transitive_imports(
2168 &mut self,
2169 mut kind: &DeclKind<'_>,
2170 trait_name: Symbol,
2171 ) -> &'tcx [LocalDefId] {
2172 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2173 while let DeclKind::Import { import, source_decl, .. } = kind {
2174 if let Some(def_id) = import.def_id() {
2175 self.maybe_unused_trait_imports.insert(def_id);
2176 import_ids.push(def_id);
2177 }
2178 self.add_to_glob_map(*import, trait_name);
2179 kind = &source_decl.kind;
2180 }
2181
2182 self.tcx.hir_arena.alloc_slice(&import_ids)
2183 }
2184
2185 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2186 if module.populate_on_access.get() {
2187 module.populate_on_access.set(false);
2188 *module.lazy_resolutions.borrow_mut_unchecked() =
2190 self.build_reduced_graph_external(module.expect_extern());
2191 }
2192 &module.0.0.lazy_resolutions
2193 }
2194
2195 fn resolution(
2196 &self,
2197 module: Module<'ra>,
2198 key: BindingKey,
2199 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2200 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.0.borrow())
2201 }
2202
2203 fn resolution_or_default(
2204 &self,
2205 module: Module<'ra>,
2206 key: BindingKey,
2207 orig_ident_span: Span,
2208 ) -> NameResolutionRef<'ra> {
2209 *self.resolutions(module).borrow_mut(self).entry(key).or_insert_with(|| {
2210 self.arenas.alloc_name_resolution(NameResolution::new(orig_ident_span))
2211 })
2212 }
2213
2214 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2216 for ambiguity_error in &self.ambiguity_errors {
2217 if ambiguity_error.kind == ambi.kind
2219 && ambiguity_error.ident == ambi.ident
2220 && ambiguity_error.ident.span == ambi.ident.span
2221 && ambiguity_error.b1.span == ambi.b1.span
2222 && ambiguity_error.b2.span == ambi.b2.span
2223 {
2224 return true;
2225 }
2226 }
2227 false
2228 }
2229
2230 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2231 if let Some((b2, warning)) = used_decl.ambiguity.get() {
2232 let ambiguity_error = AmbiguityError {
2233 kind: AmbiguityKind::GlobVsGlob,
2234 ambig_vis: None,
2235 ident,
2236 b1: used_decl,
2237 b2,
2238 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2239 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2240 warning: if warning { Some(AmbiguityWarning::GlobImport) } else { None },
2241 };
2242 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2243 self.ambiguity_errors.push(ambiguity_error);
2245 }
2246 }
2247 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2248 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2249 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2252 let empty_module = self.empty_module;
2253 let arenas = self.arenas;
2254 self.cm()
2255 .maybe_resolve_ident_in_module(
2256 ModuleOrUniformRoot::Module(prelude),
2257 ident,
2258 MacroNS,
2259 &ParentScope::module(empty_module, arenas),
2260 None,
2261 )
2262 .is_ok()
2263 });
2264 if !found_in_stdlib_prelude {
2265 self.lint_buffer().buffer_lint(
2266 PRIVATE_MACRO_USE,
2267 import.root_id,
2268 ident.span,
2269 diagnostics::MacroIsPrivate { ident },
2270 );
2271 }
2272 }
2273 if used == Used::Scope
2276 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2277 && let Some((item_decl, _, false)) = entry.item_decl
2278 && item_decl == used_decl
2279 {
2280 return;
2281 }
2282 let old_used = self.import_use_map.entry(import).or_insert(used);
2283 if *old_used < used {
2284 *old_used = used;
2285 }
2286 if let Some(id) = import.id() {
2287 self.used_imports.insert(id);
2288 }
2289 self.add_to_glob_map(import, ident.name);
2290 self.record_use(ident, source_decl, Used::Other);
2291 }
2292 }
2293
2294 #[inline]
2295 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2296 if let ImportKind::Glob { def_id, .. } = import.kind {
2297 self.glob_map.entry(def_id).or_default().insert(name);
2298 }
2299 }
2300
2301 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2302 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2302",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2302u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?})",
ident) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_crate_root({:?})", ident);
2303 let mut ctxt = ident.span.ctxt();
2304 let mark = if ident.name == kw::DollarCrate {
2305 ctxt = ctxt.normalize_to_macro_rules();
2312 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2312",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2312u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: marks={0:?}",
ctxt.marks().into_iter().map(|(i, t)|
(i.expn_data(), t)).collect::<Vec<_>>()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2313 "resolve_crate_root: marks={:?}",
2314 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2315 );
2316 let mut iter = ctxt.marks().into_iter().rev().peekable();
2317 let mut result = None;
2318 while let Some(&(mark, transparency)) = iter.peek() {
2320 if transparency == Transparency::Opaque {
2321 result = Some(mark);
2322 iter.next();
2323 } else {
2324 break;
2325 }
2326 }
2327 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2327",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2327u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2328 "resolve_crate_root: found opaque mark {:?} {:?}",
2329 result,
2330 result.map(|r| r.expn_data())
2331 );
2332 for (mark, transparency) in iter {
2334 if transparency == Transparency::SemiOpaque {
2335 result = Some(mark);
2336 } else {
2337 break;
2338 }
2339 }
2340 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2340",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2340u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found semi-opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2341 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2342 result,
2343 result.map(|r| r.expn_data())
2344 );
2345 result
2346 } else {
2347 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2347",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2347u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2348 ctxt = ctxt.normalize_to_macros_2_0();
2349 ctxt.adjust(ExpnId::root())
2350 };
2351 let module = match mark {
2352 Some(def) => self.expn_def_scope(def),
2353 None => {
2354 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2354",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2354u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
ident, ident.span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2355 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2356 ident, ident.span
2357 );
2358 return self.graph_root.to_module();
2359 }
2360 };
2361 let module = self.expect_module(
2362 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2363 );
2364 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2364",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2364u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): got module {1:?} ({2:?}) (ident.span = {3:?})",
ident, module, module.name(), ident.span) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2365 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2366 ident,
2367 module,
2368 module.name(),
2369 ident.span
2370 );
2371 module
2372 }
2373
2374 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2375 let mut module = self.expect_module(module.nearest_parent_mod().to_def_id());
2376 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2377 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2378 module = self.expect_module(parent.nearest_parent_mod().to_def_id());
2379 }
2380 module
2381 }
2382
2383 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2384 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2384",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2384u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(recording res) recording {0:?} for {1}",
resolution, node_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2385 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2386 {
::core::panicking::panic_fmt(format_args!("path resolved multiple times ({0:?} before, {1:?} now)",
prev_res, resolution));
};panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2387 }
2388 }
2389
2390 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2391 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2391",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2391u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
node, span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2392 self.pat_span_map.insert(node, span);
2393 }
2394
2395 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2396 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2397 }
2398
2399 fn disambiguate_macro_rules_vs_modularized(
2400 &self,
2401 macro_rules: Decl<'ra>,
2402 modularized: Decl<'ra>,
2403 ) -> bool {
2404 let macro_rules = macro_rules.parent_module.unwrap();
2412 let modularized = modularized.parent_module.unwrap();
2413 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2414 && modularized.is_ancestor_of(macro_rules)
2415 }
2416
2417 fn extern_prelude_get_item<'r>(
2418 mut self: CmResolver<'r, 'ra, 'tcx>,
2419 ident: IdentKey,
2420 orig_ident_span: Span,
2421 finalize: bool,
2422 ) -> Option<Decl<'ra>> {
2423 let entry = self.extern_prelude.get(&ident);
2424 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2425 if finalize {
2426 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2427 }
2428 decl
2429 })
2430 }
2431
2432 fn extern_prelude_get_flag(
2433 &self,
2434 ident: IdentKey,
2435 orig_ident_span: Span,
2436 finalize: bool,
2437 ) -> Option<Decl<'ra>> {
2438 let entry = self.extern_prelude.get(&ident);
2439 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2440 let (pending_decl, finalized, is_open) = flag_decl.get();
2441 let decl = match pending_decl {
2442 PendingDecl::Ready(decl) => {
2443 if finalize && !finalized && !is_open {
2444 self.cstore_mut().process_path_extern(
2445 self.tcx,
2446 ident.name,
2447 orig_ident_span,
2448 );
2449 }
2450 decl
2451 }
2452 PendingDecl::Pending => {
2453 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2454 if is_open {
2455 let res = Res::OpenMod(ident.name);
2456 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2457 } else {
2458 let crate_id = if finalize {
2459 self.cstore_mut().process_path_extern(
2460 self.tcx,
2461 ident.name,
2462 orig_ident_span,
2463 )
2464 } else {
2465 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2466 };
2467 crate_id.map(|crate_id| {
2468 let def_id = crate_id.as_def_id();
2469 let res = Res::Def(DefKind::Mod, def_id);
2470 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2471 })
2472 }
2473 }
2474 };
2475 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2476 decl.or_else(|| finalize.then_some(self.dummy_decl))
2477 })
2478 }
2479
2480 fn resolve_rustdoc_path(
2485 &mut self,
2486 path_str: &str,
2487 ns: Namespace,
2488 parent_scope: ParentScope<'ra>,
2489 ) -> Option<Res> {
2490 let segments: Result<Vec<_>, ()> = path_str
2491 .split("::")
2492 .enumerate()
2493 .map(|(i, s)| {
2494 let sym = if s.is_empty() {
2495 if i == 0 {
2496 kw::PathRoot
2498 } else {
2499 return Err(()); }
2501 } else {
2502 Symbol::intern(s)
2503 };
2504 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2505 })
2506 .collect();
2507 let Ok(segments) = segments else { return None };
2508
2509 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2510 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2511 PathResult::NonModule(path_res) => {
2512 path_res.full_res().filter(|res| !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Ctor(..), _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Ctor(..), _)))
2513 }
2514 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2515 None
2516 }
2517 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2518 ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
path_result))bug!("got invalid path_result: {path_result:?}")
2519 }
2520 }
2521 }
2522
2523 fn def_span(&self, def_id: DefId) -> Span {
2525 match def_id.as_local() {
2526 Some(def_id) => self.tcx.source_span(def_id),
2527 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2529 }
2530 }
2531
2532 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2533 match def_id.as_local() {
2534 Some(def_id) => self.field_names.get(&def_id).cloned(),
2535 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2536 self.tcx.def_kind(def_id),
2537 DefKind::Struct | DefKind::Union | DefKind::Variant
2538 ) =>
2539 {
2540 Some(
2541 self.tcx
2542 .associated_item_def_ids(def_id)
2543 .iter()
2544 .map(|&def_id| {
2545 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2546 })
2547 .collect(),
2548 )
2549 }
2550 _ => None,
2551 }
2552 }
2553
2554 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2555 match def_id.as_local() {
2556 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2557 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2558 self.tcx.def_kind(def_id),
2559 DefKind::Struct | DefKind::Union | DefKind::Variant
2560 ) =>
2561 {
2562 Some(
2563 self.tcx
2564 .associated_item_def_ids(def_id)
2565 .iter()
2566 .filter_map(|&def_id| {
2567 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2568 })
2569 .collect(),
2570 )
2571 }
2572 _ => None,
2573 }
2574 }
2575
2576 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2580 let ExprKind::Path(None, path) = &expr.kind else {
2581 return None;
2582 };
2583 if path.segments.last().unwrap().args.is_some() {
2586 return None;
2587 }
2588
2589 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2590
2591 if def_id.is_local() {
2595 return None;
2596 }
2597
2598 {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcLegacyConstGenerics {
fn_indexes, .. }) => {
break 'done Some(fn_indexes);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
2599 self.tcx, def_id,
2601 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2602 )
2603 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2604 }
2605
2606 fn resolve_main(&mut self) {
2607 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2608 if !any_exe {
2610 return;
2611 }
2612
2613 let module = self.graph_root;
2614 let ident = Ident::with_dummy_span(sym::main);
2615 let parent_scope = &ParentScope::module(module, self.arenas);
2616
2617 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2618 ModuleOrUniformRoot::Module(module.to_module()),
2619 ident,
2620 ValueNS,
2621 parent_scope,
2622 None,
2623 ) else {
2624 return;
2625 };
2626
2627 let res = name_binding.res();
2628 let is_import = name_binding.is_import();
2629 let span = name_binding.span;
2630 if let Res::Def(DefKind::Fn, _) = res {
2631 self.record_use(ident, name_binding, Used::Other);
2632 }
2633 self.main_def = Some(MainDefinition { res, is_import, span });
2634 }
2635}
2636
2637fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2638 this: &mut R,
2639 owner: NodeId,
2640 work: impl FnOnce(&mut R) -> T,
2641) -> T {
2642 let tables = this.as_mut().owners.remove(&owner).unwrap();
2643 with_owner_tables(this, owner, tables, work)
2644}
2645
2646#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("with_owner_tables",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2646u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("owner")
}> =
::tracing::__macro_support::FieldName::new("owner");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tables")
}> =
::tracing::__macro_support::FieldName::new("tables");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tables)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: T = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !!this.as_mut().owners.contains_key(&owner) {
::core::panicking::panic("assertion failed: !this.as_mut().owners.contains_key(&owner)")
};
};
let resolver = this.as_mut();
let old_owner = mem::replace(&mut resolver.current_owner, tables);
let ret = work(this);
let resolver = this.as_mut();
let overwritten =
resolver.owners.insert(owner,
mem::replace(&mut resolver.current_owner, old_owner));
if !overwritten.is_none() {
::core::panicking::panic("assertion failed: overwritten.is_none()")
};
ret
}
}
}#[instrument(level = "debug", skip(this, work))]
2647fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2648 this: &mut R,
2649 owner: NodeId,
2650 tables: PerOwnerResolverData<'tcx>,
2651 work: impl FnOnce(&mut R) -> T,
2652) -> T {
2653 debug_assert!(!this.as_mut().owners.contains_key(&owner));
2654 let resolver = this.as_mut();
2655 let old_owner = mem::replace(&mut resolver.current_owner, tables);
2656 let ret = work(this);
2657 let resolver = this.as_mut();
2658 let overwritten =
2659 resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2660 assert!(overwritten.is_none());
2661 ret
2662}
2663
2664fn build_extern_prelude<'tcx, 'ra>(
2665 tcx: TyCtxt<'tcx>,
2666 attrs: &[ast::Attribute],
2667) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2668 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2669 .sess
2670 .opts
2671 .externs
2672 .iter()
2673 .filter_map(|(name, entry)| {
2674 if entry.add_prelude
2677 && let sym = Symbol::intern(name)
2678 && sym.can_be_raw()
2679 {
2680 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2681 } else {
2682 None
2683 }
2684 })
2685 .collect();
2686
2687 let missing_open_bases: Vec<IdentKey> = extern_prelude
2693 .keys()
2694 .filter_map(|ident| {
2695 let (base, _) = ident.name.as_str().split_once("::")?;
2696 let base_sym = Symbol::intern(base);
2697 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2698 })
2699 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2700 .collect();
2701
2702 extern_prelude.extend(
2703 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2704 );
2705
2706 if !attr::contains_name(attrs, sym::no_core) {
2708 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2709
2710 if !attr::contains_name(attrs, sym::no_std) {
2711 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2712 }
2713 }
2714
2715 extern_prelude
2716}
2717
2718fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2719 let mut result = String::new();
2720 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2721 if i > 0 {
2722 result.push_str("::");
2723 }
2724 if Ident::with_dummy_span(name).is_raw_guess() {
2725 result.push_str("r#");
2726 }
2727 result.push_str(name.as_str());
2728 }
2729 result
2730}
2731
2732fn path_names_to_string(path: &Path) -> String {
2733 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2734}
2735
2736fn module_to_string(mut module: Module<'_>) -> Option<String> {
2738 let mut names = Vec::new();
2739 while let Some(parent) = module.parent {
2740 names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2741 module = parent;
2742 }
2743 if names.is_empty() {
2744 return None;
2745 }
2746 Some(names_to_string(names.iter().rev().copied()))
2747}
2748
2749#[derive(#[automatically_derived]
impl ::core::marker::Copy for Stage { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Stage {
#[inline]
fn clone(&self) -> Stage { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Stage {
#[inline]
fn eq(&self, other: &Stage) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Stage {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Stage::Early => "Early", Stage::Late => "Late", })
}
}Debug)]
2750enum Stage {
2751 Early,
2755 Late,
2758}
2759
2760#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImportSummary { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ImportSummary {
#[inline]
fn clone(&self) -> ImportSummary {
let _: ::core::clone::AssertParamIsClone<Visibility>;
let _: ::core::clone::AssertParamIsClone<LocalModId>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ImportSummary {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f, "ImportSummary",
"vis", &self.vis, "nearest_parent_mod", &self.nearest_parent_mod,
"is_single", &self.is_single, "priv_macro_use",
&self.priv_macro_use, "span", &&self.span)
}
}Debug)]
2763struct ImportSummary {
2764 vis: Visibility,
2765 nearest_parent_mod: LocalModId,
2766 is_single: bool,
2767 priv_macro_use: bool,
2768 span: Span,
2769}
2770
2771#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Finalize {
#[inline]
fn clone(&self) -> Finalize {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Used>;
let _: ::core::clone::AssertParamIsClone<Stage>;
let _: ::core::clone::AssertParamIsClone<Option<ImportSummary>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["node_id", "path_span", "root_span", "report_private", "used",
"stage", "import"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.node_id, &self.path_span, &self.root_span,
&self.report_private, &self.used, &self.stage,
&&self.import];
::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
names, values)
}
}Debug)]
2773struct Finalize {
2774 node_id: NodeId,
2776 path_span: Span,
2779 root_span: Span,
2782 report_private: bool = true,
2785 used: Used = Used::Other,
2787 stage: Stage = Stage::Early,
2789 import: Option<ImportSummary> = None,
2791}
2792
2793impl Finalize {
2794 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2795 Finalize::with_root_span(node_id, path_span, path_span)
2796 }
2797
2798 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2799 Finalize { node_id, path_span, root_span, .. }
2800 }
2801}
2802
2803pub fn provide(providers: &mut Providers) {
2804 providers.registered_tools = macros::registered_tools;
2805}
2806
2807type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2813
2814use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2818
2819mod ref_mut {
2820 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2821 use std::fmt;
2822 use std::ops::Deref;
2823
2824 use crate::Resolver;
2825
2826 pub(crate) struct RefOrMut<'a, T> {
2828 p: &'a mut T,
2829 mutable: bool,
2830 }
2831
2832 impl<'a, T> Deref for RefOrMut<'a, T> {
2833 type Target = T;
2834
2835 fn deref(&self) -> &Self::Target {
2836 self.p
2837 }
2838 }
2839
2840 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2841 fn as_ref(&self) -> &T {
2842 self.p
2843 }
2844 }
2845
2846 impl<'a, T> RefOrMut<'a, T> {
2847 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2848 RefOrMut { p, mutable }
2849 }
2850
2851 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2853 RefOrMut { p: self.p, mutable: self.mutable }
2854 }
2855
2856 #[track_caller]
2861 pub(crate) fn get_mut(&mut self) -> &mut T {
2862 match self.mutable {
2863 false => {
::core::panicking::panic_fmt(format_args!("can\'t mutably borrow speculative resolver"));
}panic!("can't mutably borrow speculative resolver"),
2864 true => self.p,
2865 }
2866 }
2867 }
2868
2869 #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmCell<T> {
#[inline]
fn default() -> CmCell<T> { CmCell(::core::default::Default::default()) }
}Default)]
2871 pub(crate) struct CmCell<T>(Cell<T>);
2872
2873 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2875 f.debug_tuple("CmCell").field(&self.get()).finish()
2876 }
2877 }
2878
2879 impl<T: Copy> Clone for CmCell<T> {
2880 fn clone(&self) -> CmCell<T> {
2881 CmCell::new(self.get())
2882 }
2883 }
2884
2885 impl<T: Copy> CmCell<T> {
2886 pub(crate) const fn get(&self) -> T {
2887 self.0.get()
2888 }
2889
2890 pub(crate) fn update<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>, f: impl FnOnce(T) -> T)
2891 where
2892 T: Copy,
2893 {
2894 let old = self.get();
2895 self.set(f(old), r);
2896 }
2897 }
2898
2899 impl<T> CmCell<T> {
2900 pub(crate) const fn new(value: T) -> CmCell<T> {
2901 CmCell(Cell::new(value))
2902 }
2903
2904 pub(crate) fn set<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
2905 if r.assert_speculative {
2906 {
::core::panicking::panic_fmt(format_args!("not allowed to mutate a `CmCell` during speculative resolution"));
}panic!("not allowed to mutate a `CmCell` during speculative resolution")
2907 }
2908 self.0.set(val);
2909 }
2910
2911 pub(crate) fn into_inner(self) -> T {
2912 self.0.into_inner()
2913 }
2914 }
2915
2916 #[derive(#[automatically_derived]
impl<T: ::core::default::Default> ::core::default::Default for CmRefCell<T> {
#[inline]
fn default() -> CmRefCell<T> {
CmRefCell(::core::default::Default::default())
}
}Default)]
2918 pub(crate) struct CmRefCell<T>(RefCell<T>);
2919
2920 impl<T> CmRefCell<T> {
2921 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2922 CmRefCell(RefCell::new(value))
2923 }
2924
2925 #[track_caller]
2926 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2929 self.0.borrow_mut()
2930 }
2931
2932 #[track_caller]
2933 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2934 if r.assert_speculative {
2935 {
::core::panicking::panic_fmt(format_args!("not allowed to mutably borrow a `CmRefCell` during speculative resolution"));
};panic!("not allowed to mutably borrow a `CmRefCell` during speculative resolution");
2936 }
2937 self.0.borrow_mut()
2938 }
2939
2940 #[track_caller]
2941 pub(crate) fn try_borrow_mut<'ra, 'tcx>(
2942 &self,
2943 r: &Resolver<'ra, 'tcx>,
2944 ) -> Result<RefMut<'_, T>, BorrowMutError> {
2945 if r.assert_speculative {
2946 {
::core::panicking::panic_fmt(format_args!("not allowed to mutably borrow a `CmRefCell` during speculative resolution"));
};panic!("not allowed to mutably borrow a `CmRefCell` during speculative resolution");
2947 }
2948 self.0.try_borrow_mut()
2949 }
2950
2951 #[track_caller]
2952 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2953 self.0.borrow()
2954 }
2955 }
2956
2957 impl<T: Default> CmRefCell<T> {
2958 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2959 if r.assert_speculative {
2960 {
::core::panicking::panic_fmt(format_args!("not allowed to mutate a CmRefCell during speculative resolution"));
};panic!("not allowed to mutate a CmRefCell during speculative resolution");
2961 }
2962 self.0.take()
2963 }
2964 }
2965}
2966
2967mod hygiene {
2968 use rustc_span::{ExpnId, SyntaxContext};
2969
2970 #[derive(#[automatically_derived]
impl ::core::clone::Clone for Macros20NormalizedSyntaxContext {
#[inline]
fn clone(&self) -> Macros20NormalizedSyntaxContext {
let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Macros20NormalizedSyntaxContext { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Macros20NormalizedSyntaxContext {
#[inline]
fn eq(&self, other: &Macros20NormalizedSyntaxContext) -> bool {
self.0 == other.0
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Macros20NormalizedSyntaxContext {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SyntaxContext>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Macros20NormalizedSyntaxContext {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Macros20NormalizedSyntaxContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Macros20NormalizedSyntaxContext", &&self.0)
}
}Debug)]
2973 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2974
2975 impl Macros20NormalizedSyntaxContext {
2976 #[inline]
2977 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2978 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2979 }
2980
2981 #[inline]
2982 pub(crate) fn new_adjusted(
2983 mut ctxt: SyntaxContext,
2984 expn_id: ExpnId,
2985 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2986 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2987 (Macros20NormalizedSyntaxContext(ctxt), def)
2988 }
2989
2990 #[inline]
2991 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2992 if true {
{
match (&ctxt, &ctxt.normalize_to_macros_2_0()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(ctxt, ctxt.normalize_to_macros_2_0());
2993 Macros20NormalizedSyntaxContext(ctxt)
2994 }
2995
2996 #[inline]
2998 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2999 let ret = f(&mut self.0);
3000 if true {
{
match (&self.0, &self.0.normalize_to_macros_2_0()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.0, self.0.normalize_to_macros_2_0());
3001 ret
3002 }
3003 }
3004
3005 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3006 type Target = SyntaxContext;
3007 fn deref(&self) -> &Self::Target {
3008 &self.0
3009 }
3010 }
3011}