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