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(rustc_attrs)]
19#![feature(trim_prefix_suffix)]
20#![recursion_limit = "256"]
21use std::cell::Ref;
24use std::collections::BTreeSet;
25use std::ops::ControlFlow;
26use std::sync::Arc;
27use std::{fmt, mem};
28
29use diagnostics::{ImportSuggestion, LabelSuggestion, StructCtor, Suggestion};
30use effective_visibilities::EffectiveVisibilitiesVisitor;
31use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
32use hygiene::Macros20NormalizedSyntaxContext;
33use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
34use late::{
35 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
36 UnnecessaryQualification,
37};
38use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
39use rustc_arena::{DroplessArena, TypedArena};
40use rustc_ast::node_id::NodeMap;
41use rustc_ast::{
42 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
43 GenericArg, GenericArgs, Generics, NodeId, Path, attr,
44};
45use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
46use rustc_data_structures::intern::Interned;
47use rustc_data_structures::steal::Steal;
48use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
49use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
50use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
51use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
52use rustc_feature::BUILTIN_ATTRIBUTES;
53use rustc_hir::attrs::StrippedCfgItem;
54use rustc_hir::def::Namespace::{self, *};
55use rustc_hir::def::{
56 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
57 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::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
75use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
76use smallvec::{SmallVec, smallvec};
77use tracing::{debug, instrument};
78
79type Res = def::Res<NodeId>;
80
81mod build_reduced_graph;
82mod check_unused;
83mod def_collector;
84mod diagnostics;
85mod effective_visibilities;
86mod errors;
87mod ident;
88mod imports;
89mod late;
90mod macros;
91pub mod rustdoc;
92
93pub use macros::registered_tools_ast;
94
95use crate::ref_mut::{CmCell, CmRefCell};
96
97#[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)]
98enum Determinacy {
99 Determined,
100 Undetermined,
101}
102
103impl Determinacy {
104 fn determined(determined: bool) -> Determinacy {
105 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
106 }
107}
108
109#[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)]
111enum Scope<'ra> {
112 DeriveHelpers(LocalExpnId),
114 DeriveHelpersCompat,
118 MacroRules(MacroRulesScopeRef<'ra>),
120 ModuleNonGlobs(Module<'ra>, Option<NodeId>),
124 ModuleGlobs(Module<'ra>, Option<NodeId>),
128 MacroUsePrelude,
130 BuiltinAttrs,
132 ExternPreludeItems,
134 ExternPreludeFlags,
136 ToolPrelude,
138 StdLibPrelude,
140 BuiltinTypes,
142}
143
144#[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)]
147enum ScopeSet<'ra> {
148 All(Namespace),
150 Module(Namespace, Module<'ra>),
152 ModuleAndExternPrelude(Namespace, Module<'ra>),
154 ExternPrelude,
156 Macro(MacroKind),
158}
159
160#[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)]
165struct ParentScope<'ra> {
166 module: Module<'ra>,
167 expansion: LocalExpnId,
168 macro_rules: MacroRulesScopeRef<'ra>,
169 derives: &'ra [ast::Path],
170}
171
172impl<'ra> ParentScope<'ra> {
173 fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
176 ParentScope {
177 module: module.to_module(),
178 expansion: LocalExpnId::ROOT,
179 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
180 derives: &[],
181 }
182 }
183}
184
185#[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_field5_finish(f,
"InvocationParent", "parent_def", &self.parent_def,
"impl_trait_context", &self.impl_trait_context, "in_attr",
&self.in_attr, "const_arg_context", &self.const_arg_context,
"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<ConstArgContext>;
let _: ::core::clone::AssertParamIsClone<NodeId>;
*self
}
}Clone)]
186struct InvocationParent {
187 parent_def: LocalDefId,
188 impl_trait_context: ImplTraitContext,
189 in_attr: bool,
190 const_arg_context: ConstArgContext,
191 owner: NodeId,
192}
193
194impl InvocationParent {
195 const ROOT: Self = Self {
196 parent_def: CRATE_DEF_ID,
197 impl_trait_context: ImplTraitContext::Existential,
198 in_attr: false,
199 const_arg_context: ConstArgContext::NonDirect,
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::marker::Copy for ConstArgContext { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstArgContext {
#[inline]
fn clone(&self) -> ConstArgContext { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstArgContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ConstArgContext::Direct => "Direct",
ConstArgContext::NonDirect => "NonDirect",
})
}
}Debug)]
212enum ConstArgContext {
213 Direct,
214 NonDirect,
216}
217
218#[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)]
233enum Used {
234 Scope,
235 Other,
236}
237
238#[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)]
239struct BindingError {
240 name: Ident,
241 origin: Vec<(Span, ast::Pat)>,
242 target: Vec<ast::Pat>,
243 could_be_path: bool,
244}
245
246#[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)]
247enum ResolutionError<'ra> {
248 GenericParamsFromOuterItem {
250 outer_res: Res,
251 has_generic_params: HasGenericParams,
252 def_kind: DefKind,
253 inner_item: Option<(Span, Span, ast::ItemKind)>,
255 current_self_ty: Option<String>,
256 },
257 NameAlreadyUsedInParameterList(Ident, Span),
260 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
262 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
264 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
266 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
268 VariableBoundWithDifferentMode(Ident, Span),
270 IdentifierBoundMoreThanOnceInParameterList(Ident),
272 IdentifierBoundMoreThanOnceInSamePattern(Ident),
274 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
276 FailedToResolve {
278 segment: Symbol,
279 label: String,
280 suggestion: Option<Suggestion>,
281 module: Option<ModuleOrUniformRoot<'ra>>,
282 message: String,
283 },
284 CannotCaptureDynamicEnvironmentInFnItem,
286 AttemptToUseNonConstantValueInConstant {
288 ident: Ident,
289 suggestion: &'static str,
290 current: &'static str,
291 type_span: Option<Span>,
292 },
293 BindingShadowsSomethingUnacceptable {
295 shadowing_binding: PatternSource,
296 name: Symbol,
297 participle: &'static str,
298 article: &'static str,
299 shadowed_binding: Res,
300 shadowed_binding_span: Span,
301 },
302 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
304 ParamInTyOfConstParam { name: Symbol },
308 ParamInNonTrivialAnonConst {
312 is_gca: bool,
313 name: Symbol,
314 param_kind: ParamKindInNonTrivialAnonConst,
315 },
316 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
320 ForwardDeclaredSelf(ForwardGenericParamBanReason),
322 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
324 TraitImplMismatch {
326 name: Ident,
327 kind: &'static str,
328 trait_path: String,
329 trait_item_span: Span,
330 code: ErrCode,
331 },
332 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
334 InvalidAsmSym,
336 LowercaseSelf,
338 BindingInNeverPattern,
340}
341
342#[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)]
343enum VisResolutionError {
344 Relative2018(Span, ast::Path),
345 AncestorOnly(Span),
346 FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),
347 ExpectedFound(Span, String, Res),
348 Indeterminate(Span),
349 ModuleOnly(Span),
350}
351
352#[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)]
355struct Segment {
356 ident: Ident,
357 id: Option<NodeId>,
358 has_generic_args: bool,
360 has_lifetime_args: bool,
362 args_span: Span,
363}
364
365impl Segment {
366 fn from_path(path: &Path) -> Vec<Segment> {
367 path.segments.iter().map(|s| s.into()).collect()
368 }
369
370 fn from_ident(ident: Ident) -> Segment {
371 Segment {
372 ident,
373 id: None,
374 has_generic_args: false,
375 has_lifetime_args: false,
376 args_span: DUMMY_SP,
377 }
378 }
379
380 fn names_to_string(segments: &[Segment]) -> String {
381 names_to_string(segments.iter().map(|seg| seg.ident.name))
382 }
383}
384
385impl<'a> From<&'a ast::PathSegment> for Segment {
386 fn from(seg: &'a ast::PathSegment) -> Segment {
387 let has_generic_args = seg.args.is_some();
388 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
389 match args {
390 GenericArgs::AngleBracketed(args) => {
391 let found_lifetimes = args
392 .args
393 .iter()
394 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
395 (args.span, found_lifetimes)
396 }
397 GenericArgs::Parenthesized(args) => (args.span, true),
398 GenericArgs::ParenthesizedElided(span) => (*span, true),
399 }
400 } else {
401 (DUMMY_SP, false)
402 };
403 Segment {
404 ident: seg.ident,
405 id: Some(seg.id),
406 has_generic_args,
407 has_lifetime_args,
408 args_span,
409 }
410 }
411}
412
413#[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)]
415enum LateDecl<'ra> {
416 Decl(Decl<'ra>),
418 RibDef(Res),
421}
422
423impl<'ra> LateDecl<'ra> {
424 fn res(self) -> Res {
425 match self {
426 LateDecl::Decl(binding) => binding.res(),
427 LateDecl::RibDef(res) => res,
428 }
429 }
430}
431
432#[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)]
433enum ModuleOrUniformRoot<'ra> {
434 Module(Module<'ra>),
436
437 ModuleAndExternPrelude(Module<'ra>),
441
442 ExternPrelude,
445
446 CurrentScope,
450
451 OpenModule(Symbol),
455}
456
457#[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_name: __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_name",
"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)]
458enum PathResult<'ra> {
459 Module(ModuleOrUniformRoot<'ra>),
460 NonModule(PartialRes),
461 Indeterminate,
462 Failed {
463 span: Span,
464 label: String,
465 suggestion: Option<Suggestion>,
466 is_error_from_last_segment: bool,
467 module: Option<ModuleOrUniformRoot<'ra>>,
481 segment_name: Symbol,
483 error_implied_by_parse_error: bool,
484 message: String,
485 note: Option<String>,
486 },
487}
488
489impl<'ra> PathResult<'ra> {
490 fn failed(
491 ident: Ident,
492 is_error_from_last_segment: bool,
493 finalize: bool,
494 error_implied_by_parse_error: bool,
495 module: Option<ModuleOrUniformRoot<'ra>>,
496 label_and_suggestion_and_note: impl FnOnce() -> (
497 String,
498 String,
499 Option<Suggestion>,
500 Option<String>,
501 ),
502 ) -> PathResult<'ra> {
503 let (message, label, suggestion, note) = if finalize {
504 label_and_suggestion_and_note()
505 } else {
506 (::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)
508 };
509 PathResult::Failed {
510 span: ident.span,
511 segment_name: ident.name,
512 label,
513 suggestion,
514 is_error_from_last_segment,
515 module,
516 error_implied_by_parse_error,
517 message,
518 note,
519 }
520 }
521}
522
523#[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)]
524enum ModuleKind {
525 Block,
538 Def(DefKind, DefId, NodeId, Option<Symbol>),
548}
549
550impl ModuleKind {
551 fn opt_def_id(&self) -> Option<DefId> {
552 match self {
553 ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
554 _ => None,
555 }
556 }
557
558 fn def_id(&self) -> DefId {
559 self.opt_def_id().expect("`Module::def_id` is called on a block module")
560 }
561
562 fn is_local(&self) -> bool {
563 match self {
564 ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
565 ModuleKind::Block => true,
566 }
567 }
568}
569
570#[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)]
581struct IdentKey {
582 name: Symbol,
583 ctxt: Macros20NormalizedSyntaxContext,
584}
585
586impl IdentKey {
587 #[inline]
588 fn new(ident: Ident) -> IdentKey {
589 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
590 }
591
592 #[inline]
593 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
594 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
595 (IdentKey { name: ident.name, ctxt }, def)
596 }
597
598 #[inline]
599 fn with_root_ctxt(name: Symbol) -> Self {
600 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
601 IdentKey { name, ctxt }
602 }
603
604 #[inline]
605 fn orig(self, orig_ident_span: Span) -> Ident {
606 Ident::new(self.name, orig_ident_span)
607 }
608}
609
610#[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)]
615struct BindingKey {
616 ident: IdentKey,
619 ns: Namespace,
620 disambiguator: u32,
626}
627
628impl BindingKey {
629 fn new(ident: IdentKey, ns: Namespace) -> Self {
630 BindingKey { ident, ns, disambiguator: 0 }
631 }
632
633 fn new_disambiguated(
634 ident: IdentKey,
635 ns: Namespace,
636 disambiguator: impl FnOnce() -> u32,
637 ) -> BindingKey {
638 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
639 BindingKey { ident, ns, disambiguator }
640 }
641}
642
643type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
644
645struct ModuleData<'ra> {
657 parent: Option<Module<'ra>>,
659 kind: ModuleKind,
661
662 lazy_resolutions: Resolutions<'ra>,
665 populate_on_access: CacheCell<bool>,
667 underscore_disambiguator: CmCell<u32>,
669
670 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
672
673 no_implicit_prelude: bool,
675
676 glob_importers: CmRefCell<Vec<Import<'ra>>>,
677 globs: CmRefCell<Vec<Import<'ra>>>,
678
679 traits: CmRefCell<
681 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
682 >,
683
684 span: Span,
686
687 expansion: ExpnId,
688
689 self_decl: Option<Decl<'ra>>,
692}
693
694#[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)]
697#[rustc_pass_by_value]
698struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
699
700#[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)]
702#[rustc_pass_by_value]
703struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
704
705#[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)]
707#[rustc_pass_by_value]
708struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
709
710impl std::hash::Hash for ModuleData<'_> {
715 fn hash<H>(&self, _: &mut H)
716 where
717 H: std::hash::Hasher,
718 {
719 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
720 }
721}
722
723impl<'ra> ModuleData<'ra> {
724 fn new(
725 parent: Option<Module<'ra>>,
726 kind: ModuleKind,
727 expansion: ExpnId,
728 span: Span,
729 no_implicit_prelude: bool,
730 vis: Visibility<DefId>,
731 arenas: &'ra ResolverArenas<'ra>,
732 ) -> Self {
733 let is_foreign = !kind.is_local();
734 let self_decl = match kind {
735 ModuleKind::Def(def_kind, def_id, ..) => {
736 let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
737 Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
738 }
739 ModuleKind::Block => None,
740 };
741 ModuleData {
742 parent,
743 kind,
744 lazy_resolutions: Default::default(),
745 populate_on_access: CacheCell::new(is_foreign),
746 underscore_disambiguator: CmCell::new(0),
747 unexpanded_invocations: Default::default(),
748 no_implicit_prelude,
749 glob_importers: CmRefCell::new(Vec::new()),
750 globs: CmRefCell::new(Vec::new()),
751 traits: CmRefCell::new(None),
752 span,
753 expansion,
754 self_decl,
755 }
756 }
757
758 fn name(&self) -> Option<Symbol> {
760 match self.kind {
761 ModuleKind::Block => None,
762 ModuleKind::Def(.., name) => name,
763 }
764 }
765
766 fn opt_def_id(&self) -> Option<DefId> {
767 self.kind.opt_def_id()
768 }
769
770 fn def_id(&self) -> DefId {
771 self.kind.def_id()
772 }
773
774 fn is_local(&self) -> bool {
775 self.kind.is_local()
776 }
777
778 fn has_unexpanded_invocations(&self) -> bool {
779 !self.unexpanded_invocations.borrow().is_empty()
780 }
781
782 fn res(&self) -> Option<Res> {
783 match self.kind {
784 ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
785 _ => None,
786 }
787 }
788
789 fn def_kind(&self) -> Option<DefKind> {
790 match self.kind {
791 ModuleKind::Def(def_kind, ..) => Some(def_kind),
792 ModuleKind::Block => None,
793 }
794 }
795}
796
797impl<'ra> Module<'ra> {
798 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
799 self,
800 resolver: &R,
801 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
802 ) {
803 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
804 let name_resolution = name_resolution.borrow();
805 if let Some(decl) = name_resolution.best_decl() {
806 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
807 }
808 }
809 }
810
811 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
812 self,
813 resolver: &mut R,
814 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
815 ) {
816 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
817 let name_resolution = name_resolution.borrow();
818 if let Some(decl) = name_resolution.best_decl() {
819 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
820 }
821 }
822 }
823
824 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
826 let mut traits = self.traits.borrow_mut(resolver.as_ref());
827 if traits.is_none() {
828 let mut collected_traits = Vec::new();
829 self.for_each_child(resolver, |r, ident, _, ns, binding| {
830 if ns != TypeNS {
831 return;
832 }
833 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
834 collected_traits.push((
835 ident.name,
836 binding,
837 r.as_ref().get_module(def_id),
838 binding.is_ambiguity_recursive(),
839 ));
840 }
841 });
842 *traits = Some(collected_traits.into_boxed_slice());
843 }
844 }
845
846 fn is_normal(self) -> bool {
848 self.def_kind() == Some(DefKind::Mod)
849 }
850
851 fn is_trait(self) -> bool {
852 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind() {
Some(DefKind::Trait) => true,
_ => false,
}matches!(self.def_kind(), Some(DefKind::Trait))
853 }
854
855 fn nearest_item_scope(self) -> Module<'ra> {
856 match self.def_kind() {
857 Some(DefKind::Enum | DefKind::Trait) => {
858 self.parent.expect("enum or trait module without a parent")
859 }
860 _ => self,
861 }
862 }
863
864 fn nearest_parent_mod(self) -> DefId {
867 match self.kind {
868 ModuleKind::Def(DefKind::Mod, def_id, _, _) => def_id,
869 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
870 }
871 }
872
873 fn nearest_parent_mod_node_id(self) -> NodeId {
876 match self.kind {
877 ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
878 _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
879 }
880 }
881
882 fn is_ancestor_of(self, mut other: Self) -> bool {
883 while self != other {
884 if let Some(parent) = other.parent {
885 other = parent;
886 } else {
887 return false;
888 }
889 }
890 true
891 }
892
893 #[track_caller]
894 fn expect_local(self) -> LocalModule<'ra> {
895 match self.kind {
896 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
897 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected extern module: {0:?}", self))span_bug!(self.span, "unexpected extern module: {self:?}")
898 }
899 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
900 }
901 }
902
903 #[track_caller]
904 fn expect_extern(self) -> ExternModule<'ra> {
905 match self.kind {
906 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
907 ModuleKind::Def(..) | ModuleKind::Block => {
908 ::rustc_middle::util::bug::span_bug_fmt(self.span,
format_args!("unexpected local module: {0:?}", self))span_bug!(self.span, "unexpected local module: {self:?}")
909 }
910 }
911 }
912}
913
914impl<'ra> LocalModule<'ra> {
915 fn new(
916 parent: Option<LocalModule<'ra>>,
917 kind: ModuleKind,
918 vis: Visibility<DefId>,
919 expn_id: ExpnId,
920 span: Span,
921 no_implicit_prelude: bool,
922 arenas: &'ra ResolverArenas<'ra>,
923 ) -> LocalModule<'ra> {
924 if !kind.is_local() {
::core::panicking::panic("assertion failed: kind.is_local()")
};assert!(kind.is_local());
925 let parent = parent.map(|m| m.to_module());
926 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
927 LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
928 }
929
930 fn to_module(self) -> Module<'ra> {
931 Module(self.0)
932 }
933}
934
935impl<'ra> ExternModule<'ra> {
936 fn new(
937 parent: Option<ExternModule<'ra>>,
938 kind: ModuleKind,
939 vis: Visibility<DefId>,
940 expn_id: ExpnId,
941 span: Span,
942 no_implicit_prelude: bool,
943 arenas: &'ra ResolverArenas<'ra>,
944 ) -> ExternModule<'ra> {
945 if !!kind.is_local() {
::core::panicking::panic("assertion failed: !kind.is_local()")
};assert!(!kind.is_local());
946 let parent = parent.map(|m| m.to_module());
947 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
948 ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
949 }
950
951 fn to_module(self) -> Module<'ra> {
952 Module(self.0)
953 }
954}
955
956impl<'ra> std::ops::Deref for Module<'ra> {
957 type Target = ModuleData<'ra>;
958
959 fn deref(&self) -> &Self::Target {
960 &self.0
961 }
962}
963
964impl<'ra> std::ops::Deref for LocalModule<'ra> {
965 type Target = ModuleData<'ra>;
966
967 fn deref(&self) -> &Self::Target {
968 &self.0
969 }
970}
971
972impl<'ra> std::ops::Deref for ExternModule<'ra> {
973 type Target = ModuleData<'ra>;
974
975 fn deref(&self) -> &Self::Target {
976 &self.0
977 }
978}
979
980impl<'ra> fmt::Debug for Module<'ra> {
981 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
982 match self.res() {
983 None => f.write_fmt(format_args!("block"))write!(f, "block"),
984 Some(res) => f.write_fmt(format_args!("{0:?}", res))write!(f, "{:?}", res),
985 }
986 }
987}
988
989impl<'ra> fmt::Debug for LocalModule<'ra> {
990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991 self.to_module().fmt(f)
992 }
993}
994
995#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for DeclData<'ra> {
#[inline]
fn clone(&self) -> DeclData<'ra> {
DeclData {
kind: ::core::clone::Clone::clone(&self.kind),
ambiguity: ::core::clone::Clone::clone(&self.ambiguity),
warn_ambiguity: ::core::clone::Clone::clone(&self.warn_ambiguity),
expansion: ::core::clone::Clone::clone(&self.expansion),
span: ::core::clone::Clone::clone(&self.span),
initial_vis: ::core::clone::Clone::clone(&self.initial_vis),
ambiguity_vis_max: ::core::clone::Clone::clone(&self.ambiguity_vis_max),
ambiguity_vis_min: ::core::clone::Clone::clone(&self.ambiguity_vis_min),
parent_module: ::core::clone::Clone::clone(&self.parent_module),
}
}
}Clone, #[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", "warn_ambiguity", "expansion", "span",
"initial_vis", "ambiguity_vis_max", "ambiguity_vis_min",
"parent_module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.ambiguity, &self.warn_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)]
997struct DeclData<'ra> {
998 kind: DeclKind<'ra>,
999 ambiguity: CmCell<Option<Decl<'ra>>>,
1000 warn_ambiguity: CmCell<bool>,
1003 expansion: LocalExpnId,
1004 span: Span,
1005 initial_vis: Visibility<DefId>,
1006 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
1009 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
1012 parent_module: Option<Module<'ra>>,
1013}
1014
1015type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
1018
1019impl std::hash::Hash for DeclData<'_> {
1024 fn hash<H>(&self, _: &mut H)
1025 where
1026 H: std::hash::Hasher,
1027 {
1028 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1029 }
1030}
1031
1032#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for DeclKind<'ra> {
#[inline]
fn clone(&self) -> DeclKind<'ra> {
let _: ::core::clone::AssertParamIsClone<Res>;
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Import<'ra>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for DeclKind<'ra> { }Copy, #[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)]
1034enum DeclKind<'ra> {
1035 Def(Res),
1038 Import { source_decl: Decl<'ra>, import: Import<'ra> },
1040}
1041
1042impl<'ra> DeclKind<'ra> {
1043 fn is_import(&self) -> bool {
1045 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
1046 }
1047}
1048
1049#[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)]
1050struct PrivacyError<'ra> {
1051 ident: Ident,
1052 decl: Decl<'ra>,
1053 dedup_span: Span,
1054 outermost_res: Option<(Res, Ident)>,
1055 parent_scope: ParentScope<'ra>,
1056 single_nested: bool,
1058 source: Option<ast::Expr>,
1059}
1060
1061#[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)]
1062struct UseError<'a> {
1063 err: Diag<'a>,
1064 candidates: Vec<ImportSuggestion>,
1066 node_id: NodeId,
1068 instead: bool,
1070 suggestion: Option<(Span, &'static str, String, Applicability)>,
1072 path: Vec<Segment>,
1075 is_call: bool,
1077}
1078
1079#[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)]
1080struct DelayedVisResolutionError<'ra> {
1081 vis: ast::Visibility,
1082 parent_scope: ParentScope<'ra>,
1083 error: VisResolutionError,
1084}
1085
1086#[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)]
1087enum AmbiguityKind {
1088 BuiltinAttr,
1089 DeriveHelper,
1090 MacroRulesVsModularized,
1091 GlobVsOuter,
1092 GlobVsGlob,
1093 GlobVsExpanded,
1094 MoreExpandedVsOuter,
1095}
1096
1097impl AmbiguityKind {
1098 fn descr(self) -> &'static str {
1099 match self {
1100 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1101 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1102 AmbiguityKind::MacroRulesVsModularized => {
1103 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1104 }
1105 AmbiguityKind::GlobVsOuter => {
1106 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1107 }
1108 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1109 AmbiguityKind::GlobVsExpanded => {
1110 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1111 }
1112 AmbiguityKind::MoreExpandedVsOuter => {
1113 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1114 }
1115 }
1116 }
1117}
1118
1119#[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)]
1120enum AmbiguityWarning {
1121 GlobImport,
1122 PanicImport,
1123}
1124
1125struct AmbiguityError<'ra> {
1126 kind: AmbiguityKind,
1127 ambig_vis: Option<(Visibility, Visibility)>,
1128 ident: Ident,
1129 b1: Decl<'ra>,
1130 b2: Decl<'ra>,
1131 scope1: Scope<'ra>,
1132 scope2: Scope<'ra>,
1133 warning: Option<AmbiguityWarning>,
1134}
1135
1136impl<'ra> DeclData<'ra> {
1137 fn vis(&self) -> Visibility<DefId> {
1138 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1140 }
1141
1142 fn min_vis(&self) -> Visibility<DefId> {
1143 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1145 }
1146
1147 fn res(&self) -> Res {
1148 match self.kind {
1149 DeclKind::Def(res) => res,
1150 DeclKind::Import { source_decl, .. } => source_decl.res(),
1151 }
1152 }
1153
1154 fn import_source(&self) -> Decl<'ra> {
1155 match self.kind {
1156 DeclKind::Import { source_decl, .. } => source_decl,
1157 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1158 }
1159 }
1160
1161 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1162 match self.ambiguity.get() {
1163 Some(ambig_binding) => Some((self, ambig_binding)),
1164 None => match self.kind {
1165 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1166 _ => None,
1167 },
1168 }
1169 }
1170
1171 fn is_ambiguity_recursive(&self) -> bool {
1172 self.ambiguity.get().is_some()
1173 || match self.kind {
1174 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1175 _ => false,
1176 }
1177 }
1178
1179 fn warn_ambiguity_recursive(&self) -> bool {
1180 self.warn_ambiguity.get()
1181 || match self.kind {
1182 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
1183 _ => false,
1184 }
1185 }
1186
1187 fn is_possibly_imported_variant(&self) -> bool {
1188 match self.kind {
1189 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1190 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1191 true
1192 }
1193 DeclKind::Def(..) => false,
1194 }
1195 }
1196
1197 fn is_extern_crate(&self) -> bool {
1198 match self.kind {
1199 DeclKind::Import { import, .. } => {
1200 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1201 }
1202 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1203 _ => false,
1204 }
1205 }
1206
1207 fn is_import(&self) -> bool {
1208 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1209 }
1210
1211 fn is_import_user_facing(&self) -> bool {
1214 #[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, .. }
1215 if !matches!(import.kind, ImportKind::MacroExport))
1216 }
1217
1218 fn is_glob_import(&self) -> bool {
1219 match self.kind {
1220 DeclKind::Import { import, .. } => import.is_glob(),
1221 _ => false,
1222 }
1223 }
1224
1225 fn is_assoc_item(&self) -> bool {
1226 #[allow(non_exhaustive_omitted_patterns)] match self.res() {
Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy,
_) => true,
_ => false,
}matches!(
1227 self.res(),
1228 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
1229 )
1230 }
1231
1232 fn macro_kinds(&self) -> Option<MacroKinds> {
1233 self.res().macro_kinds()
1234 }
1235
1236 fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {
1237 let mut reexport_chain = SmallVec::new();
1238 let mut next_binding = self;
1239 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1240 reexport_chain.push(import.simplify());
1241 next_binding = source_decl;
1242 }
1243 reexport_chain
1244 }
1245
1246 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1253 let self_parent_expansion = self.expansion;
1257 let other_parent_expansion = decl.expansion;
1258 let certainly_before_other_or_simultaneously =
1259 other_parent_expansion.is_descendant_of(self_parent_expansion);
1260 let certainly_before_invoc_or_simultaneously =
1261 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1262 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1263 }
1264
1265 fn determined(&self) -> bool {
1271 match &self.kind {
1272 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1273 !import.parent_scope.module.has_unexpanded_invocations() && source_decl.determined()
1274 }
1275 _ => true,
1276 }
1277 }
1278}
1279
1280#[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)]
1281struct ExternPreludeEntry<'ra> {
1282 item_decl: Option<(Decl<'ra>, Span, bool)>,
1286 flag_decl: Option<
1288 CacheCell<(
1289 PendingDecl<'ra>,
1290 bool,
1291 bool,
1292 )>,
1293 >,
1294}
1295
1296impl ExternPreludeEntry<'_> {
1297 fn introduced_by_item(&self) -> bool {
1298 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1299 }
1300
1301 fn flag() -> Self {
1302 ExternPreludeEntry {
1303 item_decl: None,
1304 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1305 }
1306 }
1307
1308 fn open_flag() -> Self {
1309 ExternPreludeEntry {
1310 item_decl: None,
1311 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
1312 }
1313 }
1314
1315 fn span(&self) -> Span {
1316 match self.item_decl {
1317 Some((_, span, _)) => span,
1318 None => DUMMY_SP,
1319 }
1320 }
1321}
1322
1323struct DeriveData {
1324 resolutions: Vec<DeriveResolution>,
1325 helper_attrs: Vec<(usize, IdentKey, Span)>,
1326 has_derive_copy: bool,
1327}
1328
1329pub struct ResolverOutputs<'tcx> {
1330 pub global_ctxt: ResolverGlobalCtxt,
1331 pub ast_lowering: ResolverAstLowering<'tcx>,
1332}
1333
1334#[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)]
1335struct DelegationFnSig {
1336 pub has_self: bool,
1337}
1338
1339pub struct Resolver<'ra, 'tcx> {
1343 tcx: TyCtxt<'tcx>,
1344
1345 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1347
1348 graph_root: LocalModule<'ra>,
1349
1350 assert_speculative: bool,
1352
1353 prelude: Option<Module<'ra>> = None,
1354 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1355
1356 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1358 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1359
1360 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1363
1364 determined_imports: Vec<Import<'ra>> = Vec::new(),
1366
1367 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1369
1370 pat_span_map: NodeMap<Span> = Default::default(),
1373
1374 partial_res_map: NodeMap<PartialRes> = Default::default(),
1376 import_res_map: NodeMap<PerNS<Option<Res>>> = Default::default(),
1378 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1380 label_res_map: NodeMap<NodeId> = Default::default(),
1382 lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
1384 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>> = Default::default(),
1386
1387 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1389 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1390 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1391 trait_map: NodeMap<&'tcx [TraitCandidate<'tcx>]> = Default::default(),
1392
1393 block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1408 empty_module: LocalModule<'ra>,
1412 local_modules: Vec<LocalModule<'ra>>,
1414 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1416 extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,
1418
1419 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1421 glob_error: Option<ErrorGuaranteed> = None,
1422 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1423 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1424 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1425
1426 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1428 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1430 issue_145575_hack_applied: bool = false,
1431 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1433 delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),
1435 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1437
1438 arenas: &'ra ResolverArenas<'ra>,
1439 dummy_decl: Decl<'ra>,
1440 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1441 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1442 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1443 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1444 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1445 registered_tools: &'tcx RegisteredTools,
1446 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1447 local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),
1449 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
1451 dummy_ext_bang: &'ra Arc<SyntaxExtension>,
1452 dummy_ext_derive: &'ra Arc<SyntaxExtension>,
1453 non_macro_attr: &'ra Arc<SyntaxExtension>,
1454 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1455 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1456 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1457 unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,
1459 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1460 single_segment_macro_resolutions:
1462 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1463 multi_segment_macro_resolutions:
1464 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1465 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1466 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1470 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1473 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1476 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1478 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1480 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1483
1484 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1486
1487 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1488
1489 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1490
1491 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1495
1496 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1499
1500 lint_buffer: LintBuffer,
1501
1502 next_node_id: NodeId = CRATE_NODE_ID,
1503
1504 owners: NodeMap<PerOwnerResolverData>,
1506
1507 current_owner: PerOwnerResolverData,
1509
1510 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1511
1512 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1514 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1518
1519 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1521 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1523 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1524 delegation_infos: LocalDefIdMap<DelegationInfo> = Default::default(),
1525
1526 main_def: Option<MainDefinition> = None,
1527 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1528 proc_macros: Vec<LocalDefId> = Vec::new(),
1531 confused_type_with_std_module: FxIndexMap<Span, Span>,
1532 lifetime_elision_allowed: FxHashSet<NodeId> = default::fx_hash_set(),
1534
1535 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1537
1538 effective_visibilities: EffectiveVisibilities,
1539 macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
1540
1541 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1542 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1543 all_macro_rules: UnordSet<Symbol> = Default::default(),
1544
1545 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1547 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1550 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1553
1554 current_crate_outer_attr_insert_span: Span,
1557
1558 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1559
1560 all_crate_macros_already_registered: bool = false,
1563
1564 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1568}
1569
1570#[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)]
1573pub struct ResolverArenas<'ra> {
1574 modules: TypedArena<ModuleData<'ra>>,
1575 imports: TypedArena<ImportData<'ra>>,
1576 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1577 ast_paths: TypedArena<ast::Path>,
1578 macros: TypedArena<Arc<SyntaxExtension>>,
1579 dropless: DroplessArena,
1580}
1581
1582impl<'ra> ResolverArenas<'ra> {
1583 fn new_def_decl(
1584 &'ra self,
1585 res: Res,
1586 vis: Visibility<DefId>,
1587 span: Span,
1588 expansion: LocalExpnId,
1589 parent_module: Option<Module<'ra>>,
1590 ) -> Decl<'ra> {
1591 self.alloc_decl(DeclData {
1592 kind: DeclKind::Def(res),
1593 ambiguity: CmCell::new(None),
1594 warn_ambiguity: CmCell::new(false),
1595 initial_vis: vis,
1596 ambiguity_vis_max: CmCell::new(None),
1597 ambiguity_vis_min: CmCell::new(None),
1598 span,
1599 expansion,
1600 parent_module,
1601 })
1602 }
1603
1604 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1605 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1606 }
1607
1608 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1609 Interned::new_unchecked(self.dropless.alloc(data))
1610 }
1611 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1612 Interned::new_unchecked(self.imports.alloc(import))
1613 }
1614 fn alloc_name_resolution(
1615 &'ra self,
1616 orig_ident_span: Span,
1617 ) -> &'ra CmRefCell<NameResolution<'ra>> {
1618 self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))
1619 }
1620 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1621 self.dropless.alloc(CacheCell::new(scope))
1622 }
1623 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1624 self.dropless.alloc(decl)
1625 }
1626 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1627 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1628 }
1629 fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
1630 self.macros.alloc(Arc::new(ext))
1631 }
1632 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1633 self.dropless.alloc_from_iter(spans)
1634 }
1635}
1636
1637impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1638 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1639 self
1640 }
1641}
1642
1643impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1644 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1645 self
1646 }
1647}
1648
1649impl<'tcx> Resolver<'_, 'tcx> {
1650 fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
1654 self.owners[&owner].def_id
1655 }
1656
1657 fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
1661 self.owners[&owner].node_id_to_def_id[&id]
1662 }
1663
1664 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1666 self.current_owner.node_id_to_def_id.get(&node).copied()
1667 }
1668
1669 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1671 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:?}`"))
1672 }
1673
1674 fn create_def(
1676 &mut self,
1677 parent: LocalDefId,
1678 node_id: ast::NodeId,
1679 name: Option<Symbol>,
1680 def_kind: DefKind,
1681 expn_id: ExpnId,
1682 span: Span,
1683 is_owner: bool,
1684 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1685 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!(
1686 !self.current_owner.node_id_to_def_id.contains_key(&node_id),
1687 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1688 node_id,
1689 name,
1690 def_kind,
1691 self.tcx
1692 .definitions_untracked()
1693 .def_key(self.current_owner.node_id_to_def_id[&node_id]),
1694 );
1695
1696 let disambiguator = self.disambiguators.get_or_create(parent);
1697
1698 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1700 let def_id = feed.def_id();
1701
1702 if expn_id != ExpnId::root() {
1704 self.expn_that_defined.insert(def_id, expn_id);
1705 }
1706
1707 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);
1709 let _id = self.tcx.untracked().source_span.push(span);
1710 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);
1711
1712 if node_id != ast::DUMMY_NODE_ID && !is_owner {
1716 {
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:1716",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1716u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
def_id, node_id) as &dyn Value))])
});
} else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1717 self.current_owner.node_id_to_def_id.insert(node_id, def_id);
1718 }
1719
1720 feed
1721 }
1722
1723 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1724 if let Some(def_id) = def_id.as_local() {
1725 self.item_generics_num_lifetimes[&def_id]
1726 } else {
1727 self.tcx.generics_of(def_id).own_counts().lifetimes
1728 }
1729 }
1730
1731 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1732 if let Some(def_id) = def_id.as_local() {
1733 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1734 } else {
1735 let required = self
1736 .tcx
1737 .generics_of(def_id)
1738 .own_params
1739 .iter()
1740 .filter_map(|param| match param.kind {
1741 ty::GenericParamDefKind::Lifetime => Some("'_"),
1742 ty::GenericParamDefKind::Type { has_default, .. }
1743 | ty::GenericParamDefKind::Const { has_default } => {
1744 if has_default {
1745 None
1746 } else {
1747 Some("_")
1748 }
1749 }
1750 })
1751 .collect::<Vec<_>>();
1752
1753 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1754 }
1755 }
1756
1757 pub fn tcx(&self) -> TyCtxt<'tcx> {
1758 self.tcx
1759 }
1760
1761 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1768 self.owners
1769 .items()
1770 .flat_map(|(_, data)| {
1771 data.node_id_to_def_id
1772 .items()
1773 .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
1774 })
1775 .filter(|(_, v)| **v == def_id)
1776 .map(|(k, _)| *k)
1777 .get_only()
1778 .unwrap()
1779 }
1780}
1781
1782impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1783 pub fn new(
1784 tcx: TyCtxt<'tcx>,
1785 attrs: &[ast::Attribute],
1786 crate_span: Span,
1787 current_crate_outer_attr_insert_span: Span,
1788 arenas: &'ra ResolverArenas<'ra>,
1789 ) -> Resolver<'ra, 'tcx> {
1790 let root_def_id = CRATE_DEF_ID.to_def_id();
1791 let graph_root = LocalModule::new(
1792 None,
1793 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1794 Visibility::Public,
1795 ExpnId::root(),
1796 crate_span,
1797 attr::contains_name(attrs, sym::no_implicit_prelude),
1798 arenas,
1799 );
1800 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];
1801 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1802 let empty_module = LocalModule::new(
1803 None,
1804 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1805 Visibility::Public,
1806 ExpnId::root(),
1807 DUMMY_SP,
1808 true,
1809 arenas,
1810 );
1811
1812 let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
1813 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1814
1815 crate_feed.def_kind(DefKind::Mod);
1816 let mut owners = NodeMap::default();
1817 owners.insert(CRATE_NODE_ID, owner_data);
1818
1819 let mut invocation_parents = FxHashMap::default();
1820 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1821
1822 let extern_prelude = build_extern_prelude(tcx, attrs);
1823 let registered_tools = tcx.registered_tools(());
1824 let edition = tcx.sess.edition();
1825
1826 let mut resolver = Resolver {
1827 tcx,
1828
1829 graph_root,
1832 assert_speculative: false, extern_prelude,
1834
1835 empty_module,
1836 local_modules,
1837 local_module_map,
1838 extern_module_map: Default::default(),
1839
1840 glob_map: Default::default(),
1841 maybe_unused_trait_imports: Default::default(),
1842
1843 arenas,
1844 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1845 builtin_type_decls: PrimTy::ALL
1846 .iter()
1847 .map(|prim_ty| {
1848 let res = Res::PrimTy(*prim_ty);
1849 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1850 (prim_ty.name(), decl)
1851 })
1852 .collect(),
1853 builtin_attr_decls: BUILTIN_ATTRIBUTES
1854 .iter()
1855 .map(|builtin_attr| {
1856 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1857 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1858 (builtin_attr.name, decl)
1859 })
1860 .collect(),
1861 registered_tool_decls: registered_tools
1862 .iter()
1863 .map(|&ident| {
1864 let res = Res::ToolMod;
1865 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1866 (IdentKey::new(ident), decl)
1867 })
1868 .collect(),
1869 registered_tools,
1870 macro_use_prelude: Default::default(),
1871 extern_macro_map: Default::default(),
1872 dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
1873 dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
1874 non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
1875 unused_macros: Default::default(),
1876 unused_macro_rules: Default::default(),
1877 single_segment_macro_resolutions: Default::default(),
1878 multi_segment_macro_resolutions: Default::default(),
1879 lint_buffer: LintBuffer::default(),
1880 owners,
1881 current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
1882 invocation_parents,
1883 trait_impls: Default::default(),
1884 confused_type_with_std_module: Default::default(),
1885 stripped_cfg_items: Default::default(),
1886 effective_visibilities: Default::default(),
1887 macro_reachable_adts: Default::default(),
1888 doc_link_resolutions: Default::default(),
1889 doc_link_traits_in_scope: Default::default(),
1890 current_crate_outer_attr_insert_span,
1891 disambiguators: Default::default(),
1892 ..
1893 };
1894
1895 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1896 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1897 resolver.feed_visibility(crate_feed, Visibility::Public);
1898
1899 resolver
1900 }
1901
1902 fn new_local_module(
1903 &mut self,
1904 parent: Option<LocalModule<'ra>>,
1905 kind: ModuleKind,
1906 expn_id: ExpnId,
1907 span: Span,
1908 no_implicit_prelude: bool,
1909 ) -> LocalModule<'ra> {
1910 let vis =
1911 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1912 let module =
1913 LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
1914 self.local_modules.push(module);
1915 if let Some(def_id) = module.opt_def_id() {
1916 self.local_module_map.insert(def_id.expect_local(), module);
1917 }
1918 module
1919 }
1920
1921 fn new_extern_module(
1922 &self,
1923 parent: Option<ExternModule<'ra>>,
1924 kind: ModuleKind,
1925 expn_id: ExpnId,
1926 span: Span,
1927 no_implicit_prelude: bool,
1928 ) -> ExternModule<'ra> {
1929 let def_id = kind.def_id();
1930 let module = ExternModule::new(
1931 parent,
1932 kind,
1933 self.tcx.visibility(def_id),
1934 expn_id,
1935 span,
1936 no_implicit_prelude,
1937 self.arenas,
1938 );
1939 self.extern_module_map.borrow_mut().insert(def_id, module);
1940 module
1941 }
1942
1943 fn next_node_id(&mut self) -> NodeId {
1944 let start = self.next_node_id;
1945 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1946 self.next_node_id = ast::NodeId::from_u32(next);
1947 start
1948 }
1949
1950 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1951 let start = self.next_node_id;
1952 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1953 self.next_node_id = ast::NodeId::from_usize(end);
1954 start..self.next_node_id
1955 }
1956
1957 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1958 &mut self.lint_buffer
1959 }
1960
1961 pub fn arenas() -> ResolverArenas<'ra> {
1962 Default::default()
1963 }
1964
1965 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1966 feed.visibility(vis.to_def_id());
1967 self.visibilities_for_hashing.push((feed.def_id(), vis));
1968 }
1969
1970 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1971 let proc_macros = self.proc_macros;
1972 let expn_that_defined = self.expn_that_defined;
1973 let extern_crate_map = self.extern_crate_map;
1974 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1975 let glob_map = self.glob_map;
1976 let main_def = self.main_def;
1977 let confused_type_with_std_module = self.confused_type_with_std_module;
1978 let effective_visibilities = self.effective_visibilities;
1979
1980 let stripped_cfg_items = self
1981 .stripped_cfg_items
1982 .into_iter()
1983 .filter_map(|item| {
1984 let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
1985 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1986 })
1987 .collect();
1988 let disambiguators = self
1989 .disambiguators
1990 .into_items()
1991 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
1992 .collect();
1993
1994 let global_ctxt = ResolverGlobalCtxt {
1995 expn_that_defined,
1996 visibilities_for_hashing: self.visibilities_for_hashing,
1997 effective_visibilities,
1998 macro_reachable_adts: self.macro_reachable_adts,
1999 extern_crate_map,
2000 module_children: self.module_children,
2001 ambig_module_children: self.ambig_module_children,
2002 glob_map,
2003 maybe_unused_trait_imports,
2004 main_def,
2005 trait_impls: self.trait_impls,
2006 proc_macros,
2007 confused_type_with_std_module,
2008 doc_link_resolutions: self.doc_link_resolutions,
2009 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
2010 all_macro_rules: self.all_macro_rules,
2011 stripped_cfg_items,
2012 };
2013 let ast_lowering = ty::ResolverAstLowering {
2014 partial_res_map: self.partial_res_map,
2015 import_res_map: self.import_res_map,
2016 label_res_map: self.label_res_map,
2017 lifetimes_res_map: self.lifetimes_res_map,
2018 extra_lifetime_params_map: self.extra_lifetime_params_map,
2019 next_node_id: self.next_node_id,
2020 owners: self.owners,
2021 trait_map: self.trait_map,
2022 lifetime_elision_allowed: self.lifetime_elision_allowed,
2023 lint_buffer: Steal::new(self.lint_buffer),
2024 delegation_infos: self.delegation_infos,
2025 disambiguators,
2026 };
2027 ResolverOutputs { global_ctxt, ast_lowering }
2028 }
2029
2030 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
2031 CStore::from_tcx(self.tcx)
2032 }
2033
2034 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
2035 CStore::from_tcx_mut(self.tcx)
2036 }
2037
2038 fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
2039 match macro_kind {
2040 MacroKind::Bang => self.dummy_ext_bang,
2041 MacroKind::Derive => self.dummy_ext_derive,
2042 MacroKind::Attr => self.non_macro_attr,
2043 }
2044 }
2045
2046 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
2051 CmResolver::new(self, !self.assert_speculative)
2052 }
2053
2054 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2056 f(self, TypeNS);
2057 f(self, ValueNS);
2058 f(self, MacroNS);
2059 }
2060
2061 fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
2062 mut self: CmResolver<'r, 'ra, 'tcx>,
2063 mut f: F,
2064 ) {
2065 f(self.reborrow(), TypeNS);
2066 f(self.reborrow(), ValueNS);
2067 f(self, MacroNS);
2068 }
2069
2070 fn is_builtin_macro(&self, res: Res) -> bool {
2071 self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
2072 }
2073
2074 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2075 self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
2076 }
2077
2078 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2079 loop {
2080 match ctxt.outer_expn_data().macro_def_id {
2081 Some(def_id) => return def_id,
2082 None => ctxt.remove_mark(),
2083 };
2084 }
2085 }
2086
2087 pub fn resolve_crate(&mut self, krate: &Crate) {
2089 self.tcx.sess.time("resolve_crate", || {
2090 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2091 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2092 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2093 });
2094 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2095 self.tcx
2096 .sess
2097 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2098 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2099 self.tcx.sess.time("resolve_main", || self.resolve_main());
2100 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
2101 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
2102 self.tcx
2103 .sess
2104 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2105 });
2106
2107 self.tcx.untracked().cstore.freeze();
2109 }
2110
2111 fn traits_in_scope(
2112 &mut self,
2113 current_trait: Option<Module<'ra>>,
2114 parent_scope: &ParentScope<'ra>,
2115 sp: Span,
2116 assoc_item: Option<(Symbol, Namespace)>,
2117 ) -> &'tcx [TraitCandidate<'tcx>] {
2118 let mut found_traits = Vec::new();
2119
2120 if let Some(module) = current_trait {
2121 if self.trait_may_have_item(Some(module), assoc_item) {
2122 let def_id = module.def_id();
2123 found_traits.push(TraitCandidate {
2124 def_id,
2125 import_ids: &[],
2126 lint_ambiguous: false,
2127 });
2128 }
2129 }
2130
2131 let scope_set = ScopeSet::All(TypeNS);
2132 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2133 self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2134 match scope {
2135 Scope::ModuleNonGlobs(module, _) => {
2136 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2137 }
2138 Scope::ModuleGlobs(..) => {
2139 }
2141 Scope::StdLibPrelude => {
2142 if let Some(module) = this.prelude {
2143 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2144 }
2145 }
2146 Scope::ExternPreludeItems
2147 | Scope::ExternPreludeFlags
2148 | Scope::ToolPrelude
2149 | Scope::BuiltinTypes => {}
2150 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2151 }
2152 ControlFlow::<()>::Continue(())
2153 });
2154
2155 self.tcx.hir_arena.alloc_slice(&found_traits)
2156 }
2157
2158 fn traits_in_module(
2159 &mut self,
2160 module: Module<'ra>,
2161 assoc_item: Option<(Symbol, Namespace)>,
2162 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2163 ) {
2164 module.ensure_traits(self);
2165 let traits = module.traits.borrow();
2166 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2167 traits.as_ref().unwrap().iter()
2168 {
2169 if self.trait_may_have_item(trait_module, assoc_item) {
2170 let def_id = trait_binding.res().def_id();
2171 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2172 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2173 }
2174 }
2175 }
2176
2177 fn trait_may_have_item(
2183 &self,
2184 trait_module: Option<Module<'ra>>,
2185 assoc_item: Option<(Symbol, Namespace)>,
2186 ) -> bool {
2187 match (trait_module, assoc_item) {
2188 (Some(trait_module), Some((name, ns))) => self
2189 .resolutions(trait_module)
2190 .borrow()
2191 .iter()
2192 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2193 _ => true,
2194 }
2195 }
2196
2197 fn find_transitive_imports(
2198 &mut self,
2199 mut kind: &DeclKind<'_>,
2200 trait_name: Symbol,
2201 ) -> &'tcx [LocalDefId] {
2202 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2203 while let DeclKind::Import { import, source_decl, .. } = kind {
2204 if let Some(def_id) = import.def_id() {
2205 self.maybe_unused_trait_imports.insert(def_id);
2206 import_ids.push(def_id);
2207 }
2208 self.add_to_glob_map(*import, trait_name);
2209 kind = &source_decl.kind;
2210 }
2211
2212 self.tcx.hir_arena.alloc_slice(&import_ids)
2213 }
2214
2215 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2216 if module.populate_on_access.get() {
2217 module.populate_on_access.set(false);
2218 self.build_reduced_graph_external(module.expect_extern());
2219 }
2220 &module.0.0.lazy_resolutions
2221 }
2222
2223 fn resolution(
2224 &self,
2225 module: Module<'ra>,
2226 key: BindingKey,
2227 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2228 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2229 }
2230
2231 fn resolution_or_default(
2232 &self,
2233 module: Module<'ra>,
2234 key: BindingKey,
2235 orig_ident_span: Span,
2236 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2237 self.resolutions(module)
2238 .borrow_mut_unchecked()
2239 .entry(key)
2240 .or_insert_with(|| self.arenas.alloc_name_resolution(orig_ident_span))
2241 }
2242
2243 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2245 for ambiguity_error in &self.ambiguity_errors {
2246 if ambiguity_error.kind == ambi.kind
2248 && ambiguity_error.ident == ambi.ident
2249 && ambiguity_error.ident.span == ambi.ident.span
2250 && ambiguity_error.b1.span == ambi.b1.span
2251 && ambiguity_error.b2.span == ambi.b2.span
2252 {
2253 return true;
2254 }
2255 }
2256 false
2257 }
2258
2259 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2260 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2261 }
2262
2263 fn record_use_inner(
2264 &mut self,
2265 ident: Ident,
2266 used_decl: Decl<'ra>,
2267 used: Used,
2268 warn_ambiguity: bool,
2269 ) {
2270 if let Some(b2) = used_decl.ambiguity.get() {
2271 let ambiguity_error = AmbiguityError {
2272 kind: AmbiguityKind::GlobVsGlob,
2273 ambig_vis: None,
2274 ident,
2275 b1: used_decl,
2276 b2,
2277 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2278 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2279 warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
2280 };
2281 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2282 self.ambiguity_errors.push(ambiguity_error);
2284 }
2285 }
2286 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2287 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2288 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2291 let empty_module = self.empty_module;
2292 let arenas = self.arenas;
2293 self.cm()
2294 .maybe_resolve_ident_in_module(
2295 ModuleOrUniformRoot::Module(prelude),
2296 ident,
2297 MacroNS,
2298 &ParentScope::module(empty_module, arenas),
2299 None,
2300 )
2301 .is_ok()
2302 });
2303 if !found_in_stdlib_prelude {
2304 self.lint_buffer().buffer_lint(
2305 PRIVATE_MACRO_USE,
2306 import.root_id,
2307 ident.span,
2308 errors::MacroIsPrivate { ident },
2309 );
2310 }
2311 }
2312 if used == Used::Scope
2315 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2316 && let Some((item_decl, _, false)) = entry.item_decl
2317 && item_decl == used_decl
2318 {
2319 return;
2320 }
2321 let old_used = self.import_use_map.entry(import).or_insert(used);
2322 if *old_used < used {
2323 *old_used = used;
2324 }
2325 if let Some(id) = import.id() {
2326 self.used_imports.insert(id);
2327 }
2328 self.add_to_glob_map(import, ident.name);
2329 self.record_use_inner(
2330 ident,
2331 source_decl,
2332 Used::Other,
2333 warn_ambiguity || source_decl.warn_ambiguity.get(),
2334 );
2335 }
2336 }
2337
2338 #[inline]
2339 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2340 if let ImportKind::Glob { def_id, .. } = import.kind {
2341 self.glob_map.entry(def_id).or_default().insert(name);
2342 }
2343 }
2344
2345 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2346 {
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:2346",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2346u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?})",
ident) as &dyn Value))])
});
} else { ; }
};debug!("resolve_crate_root({:?})", ident);
2347 let mut ctxt = ident.span.ctxt();
2348 let mark = if ident.name == kw::DollarCrate {
2349 ctxt = ctxt.normalize_to_macro_rules();
2356 {
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:2356",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2356u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
2357 "resolve_crate_root: marks={:?}",
2358 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2359 );
2360 let mut iter = ctxt.marks().into_iter().rev().peekable();
2361 let mut result = None;
2362 while let Some(&(mark, transparency)) = iter.peek() {
2364 if transparency == Transparency::Opaque {
2365 result = Some(mark);
2366 iter.next();
2367 } else {
2368 break;
2369 }
2370 }
2371 {
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:2371",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2371u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as &dyn Value))])
});
} else { ; }
};debug!(
2372 "resolve_crate_root: found opaque mark {:?} {:?}",
2373 result,
2374 result.map(|r| r.expn_data())
2375 );
2376 for (mark, transparency) in iter {
2378 if transparency == Transparency::SemiOpaque {
2379 result = Some(mark);
2380 } else {
2381 break;
2382 }
2383 }
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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
2385 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2386 result,
2387 result.map(|r| r.expn_data())
2388 );
2389 result
2390 } else {
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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
as &dyn Value))])
});
} else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2392 ctxt = ctxt.normalize_to_macros_2_0();
2393 ctxt.adjust(ExpnId::root())
2394 };
2395 let module = match mark {
2396 Some(def) => self.expn_def_scope(def),
2397 None => {
2398 {
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:2398",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2398u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
ident, ident.span) as &dyn Value))])
});
} else { ; }
};debug!(
2399 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2400 ident, ident.span
2401 );
2402 return self.graph_root.to_module();
2403 }
2404 };
2405 let module = self.expect_module(
2406 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2407 );
2408 {
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:2408",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2408u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
2409 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2410 ident,
2411 module,
2412 module.name(),
2413 ident.span
2414 );
2415 module
2416 }
2417
2418 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2419 let mut module = self.expect_module(module.nearest_parent_mod());
2420 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2421 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2422 module = self.expect_module(parent.nearest_parent_mod());
2423 }
2424 module
2425 }
2426
2427 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2428 {
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:2428",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2428u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(recording res) recording {0:?} for {1}",
resolution, node_id) as &dyn Value))])
});
} else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2429 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2430 {
::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)");
2431 }
2432 }
2433
2434 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2435 {
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:2435",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2435u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
node, span) as &dyn Value))])
});
} else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2436 self.pat_span_map.insert(node, span);
2437 }
2438
2439 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2440 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2441 }
2442
2443 fn disambiguate_macro_rules_vs_modularized(
2444 &self,
2445 macro_rules: Decl<'ra>,
2446 modularized: Decl<'ra>,
2447 ) -> bool {
2448 let macro_rules = macro_rules.parent_module.unwrap();
2456 let modularized = modularized.parent_module.unwrap();
2457 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2458 && modularized.is_ancestor_of(macro_rules)
2459 }
2460
2461 fn extern_prelude_get_item<'r>(
2462 mut self: CmResolver<'r, 'ra, 'tcx>,
2463 ident: IdentKey,
2464 orig_ident_span: Span,
2465 finalize: bool,
2466 ) -> Option<Decl<'ra>> {
2467 let entry = self.extern_prelude.get(&ident);
2468 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2469 if finalize {
2470 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2471 }
2472 decl
2473 })
2474 }
2475
2476 fn extern_prelude_get_flag(
2477 &self,
2478 ident: IdentKey,
2479 orig_ident_span: Span,
2480 finalize: bool,
2481 ) -> Option<Decl<'ra>> {
2482 let entry = self.extern_prelude.get(&ident);
2483 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2484 let (pending_decl, finalized, is_open) = flag_decl.get();
2485 let decl = match pending_decl {
2486 PendingDecl::Ready(decl) => {
2487 if finalize && !finalized && !is_open {
2488 self.cstore_mut().process_path_extern(
2489 self.tcx,
2490 ident.name,
2491 orig_ident_span,
2492 );
2493 }
2494 decl
2495 }
2496 PendingDecl::Pending => {
2497 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2498 if is_open {
2499 let res = Res::OpenMod(ident.name);
2500 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2501 } else {
2502 let crate_id = if finalize {
2503 self.cstore_mut().process_path_extern(
2504 self.tcx,
2505 ident.name,
2506 orig_ident_span,
2507 )
2508 } else {
2509 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2510 };
2511 crate_id.map(|crate_id| {
2512 let def_id = crate_id.as_def_id();
2513 let res = Res::Def(DefKind::Mod, def_id);
2514 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2515 })
2516 }
2517 }
2518 };
2519 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2520 decl.or_else(|| finalize.then_some(self.dummy_decl))
2521 })
2522 }
2523
2524 fn resolve_rustdoc_path(
2529 &mut self,
2530 path_str: &str,
2531 ns: Namespace,
2532 parent_scope: ParentScope<'ra>,
2533 ) -> Option<Res> {
2534 let segments: Result<Vec<_>, ()> = path_str
2535 .split("::")
2536 .enumerate()
2537 .map(|(i, s)| {
2538 let sym = if s.is_empty() {
2539 if i == 0 {
2540 kw::PathRoot
2542 } else {
2543 return Err(()); }
2545 } else {
2546 Symbol::intern(s)
2547 };
2548 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2549 })
2550 .collect();
2551 let Ok(segments) = segments else { return None };
2552
2553 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2554 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2555 PathResult::NonModule(path_res) => {
2556 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(..), _)))
2557 }
2558 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2559 None
2560 }
2561 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2562 ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
path_result))bug!("got invalid path_result: {path_result:?}")
2563 }
2564 }
2565 }
2566
2567 fn def_span(&self, def_id: DefId) -> Span {
2569 match def_id.as_local() {
2570 Some(def_id) => self.tcx.source_span(def_id),
2571 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2573 }
2574 }
2575
2576 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2577 match def_id.as_local() {
2578 Some(def_id) => self.field_names.get(&def_id).cloned(),
2579 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2580 self.tcx.def_kind(def_id),
2581 DefKind::Struct | DefKind::Union | DefKind::Variant
2582 ) =>
2583 {
2584 Some(
2585 self.tcx
2586 .associated_item_def_ids(def_id)
2587 .iter()
2588 .map(|&def_id| {
2589 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2590 })
2591 .collect(),
2592 )
2593 }
2594 _ => None,
2595 }
2596 }
2597
2598 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2599 match def_id.as_local() {
2600 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2601 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2602 self.tcx.def_kind(def_id),
2603 DefKind::Struct | DefKind::Union | DefKind::Variant
2604 ) =>
2605 {
2606 Some(
2607 self.tcx
2608 .associated_item_def_ids(def_id)
2609 .iter()
2610 .filter_map(|&def_id| {
2611 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2612 })
2613 .collect(),
2614 )
2615 }
2616 _ => None,
2617 }
2618 }
2619
2620 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2624 let ExprKind::Path(None, path) = &expr.kind else {
2625 return None;
2626 };
2627 if path.segments.last().unwrap().args.is_some() {
2630 return None;
2631 }
2632
2633 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2634
2635 if def_id.is_local() {
2639 return None;
2640 }
2641
2642 {
{
'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!(
2643 self.tcx, def_id,
2645 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2646 )
2647 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2648 }
2649
2650 fn resolve_main(&mut self) {
2651 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2652 if !any_exe {
2654 return;
2655 }
2656
2657 let module = self.graph_root;
2658 let ident = Ident::with_dummy_span(sym::main);
2659 let parent_scope = &ParentScope::module(module, self.arenas);
2660
2661 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2662 ModuleOrUniformRoot::Module(module.to_module()),
2663 ident,
2664 ValueNS,
2665 parent_scope,
2666 None,
2667 ) else {
2668 return;
2669 };
2670
2671 let res = name_binding.res();
2672 let is_import = name_binding.is_import();
2673 let span = name_binding.span;
2674 if let Res::Def(DefKind::Fn, _) = res {
2675 self.record_use(ident, name_binding, Used::Other);
2676 }
2677 self.main_def = Some(MainDefinition { res, is_import, span });
2678 }
2679}
2680
2681fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2682 this: &mut R,
2683 owner: NodeId,
2684 work: impl FnOnce(&mut R) -> T,
2685) -> T {
2686 let tables = this.as_mut().owners.remove(&owner).unwrap();
2687 with_owner_tables(this, owner, tables, work)
2688}
2689
2690#[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(2690u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["owner", "tables"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tables)
as &dyn 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))]
2691fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2692 this: &mut R,
2693 owner: NodeId,
2694 tables: PerOwnerResolverData,
2695 work: impl FnOnce(&mut R) -> T,
2696) -> T {
2697 debug_assert!(!this.as_mut().owners.contains_key(&owner));
2698 let resolver = this.as_mut();
2699 let old_owner = mem::replace(&mut resolver.current_owner, tables);
2700 let ret = work(this);
2701 let resolver = this.as_mut();
2702 let overwritten =
2703 resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2704 assert!(overwritten.is_none());
2705 ret
2706}
2707
2708fn build_extern_prelude<'tcx, 'ra>(
2709 tcx: TyCtxt<'tcx>,
2710 attrs: &[ast::Attribute],
2711) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2712 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2713 .sess
2714 .opts
2715 .externs
2716 .iter()
2717 .filter_map(|(name, entry)| {
2718 if entry.add_prelude
2721 && let sym = Symbol::intern(name)
2722 && sym.can_be_raw()
2723 {
2724 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2725 } else {
2726 None
2727 }
2728 })
2729 .collect();
2730
2731 let missing_open_bases: Vec<IdentKey> = extern_prelude
2737 .keys()
2738 .filter_map(|ident| {
2739 let (base, _) = ident.name.as_str().split_once("::")?;
2740 let base_sym = Symbol::intern(base);
2741 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2742 })
2743 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2744 .collect();
2745
2746 extern_prelude.extend(
2747 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2748 );
2749
2750 if !attr::contains_name(attrs, sym::no_core) {
2752 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2753
2754 if !attr::contains_name(attrs, sym::no_std) {
2755 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2756 }
2757 }
2758
2759 extern_prelude
2760}
2761
2762fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2763 let mut result = String::new();
2764 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2765 if i > 0 {
2766 result.push_str("::");
2767 }
2768 if Ident::with_dummy_span(name).is_raw_guess() {
2769 result.push_str("r#");
2770 }
2771 result.push_str(name.as_str());
2772 }
2773 result
2774}
2775
2776fn path_names_to_string(path: &Path) -> String {
2777 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2778}
2779
2780fn module_to_string(mut module: Module<'_>) -> Option<String> {
2782 let mut names = Vec::new();
2783 while let Some(parent) = module.parent {
2784 names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2785 module = parent;
2786 }
2787 if names.is_empty() {
2788 return None;
2789 }
2790 Some(names_to_string(names.iter().rev().copied()))
2791}
2792
2793#[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)]
2794enum Stage {
2795 Early,
2799 Late,
2802}
2803
2804#[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<LocalDefId>;
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)]
2807struct ImportSummary {
2808 vis: Visibility,
2809 nearest_parent_mod: LocalDefId,
2810 is_single: bool,
2811 priv_macro_use: bool,
2812 span: Span,
2813}
2814
2815#[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)]
2817struct Finalize {
2818 node_id: NodeId,
2820 path_span: Span,
2823 root_span: Span,
2826 report_private: bool = true,
2829 used: Used = Used::Other,
2831 stage: Stage = Stage::Early,
2833 import: Option<ImportSummary> = None,
2835}
2836
2837impl Finalize {
2838 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2839 Finalize::with_root_span(node_id, path_span, path_span)
2840 }
2841
2842 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2843 Finalize { node_id, path_span, root_span, .. }
2844 }
2845}
2846
2847pub fn provide(providers: &mut Providers) {
2848 providers.registered_tools = macros::registered_tools;
2849}
2850
2851type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2857
2858use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2862
2863mod ref_mut {
2866 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2867 use std::fmt;
2868 use std::ops::Deref;
2869
2870 use crate::Resolver;
2871
2872 pub(crate) struct RefOrMut<'a, T> {
2874 p: &'a mut T,
2875 mutable: bool,
2876 }
2877
2878 impl<'a, T> Deref for RefOrMut<'a, T> {
2879 type Target = T;
2880
2881 fn deref(&self) -> &Self::Target {
2882 self.p
2883 }
2884 }
2885
2886 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2887 fn as_ref(&self) -> &T {
2888 self.p
2889 }
2890 }
2891
2892 impl<'a, T> RefOrMut<'a, T> {
2893 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2894 RefOrMut { p, mutable }
2895 }
2896
2897 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2899 RefOrMut { p: self.p, mutable: self.mutable }
2900 }
2901
2902 #[track_caller]
2907 pub(crate) fn get_mut(&mut self) -> &mut T {
2908 match self.mutable {
2909 false => {
::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2910 true => self.p,
2911 }
2912 }
2913
2914 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2917 self.p
2918 }
2919 }
2920
2921 #[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)]
2923 pub(crate) struct CmCell<T>(Cell<T>);
2924
2925 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2926 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2927 f.debug_tuple("CmCell").field(&self.get()).finish()
2928 }
2929 }
2930
2931 impl<T: Copy> Clone for CmCell<T> {
2932 fn clone(&self) -> CmCell<T> {
2933 CmCell::new(self.get())
2934 }
2935 }
2936
2937 impl<T: Copy> CmCell<T> {
2938 pub(crate) const fn get(&self) -> T {
2939 self.0.get()
2940 }
2941
2942 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2943 where
2944 T: Copy,
2945 {
2946 let old = self.get();
2947 self.set_unchecked(f(old));
2948 }
2949 }
2950
2951 impl<T> CmCell<T> {
2952 pub(crate) const fn new(value: T) -> CmCell<T> {
2953 CmCell(Cell::new(value))
2954 }
2955
2956 pub(crate) fn set_unchecked(&self, val: T) {
2957 self.0.set(val);
2958 }
2959
2960 pub(crate) fn into_inner(self) -> T {
2961 self.0.into_inner()
2962 }
2963 }
2964
2965 #[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)]
2967 pub(crate) struct CmRefCell<T>(RefCell<T>);
2968
2969 impl<T> CmRefCell<T> {
2970 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2971 CmRefCell(RefCell::new(value))
2972 }
2973
2974 #[track_caller]
2975 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2976 self.0.borrow_mut()
2977 }
2978
2979 #[track_caller]
2980 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2981 if r.assert_speculative {
2982 {
::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");
2983 }
2984 self.borrow_mut_unchecked()
2985 }
2986
2987 #[track_caller]
2988 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2989 self.0.try_borrow_mut()
2990 }
2991
2992 #[track_caller]
2993 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2994 self.0.borrow()
2995 }
2996 }
2997
2998 impl<T: Default> CmRefCell<T> {
2999 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
3000 if r.assert_speculative {
3001 {
::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");
3002 }
3003 self.0.take()
3004 }
3005 }
3006}
3007
3008mod hygiene {
3009 use rustc_span::{ExpnId, SyntaxContext};
3010
3011 #[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)]
3014 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
3015
3016 impl Macros20NormalizedSyntaxContext {
3017 #[inline]
3018 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3019 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
3020 }
3021
3022 #[inline]
3023 pub(crate) fn new_adjusted(
3024 mut ctxt: SyntaxContext,
3025 expn_id: ExpnId,
3026 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
3027 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
3028 (Macros20NormalizedSyntaxContext(ctxt), def)
3029 }
3030
3031 #[inline]
3032 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3033 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());
3034 Macros20NormalizedSyntaxContext(ctxt)
3035 }
3036
3037 #[inline]
3039 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
3040 let ret = f(&mut self.0);
3041 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());
3042 ret
3043 }
3044 }
3045
3046 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3047 type Target = SyntaxContext;
3048 fn deref(&self) -> &Self::Target {
3049 &self.0
3050 }
3051 }
3052}