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