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, 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::DisambiguatorState;
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, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
70 ResolverGlobalCtxt, 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::SelfImportsOnlyAllowedWithin {
root: __self_0, span_with_rename: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SelfImportsOnlyAllowedWithin", "root", __self_0,
"span_with_rename", &__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_ogca: __self_0, name: __self_1, param_kind: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ParamInNonTrivialAnonConst", "is_ogca", __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 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
275 FailedToResolve {
277 segment: Symbol,
278 label: String,
279 suggestion: Option<Suggestion>,
280 module: Option<ModuleOrUniformRoot<'ra>>,
281 message: String,
282 },
283 CannotCaptureDynamicEnvironmentInFnItem,
285 AttemptToUseNonConstantValueInConstant {
287 ident: Ident,
288 suggestion: &'static str,
289 current: &'static str,
290 type_span: Option<Span>,
291 },
292 BindingShadowsSomethingUnacceptable {
294 shadowing_binding: PatternSource,
295 name: Symbol,
296 participle: &'static str,
297 article: &'static str,
298 shadowed_binding: Res,
299 shadowed_binding_span: Span,
300 },
301 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
303 ParamInTyOfConstParam { name: Symbol },
307 ParamInNonTrivialAnonConst {
311 is_ogca: bool,
312 name: Symbol,
313 param_kind: ParamKindInNonTrivialAnonConst,
314 },
315 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
319 ForwardDeclaredSelf(ForwardGenericParamBanReason),
321 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
323 TraitImplMismatch {
325 name: Ident,
326 kind: &'static str,
327 trait_path: String,
328 trait_item_span: Span,
329 code: ErrCode,
330 },
331 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
333 InvalidAsmSym,
335 LowercaseSelf,
337 BindingInNeverPattern,
339}
340
341enum VisResolutionError<'a> {
342 Relative2018(Span, &'a ast::Path),
343 AncestorOnly(Span),
344 FailedToResolve(Span, Symbol, String, Option<Suggestion>, String),
345 ExpectedFound(Span, String, Res),
346 Indeterminate(Span),
347 ModuleOnly(Span),
348}
349
350#[derive(#[automatically_derived]
impl ::core::clone::Clone for Segment {
#[inline]
fn clone(&self) -> Segment {
let _: ::core::clone::AssertParamIsClone<Ident>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Segment { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Segment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f, "Segment",
"ident", &self.ident, "id", &self.id, "has_generic_args",
&self.has_generic_args, "has_lifetime_args",
&self.has_lifetime_args, "args_span", &&self.args_span)
}
}Debug)]
353struct Segment {
354 ident: Ident,
355 id: Option<NodeId>,
356 has_generic_args: bool,
359 has_lifetime_args: bool,
361 args_span: Span,
362}
363
364impl Segment {
365 fn from_path(path: &Path) -> Vec<Segment> {
366 path.segments.iter().map(|s| s.into()).collect()
367 }
368
369 fn from_ident(ident: Ident) -> Segment {
370 Segment {
371 ident,
372 id: None,
373 has_generic_args: false,
374 has_lifetime_args: false,
375 args_span: DUMMY_SP,
376 }
377 }
378
379 fn names_to_string(segments: &[Segment]) -> String {
380 names_to_string(segments.iter().map(|seg| seg.ident.name))
381 }
382}
383
384impl<'a> From<&'a ast::PathSegment> for Segment {
385 fn from(seg: &'a ast::PathSegment) -> Segment {
386 let has_generic_args = seg.args.is_some();
387 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
388 match args {
389 GenericArgs::AngleBracketed(args) => {
390 let found_lifetimes = args
391 .args
392 .iter()
393 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
394 (args.span, found_lifetimes)
395 }
396 GenericArgs::Parenthesized(args) => (args.span, true),
397 GenericArgs::ParenthesizedElided(span) => (*span, true),
398 }
399 } else {
400 (DUMMY_SP, false)
401 };
402 Segment {
403 ident: seg.ident,
404 id: Some(seg.id),
405 has_generic_args,
406 has_lifetime_args,
407 args_span,
408 }
409 }
410}
411
412#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for LateDecl<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LateDecl::Decl(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Decl",
&__self_0),
LateDecl::RibDef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "RibDef",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LateDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for LateDecl<'ra> {
#[inline]
fn clone(&self) -> LateDecl<'ra> {
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Res>;
*self
}
}Clone)]
414enum LateDecl<'ra> {
415 Decl(Decl<'ra>),
417 RibDef(Res),
420}
421
422impl<'ra> LateDecl<'ra> {
423 fn res(self) -> Res {
424 match self {
425 LateDecl::Decl(binding) => binding.res(),
426 LateDecl::RibDef(res) => res,
427 }
428 }
429}
430
431#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ModuleOrUniformRoot<'ra> {
#[inline]
fn clone(&self) -> ModuleOrUniformRoot<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Symbol>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ModuleOrUniformRoot<'ra> {
#[inline]
fn eq(&self, other: &ModuleOrUniformRoot<'ra>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ModuleOrUniformRoot::Module(__self_0),
ModuleOrUniformRoot::Module(__arg1_0)) =>
__self_0 == __arg1_0,
(ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0),
ModuleOrUniformRoot::ModuleAndExternPrelude(__arg1_0)) =>
__self_0 == __arg1_0,
(ModuleOrUniformRoot::OpenModule(__self_0),
ModuleOrUniformRoot::OpenModule(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ModuleOrUniformRoot<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleOrUniformRoot::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ModuleAndExternPrelude", &__self_0),
ModuleOrUniformRoot::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
ModuleOrUniformRoot::CurrentScope =>
::core::fmt::Formatter::write_str(f, "CurrentScope"),
ModuleOrUniformRoot::OpenModule(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"OpenModule", &__self_0),
}
}
}Debug)]
432enum ModuleOrUniformRoot<'ra> {
433 Module(Module<'ra>),
435
436 ModuleAndExternPrelude(Module<'ra>),
440
441 ExternPrelude,
444
445 CurrentScope,
449
450 OpenModule(Symbol),
454}
455
456#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PathResult::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
PathResult::NonModule(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonModule", &__self_0),
PathResult::Indeterminate =>
::core::fmt::Formatter::write_str(f, "Indeterminate"),
PathResult::Failed {
span: __self_0,
label: __self_1,
suggestion: __self_2,
is_error_from_last_segment: __self_3,
module: __self_4,
segment_name: __self_5,
error_implied_by_parse_error: __self_6,
message: __self_7 } => {
let names: &'static _ =
&["span", "label", "suggestion",
"is_error_from_last_segment", "module", "segment_name",
"error_implied_by_parse_error", "message"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, __self_6, &__self_7];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Failed", names, values)
}
}
}
}Debug)]
457enum PathResult<'ra> {
458 Module(ModuleOrUniformRoot<'ra>),
459 NonModule(PartialRes),
460 Indeterminate,
461 Failed {
462 span: Span,
463 label: String,
464 suggestion: Option<Suggestion>,
465 is_error_from_last_segment: bool,
466 module: Option<ModuleOrUniformRoot<'ra>>,
480 segment_name: Symbol,
482 error_implied_by_parse_error: bool,
483 message: String,
484 },
485}
486
487impl<'ra> PathResult<'ra> {
488 fn failed(
489 ident: Ident,
490 is_error_from_last_segment: bool,
491 finalize: bool,
492 error_implied_by_parse_error: bool,
493 module: Option<ModuleOrUniformRoot<'ra>>,
494 label_and_suggestion: impl FnOnce() -> (String, String, Option<Suggestion>),
495 ) -> PathResult<'ra> {
496 let (message, label, suggestion) = if finalize {
497 label_and_suggestion()
498 } else {
499 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in this scope",
ident))
})format!("cannot find `{ident}` in this scope"), String::new(), None)
501 };
502 PathResult::Failed {
503 span: ident.span,
504 segment_name: ident.name,
505 label,
506 suggestion,
507 is_error_from_last_segment,
508 module,
509 error_implied_by_parse_error,
510 message,
511 }
512 }
513}
514
515#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleKind::Block =>
::core::fmt::Formatter::write_str(f, "Block"),
ModuleKind::Def(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f, "Def",
__self_0, __self_1, &__self_2),
}
}
}Debug)]
516enum ModuleKind {
517 Block,
530 Def(DefKind, DefId, Option<Symbol>),
540}
541
542impl ModuleKind {
543 fn name(&self) -> Option<Symbol> {
545 match *self {
546 ModuleKind::Block => None,
547 ModuleKind::Def(.., name) => name,
548 }
549 }
550
551 fn opt_def_id(&self) -> Option<DefId> {
552 match self {
553 ModuleKind::Def(_, def_id, _) => Some(*def_id),
554 _ => None,
555 }
556 }
557}
558
559#[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)]
570struct IdentKey {
571 name: Symbol,
572 ctxt: Macros20NormalizedSyntaxContext,
573}
574
575impl IdentKey {
576 #[inline]
577 fn new(ident: Ident) -> IdentKey {
578 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
579 }
580
581 #[inline]
582 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
583 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
584 (IdentKey { name: ident.name, ctxt }, def)
585 }
586
587 #[inline]
588 fn with_root_ctxt(name: Symbol) -> Self {
589 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
590 IdentKey { name, ctxt }
591 }
592
593 #[inline]
594 fn orig(self, orig_ident_span: Span) -> Ident {
595 Ident::new(self.name, orig_ident_span)
596 }
597}
598
599#[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)]
604struct BindingKey {
605 ident: IdentKey,
608 ns: Namespace,
609 disambiguator: u32,
615}
616
617impl BindingKey {
618 fn new(ident: IdentKey, ns: Namespace) -> Self {
619 BindingKey { ident, ns, disambiguator: 0 }
620 }
621
622 fn new_disambiguated(
623 ident: IdentKey,
624 ns: Namespace,
625 disambiguator: impl FnOnce() -> u32,
626 ) -> BindingKey {
627 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
628 BindingKey { ident, ns, disambiguator }
629 }
630}
631
632type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
633
634struct ModuleData<'ra> {
646 parent: Option<Module<'ra>>,
648 kind: ModuleKind,
650
651 lazy_resolutions: Resolutions<'ra>,
654 populate_on_access: CacheCell<bool>,
656 underscore_disambiguator: CmCell<u32>,
658
659 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
661
662 no_implicit_prelude: bool,
664
665 glob_importers: CmRefCell<Vec<Import<'ra>>>,
666 globs: CmRefCell<Vec<Import<'ra>>>,
667
668 traits: CmRefCell<
670 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
671 >,
672
673 span: Span,
675
676 expansion: ExpnId,
677
678 self_decl: Option<Decl<'ra>>,
681}
682
683#[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)]
686#[rustc_pass_by_value]
687struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
688
689impl std::hash::Hash for ModuleData<'_> {
694 fn hash<H>(&self, _: &mut H)
695 where
696 H: std::hash::Hasher,
697 {
698 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
699 }
700}
701
702impl<'ra> ModuleData<'ra> {
703 fn new(
704 parent: Option<Module<'ra>>,
705 kind: ModuleKind,
706 expansion: ExpnId,
707 span: Span,
708 no_implicit_prelude: bool,
709 self_decl: Option<Decl<'ra>>,
710 ) -> Self {
711 let is_foreign = match kind {
712 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
713 ModuleKind::Block => false,
714 };
715 ModuleData {
716 parent,
717 kind,
718 lazy_resolutions: Default::default(),
719 populate_on_access: CacheCell::new(is_foreign),
720 underscore_disambiguator: CmCell::new(0),
721 unexpanded_invocations: Default::default(),
722 no_implicit_prelude,
723 glob_importers: CmRefCell::new(Vec::new()),
724 globs: CmRefCell::new(Vec::new()),
725 traits: CmRefCell::new(None),
726 span,
727 expansion,
728 self_decl,
729 }
730 }
731}
732
733impl<'ra> Module<'ra> {
734 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
735 self,
736 resolver: &R,
737 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
738 ) {
739 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
740 let name_resolution = name_resolution.borrow();
741 if let Some(decl) = name_resolution.best_decl() {
742 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
743 }
744 }
745 }
746
747 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
748 self,
749 resolver: &mut R,
750 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
751 ) {
752 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
753 let name_resolution = name_resolution.borrow();
754 if let Some(decl) = name_resolution.best_decl() {
755 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
756 }
757 }
758 }
759
760 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
762 let mut traits = self.traits.borrow_mut(resolver.as_ref());
763 if traits.is_none() {
764 let mut collected_traits = Vec::new();
765 self.for_each_child(resolver, |r, ident, _, ns, binding| {
766 if ns != TypeNS {
767 return;
768 }
769 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
770 collected_traits.push((
771 ident.name,
772 binding,
773 r.as_ref().get_module(def_id),
774 binding.is_ambiguity_recursive(),
775 ));
776 }
777 });
778 *traits = Some(collected_traits.into_boxed_slice());
779 }
780 }
781
782 fn res(self) -> Option<Res> {
783 match self.kind {
784 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
785 _ => None,
786 }
787 }
788
789 fn def_id(self) -> DefId {
790 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
791 }
792
793 fn opt_def_id(self) -> Option<DefId> {
794 self.kind.opt_def_id()
795 }
796
797 fn is_normal(self) -> bool {
799 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Mod, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
800 }
801
802 fn is_trait(self) -> bool {
803 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Trait, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
804 }
805
806 fn nearest_item_scope(self) -> Module<'ra> {
807 match self.kind {
808 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
809 self.parent.expect("enum or trait module without a parent")
810 }
811 _ => self,
812 }
813 }
814
815 fn nearest_parent_mod(self) -> DefId {
818 match self.kind {
819 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
820 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
821 }
822 }
823
824 fn is_ancestor_of(self, mut other: Self) -> bool {
825 while self != other {
826 if let Some(parent) = other.parent {
827 other = parent;
828 } else {
829 return false;
830 }
831 }
832 true
833 }
834}
835
836impl<'ra> std::ops::Deref for Module<'ra> {
837 type Target = ModuleData<'ra>;
838
839 fn deref(&self) -> &Self::Target {
840 &self.0
841 }
842}
843
844impl<'ra> fmt::Debug for Module<'ra> {
845 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
846 match self.kind {
847 ModuleKind::Block => f.write_fmt(format_args!("block"))write!(f, "block"),
848 ModuleKind::Def(..) => f.write_fmt(format_args!("{0:?}", self.res()))write!(f, "{:?}", self.res()),
849 }
850 }
851}
852
853#[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),
vis: ::core::clone::Clone::clone(&self.vis),
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",
"vis", "parent_module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.ambiguity, &self.warn_ambiguity,
&self.expansion, &self.span, &self.vis,
&&self.parent_module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DeclData",
names, values)
}
}Debug)]
855struct DeclData<'ra> {
856 kind: DeclKind<'ra>,
857 ambiguity: CmCell<Option<Decl<'ra>>>,
858 warn_ambiguity: CmCell<bool>,
861 expansion: LocalExpnId,
862 span: Span,
863 vis: CmCell<Visibility<DefId>>,
864 parent_module: Option<Module<'ra>>,
865}
866
867type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
870
871impl std::hash::Hash for DeclData<'_> {
876 fn hash<H>(&self, _: &mut H)
877 where
878 H: std::hash::Hasher,
879 {
880 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
881 }
882}
883
884#[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)]
886enum DeclKind<'ra> {
887 Def(Res),
890 Import { source_decl: Decl<'ra>, import: Import<'ra> },
892}
893
894impl<'ra> DeclKind<'ra> {
895 fn is_import(&self) -> bool {
897 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
898 }
899}
900
901#[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)]
902struct PrivacyError<'ra> {
903 ident: Ident,
904 decl: Decl<'ra>,
905 dedup_span: Span,
906 outermost_res: Option<(Res, Ident)>,
907 parent_scope: ParentScope<'ra>,
908 single_nested: bool,
910 source: Option<ast::Expr>,
911}
912
913#[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)]
914struct UseError<'a> {
915 err: Diag<'a>,
916 candidates: Vec<ImportSuggestion>,
918 def_id: DefId,
920 instead: bool,
922 suggestion: Option<(Span, &'static str, String, Applicability)>,
924 path: Vec<Segment>,
927 is_call: bool,
929}
930
931#[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)]
932enum AmbiguityKind {
933 BuiltinAttr,
934 DeriveHelper,
935 MacroRulesVsModularized,
936 GlobVsOuter,
937 GlobVsGlob,
938 GlobVsExpanded,
939 MoreExpandedVsOuter,
940}
941
942impl AmbiguityKind {
943 fn descr(self) -> &'static str {
944 match self {
945 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
946 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
947 AmbiguityKind::MacroRulesVsModularized => {
948 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
949 }
950 AmbiguityKind::GlobVsOuter => {
951 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
952 }
953 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
954 AmbiguityKind::GlobVsExpanded => {
955 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
956 }
957 AmbiguityKind::MoreExpandedVsOuter => {
958 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
959 }
960 }
961 }
962}
963
964#[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)]
965enum AmbiguityWarning {
966 GlobImport,
967 PanicImport,
968}
969
970struct AmbiguityError<'ra> {
971 kind: AmbiguityKind,
972 ambig_vis: Option<(Visibility, Visibility)>,
973 ident: Ident,
974 b1: Decl<'ra>,
975 b2: Decl<'ra>,
976 scope1: Scope<'ra>,
977 scope2: Scope<'ra>,
978 warning: Option<AmbiguityWarning>,
979}
980
981impl<'ra> DeclData<'ra> {
982 fn vis(&self) -> Visibility<DefId> {
983 self.vis.get()
984 }
985
986 fn res(&self) -> Res {
987 match self.kind {
988 DeclKind::Def(res) => res,
989 DeclKind::Import { source_decl, .. } => source_decl.res(),
990 }
991 }
992
993 fn import_source(&self) -> Decl<'ra> {
994 match self.kind {
995 DeclKind::Import { source_decl, .. } => source_decl,
996 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
997 }
998 }
999
1000 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1001 match self.ambiguity.get() {
1002 Some(ambig_binding) => Some((self, ambig_binding)),
1003 None => match self.kind {
1004 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1005 _ => None,
1006 },
1007 }
1008 }
1009
1010 fn is_ambiguity_recursive(&self) -> bool {
1011 self.ambiguity.get().is_some()
1012 || match self.kind {
1013 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1014 _ => false,
1015 }
1016 }
1017
1018 fn warn_ambiguity_recursive(&self) -> bool {
1019 self.warn_ambiguity.get()
1020 || match self.kind {
1021 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
1022 _ => false,
1023 }
1024 }
1025
1026 fn is_possibly_imported_variant(&self) -> bool {
1027 match self.kind {
1028 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1029 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1030 true
1031 }
1032 DeclKind::Def(..) => false,
1033 }
1034 }
1035
1036 fn is_extern_crate(&self) -> bool {
1037 match self.kind {
1038 DeclKind::Import { import, .. } => {
1039 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1040 }
1041 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1042 _ => false,
1043 }
1044 }
1045
1046 fn is_import(&self) -> bool {
1047 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1048 }
1049
1050 fn is_import_user_facing(&self) -> bool {
1053 #[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, .. }
1054 if !matches!(import.kind, ImportKind::MacroExport))
1055 }
1056
1057 fn is_glob_import(&self) -> bool {
1058 match self.kind {
1059 DeclKind::Import { import, .. } => import.is_glob(),
1060 _ => false,
1061 }
1062 }
1063
1064 fn is_assoc_item(&self) -> bool {
1065 #[allow(non_exhaustive_omitted_patterns)] match self.res() {
Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy,
_) => true,
_ => false,
}matches!(
1066 self.res(),
1067 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy, _)
1068 )
1069 }
1070
1071 fn macro_kinds(&self) -> Option<MacroKinds> {
1072 self.res().macro_kinds()
1073 }
1074
1075 fn reexport_chain(self: Decl<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1076 let mut reexport_chain = SmallVec::new();
1077 let mut next_binding = self;
1078 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1079 reexport_chain.push(import.simplify(r));
1080 next_binding = source_decl;
1081 }
1082 reexport_chain
1083 }
1084
1085 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1092 let self_parent_expansion = self.expansion;
1096 let other_parent_expansion = decl.expansion;
1097 let certainly_before_other_or_simultaneously =
1098 other_parent_expansion.is_descendant_of(self_parent_expansion);
1099 let certainly_before_invoc_or_simultaneously =
1100 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1101 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1102 }
1103
1104 fn determined(&self) -> bool {
1108 match &self.kind {
1109 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1110 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1111 && source_decl.determined()
1112 }
1113 _ => true,
1114 }
1115 }
1116}
1117
1118#[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)]
1119struct ExternPreludeEntry<'ra> {
1120 item_decl: Option<(Decl<'ra>, Span, bool)>,
1124 flag_decl: Option<
1126 CacheCell<(
1127 PendingDecl<'ra>,
1128 bool,
1129 bool,
1130 )>,
1131 >,
1132}
1133
1134impl ExternPreludeEntry<'_> {
1135 fn introduced_by_item(&self) -> bool {
1136 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1137 }
1138
1139 fn flag() -> Self {
1140 ExternPreludeEntry {
1141 item_decl: None,
1142 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, false))),
1143 }
1144 }
1145
1146 fn open_flag() -> Self {
1147 ExternPreludeEntry {
1148 item_decl: None,
1149 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false, true))),
1150 }
1151 }
1152
1153 fn span(&self) -> Span {
1154 match self.item_decl {
1155 Some((_, span, _)) => span,
1156 None => DUMMY_SP,
1157 }
1158 }
1159}
1160
1161struct DeriveData {
1162 resolutions: Vec<DeriveResolution>,
1163 helper_attrs: Vec<(usize, IdentKey, Span)>,
1164 has_derive_copy: bool,
1165}
1166
1167struct MacroData {
1168 ext: Arc<SyntaxExtension>,
1169 nrules: usize,
1170 macro_rules: bool,
1171}
1172
1173impl MacroData {
1174 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1175 MacroData { ext, nrules: 0, macro_rules: false }
1176 }
1177}
1178
1179pub struct ResolverOutputs<'tcx> {
1180 pub global_ctxt: ResolverGlobalCtxt,
1181 pub ast_lowering: ResolverAstLowering<'tcx>,
1182}
1183
1184#[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)]
1185struct DelegationFnSig {
1186 pub has_self: bool,
1187}
1188
1189pub struct Resolver<'ra, 'tcx> {
1193 tcx: TyCtxt<'tcx>,
1194
1195 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1197
1198 graph_root: Module<'ra>,
1199
1200 assert_speculative: bool,
1202
1203 prelude: Option<Module<'ra>> = None,
1204 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1205
1206 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1208 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1209
1210 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1213
1214 determined_imports: Vec<Import<'ra>> = Vec::new(),
1216
1217 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1219
1220 pat_span_map: NodeMap<Span> = Default::default(),
1223
1224 partial_res_map: NodeMap<PartialRes> = Default::default(),
1226 import_res_map: NodeMap<PerNS<Option<Res>>> = Default::default(),
1228 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1230 label_res_map: NodeMap<NodeId> = Default::default(),
1232 lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
1234 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>> = Default::default(),
1236
1237 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1239 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1240 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1241 trait_map: NodeMap<&'tcx [TraitCandidate<'tcx>]> = Default::default(),
1242
1243 block_map: NodeMap<Module<'ra>> = Default::default(),
1258 empty_module: Module<'ra>,
1262 local_modules: Vec<Module<'ra>>,
1264 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1266 extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1268
1269 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1271 glob_error: Option<ErrorGuaranteed> = None,
1272 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1273 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1274 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1275
1276 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1278 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1280 issue_145575_hack_applied: bool = false,
1281 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1283 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1285
1286 inaccessible_ctor_reexport: FxHashMap<Span, Span> = default::fx_hash_map(),
1290
1291 arenas: &'ra ResolverArenas<'ra>,
1292 dummy_decl: Decl<'ra>,
1293 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1294 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1295 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1296 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1297 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1298 registered_tools: &'tcx RegisteredTools,
1299 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1300 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData> = default::fx_hash_map(),
1302 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1304 dummy_ext_bang: Arc<SyntaxExtension>,
1305 dummy_ext_derive: Arc<SyntaxExtension>,
1306 non_macro_attr: &'ra MacroData,
1307 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>> = default::fx_hash_map(),
1308 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>> = default::fx_hash_map(),
1309 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1310 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1312 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1313 single_segment_macro_resolutions:
1315 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1316 multi_segment_macro_resolutions:
1317 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1318 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1319 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1323 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1326 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1329 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1331 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1333 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1336
1337 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1339
1340 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1341
1342 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1343
1344 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)> = Default::default(),
1348
1349 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1352
1353 lint_buffer: LintBuffer,
1354
1355 next_node_id: NodeId = CRATE_NODE_ID,
1356
1357 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1358
1359 disambiguator: DisambiguatorState = DisambiguatorState::new(),
1360
1361 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1363 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1367
1368 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1370 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1372 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1373 delegation_infos: LocalDefIdMap<DelegationInfo> = Default::default(),
1374
1375 main_def: Option<MainDefinition> = None,
1376 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1377 proc_macros: Vec<LocalDefId> = Vec::new(),
1380 confused_type_with_std_module: FxIndexMap<Span, Span>,
1381 lifetime_elision_allowed: FxHashSet<NodeId> = default::fx_hash_set(),
1383
1384 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1386
1387 effective_visibilities: EffectiveVisibilities,
1388 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1389 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1390 all_macro_rules: UnordSet<Symbol> = Default::default(),
1391
1392 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1394 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1397 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1400
1401 current_crate_outer_attr_insert_span: Span,
1404
1405 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1406
1407 all_crate_macros_already_registered: bool = false,
1410
1411 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1415}
1416
1417#[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)]
1420pub struct ResolverArenas<'ra> {
1421 modules: TypedArena<ModuleData<'ra>>,
1422 imports: TypedArena<ImportData<'ra>>,
1423 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1424 ast_paths: TypedArena<ast::Path>,
1425 macros: TypedArena<MacroData>,
1426 dropless: DroplessArena,
1427}
1428
1429impl<'ra> ResolverArenas<'ra> {
1430 fn new_def_decl(
1431 &'ra self,
1432 res: Res,
1433 vis: Visibility<DefId>,
1434 span: Span,
1435 expansion: LocalExpnId,
1436 parent_module: Option<Module<'ra>>,
1437 ) -> Decl<'ra> {
1438 self.alloc_decl(DeclData {
1439 kind: DeclKind::Def(res),
1440 ambiguity: CmCell::new(None),
1441 warn_ambiguity: CmCell::new(false),
1442 vis: CmCell::new(vis),
1443 span,
1444 expansion,
1445 parent_module,
1446 })
1447 }
1448
1449 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1450 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1451 }
1452
1453 fn new_module(
1454 &'ra self,
1455 parent: Option<Module<'ra>>,
1456 kind: ModuleKind,
1457 vis: Visibility<DefId>,
1458 expn_id: ExpnId,
1459 span: Span,
1460 no_implicit_prelude: bool,
1461 ) -> Module<'ra> {
1462 let self_decl = match kind {
1463 ModuleKind::Def(def_kind, def_id, _) => Some(self.new_def_decl(
1464 Res::Def(def_kind, def_id),
1465 vis,
1466 span,
1467 LocalExpnId::ROOT,
1468 None,
1469 )),
1470 ModuleKind::Block => None,
1471 };
1472 Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1473 parent,
1474 kind,
1475 expn_id,
1476 span,
1477 no_implicit_prelude,
1478 self_decl,
1479 ))))
1480 }
1481 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1482 Interned::new_unchecked(self.dropless.alloc(data))
1483 }
1484 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1485 Interned::new_unchecked(self.imports.alloc(import))
1486 }
1487 fn alloc_name_resolution(
1488 &'ra self,
1489 orig_ident_span: Span,
1490 ) -> &'ra CmRefCell<NameResolution<'ra>> {
1491 self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))
1492 }
1493 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1494 self.dropless.alloc(CacheCell::new(scope))
1495 }
1496 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1497 self.dropless.alloc(decl)
1498 }
1499 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1500 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1501 }
1502 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1503 self.macros.alloc(macro_data)
1504 }
1505 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1506 self.dropless.alloc_from_iter(spans)
1507 }
1508}
1509
1510impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1511 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1512 self
1513 }
1514}
1515
1516impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1517 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1518 self
1519 }
1520}
1521
1522impl<'tcx> Resolver<'_, 'tcx> {
1523 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1524 self.opt_feed(node).map(|f| f.key())
1525 }
1526
1527 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1528 self.feed(node).key()
1529 }
1530
1531 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1532 self.node_id_to_def_id.get(&node).copied()
1533 }
1534
1535 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1536 self.opt_feed(node).unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
node));
}panic!("no entry for node id: `{node:?}`"))
1537 }
1538
1539 fn local_def_kind(&self, node: NodeId) -> DefKind {
1540 self.tcx.def_kind(self.local_def_id(node))
1541 }
1542
1543 fn create_def(
1545 &mut self,
1546 parent: LocalDefId,
1547 node_id: ast::NodeId,
1548 name: Option<Symbol>,
1549 def_kind: DefKind,
1550 expn_id: ExpnId,
1551 span: Span,
1552 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1553 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].key())));
}
};assert!(
1554 !self.node_id_to_def_id.contains_key(&node_id),
1555 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1556 node_id,
1557 name,
1558 def_kind,
1559 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1560 );
1561
1562 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1564 let def_id = feed.def_id();
1565
1566 if expn_id != ExpnId::root() {
1568 self.expn_that_defined.insert(def_id, expn_id);
1569 }
1570
1571 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);
1573 let _id = self.tcx.untracked().source_span.push(span);
1574 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);
1575
1576 if node_id != ast::DUMMY_NODE_ID {
1580 {
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:1580",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1580u32),
::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);
1581 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1582 }
1583
1584 feed
1585 }
1586
1587 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1588 if let Some(def_id) = def_id.as_local() {
1589 self.item_generics_num_lifetimes[&def_id]
1590 } else {
1591 self.tcx.generics_of(def_id).own_counts().lifetimes
1592 }
1593 }
1594
1595 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1596 if let Some(def_id) = def_id.as_local() {
1597 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1598 } else {
1599 let required = self
1600 .tcx
1601 .generics_of(def_id)
1602 .own_params
1603 .iter()
1604 .filter_map(|param| match param.kind {
1605 ty::GenericParamDefKind::Lifetime => Some("'_"),
1606 ty::GenericParamDefKind::Type { has_default, .. }
1607 | ty::GenericParamDefKind::Const { has_default } => {
1608 if has_default {
1609 None
1610 } else {
1611 Some("_")
1612 }
1613 }
1614 })
1615 .collect::<Vec<_>>();
1616
1617 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1618 }
1619 }
1620
1621 pub fn tcx(&self) -> TyCtxt<'tcx> {
1622 self.tcx
1623 }
1624
1625 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1630 self.node_id_to_def_id
1631 .items()
1632 .filter(|(_, v)| v.key() == def_id)
1633 .map(|(k, _)| *k)
1634 .get_only()
1635 .unwrap()
1636 }
1637}
1638
1639impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1640 pub fn new(
1641 tcx: TyCtxt<'tcx>,
1642 attrs: &[ast::Attribute],
1643 crate_span: Span,
1644 current_crate_outer_attr_insert_span: Span,
1645 arenas: &'ra ResolverArenas<'ra>,
1646 ) -> Resolver<'ra, 'tcx> {
1647 let root_def_id = CRATE_DEF_ID.to_def_id();
1648 let graph_root = arenas.new_module(
1649 None,
1650 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1651 Visibility::Public,
1652 ExpnId::root(),
1653 crate_span,
1654 attr::contains_name(attrs, sym::no_implicit_prelude),
1655 );
1656 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];
1657 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1658 let empty_module = arenas.new_module(
1659 None,
1660 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1661 Visibility::Public,
1662 ExpnId::root(),
1663 DUMMY_SP,
1664 true,
1665 );
1666
1667 let mut node_id_to_def_id = NodeMap::default();
1668 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1669
1670 crate_feed.def_kind(DefKind::Mod);
1671 let crate_feed = crate_feed.downgrade();
1672 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1673
1674 let mut invocation_parents = FxHashMap::default();
1675 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1676
1677 let extern_prelude = build_extern_prelude(tcx, attrs);
1678 let registered_tools = tcx.registered_tools(());
1679 let edition = tcx.sess.edition();
1680
1681 let mut resolver = Resolver {
1682 tcx,
1683
1684 graph_root,
1687 assert_speculative: false, extern_prelude,
1689
1690 empty_module,
1691 local_modules,
1692 local_module_map,
1693 extern_module_map: Default::default(),
1694
1695 glob_map: Default::default(),
1696 maybe_unused_trait_imports: Default::default(),
1697
1698 arenas,
1699 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1700 builtin_type_decls: PrimTy::ALL
1701 .iter()
1702 .map(|prim_ty| {
1703 let res = Res::PrimTy(*prim_ty);
1704 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1705 (prim_ty.name(), decl)
1706 })
1707 .collect(),
1708 builtin_attr_decls: BUILTIN_ATTRIBUTES
1709 .iter()
1710 .map(|builtin_attr| {
1711 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1712 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1713 (builtin_attr.name, decl)
1714 })
1715 .collect(),
1716 registered_tool_decls: registered_tools
1717 .iter()
1718 .map(|&ident| {
1719 let res = Res::ToolMod;
1720 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1721 (IdentKey::new(ident), decl)
1722 })
1723 .collect(),
1724 registered_tools,
1725 macro_use_prelude: Default::default(),
1726 extern_macro_map: Default::default(),
1727 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1728 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1729 non_macro_attr: arenas
1730 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1731 unused_macros: Default::default(),
1732 unused_macro_rules: Default::default(),
1733 single_segment_macro_resolutions: Default::default(),
1734 multi_segment_macro_resolutions: Default::default(),
1735 lint_buffer: LintBuffer::default(),
1736 node_id_to_def_id,
1737 invocation_parents,
1738 trait_impls: Default::default(),
1739 confused_type_with_std_module: Default::default(),
1740 stripped_cfg_items: Default::default(),
1741 effective_visibilities: Default::default(),
1742 doc_link_resolutions: Default::default(),
1743 doc_link_traits_in_scope: Default::default(),
1744 current_crate_outer_attr_insert_span,
1745 ..
1746 };
1747
1748 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1749 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1750 resolver.feed_visibility(crate_feed, Visibility::Public);
1751
1752 resolver
1753 }
1754
1755 fn new_local_module(
1756 &mut self,
1757 parent: Option<Module<'ra>>,
1758 kind: ModuleKind,
1759 expn_id: ExpnId,
1760 span: Span,
1761 no_implicit_prelude: bool,
1762 ) -> Module<'ra> {
1763 let vis =
1764 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1765 let module = self.arenas.new_module(parent, kind, vis, expn_id, span, no_implicit_prelude);
1766 self.local_modules.push(module);
1767 if let Some(def_id) = module.opt_def_id() {
1768 self.local_module_map.insert(def_id.expect_local(), module);
1769 }
1770 module
1771 }
1772
1773 fn new_extern_module(
1774 &self,
1775 parent: Option<Module<'ra>>,
1776 kind: ModuleKind,
1777 expn_id: ExpnId,
1778 span: Span,
1779 no_implicit_prelude: bool,
1780 ) -> Module<'ra> {
1781 let vis =
1782 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1783 let module = self.arenas.new_module(parent, kind, vis, expn_id, span, no_implicit_prelude);
1784 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1785 module
1786 }
1787
1788 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1789 let mac = self.arenas.alloc_macro(macro_data);
1790 self.local_macro_map.insert(def_id, mac);
1791 mac
1792 }
1793
1794 fn next_node_id(&mut self) -> NodeId {
1795 let start = self.next_node_id;
1796 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1797 self.next_node_id = ast::NodeId::from_u32(next);
1798 start
1799 }
1800
1801 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1802 let start = self.next_node_id;
1803 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1804 self.next_node_id = ast::NodeId::from_usize(end);
1805 start..self.next_node_id
1806 }
1807
1808 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1809 &mut self.lint_buffer
1810 }
1811
1812 pub fn arenas() -> ResolverArenas<'ra> {
1813 Default::default()
1814 }
1815
1816 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1817 let feed = feed.upgrade(self.tcx);
1818 feed.visibility(vis.to_def_id());
1819 self.visibilities_for_hashing.push((feed.def_id(), vis));
1820 }
1821
1822 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1823 let proc_macros = self.proc_macros;
1824 let expn_that_defined = self.expn_that_defined;
1825 let extern_crate_map = self.extern_crate_map;
1826 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1827 let glob_map = self.glob_map;
1828 let main_def = self.main_def;
1829 let confused_type_with_std_module = self.confused_type_with_std_module;
1830 let effective_visibilities = self.effective_visibilities;
1831
1832 let stripped_cfg_items = self
1833 .stripped_cfg_items
1834 .into_iter()
1835 .filter_map(|item| {
1836 let parent_scope =
1837 self.node_id_to_def_id.get(&item.parent_scope)?.key().to_def_id();
1838 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1839 })
1840 .collect();
1841
1842 let global_ctxt = ResolverGlobalCtxt {
1843 expn_that_defined,
1844 visibilities_for_hashing: self.visibilities_for_hashing,
1845 effective_visibilities,
1846 extern_crate_map,
1847 module_children: self.module_children,
1848 ambig_module_children: self.ambig_module_children,
1849 glob_map,
1850 maybe_unused_trait_imports,
1851 main_def,
1852 trait_impls: self.trait_impls,
1853 proc_macros,
1854 confused_type_with_std_module,
1855 doc_link_resolutions: self.doc_link_resolutions,
1856 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1857 all_macro_rules: self.all_macro_rules,
1858 stripped_cfg_items,
1859 };
1860 let ast_lowering = ty::ResolverAstLowering {
1861 partial_res_map: self.partial_res_map,
1862 import_res_map: self.import_res_map,
1863 label_res_map: self.label_res_map,
1864 lifetimes_res_map: self.lifetimes_res_map,
1865 extra_lifetime_params_map: self.extra_lifetime_params_map,
1866 next_node_id: self.next_node_id,
1867 node_id_to_def_id: self
1868 .node_id_to_def_id
1869 .into_items()
1870 .map(|(k, f)| (k, f.key()))
1871 .collect(),
1872 trait_map: self.trait_map,
1873 lifetime_elision_allowed: self.lifetime_elision_allowed,
1874 lint_buffer: Steal::new(self.lint_buffer),
1875 delegation_infos: self.delegation_infos,
1876 };
1877 ResolverOutputs { global_ctxt, ast_lowering }
1878 }
1879
1880 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1881 CStore::from_tcx(self.tcx)
1882 }
1883
1884 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1885 CStore::from_tcx_mut(self.tcx)
1886 }
1887
1888 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1889 match macro_kind {
1890 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1891 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1892 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1893 }
1894 }
1895
1896 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1901 CmResolver::new(self, !self.assert_speculative)
1902 }
1903
1904 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1906 f(self, TypeNS);
1907 f(self, ValueNS);
1908 f(self, MacroNS);
1909 }
1910
1911 fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
1912 mut self: CmResolver<'r, 'ra, 'tcx>,
1913 mut f: F,
1914 ) {
1915 f(self.reborrow(), TypeNS);
1916 f(self.reborrow(), ValueNS);
1917 f(self, MacroNS);
1918 }
1919
1920 fn is_builtin_macro(&self, res: Res) -> bool {
1921 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1922 }
1923
1924 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
1925 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name == Some(symbol))
1926 }
1927
1928 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1929 loop {
1930 match ctxt.outer_expn_data().macro_def_id {
1931 Some(def_id) => return def_id,
1932 None => ctxt.remove_mark(),
1933 };
1934 }
1935 }
1936
1937 pub fn resolve_crate(&mut self, krate: &Crate) {
1939 self.tcx.sess.time("resolve_crate", || {
1940 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1941 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1942 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1943 });
1944 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1945 self.tcx
1946 .sess
1947 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1948 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1949 self.tcx.sess.time("resolve_main", || self.resolve_main());
1950 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1951 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1952 self.tcx
1953 .sess
1954 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1955 });
1956
1957 self.tcx.untracked().cstore.freeze();
1959 }
1960
1961 fn traits_in_scope(
1962 &mut self,
1963 current_trait: Option<Module<'ra>>,
1964 parent_scope: &ParentScope<'ra>,
1965 sp: Span,
1966 assoc_item: Option<(Symbol, Namespace)>,
1967 ) -> &'tcx [TraitCandidate<'tcx>] {
1968 let mut found_traits = Vec::new();
1969
1970 if let Some(module) = current_trait {
1971 if self.trait_may_have_item(Some(module), assoc_item) {
1972 let def_id = module.def_id();
1973 found_traits.push(TraitCandidate {
1974 def_id,
1975 import_ids: &[],
1976 lint_ambiguous: false,
1977 });
1978 }
1979 }
1980
1981 let scope_set = ScopeSet::All(TypeNS);
1982 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1983 self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
1984 match scope {
1985 Scope::ModuleNonGlobs(module, _) => {
1986 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1987 }
1988 Scope::ModuleGlobs(..) => {
1989 }
1991 Scope::StdLibPrelude => {
1992 if let Some(module) = this.prelude {
1993 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1994 }
1995 }
1996 Scope::ExternPreludeItems
1997 | Scope::ExternPreludeFlags
1998 | Scope::ToolPrelude
1999 | Scope::BuiltinTypes => {}
2000 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2001 }
2002 ControlFlow::<()>::Continue(())
2003 });
2004
2005 self.tcx.hir_arena.alloc_slice(&found_traits)
2006 }
2007
2008 fn traits_in_module(
2009 &mut self,
2010 module: Module<'ra>,
2011 assoc_item: Option<(Symbol, Namespace)>,
2012 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2013 ) {
2014 module.ensure_traits(self);
2015 let traits = module.traits.borrow();
2016 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2017 traits.as_ref().unwrap().iter()
2018 {
2019 if self.trait_may_have_item(trait_module, assoc_item) {
2020 let def_id = trait_binding.res().def_id();
2021 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2022 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2023 }
2024 }
2025 }
2026
2027 fn trait_may_have_item(
2033 &self,
2034 trait_module: Option<Module<'ra>>,
2035 assoc_item: Option<(Symbol, Namespace)>,
2036 ) -> bool {
2037 match (trait_module, assoc_item) {
2038 (Some(trait_module), Some((name, ns))) => self
2039 .resolutions(trait_module)
2040 .borrow()
2041 .iter()
2042 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2043 _ => true,
2044 }
2045 }
2046
2047 fn find_transitive_imports(
2048 &mut self,
2049 mut kind: &DeclKind<'_>,
2050 trait_name: Symbol,
2051 ) -> &'tcx [LocalDefId] {
2052 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2053 while let DeclKind::Import { import, source_decl, .. } = kind {
2054 if let Some(node_id) = import.id() {
2055 let def_id = self.local_def_id(node_id);
2056 self.maybe_unused_trait_imports.insert(def_id);
2057 import_ids.push(def_id);
2058 }
2059 self.add_to_glob_map(*import, trait_name);
2060 kind = &source_decl.kind;
2061 }
2062
2063 self.tcx.hir_arena.alloc_slice(&import_ids)
2064 }
2065
2066 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2067 if module.populate_on_access.get() {
2068 module.populate_on_access.set(false);
2069 self.build_reduced_graph_external(module);
2070 }
2071 &module.0.0.lazy_resolutions
2072 }
2073
2074 fn resolution(
2075 &self,
2076 module: Module<'ra>,
2077 key: BindingKey,
2078 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2079 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2080 }
2081
2082 fn resolution_or_default(
2083 &self,
2084 module: Module<'ra>,
2085 key: BindingKey,
2086 orig_ident_span: Span,
2087 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2088 self.resolutions(module)
2089 .borrow_mut_unchecked()
2090 .entry(key)
2091 .or_insert_with(|| self.arenas.alloc_name_resolution(orig_ident_span))
2092 }
2093
2094 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2096 for ambiguity_error in &self.ambiguity_errors {
2097 if ambiguity_error.kind == ambi.kind
2099 && ambiguity_error.ident == ambi.ident
2100 && ambiguity_error.ident.span == ambi.ident.span
2101 && ambiguity_error.b1.span == ambi.b1.span
2102 && ambiguity_error.b2.span == ambi.b2.span
2103 {
2104 return true;
2105 }
2106 }
2107 false
2108 }
2109
2110 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2111 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2112 }
2113
2114 fn record_use_inner(
2115 &mut self,
2116 ident: Ident,
2117 used_decl: Decl<'ra>,
2118 used: Used,
2119 warn_ambiguity: bool,
2120 ) {
2121 if let Some(b2) = used_decl.ambiguity.get() {
2122 let ambiguity_error = AmbiguityError {
2123 kind: AmbiguityKind::GlobVsGlob,
2124 ambig_vis: None,
2125 ident,
2126 b1: used_decl,
2127 b2,
2128 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2129 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2130 warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
2131 };
2132 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2133 self.ambiguity_errors.push(ambiguity_error);
2135 }
2136 }
2137 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2138 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2139 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2142 let empty_module = self.empty_module;
2143 let arenas = self.arenas;
2144 self.cm()
2145 .maybe_resolve_ident_in_module(
2146 ModuleOrUniformRoot::Module(prelude),
2147 ident,
2148 MacroNS,
2149 &ParentScope::module(empty_module, arenas),
2150 None,
2151 )
2152 .is_ok()
2153 });
2154 if !found_in_stdlib_prelude {
2155 self.lint_buffer().buffer_lint(
2156 PRIVATE_MACRO_USE,
2157 import.root_id,
2158 ident.span,
2159 errors::MacroIsPrivate { ident },
2160 );
2161 }
2162 }
2163 if used == Used::Scope
2166 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2167 && let Some((item_decl, _, false)) = entry.item_decl
2168 && item_decl == used_decl
2169 {
2170 return;
2171 }
2172 let old_used = self.import_use_map.entry(import).or_insert(used);
2173 if *old_used < used {
2174 *old_used = used;
2175 }
2176 if let Some(id) = import.id() {
2177 self.used_imports.insert(id);
2178 }
2179 self.add_to_glob_map(import, ident.name);
2180 self.record_use_inner(
2181 ident,
2182 source_decl,
2183 Used::Other,
2184 warn_ambiguity || source_decl.warn_ambiguity.get(),
2185 );
2186 }
2187 }
2188
2189 #[inline]
2190 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2191 if let ImportKind::Glob { id, .. } = import.kind {
2192 let def_id = self.local_def_id(id);
2193 self.glob_map.entry(def_id).or_default().insert(name);
2194 }
2195 }
2196
2197 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2198 {
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:2198",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2198u32),
::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);
2199 let mut ctxt = ident.span.ctxt();
2200 let mark = if ident.name == kw::DollarCrate {
2201 ctxt = ctxt.normalize_to_macro_rules();
2208 {
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:2208",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2208u32),
::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!(
2209 "resolve_crate_root: marks={:?}",
2210 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2211 );
2212 let mut iter = ctxt.marks().into_iter().rev().peekable();
2213 let mut result = None;
2214 while let Some(&(mark, transparency)) = iter.peek() {
2216 if transparency == Transparency::Opaque {
2217 result = Some(mark);
2218 iter.next();
2219 } else {
2220 break;
2221 }
2222 }
2223 {
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:2223",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2223u32),
::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!(
2224 "resolve_crate_root: found opaque mark {:?} {:?}",
2225 result,
2226 result.map(|r| r.expn_data())
2227 );
2228 for (mark, transparency) in iter {
2230 if transparency == Transparency::SemiOpaque {
2231 result = Some(mark);
2232 } else {
2233 break;
2234 }
2235 }
2236 {
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:2236",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2236u32),
::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!(
2237 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2238 result,
2239 result.map(|r| r.expn_data())
2240 );
2241 result
2242 } else {
2243 {
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:2243",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2243u32),
::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");
2244 ctxt = ctxt.normalize_to_macros_2_0();
2245 ctxt.adjust(ExpnId::root())
2246 };
2247 let module = match mark {
2248 Some(def) => self.expn_def_scope(def),
2249 None => {
2250 {
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:2250",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2250u32),
::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!(
2251 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2252 ident, ident.span
2253 );
2254 return self.graph_root;
2255 }
2256 };
2257 let module = self.expect_module(
2258 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2259 );
2260 {
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:2260",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2260u32),
::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!(
2261 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2262 ident,
2263 module,
2264 module.kind.name(),
2265 ident.span
2266 );
2267 module
2268 }
2269
2270 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2271 let mut module = self.expect_module(module.nearest_parent_mod());
2272 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2273 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2274 module = self.expect_module(parent.nearest_parent_mod());
2275 }
2276 module
2277 }
2278
2279 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2280 {
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:2280",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2280u32),
::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);
2281 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2282 {
::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)");
2283 }
2284 }
2285
2286 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2287 {
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:2287",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2287u32),
::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);
2288 self.pat_span_map.insert(node, span);
2289 }
2290
2291 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2292 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2293 }
2294
2295 fn disambiguate_macro_rules_vs_modularized(
2296 &self,
2297 macro_rules: Decl<'ra>,
2298 modularized: Decl<'ra>,
2299 ) -> bool {
2300 let macro_rules = macro_rules.parent_module.unwrap();
2308 let modularized = modularized.parent_module.unwrap();
2309 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2310 && modularized.is_ancestor_of(macro_rules)
2311 }
2312
2313 fn extern_prelude_get_item<'r>(
2314 mut self: CmResolver<'r, 'ra, 'tcx>,
2315 ident: IdentKey,
2316 orig_ident_span: Span,
2317 finalize: bool,
2318 ) -> Option<Decl<'ra>> {
2319 let entry = self.extern_prelude.get(&ident);
2320 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2321 if finalize {
2322 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2323 }
2324 decl
2325 })
2326 }
2327
2328 fn extern_prelude_get_flag(
2329 &self,
2330 ident: IdentKey,
2331 orig_ident_span: Span,
2332 finalize: bool,
2333 ) -> Option<Decl<'ra>> {
2334 let entry = self.extern_prelude.get(&ident);
2335 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2336 let (pending_decl, finalized, is_open) = flag_decl.get();
2337 let decl = match pending_decl {
2338 PendingDecl::Ready(decl) => {
2339 if finalize && !finalized && !is_open {
2340 self.cstore_mut().process_path_extern(
2341 self.tcx,
2342 ident.name,
2343 orig_ident_span,
2344 );
2345 }
2346 decl
2347 }
2348 PendingDecl::Pending => {
2349 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2350 if is_open {
2351 let res = Res::OpenMod(ident.name);
2352 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2353 } else {
2354 let crate_id = if finalize {
2355 self.cstore_mut().process_path_extern(
2356 self.tcx,
2357 ident.name,
2358 orig_ident_span,
2359 )
2360 } else {
2361 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2362 };
2363 crate_id.map(|crate_id| {
2364 let def_id = crate_id.as_def_id();
2365 let res = Res::Def(DefKind::Mod, def_id);
2366 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2367 })
2368 }
2369 }
2370 };
2371 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized, is_open));
2372 decl.or_else(|| finalize.then_some(self.dummy_decl))
2373 })
2374 }
2375
2376 fn resolve_rustdoc_path(
2381 &mut self,
2382 path_str: &str,
2383 ns: Namespace,
2384 parent_scope: ParentScope<'ra>,
2385 ) -> Option<Res> {
2386 let segments: Result<Vec<_>, ()> = path_str
2387 .split("::")
2388 .enumerate()
2389 .map(|(i, s)| {
2390 let sym = if s.is_empty() {
2391 if i == 0 {
2392 kw::PathRoot
2394 } else {
2395 return Err(()); }
2397 } else {
2398 Symbol::intern(s)
2399 };
2400 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2401 })
2402 .collect();
2403 let Ok(segments) = segments else { return None };
2404
2405 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2406 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2407 PathResult::NonModule(path_res) => {
2408 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(..), _)))
2409 }
2410 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2411 None
2412 }
2413 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2414 ::rustc_middle::util::bug::bug_fmt(format_args!("got invalid path_result: {0:?}",
path_result))bug!("got invalid path_result: {path_result:?}")
2415 }
2416 }
2417 }
2418
2419 fn def_span(&self, def_id: DefId) -> Span {
2421 match def_id.as_local() {
2422 Some(def_id) => self.tcx.source_span(def_id),
2423 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2425 }
2426 }
2427
2428 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2429 match def_id.as_local() {
2430 Some(def_id) => self.field_names.get(&def_id).cloned(),
2431 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2432 self.tcx.def_kind(def_id),
2433 DefKind::Struct | DefKind::Union | DefKind::Variant
2434 ) =>
2435 {
2436 Some(
2437 self.tcx
2438 .associated_item_def_ids(def_id)
2439 .iter()
2440 .map(|&def_id| {
2441 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2442 })
2443 .collect(),
2444 )
2445 }
2446 _ => None,
2447 }
2448 }
2449
2450 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2451 match def_id.as_local() {
2452 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2453 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2454 self.tcx.def_kind(def_id),
2455 DefKind::Struct | DefKind::Union | DefKind::Variant
2456 ) =>
2457 {
2458 Some(
2459 self.tcx
2460 .associated_item_def_ids(def_id)
2461 .iter()
2462 .filter_map(|&def_id| {
2463 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2464 })
2465 .collect(),
2466 )
2467 }
2468 _ => None,
2469 }
2470 }
2471
2472 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2476 let ExprKind::Path(None, path) = &expr.kind else {
2477 return None;
2478 };
2479 if path.segments.last().unwrap().args.is_some() {
2482 return None;
2483 }
2484
2485 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2486
2487 if def_id.is_local() {
2491 return None;
2492 }
2493
2494 {
{
'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!(
2495 self.tcx, def_id,
2497 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2498 )
2499 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2500 }
2501
2502 fn resolve_main(&mut self) {
2503 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2504 if !any_exe {
2506 return;
2507 }
2508
2509 let module = self.graph_root;
2510 let ident = Ident::with_dummy_span(sym::main);
2511 let parent_scope = &ParentScope::module(module, self.arenas);
2512
2513 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2514 ModuleOrUniformRoot::Module(module),
2515 ident,
2516 ValueNS,
2517 parent_scope,
2518 None,
2519 ) else {
2520 return;
2521 };
2522
2523 let res = name_binding.res();
2524 let is_import = name_binding.is_import();
2525 let span = name_binding.span;
2526 if let Res::Def(DefKind::Fn, _) = res {
2527 self.record_use(ident, name_binding, Used::Other);
2528 }
2529 self.main_def = Some(MainDefinition { res, is_import, span });
2530 }
2531}
2532
2533fn build_extern_prelude<'tcx, 'ra>(
2534 tcx: TyCtxt<'tcx>,
2535 attrs: &[ast::Attribute],
2536) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2537 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2538 .sess
2539 .opts
2540 .externs
2541 .iter()
2542 .filter_map(|(name, entry)| {
2543 if entry.add_prelude
2546 && let sym = Symbol::intern(name)
2547 && sym.can_be_raw()
2548 {
2549 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2550 } else {
2551 None
2552 }
2553 })
2554 .collect();
2555
2556 let missing_open_bases: Vec<IdentKey> = extern_prelude
2562 .keys()
2563 .filter_map(|ident| {
2564 let (base, _) = ident.name.as_str().split_once("::")?;
2565 let base_sym = Symbol::intern(base);
2566 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2567 })
2568 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2569 .collect();
2570
2571 extern_prelude.extend(
2572 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2573 );
2574
2575 if !attr::contains_name(attrs, sym::no_core) {
2577 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2578
2579 if !attr::contains_name(attrs, sym::no_std) {
2580 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2581 }
2582 }
2583
2584 extern_prelude
2585}
2586
2587fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2588 let mut result = String::new();
2589 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2590 if i > 0 {
2591 result.push_str("::");
2592 }
2593 if Ident::with_dummy_span(name).is_raw_guess() {
2594 result.push_str("r#");
2595 }
2596 result.push_str(name.as_str());
2597 }
2598 result
2599}
2600
2601fn path_names_to_string(path: &Path) -> String {
2602 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2603}
2604
2605fn module_to_string(mut module: Module<'_>) -> Option<String> {
2607 let mut names = Vec::new();
2608 loop {
2609 if let ModuleKind::Def(.., name) = module.kind {
2610 if let Some(parent) = module.parent {
2611 names.push(name.unwrap());
2613 module = parent
2614 } else {
2615 break;
2616 }
2617 } else {
2618 names.push(sym::opaque_module_name_placeholder);
2619 let Some(parent) = module.parent else {
2620 return None;
2621 };
2622 module = parent;
2623 }
2624 }
2625 if names.is_empty() {
2626 return None;
2627 }
2628 Some(names_to_string(names.iter().rev().copied()))
2629}
2630
2631#[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)]
2632enum Stage {
2633 Early,
2637 Late,
2640}
2641
2642#[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<Visibility>>;
*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_vis"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.node_id, &self.path_span, &self.root_span,
&self.report_private, &self.used, &self.stage,
&&self.import_vis];
::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
names, values)
}
}Debug)]
2644struct Finalize {
2645 node_id: NodeId,
2647 path_span: Span,
2650 root_span: Span,
2653 report_private: bool = true,
2656 used: Used = Used::Other,
2658 stage: Stage = Stage::Early,
2660 import_vis: Option<Visibility> = None,
2662}
2663
2664impl Finalize {
2665 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2666 Finalize::with_root_span(node_id, path_span, path_span)
2667 }
2668
2669 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2670 Finalize { node_id, path_span, root_span, .. }
2671 }
2672}
2673
2674pub fn provide(providers: &mut Providers) {
2675 providers.registered_tools = macros::registered_tools;
2676}
2677
2678type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2684
2685use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2689
2690mod ref_mut {
2693 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2694 use std::fmt;
2695 use std::ops::Deref;
2696
2697 use crate::Resolver;
2698
2699 pub(crate) struct RefOrMut<'a, T> {
2701 p: &'a mut T,
2702 mutable: bool,
2703 }
2704
2705 impl<'a, T> Deref for RefOrMut<'a, T> {
2706 type Target = T;
2707
2708 fn deref(&self) -> &Self::Target {
2709 self.p
2710 }
2711 }
2712
2713 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2714 fn as_ref(&self) -> &T {
2715 self.p
2716 }
2717 }
2718
2719 impl<'a, T> RefOrMut<'a, T> {
2720 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2721 RefOrMut { p, mutable }
2722 }
2723
2724 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2726 RefOrMut { p: self.p, mutable: self.mutable }
2727 }
2728
2729 #[track_caller]
2734 pub(crate) fn get_mut(&mut self) -> &mut T {
2735 match self.mutable {
2736 false => {
::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2737 true => self.p,
2738 }
2739 }
2740
2741 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2744 self.p
2745 }
2746 }
2747
2748 #[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)]
2750 pub(crate) struct CmCell<T>(Cell<T>);
2751
2752 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2754 f.debug_tuple("CmCell").field(&self.get()).finish()
2755 }
2756 }
2757
2758 impl<T: Copy> Clone for CmCell<T> {
2759 fn clone(&self) -> CmCell<T> {
2760 CmCell::new(self.get())
2761 }
2762 }
2763
2764 impl<T: Copy> CmCell<T> {
2765 pub(crate) const fn get(&self) -> T {
2766 self.0.get()
2767 }
2768
2769 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2770 where
2771 T: Copy,
2772 {
2773 let old = self.get();
2774 self.set_unchecked(f(old));
2775 }
2776 }
2777
2778 impl<T> CmCell<T> {
2779 pub(crate) const fn new(value: T) -> CmCell<T> {
2780 CmCell(Cell::new(value))
2781 }
2782
2783 pub(crate) fn set_unchecked(&self, val: T) {
2784 self.0.set(val);
2785 }
2786
2787 pub(crate) fn into_inner(self) -> T {
2788 self.0.into_inner()
2789 }
2790 }
2791
2792 #[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)]
2794 pub(crate) struct CmRefCell<T>(RefCell<T>);
2795
2796 impl<T> CmRefCell<T> {
2797 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2798 CmRefCell(RefCell::new(value))
2799 }
2800
2801 #[track_caller]
2802 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2803 self.0.borrow_mut()
2804 }
2805
2806 #[track_caller]
2807 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2808 if r.assert_speculative {
2809 {
::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");
2810 }
2811 self.borrow_mut_unchecked()
2812 }
2813
2814 #[track_caller]
2815 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2816 self.0.try_borrow_mut()
2817 }
2818
2819 #[track_caller]
2820 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2821 self.0.borrow()
2822 }
2823 }
2824
2825 impl<T: Default> CmRefCell<T> {
2826 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2827 if r.assert_speculative {
2828 {
::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");
2829 }
2830 self.0.take()
2831 }
2832 }
2833}
2834
2835mod hygiene {
2836 use rustc_span::{ExpnId, SyntaxContext};
2837
2838 #[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)]
2841 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2842
2843 impl Macros20NormalizedSyntaxContext {
2844 #[inline]
2845 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2846 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2847 }
2848
2849 #[inline]
2850 pub(crate) fn new_adjusted(
2851 mut ctxt: SyntaxContext,
2852 expn_id: ExpnId,
2853 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2854 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2855 (Macros20NormalizedSyntaxContext(ctxt), def)
2856 }
2857
2858 #[inline]
2859 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2860 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());
2861 Macros20NormalizedSyntaxContext(ctxt)
2862 }
2863
2864 #[inline]
2866 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2867 let ret = f(&mut self.0);
2868 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());
2869 ret
2870 }
2871 }
2872
2873 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
2874 type Target = SyntaxContext;
2875 fn deref(&self) -> &Self::Target {
2876 &self.0
2877 }
2878 }
2879}