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, ast::ItemKind)>,
252 current_self_ty: Option<String>,
253 },
254 NameAlreadyUsedInParameterList(Ident, Span),
257 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
259 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
261 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
263 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
265 VariableBoundWithDifferentMode(Ident, Span),
267 IdentifierBoundMoreThanOnceInParameterList(Ident),
269 IdentifierBoundMoreThanOnceInSamePattern(Ident),
271 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
273 FailedToResolve {
275 segment: Symbol,
276 label: String,
277 suggestion: Option<Suggestion>,
278 module: Option<ModuleOrUniformRoot<'ra>>,
279 message: String,
280 },
281 CannotCaptureDynamicEnvironmentInFnItem,
283 AttemptToUseNonConstantValueInConstant {
285 ident: Ident,
286 suggestion: &'static str,
287 current: &'static str,
288 type_span: Option<Span>,
289 },
290 BindingShadowsSomethingUnacceptable {
292 shadowing_binding: PatternSource,
293 name: Symbol,
294 participle: &'static str,
295 article: &'static str,
296 shadowed_binding: Res,
297 shadowed_binding_span: Span,
298 },
299 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
301 ParamInTyOfConstParam { name: Symbol },
305 ParamInNonTrivialAnonConst {
309 is_gca: bool,
310 name: Symbol,
311 param_kind: ParamKindInNonTrivialAnonConst,
312 },
313 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
317 ForwardDeclaredSelf(ForwardGenericParamBanReason),
319 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
321 TraitImplMismatch {
323 name: Ident,
324 kind: &'static str,
325 trait_path: String,
326 trait_item_span: Span,
327 code: ErrCode,
328 },
329 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
331 InvalidAsmSym,
333 LowercaseSelf,
335 BindingInNeverPattern,
337}
338
339enum VisResolutionError<'a> {
340 Relative2018(Span, &'a ast::Path),
341 AncestorOnly(Span),
342 FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),
343 ExpectedFound(Span, String, Res),
344 Indeterminate(Span),
345 ModuleOnly(Span),
346}
347
348#[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)]
351struct Segment {
352 ident: Ident,
353 id: Option<NodeId>,
354 has_generic_args: bool,
357 has_lifetime_args: bool,
359 args_span: Span,
360}
361
362impl Segment {
363 fn from_path(path: &Path) -> Vec<Segment> {
364 path.segments.iter().map(|s| s.into()).collect()
365 }
366
367 fn from_ident(ident: Ident) -> Segment {
368 Segment {
369 ident,
370 id: None,
371 has_generic_args: false,
372 has_lifetime_args: false,
373 args_span: DUMMY_SP,
374 }
375 }
376
377 fn names_to_string(segments: &[Segment]) -> String {
378 names_to_string(segments.iter().map(|seg| seg.ident.name))
379 }
380}
381
382impl<'a> From<&'a ast::PathSegment> for Segment {
383 fn from(seg: &'a ast::PathSegment) -> Segment {
384 let has_generic_args = seg.args.is_some();
385 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
386 match args {
387 GenericArgs::AngleBracketed(args) => {
388 let found_lifetimes = args
389 .args
390 .iter()
391 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
392 (args.span, found_lifetimes)
393 }
394 GenericArgs::Parenthesized(args) => (args.span, true),
395 GenericArgs::ParenthesizedElided(span) => (*span, true),
396 }
397 } else {
398 (DUMMY_SP, false)
399 };
400 Segment {
401 ident: seg.ident,
402 id: Some(seg.id),
403 has_generic_args,
404 has_lifetime_args,
405 args_span,
406 }
407 }
408}
409
410#[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)]
412enum LateDecl<'ra> {
413 Decl(Decl<'ra>),
415 RibDef(Res),
418}
419
420impl<'ra> LateDecl<'ra> {
421 fn res(self) -> Res {
422 match self {
423 LateDecl::Decl(binding) => binding.res(),
424 LateDecl::RibDef(res) => res,
425 }
426 }
427}
428
429#[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)]
430enum ModuleOrUniformRoot<'ra> {
431 Module(Module<'ra>),
433
434 ModuleAndExternPrelude(Module<'ra>),
438
439 ExternPrelude,
442
443 CurrentScope,
447
448 OpenModule(Symbol),
452}
453
454#[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)]
455enum PathResult<'ra> {
456 Module(ModuleOrUniformRoot<'ra>),
457 NonModule(PartialRes),
458 Indeterminate,
459 Failed {
460 span: Span,
461 label: String,
462 suggestion: Option<Suggestion>,
463 is_error_from_last_segment: bool,
464 module: Option<ModuleOrUniformRoot<'ra>>,
478 segment_name: Symbol,
480 error_implied_by_parse_error: bool,
481 message: String,
482 note: Option<String>,
483 },
484}
485
486impl<'ra> PathResult<'ra> {
487 fn failed(
488 ident: Ident,
489 is_error_from_last_segment: bool,
490 finalize: bool,
491 error_implied_by_parse_error: bool,
492 module: Option<ModuleOrUniformRoot<'ra>>,
493 label_and_suggestion_and_note: impl FnOnce() -> (
494 String,
495 String,
496 Option<Suggestion>,
497 Option<String>,
498 ),
499 ) -> PathResult<'ra> {
500 let (message, label, suggestion, note) = if finalize {
501 label_and_suggestion_and_note()
502 } else {
503 (::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)
505 };
506 PathResult::Failed {
507 span: ident.span,
508 segment_name: ident.name,
509 label,
510 suggestion,
511 is_error_from_last_segment,
512 module,
513 error_implied_by_parse_error,
514 message,
515 note,
516 }
517 }
518}
519
520#[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)]
521enum ModuleKind {
522 Block,
535 Def(DefKind, DefId, Option<Symbol>),
545}
546
547impl ModuleKind {
548 fn name(&self) -> Option<Symbol> {
550 match *self {
551 ModuleKind::Block => None,
552 ModuleKind::Def(.., name) => name,
553 }
554 }
555
556 fn opt_def_id(&self) -> Option<DefId> {
557 match self {
558 ModuleKind::Def(_, def_id, _) => Some(*def_id),
559 _ => None,
560 }
561 }
562}
563
564#[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)]
575struct IdentKey {
576 name: Symbol,
577 ctxt: Macros20NormalizedSyntaxContext,
578}
579
580impl IdentKey {
581 #[inline]
582 fn new(ident: Ident) -> IdentKey {
583 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
584 }
585
586 #[inline]
587 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
588 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
589 (IdentKey { name: ident.name, ctxt }, def)
590 }
591
592 #[inline]
593 fn with_root_ctxt(name: Symbol) -> Self {
594 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
595 IdentKey { name, ctxt }
596 }
597
598 #[inline]
599 fn orig(self, orig_ident_span: Span) -> Ident {
600 Ident::new(self.name, orig_ident_span)
601 }
602}
603
604#[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)]
609struct BindingKey {
610 ident: IdentKey,
613 ns: Namespace,
614 disambiguator: u32,
620}
621
622impl BindingKey {
623 fn new(ident: IdentKey, ns: Namespace) -> Self {
624 BindingKey { ident, ns, disambiguator: 0 }
625 }
626
627 fn new_disambiguated(
628 ident: IdentKey,
629 ns: Namespace,
630 disambiguator: impl FnOnce() -> u32,
631 ) -> BindingKey {
632 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
633 BindingKey { ident, ns, disambiguator }
634 }
635}
636
637type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
638
639struct ModuleData<'ra> {
651 parent: Option<Module<'ra>>,
653 kind: ModuleKind,
655
656 lazy_resolutions: Resolutions<'ra>,
659 populate_on_access: CacheCell<bool>,
661 underscore_disambiguator: CmCell<u32>,
663
664 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
666
667 no_implicit_prelude: bool,
669
670 glob_importers: CmRefCell<Vec<Import<'ra>>>,
671 globs: CmRefCell<Vec<Import<'ra>>>,
672
673 traits: CmRefCell<
675 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
676 >,
677
678 span: Span,
680
681 expansion: ExpnId,
682
683 self_decl: Option<Decl<'ra>>,
686}
687
688#[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)]
691#[rustc_pass_by_value]
692struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
693
694#[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)]
696#[rustc_pass_by_value]
697struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
698
699#[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)]
701#[rustc_pass_by_value]
702struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
703
704impl std::hash::Hash for ModuleData<'_> {
709 fn hash<H>(&self, _: &mut H)
710 where
711 H: std::hash::Hasher,
712 {
713 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
714 }
715}
716
717impl<'ra> ModuleData<'ra> {
718 fn new(
719 parent: Option<Module<'ra>>,
720 kind: ModuleKind,
721 expansion: ExpnId,
722 span: Span,
723 no_implicit_prelude: bool,
724 self_decl: Option<Decl<'ra>>,
725 ) -> Self {
726 let is_foreign = match kind {
727 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
728 ModuleKind::Block => false,
729 };
730 ModuleData {
731 parent,
732 kind,
733 lazy_resolutions: Default::default(),
734 populate_on_access: CacheCell::new(is_foreign),
735 underscore_disambiguator: CmCell::new(0),
736 unexpanded_invocations: Default::default(),
737 no_implicit_prelude,
738 glob_importers: CmRefCell::new(Vec::new()),
739 globs: CmRefCell::new(Vec::new()),
740 traits: CmRefCell::new(None),
741 span,
742 expansion,
743 self_decl,
744 }
745 }
746
747 fn opt_def_id(&self) -> Option<DefId> {
748 self.kind.opt_def_id()
749 }
750
751 fn def_id(&self) -> DefId {
752 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
753 }
754
755 fn res(&self) -> Option<Res> {
756 match self.kind {
757 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
758 _ => None,
759 }
760 }
761}
762
763impl<'ra> Module<'ra> {
764 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
765 self,
766 resolver: &R,
767 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
768 ) {
769 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
770 let name_resolution = name_resolution.borrow();
771 if let Some(decl) = name_resolution.best_decl() {
772 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
773 }
774 }
775 }
776
777 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
778 self,
779 resolver: &mut R,
780 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
781 ) {
782 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
783 let name_resolution = name_resolution.borrow();
784 if let Some(decl) = name_resolution.best_decl() {
785 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
786 }
787 }
788 }
789
790 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
792 let mut traits = self.traits.borrow_mut(resolver.as_ref());
793 if traits.is_none() {
794 let mut collected_traits = Vec::new();
795 self.for_each_child(resolver, |r, ident, _, ns, binding| {
796 if ns != TypeNS {
797 return;
798 }
799 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
800 collected_traits.push((
801 ident.name,
802 binding,
803 r.as_ref().get_module(def_id),
804 binding.is_ambiguity_recursive(),
805 ));
806 }
807 });
808 *traits = Some(collected_traits.into_boxed_slice());
809 }
810 }
811
812 fn is_normal(self) -> bool {
814 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Mod, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
815 }
816
817 fn is_trait(self) -> bool {
818 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Trait, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
819 }
820
821 fn nearest_item_scope(self) -> Module<'ra> {
822 match self.kind {
823 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
824 self.parent.expect("enum or trait module without a parent")
825 }
826 _ => self,
827 }
828 }
829
830 fn nearest_parent_mod(self) -> DefId {
833 match self.kind {
834 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
835 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
836 }
837 }
838
839 fn is_ancestor_of(self, mut other: Self) -> bool {
840 while self != other {
841 if let Some(parent) = other.parent {
842 other = parent;
843 } else {
844 return false;
845 }
846 }
847 true
848 }
849
850 #[track_caller]
851 fn expect_local(self) -> LocalModule<'ra> {
852 match self.kind {
853 ModuleKind::Def(_, def_id, _) if !def_id.is_local() => {
854 {
::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:?}")
855 }
856 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
857 }
858 }
859
860 #[track_caller]
861 fn expect_extern(self) -> ExternModule<'ra> {
862 match self.kind {
863 ModuleKind::Def(_, def_id, _) if !def_id.is_local() => ExternModule(self.0),
864 ModuleKind::Def(..) | ModuleKind::Block => {
865 {
::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:?}")
866 }
867 }
868 }
869}
870
871impl<'ra> LocalModule<'ra> {
872 fn to_module(self) -> Module<'ra> {
873 Module(self.0)
874 }
875}
876
877impl<'ra> ExternModule<'ra> {
878 fn to_module(self) -> Module<'ra> {
879 Module(self.0)
880 }
881}
882
883impl<'ra> std::ops::Deref for Module<'ra> {
884 type Target = ModuleData<'ra>;
885
886 fn deref(&self) -> &Self::Target {
887 &self.0
888 }
889}
890
891impl<'ra> std::ops::Deref for LocalModule<'ra> {
892 type Target = ModuleData<'ra>;
893
894 fn deref(&self) -> &Self::Target {
895 &self.0
896 }
897}
898
899impl<'ra> std::ops::Deref for ExternModule<'ra> {
900 type Target = ModuleData<'ra>;
901
902 fn deref(&self) -> &Self::Target {
903 &self.0
904 }
905}
906
907impl<'ra> fmt::Debug for Module<'ra> {
908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909 match self.kind {
910 ModuleKind::Block => f.write_fmt(format_args!("block"))write!(f, "block"),
911 ModuleKind::Def(..) => f.write_fmt(format_args!("{0:?}", self.res()))write!(f, "{:?}", self.res()),
912 }
913 }
914}
915
916impl<'ra> fmt::Debug for LocalModule<'ra> {
917 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
918 self.to_module().fmt(f)
919 }
920}
921
922#[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)]
924struct DeclData<'ra> {
925 kind: DeclKind<'ra>,
926 ambiguity: CmCell<Option<Decl<'ra>>>,
927 warn_ambiguity: CmCell<bool>,
930 expansion: LocalExpnId,
931 span: Span,
932 initial_vis: Visibility<DefId>,
933 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
936 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
939 parent_module: Option<Module<'ra>>,
940}
941
942type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
945
946impl std::hash::Hash for DeclData<'_> {
951 fn hash<H>(&self, _: &mut H)
952 where
953 H: std::hash::Hasher,
954 {
955 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
956 }
957}
958
959#[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)]
961enum DeclKind<'ra> {
962 Def(Res),
965 Import { source_decl: Decl<'ra>, import: Import<'ra> },
967}
968
969impl<'ra> DeclKind<'ra> {
970 fn is_import(&self) -> bool {
972 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
973 }
974}
975
976#[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)]
977struct PrivacyError<'ra> {
978 ident: Ident,
979 decl: Decl<'ra>,
980 dedup_span: Span,
981 outermost_res: Option<(Res, Ident)>,
982 parent_scope: ParentScope<'ra>,
983 single_nested: bool,
985 source: Option<ast::Expr>,
986}
987
988#[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)]
989struct UseError<'a> {
990 err: Diag<'a>,
991 candidates: Vec<ImportSuggestion>,
993 def_id: DefId,
995 instead: bool,
997 suggestion: Option<(Span, &'static str, String, Applicability)>,
999 path: Vec<Segment>,
1002 is_call: bool,
1004}
1005
1006#[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)]
1007enum AmbiguityKind {
1008 BuiltinAttr,
1009 DeriveHelper,
1010 MacroRulesVsModularized,
1011 GlobVsOuter,
1012 GlobVsGlob,
1013 GlobVsExpanded,
1014 MoreExpandedVsOuter,
1015}
1016
1017impl AmbiguityKind {
1018 fn descr(self) -> &'static str {
1019 match self {
1020 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1021 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1022 AmbiguityKind::MacroRulesVsModularized => {
1023 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1024 }
1025 AmbiguityKind::GlobVsOuter => {
1026 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1027 }
1028 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1029 AmbiguityKind::GlobVsExpanded => {
1030 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1031 }
1032 AmbiguityKind::MoreExpandedVsOuter => {
1033 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1034 }
1035 }
1036 }
1037}
1038
1039#[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)]
1040enum AmbiguityWarning {
1041 GlobImport,
1042 PanicImport,
1043}
1044
1045struct AmbiguityError<'ra> {
1046 kind: AmbiguityKind,
1047 ambig_vis: Option<(Visibility, Visibility)>,
1048 ident: Ident,
1049 b1: Decl<'ra>,
1050 b2: Decl<'ra>,
1051 scope1: Scope<'ra>,
1052 scope2: Scope<'ra>,
1053 warning: Option<AmbiguityWarning>,
1054}
1055
1056impl<'ra> DeclData<'ra> {
1057 fn vis(&self) -> Visibility<DefId> {
1058 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1060 }
1061
1062 fn min_vis(&self) -> Visibility<DefId> {
1063 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1065 }
1066
1067 fn res(&self) -> Res {
1068 match self.kind {
1069 DeclKind::Def(res) => res,
1070 DeclKind::Import { source_decl, .. } => source_decl.res(),
1071 }
1072 }
1073
1074 fn import_source(&self) -> Decl<'ra> {
1075 match self.kind {
1076 DeclKind::Import { source_decl, .. } => source_decl,
1077 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1078 }
1079 }
1080
1081 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1082 match self.ambiguity.get() {
1083 Some(ambig_binding) => Some((self, ambig_binding)),
1084 None => match self.kind {
1085 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1086 _ => None,
1087 },
1088 }
1089 }
1090
1091 fn is_ambiguity_recursive(&self) -> bool {
1092 self.ambiguity.get().is_some()
1093 || match self.kind {
1094 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1095 _ => false,
1096 }
1097 }
1098
1099 fn warn_ambiguity_recursive(&self) -> bool {
1100 self.warn_ambiguity.get()
1101 || match self.kind {
1102 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
1103 _ => false,
1104 }
1105 }
1106
1107 fn is_possibly_imported_variant(&self) -> bool {
1108 match self.kind {
1109 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1110 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1111 true
1112 }
1113 DeclKind::Def(..) => false,
1114 }
1115 }
1116
1117 fn is_extern_crate(&self) -> bool {
1118 match self.kind {
1119 DeclKind::Import { import, .. } => {
1120 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1121 }
1122 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1123 _ => false,
1124 }
1125 }
1126
1127 fn is_import(&self) -> bool {
1128 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1129 }
1130
1131 fn is_import_user_facing(&self) -> bool {
1134 #[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, .. }
1135 if !matches!(import.kind, ImportKind::MacroExport))
1136 }
1137
1138 fn is_glob_import(&self) -> bool {
1139 match self.kind {
1140 DeclKind::Import { import, .. } => import.is_glob(),
1141 _ => false,
1142 }
1143 }
1144
1145 fn is_assoc_item(&self) -> bool {
1146 #[allow(non_exhaustive_omitted_patterns)] match self.res() {
Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy,
_) => true,
_ => false,
}matches!(
1147 self.res(),
1148 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
1149 )
1150 }
1151
1152 fn macro_kinds(&self) -> Option<MacroKinds> {
1153 self.res().macro_kinds()
1154 }
1155
1156 fn reexport_chain(self: Decl<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1157 let mut reexport_chain = SmallVec::new();
1158 let mut next_binding = self;
1159 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1160 reexport_chain.push(import.simplify(r));
1161 next_binding = source_decl;
1162 }
1163 reexport_chain
1164 }
1165
1166 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1173 let self_parent_expansion = self.expansion;
1177 let other_parent_expansion = decl.expansion;
1178 let certainly_before_other_or_simultaneously =
1179 other_parent_expansion.is_descendant_of(self_parent_expansion);
1180 let certainly_before_invoc_or_simultaneously =
1181 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1182 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1183 }
1184
1185 fn determined(&self) -> bool {
1191 match &self.kind {
1192 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1193 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1194 && source_decl.determined()
1195 }
1196 _ => true,
1197 }
1198 }
1199}
1200
1201#[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)]
1202struct ExternPreludeEntry<'ra> {
1203 item_decl: Option<(Decl<'ra>, Span, bool)>,
1207 flag_decl: Option<
1209 CacheCell<(
1210 PendingDecl<'ra>,
1211 bool,
1212 bool,
1213 )>,
1214 >,
1215}
1216
1217impl ExternPreludeEntry<'_> {
1218 fn introduced_by_item(&self) -> bool {
1219 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1220 }
1221
1222 fn flag() -> Self {
1223 ExternPreludeEntry {
1224 item_decl: None,
1225 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1226 }
1227 }
1228
1229 fn open_flag() -> Self {
1230 ExternPreludeEntry {
1231 item_decl: None,
1232 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
1233 }
1234 }
1235
1236 fn span(&self) -> Span {
1237 match self.item_decl {
1238 Some((_, span, _)) => span,
1239 None => DUMMY_SP,
1240 }
1241 }
1242}
1243
1244struct DeriveData {
1245 resolutions: Vec<DeriveResolution>,
1246 helper_attrs: Vec<(usize, IdentKey, Span)>,
1247 has_derive_copy: bool,
1248}
1249
1250struct MacroData {
1251 ext: Arc<SyntaxExtension>,
1252 nrules: usize,
1253 macro_rules: bool,
1254}
1255
1256impl MacroData {
1257 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1258 MacroData { ext, nrules: 0, macro_rules: false }
1259 }
1260}
1261
1262pub struct ResolverOutputs<'tcx> {
1263 pub global_ctxt: ResolverGlobalCtxt,
1264 pub ast_lowering: ResolverAstLowering<'tcx>,
1265}
1266
1267#[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)]
1268struct DelegationFnSig {
1269 pub has_self: bool,
1270}
1271
1272pub struct Resolver<'ra, 'tcx> {
1276 tcx: TyCtxt<'tcx>,
1277
1278 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1280
1281 graph_root: LocalModule<'ra>,
1282
1283 assert_speculative: bool,
1285
1286 prelude: Option<Module<'ra>> = None,
1287 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1288
1289 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1291 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1292
1293 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1296
1297 determined_imports: Vec<Import<'ra>> = Vec::new(),
1299
1300 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1302
1303 pat_span_map: NodeMap<Span> = Default::default(),
1306
1307 partial_res_map: NodeMap<PartialRes> = Default::default(),
1309 import_res_map: NodeMap<PerNS<Option<Res>>> = Default::default(),
1311 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1313 label_res_map: NodeMap<NodeId> = Default::default(),
1315 lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
1317 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>> = Default::default(),
1319
1320 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1322 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1323 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1324 trait_map: NodeMap<&'tcx [TraitCandidate<'tcx>]> = Default::default(),
1325
1326 block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1341 empty_module: LocalModule<'ra>,
1345 local_modules: Vec<LocalModule<'ra>>,
1347 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1349 extern_module_map: CacheRefCell<FxIndexMap<DefId, ExternModule<'ra>>>,
1351
1352 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1354 glob_error: Option<ErrorGuaranteed> = None,
1355 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1356 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1357 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1358
1359 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1361 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1363 issue_145575_hack_applied: bool = false,
1364 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1366 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1368
1369 arenas: &'ra ResolverArenas<'ra>,
1370 dummy_decl: Decl<'ra>,
1371 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1372 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1373 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1374 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1375 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1376 registered_tools: &'tcx RegisteredTools,
1377 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1378 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData> = default::fx_hash_map(),
1380 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1382 dummy_ext_bang: Arc<SyntaxExtension>,
1383 dummy_ext_derive: Arc<SyntaxExtension>,
1384 non_macro_attr: &'ra MacroData,
1385 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1386 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1387 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1388 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1390 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1391 single_segment_macro_resolutions:
1393 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1394 multi_segment_macro_resolutions:
1395 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1396 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1397 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1401 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1404 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1407 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1409 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1411 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1414
1415 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1417
1418 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1419
1420 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1421
1422 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1426
1427 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1430
1431 lint_buffer: LintBuffer,
1432
1433 next_node_id: NodeId = CRATE_NODE_ID,
1434
1435 node_id_to_def_id: NodeMap<LocalDefId>,
1436
1437 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1438
1439 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1441 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1445
1446 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1448 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1450 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1451 delegation_infos: LocalDefIdMap<DelegationInfo> = Default::default(),
1452
1453 main_def: Option<MainDefinition> = None,
1454 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1455 proc_macros: Vec<LocalDefId> = Vec::new(),
1458 confused_type_with_std_module: FxIndexMap<Span, Span>,
1459 lifetime_elision_allowed: FxHashSet<NodeId> = default::fx_hash_set(),
1461
1462 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1464
1465 effective_visibilities: EffectiveVisibilities,
1466 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1467 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1468 all_macro_rules: UnordSet<Symbol> = Default::default(),
1469
1470 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1472 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1475 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1478
1479 current_crate_outer_attr_insert_span: Span,
1482
1483 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1484
1485 all_crate_macros_already_registered: bool = false,
1488
1489 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1493}
1494
1495#[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)]
1498pub struct ResolverArenas<'ra> {
1499 modules: TypedArena<ModuleData<'ra>>,
1500 imports: TypedArena<ImportData<'ra>>,
1501 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1502 ast_paths: TypedArena<ast::Path>,
1503 macros: TypedArena<MacroData>,
1504 dropless: DroplessArena,
1505}
1506
1507impl<'ra> ResolverArenas<'ra> {
1508 fn new_def_decl(
1509 &'ra self,
1510 res: Res,
1511 vis: Visibility<DefId>,
1512 span: Span,
1513 expansion: LocalExpnId,
1514 parent_module: Option<Module<'ra>>,
1515 ) -> Decl<'ra> {
1516 self.alloc_decl(DeclData {
1517 kind: DeclKind::Def(res),
1518 ambiguity: CmCell::new(None),
1519 warn_ambiguity: CmCell::new(false),
1520 initial_vis: vis,
1521 ambiguity_vis_max: CmCell::new(None),
1522 ambiguity_vis_min: CmCell::new(None),
1523 span,
1524 expansion,
1525 parent_module,
1526 })
1527 }
1528
1529 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1530 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1531 }
1532
1533 fn new_module(
1534 &'ra self,
1535 parent: Option<Module<'ra>>,
1536 kind: ModuleKind,
1537 vis: Visibility<DefId>,
1538 expn_id: ExpnId,
1539 span: Span,
1540 no_implicit_prelude: bool,
1541 ) -> Module<'ra> {
1542 let self_decl = match kind {
1543 ModuleKind::Def(def_kind, def_id, _) => Some(self.new_def_decl(
1544 Res::Def(def_kind, def_id),
1545 vis,
1546 span,
1547 LocalExpnId::ROOT,
1548 None,
1549 )),
1550 ModuleKind::Block => None,
1551 };
1552 Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1553 parent,
1554 kind,
1555 expn_id,
1556 span,
1557 no_implicit_prelude,
1558 self_decl,
1559 ))))
1560 }
1561 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1562 Interned::new_unchecked(self.dropless.alloc(data))
1563 }
1564 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1565 Interned::new_unchecked(self.imports.alloc(import))
1566 }
1567 fn alloc_name_resolution(
1568 &'ra self,
1569 orig_ident_span: Span,
1570 ) -> &'ra CmRefCell<NameResolution<'ra>> {
1571 self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))
1572 }
1573 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1574 self.dropless.alloc(CacheCell::new(scope))
1575 }
1576 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1577 self.dropless.alloc(decl)
1578 }
1579 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1580 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1581 }
1582 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1583 self.macros.alloc(macro_data)
1584 }
1585 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1586 self.dropless.alloc_from_iter(spans)
1587 }
1588}
1589
1590impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1591 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1592 self
1593 }
1594}
1595
1596impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1597 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1598 self
1599 }
1600}
1601
1602impl<'tcx> Resolver<'_, 'tcx> {
1603 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1604 self.node_id_to_def_id.get(&node).copied()
1605 }
1606
1607 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1608 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:?}`"))
1609 }
1610
1611 fn local_def_kind(&self, node: NodeId) -> DefKind {
1612 self.tcx.def_kind(self.local_def_id(node))
1613 }
1614
1615 fn create_def(
1617 &mut self,
1618 parent: LocalDefId,
1619 node_id: ast::NodeId,
1620 name: Option<Symbol>,
1621 def_kind: DefKind,
1622 expn_id: ExpnId,
1623 span: Span,
1624 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1625 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!(
1626 !self.node_id_to_def_id.contains_key(&node_id),
1627 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1628 node_id,
1629 name,
1630 def_kind,
1631 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id]),
1632 );
1633
1634 let disambiguator = self.disambiguators.get_or_create(parent);
1635
1636 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1638 let def_id = feed.def_id();
1639
1640 if expn_id != ExpnId::root() {
1642 self.expn_that_defined.insert(def_id, expn_id);
1643 }
1644
1645 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);
1647 let _id = self.tcx.untracked().source_span.push(span);
1648 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);
1649
1650 if node_id != ast::DUMMY_NODE_ID {
1654 {
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:1654",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1654u32),
::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);
1655 self.node_id_to_def_id.insert(node_id, def_id);
1656 }
1657
1658 feed
1659 }
1660
1661 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1662 if let Some(def_id) = def_id.as_local() {
1663 self.item_generics_num_lifetimes[&def_id]
1664 } else {
1665 self.tcx.generics_of(def_id).own_counts().lifetimes
1666 }
1667 }
1668
1669 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1670 if let Some(def_id) = def_id.as_local() {
1671 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1672 } else {
1673 let required = self
1674 .tcx
1675 .generics_of(def_id)
1676 .own_params
1677 .iter()
1678 .filter_map(|param| match param.kind {
1679 ty::GenericParamDefKind::Lifetime => Some("'_"),
1680 ty::GenericParamDefKind::Type { has_default, .. }
1681 | ty::GenericParamDefKind::Const { has_default } => {
1682 if has_default {
1683 None
1684 } else {
1685 Some("_")
1686 }
1687 }
1688 })
1689 .collect::<Vec<_>>();
1690
1691 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1692 }
1693 }
1694
1695 pub fn tcx(&self) -> TyCtxt<'tcx> {
1696 self.tcx
1697 }
1698
1699 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1704 self.node_id_to_def_id
1705 .items()
1706 .filter(|(_, v)| **v == def_id)
1707 .map(|(k, _)| *k)
1708 .get_only()
1709 .unwrap()
1710 }
1711}
1712
1713impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1714 pub fn new(
1715 tcx: TyCtxt<'tcx>,
1716 attrs: &[ast::Attribute],
1717 crate_span: Span,
1718 current_crate_outer_attr_insert_span: Span,
1719 arenas: &'ra ResolverArenas<'ra>,
1720 ) -> Resolver<'ra, 'tcx> {
1721 let root_def_id = CRATE_DEF_ID.to_def_id();
1722 let graph_root = arenas.new_module(
1723 None,
1724 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1725 Visibility::Public,
1726 ExpnId::root(),
1727 crate_span,
1728 attr::contains_name(attrs, sym::no_implicit_prelude),
1729 );
1730 let graph_root = graph_root.expect_local();
1731 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];
1732 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1733 let empty_module = arenas.new_module(
1734 None,
1735 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1736 Visibility::Public,
1737 ExpnId::root(),
1738 DUMMY_SP,
1739 true,
1740 );
1741 let empty_module = empty_module.expect_local();
1742
1743 let mut node_id_to_def_id = NodeMap::default();
1744 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1745
1746 crate_feed.def_kind(DefKind::Mod);
1747 node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1748
1749 let mut invocation_parents = FxHashMap::default();
1750 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1751
1752 let extern_prelude = build_extern_prelude(tcx, attrs);
1753 let registered_tools = tcx.registered_tools(());
1754 let edition = tcx.sess.edition();
1755
1756 let mut resolver = Resolver {
1757 tcx,
1758
1759 graph_root,
1762 assert_speculative: false, extern_prelude,
1764
1765 empty_module,
1766 local_modules,
1767 local_module_map,
1768 extern_module_map: Default::default(),
1769
1770 glob_map: Default::default(),
1771 maybe_unused_trait_imports: Default::default(),
1772
1773 arenas,
1774 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1775 builtin_type_decls: PrimTy::ALL
1776 .iter()
1777 .map(|prim_ty| {
1778 let res = Res::PrimTy(*prim_ty);
1779 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1780 (prim_ty.name(), decl)
1781 })
1782 .collect(),
1783 builtin_attr_decls: BUILTIN_ATTRIBUTES
1784 .iter()
1785 .map(|builtin_attr| {
1786 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1787 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1788 (builtin_attr.name, decl)
1789 })
1790 .collect(),
1791 registered_tool_decls: registered_tools
1792 .iter()
1793 .map(|&ident| {
1794 let res = Res::ToolMod;
1795 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1796 (IdentKey::new(ident), decl)
1797 })
1798 .collect(),
1799 registered_tools,
1800 macro_use_prelude: Default::default(),
1801 extern_macro_map: Default::default(),
1802 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1803 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1804 non_macro_attr: arenas
1805 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1806 unused_macros: Default::default(),
1807 unused_macro_rules: Default::default(),
1808 single_segment_macro_resolutions: Default::default(),
1809 multi_segment_macro_resolutions: Default::default(),
1810 lint_buffer: LintBuffer::default(),
1811 node_id_to_def_id,
1812 invocation_parents,
1813 trait_impls: Default::default(),
1814 confused_type_with_std_module: Default::default(),
1815 stripped_cfg_items: Default::default(),
1816 effective_visibilities: Default::default(),
1817 doc_link_resolutions: Default::default(),
1818 doc_link_traits_in_scope: Default::default(),
1819 current_crate_outer_attr_insert_span,
1820 disambiguators: Default::default(),
1821 ..
1822 };
1823
1824 let root_parent_scope = ParentScope::module(graph_root.to_module(), resolver.arenas);
1825 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1826 resolver.feed_visibility(crate_feed, Visibility::Public);
1827
1828 resolver
1829 }
1830
1831 fn new_local_module(
1832 &mut self,
1833 parent: Option<LocalModule<'ra>>,
1834 kind: ModuleKind,
1835 expn_id: ExpnId,
1836 span: Span,
1837 no_implicit_prelude: bool,
1838 ) -> LocalModule<'ra> {
1839 let parent = parent.map(|m| m.to_module());
1840 let vis =
1841 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1842 let module = self
1843 .arenas
1844 .new_module(parent, kind, vis, expn_id, span, no_implicit_prelude)
1845 .expect_local();
1846 self.local_modules.push(module);
1847 if let Some(def_id) = module.opt_def_id() {
1848 self.local_module_map.insert(def_id.expect_local(), module);
1849 }
1850 module
1851 }
1852
1853 fn new_extern_module(
1854 &self,
1855 parent: Option<ExternModule<'ra>>,
1856 kind: ModuleKind,
1857 expn_id: ExpnId,
1858 span: Span,
1859 no_implicit_prelude: bool,
1860 ) -> ExternModule<'ra> {
1861 let parent = parent.map(|m| m.to_module());
1862 let vis =
1863 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1864 let module = self
1865 .arenas
1866 .new_module(parent, kind, vis, expn_id, span, no_implicit_prelude)
1867 .expect_extern();
1868 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1869 module
1870 }
1871
1872 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1873 let mac = self.arenas.alloc_macro(macro_data);
1874 self.local_macro_map.insert(def_id, mac);
1875 mac
1876 }
1877
1878 fn next_node_id(&mut self) -> NodeId {
1879 let start = self.next_node_id;
1880 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1881 self.next_node_id = ast::NodeId::from_u32(next);
1882 start
1883 }
1884
1885 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1886 let start = self.next_node_id;
1887 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1888 self.next_node_id = ast::NodeId::from_usize(end);
1889 start..self.next_node_id
1890 }
1891
1892 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1893 &mut self.lint_buffer
1894 }
1895
1896 pub fn arenas() -> ResolverArenas<'ra> {
1897 Default::default()
1898 }
1899
1900 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1901 feed.visibility(vis.to_def_id());
1902 self.visibilities_for_hashing.push((feed.def_id(), vis));
1903 }
1904
1905 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1906 let proc_macros = self.proc_macros;
1907 let expn_that_defined = self.expn_that_defined;
1908 let extern_crate_map = self.extern_crate_map;
1909 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1910 let glob_map = self.glob_map;
1911 let main_def = self.main_def;
1912 let confused_type_with_std_module = self.confused_type_with_std_module;
1913 let effective_visibilities = self.effective_visibilities;
1914
1915 let stripped_cfg_items = self
1916 .stripped_cfg_items
1917 .into_iter()
1918 .filter_map(|item| {
1919 let parent_scope = self.node_id_to_def_id.get(&item.parent_scope)?.to_def_id();
1920 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1921 })
1922 .collect();
1923 let disambiguators = self
1924 .disambiguators
1925 .into_items()
1926 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
1927 .collect();
1928
1929 let global_ctxt = ResolverGlobalCtxt {
1930 expn_that_defined,
1931 visibilities_for_hashing: self.visibilities_for_hashing,
1932 effective_visibilities,
1933 extern_crate_map,
1934 module_children: self.module_children,
1935 ambig_module_children: self.ambig_module_children,
1936 glob_map,
1937 maybe_unused_trait_imports,
1938 main_def,
1939 trait_impls: self.trait_impls,
1940 proc_macros,
1941 confused_type_with_std_module,
1942 doc_link_resolutions: self.doc_link_resolutions,
1943 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1944 all_macro_rules: self.all_macro_rules,
1945 stripped_cfg_items,
1946 };
1947 let ast_lowering = ty::ResolverAstLowering {
1948 partial_res_map: self.partial_res_map,
1949 import_res_map: self.import_res_map,
1950 label_res_map: self.label_res_map,
1951 lifetimes_res_map: self.lifetimes_res_map,
1952 extra_lifetime_params_map: self.extra_lifetime_params_map,
1953 next_node_id: self.next_node_id,
1954 node_id_to_def_id: self.node_id_to_def_id,
1955 trait_map: self.trait_map,
1956 lifetime_elision_allowed: self.lifetime_elision_allowed,
1957 lint_buffer: Steal::new(self.lint_buffer),
1958 delegation_infos: self.delegation_infos,
1959 disambiguators,
1960 };
1961 ResolverOutputs { global_ctxt, ast_lowering }
1962 }
1963
1964 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1965 CStore::from_tcx(self.tcx)
1966 }
1967
1968 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1969 CStore::from_tcx_mut(self.tcx)
1970 }
1971
1972 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1973 match macro_kind {
1974 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1975 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1976 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1977 }
1978 }
1979
1980 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1985 CmResolver::new(self, !self.assert_speculative)
1986 }
1987
1988 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1990 f(self, TypeNS);
1991 f(self, ValueNS);
1992 f(self, MacroNS);
1993 }
1994
1995 fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
1996 mut self: CmResolver<'r, 'ra, 'tcx>,
1997 mut f: F,
1998 ) {
1999 f(self.reborrow(), TypeNS);
2000 f(self.reborrow(), ValueNS);
2001 f(self, MacroNS);
2002 }
2003
2004 fn is_builtin_macro(&self, res: Res) -> bool {
2005 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
2006 }
2007
2008 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2009 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name == Some(symbol))
2010 }
2011
2012 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2013 loop {
2014 match ctxt.outer_expn_data().macro_def_id {
2015 Some(def_id) => return def_id,
2016 None => ctxt.remove_mark(),
2017 };
2018 }
2019 }
2020
2021 pub fn resolve_crate(&mut self, krate: &Crate) {
2023 self.tcx.sess.time("resolve_crate", || {
2024 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2025 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2026 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2027 });
2028 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2029 self.tcx
2030 .sess
2031 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2032 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2033 self.tcx.sess.time("resolve_main", || self.resolve_main());
2034 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
2035 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
2036 self.tcx
2037 .sess
2038 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2039 });
2040
2041 self.tcx.untracked().cstore.freeze();
2043 }
2044
2045 fn traits_in_scope(
2046 &mut self,
2047 current_trait: Option<Module<'ra>>,
2048 parent_scope: &ParentScope<'ra>,
2049 sp: Span,
2050 assoc_item: Option<(Symbol, Namespace)>,
2051 ) -> &'tcx [TraitCandidate<'tcx>] {
2052 let mut found_traits = Vec::new();
2053
2054 if let Some(module) = current_trait {
2055 if self.trait_may_have_item(Some(module), assoc_item) {
2056 let def_id = module.def_id();
2057 found_traits.push(TraitCandidate {
2058 def_id,
2059 import_ids: &[],
2060 lint_ambiguous: false,
2061 });
2062 }
2063 }
2064
2065 let scope_set = ScopeSet::All(TypeNS);
2066 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2067 self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2068 match scope {
2069 Scope::ModuleNonGlobs(module, _) => {
2070 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2071 }
2072 Scope::ModuleGlobs(..) => {
2073 }
2075 Scope::StdLibPrelude => {
2076 if let Some(module) = this.prelude {
2077 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2078 }
2079 }
2080 Scope::ExternPreludeItems
2081 | Scope::ExternPreludeFlags
2082 | Scope::ToolPrelude
2083 | Scope::BuiltinTypes => {}
2084 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2085 }
2086 ControlFlow::<()>::Continue(())
2087 });
2088
2089 self.tcx.hir_arena.alloc_slice(&found_traits)
2090 }
2091
2092 fn traits_in_module(
2093 &mut self,
2094 module: Module<'ra>,
2095 assoc_item: Option<(Symbol, Namespace)>,
2096 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2097 ) {
2098 module.ensure_traits(self);
2099 let traits = module.traits.borrow();
2100 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2101 traits.as_ref().unwrap().iter()
2102 {
2103 if self.trait_may_have_item(trait_module, assoc_item) {
2104 let def_id = trait_binding.res().def_id();
2105 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2106 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2107 }
2108 }
2109 }
2110
2111 fn trait_may_have_item(
2117 &self,
2118 trait_module: Option<Module<'ra>>,
2119 assoc_item: Option<(Symbol, Namespace)>,
2120 ) -> bool {
2121 match (trait_module, assoc_item) {
2122 (Some(trait_module), Some((name, ns))) => self
2123 .resolutions(trait_module)
2124 .borrow()
2125 .iter()
2126 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2127 _ => true,
2128 }
2129 }
2130
2131 fn find_transitive_imports(
2132 &mut self,
2133 mut kind: &DeclKind<'_>,
2134 trait_name: Symbol,
2135 ) -> &'tcx [LocalDefId] {
2136 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2137 while let DeclKind::Import { import, source_decl, .. } = kind {
2138 if let Some(node_id) = import.id() {
2139 let def_id = self.local_def_id(node_id);
2140 self.maybe_unused_trait_imports.insert(def_id);
2141 import_ids.push(def_id);
2142 }
2143 self.add_to_glob_map(*import, trait_name);
2144 kind = &source_decl.kind;
2145 }
2146
2147 self.tcx.hir_arena.alloc_slice(&import_ids)
2148 }
2149
2150 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2151 if module.populate_on_access.get() {
2152 module.populate_on_access.set(false);
2153 self.build_reduced_graph_external(module.expect_extern());
2154 }
2155 &module.0.0.lazy_resolutions
2156 }
2157
2158 fn resolution(
2159 &self,
2160 module: Module<'ra>,
2161 key: BindingKey,
2162 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2163 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2164 }
2165
2166 fn resolution_or_default(
2167 &self,
2168 module: Module<'ra>,
2169 key: BindingKey,
2170 orig_ident_span: Span,
2171 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2172 self.resolutions(module)
2173 .borrow_mut_unchecked()
2174 .entry(key)
2175 .or_insert_with(|| self.arenas.alloc_name_resolution(orig_ident_span))
2176 }
2177
2178 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2180 for ambiguity_error in &self.ambiguity_errors {
2181 if ambiguity_error.kind == ambi.kind
2183 && ambiguity_error.ident == ambi.ident
2184 && ambiguity_error.ident.span == ambi.ident.span
2185 && ambiguity_error.b1.span == ambi.b1.span
2186 && ambiguity_error.b2.span == ambi.b2.span
2187 {
2188 return true;
2189 }
2190 }
2191 false
2192 }
2193
2194 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2195 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2196 }
2197
2198 fn record_use_inner(
2199 &mut self,
2200 ident: Ident,
2201 used_decl: Decl<'ra>,
2202 used: Used,
2203 warn_ambiguity: bool,
2204 ) {
2205 if let Some(b2) = used_decl.ambiguity.get() {
2206 let ambiguity_error = AmbiguityError {
2207 kind: AmbiguityKind::GlobVsGlob,
2208 ambig_vis: None,
2209 ident,
2210 b1: used_decl,
2211 b2,
2212 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2213 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2214 warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
2215 };
2216 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2217 self.ambiguity_errors.push(ambiguity_error);
2219 }
2220 }
2221 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2222 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2223 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2226 let empty_module = self.empty_module.to_module();
2227 let arenas = self.arenas;
2228 self.cm()
2229 .maybe_resolve_ident_in_module(
2230 ModuleOrUniformRoot::Module(prelude),
2231 ident,
2232 MacroNS,
2233 &ParentScope::module(empty_module, arenas),
2234 None,
2235 )
2236 .is_ok()
2237 });
2238 if !found_in_stdlib_prelude {
2239 self.lint_buffer().buffer_lint(
2240 PRIVATE_MACRO_USE,
2241 import.root_id,
2242 ident.span,
2243 errors::MacroIsPrivate { ident },
2244 );
2245 }
2246 }
2247 if used == Used::Scope
2250 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2251 && let Some((item_decl, _, false)) = entry.item_decl
2252 && item_decl == used_decl
2253 {
2254 return;
2255 }
2256 let old_used = self.import_use_map.entry(import).or_insert(used);
2257 if *old_used < used {
2258 *old_used = used;
2259 }
2260 if let Some(id) = import.id() {
2261 self.used_imports.insert(id);
2262 }
2263 self.add_to_glob_map(import, ident.name);
2264 self.record_use_inner(
2265 ident,
2266 source_decl,
2267 Used::Other,
2268 warn_ambiguity || source_decl.warn_ambiguity.get(),
2269 );
2270 }
2271 }
2272
2273 #[inline]
2274 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2275 if let ImportKind::Glob { id, .. } = import.kind {
2276 let def_id = self.local_def_id(id);
2277 self.glob_map.entry(def_id).or_default().insert(name);
2278 }
2279 }
2280
2281 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2282 {
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:2282",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2282u32),
::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);
2283 let mut ctxt = ident.span.ctxt();
2284 let mark = if ident.name == kw::DollarCrate {
2285 ctxt = ctxt.normalize_to_macro_rules();
2292 {
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:2292",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2292u32),
::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!(
2293 "resolve_crate_root: marks={:?}",
2294 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2295 );
2296 let mut iter = ctxt.marks().into_iter().rev().peekable();
2297 let mut result = None;
2298 while let Some(&(mark, transparency)) = iter.peek() {
2300 if transparency == Transparency::Opaque {
2301 result = Some(mark);
2302 iter.next();
2303 } else {
2304 break;
2305 }
2306 }
2307 {
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:2307",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2307u32),
::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!(
2308 "resolve_crate_root: found opaque mark {:?} {:?}",
2309 result,
2310 result.map(|r| r.expn_data())
2311 );
2312 for (mark, transparency) in iter {
2314 if transparency == Transparency::SemiOpaque {
2315 result = Some(mark);
2316 } else {
2317 break;
2318 }
2319 }
2320 {
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:2320",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2320u32),
::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!(
2321 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2322 result,
2323 result.map(|r| r.expn_data())
2324 );
2325 result
2326 } else {
2327 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2327",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2327u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
as &dyn Value))])
});
} else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2328 ctxt = ctxt.normalize_to_macros_2_0();
2329 ctxt.adjust(ExpnId::root())
2330 };
2331 let module = match mark {
2332 Some(def) => self.expn_def_scope(def),
2333 None => {
2334 {
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:2334",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2334u32),
::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!(
2335 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2336 ident, ident.span
2337 );
2338 return self.graph_root.to_module();
2339 }
2340 };
2341 let module = self.expect_module(
2342 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2343 );
2344 {
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:2344",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2344u32),
::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!(
2345 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2346 ident,
2347 module,
2348 module.kind.name(),
2349 ident.span
2350 );
2351 module
2352 }
2353
2354 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2355 let mut module = self.expect_module(module.nearest_parent_mod());
2356 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2357 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2358 module = self.expect_module(parent.nearest_parent_mod());
2359 }
2360 module
2361 }
2362
2363 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2364 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2364",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2364u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
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);
2365 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2366 {
::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)");
2367 }
2368 }
2369
2370 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2371 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2371",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2371u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
node, span) as &dyn Value))])
});
} else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2372 self.pat_span_map.insert(node, span);
2373 }
2374
2375 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2376 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2377 }
2378
2379 fn disambiguate_macro_rules_vs_modularized(
2380 &self,
2381 macro_rules: Decl<'ra>,
2382 modularized: Decl<'ra>,
2383 ) -> bool {
2384 let macro_rules = macro_rules.parent_module.unwrap();
2392 let modularized = modularized.parent_module.unwrap();
2393 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2394 && modularized.is_ancestor_of(macro_rules)
2395 }
2396
2397 fn extern_prelude_get_item<'r>(
2398 mut self: CmResolver<'r, 'ra, 'tcx>,
2399 ident: IdentKey,
2400 orig_ident_span: Span,
2401 finalize: bool,
2402 ) -> Option<Decl<'ra>> {
2403 let entry = self.extern_prelude.get(&ident);
2404 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2405 if finalize {
2406 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2407 }
2408 decl
2409 })
2410 }
2411
2412 fn extern_prelude_get_flag(
2413 &self,
2414 ident: IdentKey,
2415 orig_ident_span: Span,
2416 finalize: bool,
2417 ) -> Option<Decl<'ra>> {
2418 let entry = self.extern_prelude.get(&ident);
2419 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2420 let (pending_decl, finalized, is_open) = flag_decl.get();
2421 let decl = match pending_decl {
2422 PendingDecl::Ready(decl) => {
2423 if finalize && !finalized && !is_open {
2424 self.cstore_mut().process_path_extern(
2425 self.tcx,
2426 ident.name,
2427 orig_ident_span,
2428 );
2429 }
2430 decl
2431 }
2432 PendingDecl::Pending => {
2433 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2434 if is_open {
2435 let res = Res::OpenMod(ident.name);
2436 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2437 } else {
2438 let crate_id = if finalize {
2439 self.cstore_mut().process_path_extern(
2440 self.tcx,
2441 ident.name,
2442 orig_ident_span,
2443 )
2444 } else {
2445 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2446 };
2447 crate_id.map(|crate_id| {
2448 let def_id = crate_id.as_def_id();
2449 let res = Res::Def(DefKind::Mod, def_id);
2450 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2451 })
2452 }
2453 }
2454 };
2455 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2456 decl.or_else(|| finalize.then_some(self.dummy_decl))
2457 })
2458 }
2459
2460 fn resolve_rustdoc_path(
2465 &mut self,
2466 path_str: &str,
2467 ns: Namespace,
2468 parent_scope: ParentScope<'ra>,
2469 ) -> Option<Res> {
2470 let segments: Result<Vec<_>, ()> = path_str
2471 .split("::")
2472 .enumerate()
2473 .map(|(i, s)| {
2474 let sym = if s.is_empty() {
2475 if i == 0 {
2476 kw::PathRoot
2478 } else {
2479 return Err(()); }
2481 } else {
2482 Symbol::intern(s)
2483 };
2484 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2485 })
2486 .collect();
2487 let Ok(segments) = segments else { return None };
2488
2489 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2490 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2491 PathResult::NonModule(path_res) => {
2492 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(..), _)))
2493 }
2494 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2495 None
2496 }
2497 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2498 ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
path_result))bug!("got invalid path_result: {path_result:?}")
2499 }
2500 }
2501 }
2502
2503 fn def_span(&self, def_id: DefId) -> Span {
2505 match def_id.as_local() {
2506 Some(def_id) => self.tcx.source_span(def_id),
2507 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2509 }
2510 }
2511
2512 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2513 match def_id.as_local() {
2514 Some(def_id) => self.field_names.get(&def_id).cloned(),
2515 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2516 self.tcx.def_kind(def_id),
2517 DefKind::Struct | DefKind::Union | DefKind::Variant
2518 ) =>
2519 {
2520 Some(
2521 self.tcx
2522 .associated_item_def_ids(def_id)
2523 .iter()
2524 .map(|&def_id| {
2525 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2526 })
2527 .collect(),
2528 )
2529 }
2530 _ => None,
2531 }
2532 }
2533
2534 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2535 match def_id.as_local() {
2536 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2537 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2538 self.tcx.def_kind(def_id),
2539 DefKind::Struct | DefKind::Union | DefKind::Variant
2540 ) =>
2541 {
2542 Some(
2543 self.tcx
2544 .associated_item_def_ids(def_id)
2545 .iter()
2546 .filter_map(|&def_id| {
2547 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2548 })
2549 .collect(),
2550 )
2551 }
2552 _ => None,
2553 }
2554 }
2555
2556 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2560 let ExprKind::Path(None, path) = &expr.kind else {
2561 return None;
2562 };
2563 if path.segments.last().unwrap().args.is_some() {
2566 return None;
2567 }
2568
2569 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2570
2571 if def_id.is_local() {
2575 return None;
2576 }
2577
2578 {
{
'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!(
2579 self.tcx, def_id,
2581 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2582 )
2583 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2584 }
2585
2586 fn resolve_main(&mut self) {
2587 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2588 if !any_exe {
2590 return;
2591 }
2592
2593 let module = self.graph_root.to_module();
2594 let ident = Ident::with_dummy_span(sym::main);
2595 let parent_scope = &ParentScope::module(module, self.arenas);
2596
2597 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2598 ModuleOrUniformRoot::Module(module),
2599 ident,
2600 ValueNS,
2601 parent_scope,
2602 None,
2603 ) else {
2604 return;
2605 };
2606
2607 let res = name_binding.res();
2608 let is_import = name_binding.is_import();
2609 let span = name_binding.span;
2610 if let Res::Def(DefKind::Fn, _) = res {
2611 self.record_use(ident, name_binding, Used::Other);
2612 }
2613 self.main_def = Some(MainDefinition { res, is_import, span });
2614 }
2615}
2616
2617fn build_extern_prelude<'tcx, 'ra>(
2618 tcx: TyCtxt<'tcx>,
2619 attrs: &[ast::Attribute],
2620) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2621 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2622 .sess
2623 .opts
2624 .externs
2625 .iter()
2626 .filter_map(|(name, entry)| {
2627 if entry.add_prelude
2630 && let sym = Symbol::intern(name)
2631 && sym.can_be_raw()
2632 {
2633 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2634 } else {
2635 None
2636 }
2637 })
2638 .collect();
2639
2640 let missing_open_bases: Vec<IdentKey> = extern_prelude
2646 .keys()
2647 .filter_map(|ident| {
2648 let (base, _) = ident.name.as_str().split_once("::")?;
2649 let base_sym = Symbol::intern(base);
2650 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2651 })
2652 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2653 .collect();
2654
2655 extern_prelude.extend(
2656 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2657 );
2658
2659 if !attr::contains_name(attrs, sym::no_core) {
2661 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2662
2663 if !attr::contains_name(attrs, sym::no_std) {
2664 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2665 }
2666 }
2667
2668 extern_prelude
2669}
2670
2671fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2672 let mut result = String::new();
2673 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2674 if i > 0 {
2675 result.push_str("::");
2676 }
2677 if Ident::with_dummy_span(name).is_raw_guess() {
2678 result.push_str("r#");
2679 }
2680 result.push_str(name.as_str());
2681 }
2682 result
2683}
2684
2685fn path_names_to_string(path: &Path) -> String {
2686 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2687}
2688
2689fn module_to_string(mut module: Module<'_>) -> Option<String> {
2691 let mut names = Vec::new();
2692 loop {
2693 if let ModuleKind::Def(.., name) = module.kind {
2694 if let Some(parent) = module.parent {
2695 names.push(name.unwrap());
2697 module = parent
2698 } else {
2699 break;
2700 }
2701 } else {
2702 names.push(sym::opaque_module_name_placeholder);
2703 let Some(parent) = module.parent else {
2704 return None;
2705 };
2706 module = parent;
2707 }
2708 }
2709 if names.is_empty() {
2710 return None;
2711 }
2712 Some(names_to_string(names.iter().rev().copied()))
2713}
2714
2715#[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)]
2716enum Stage {
2717 Early,
2721 Late,
2724}
2725
2726#[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)]
2729struct ImportSummary {
2730 vis: Visibility,
2731 nearest_parent_mod: LocalDefId,
2732 is_single: bool,
2733}
2734
2735#[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)]
2737struct Finalize {
2738 node_id: NodeId,
2740 path_span: Span,
2743 root_span: Span,
2746 report_private: bool = true,
2749 used: Used = Used::Other,
2751 stage: Stage = Stage::Early,
2753 import: Option<ImportSummary> = None,
2755}
2756
2757impl Finalize {
2758 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2759 Finalize::with_root_span(node_id, path_span, path_span)
2760 }
2761
2762 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2763 Finalize { node_id, path_span, root_span, .. }
2764 }
2765}
2766
2767pub fn provide(providers: &mut Providers) {
2768 providers.registered_tools = macros::registered_tools;
2769}
2770
2771type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2777
2778use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2782
2783mod ref_mut {
2786 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2787 use std::fmt;
2788 use std::ops::Deref;
2789
2790 use crate::Resolver;
2791
2792 pub(crate) struct RefOrMut<'a, T> {
2794 p: &'a mut T,
2795 mutable: bool,
2796 }
2797
2798 impl<'a, T> Deref for RefOrMut<'a, T> {
2799 type Target = T;
2800
2801 fn deref(&self) -> &Self::Target {
2802 self.p
2803 }
2804 }
2805
2806 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2807 fn as_ref(&self) -> &T {
2808 self.p
2809 }
2810 }
2811
2812 impl<'a, T> RefOrMut<'a, T> {
2813 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2814 RefOrMut { p, mutable }
2815 }
2816
2817 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2819 RefOrMut { p: self.p, mutable: self.mutable }
2820 }
2821
2822 #[track_caller]
2827 pub(crate) fn get_mut(&mut self) -> &mut T {
2828 match self.mutable {
2829 false => {
::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2830 true => self.p,
2831 }
2832 }
2833
2834 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2837 self.p
2838 }
2839 }
2840
2841 #[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)]
2843 pub(crate) struct CmCell<T>(Cell<T>);
2844
2845 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2846 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2847 f.debug_tuple("CmCell").field(&self.get()).finish()
2848 }
2849 }
2850
2851 impl<T: Copy> Clone for CmCell<T> {
2852 fn clone(&self) -> CmCell<T> {
2853 CmCell::new(self.get())
2854 }
2855 }
2856
2857 impl<T: Copy> CmCell<T> {
2858 pub(crate) const fn get(&self) -> T {
2859 self.0.get()
2860 }
2861
2862 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2863 where
2864 T: Copy,
2865 {
2866 let old = self.get();
2867 self.set_unchecked(f(old));
2868 }
2869 }
2870
2871 impl<T> CmCell<T> {
2872 pub(crate) const fn new(value: T) -> CmCell<T> {
2873 CmCell(Cell::new(value))
2874 }
2875
2876 pub(crate) fn set_unchecked(&self, val: T) {
2877 self.0.set(val);
2878 }
2879
2880 pub(crate) fn into_inner(self) -> T {
2881 self.0.into_inner()
2882 }
2883 }
2884
2885 #[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)]
2887 pub(crate) struct CmRefCell<T>(RefCell<T>);
2888
2889 impl<T> CmRefCell<T> {
2890 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2891 CmRefCell(RefCell::new(value))
2892 }
2893
2894 #[track_caller]
2895 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2896 self.0.borrow_mut()
2897 }
2898
2899 #[track_caller]
2900 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2901 if r.assert_speculative {
2902 {
::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");
2903 }
2904 self.borrow_mut_unchecked()
2905 }
2906
2907 #[track_caller]
2908 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2909 self.0.try_borrow_mut()
2910 }
2911
2912 #[track_caller]
2913 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2914 self.0.borrow()
2915 }
2916 }
2917
2918 impl<T: Default> CmRefCell<T> {
2919 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2920 if r.assert_speculative {
2921 {
::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");
2922 }
2923 self.0.take()
2924 }
2925 }
2926}
2927
2928mod hygiene {
2929 use rustc_span::{ExpnId, SyntaxContext};
2930
2931 #[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)]
2934 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2935
2936 impl Macros20NormalizedSyntaxContext {
2937 #[inline]
2938 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2939 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2940 }
2941
2942 #[inline]
2943 pub(crate) fn new_adjusted(
2944 mut ctxt: SyntaxContext,
2945 expn_id: ExpnId,
2946 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2947 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2948 (Macros20NormalizedSyntaxContext(ctxt), def)
2949 }
2950
2951 #[inline]
2952 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2953 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());
2954 Macros20NormalizedSyntaxContext(ctxt)
2955 }
2956
2957 #[inline]
2959 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2960 let ret = f(&mut self.0);
2961 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());
2962 ret
2963 }
2964 }
2965
2966 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
2967 type Target = SyntaxContext;
2968 fn deref(&self) -> &Self::Target {
2969 &self.0
2970 }
2971 }
2972}