1#![allow(internal_features)]
11#![feature(arbitrary_self_types)]
12#![feature(const_default)]
13#![feature(const_trait_impl)]
14#![feature(control_flow_into_value)]
15#![feature(default_field_values)]
16#![feature(deref_patterns)]
17#![feature(iter_intersperse)]
18#![feature(option_into_flat_iter)]
19#![feature(rustc_attrs)]
20#![feature(trim_prefix_suffix)]
21#![recursion_limit = "256"]
22use std::cell::RefMut;
25use std::collections::BTreeSet;
26use std::ops::ControlFlow;
27use std::sync::{Arc, OnceLock};
28use std::{fmt, mem};
29
30use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
31use effective_visibilities::EffectiveVisibilitiesVisitor;
32use hygiene::Macros20NormalizedSyntaxContext;
33use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
34use late::{
35 ConstantRequiresType, ForwardGenericParamBanReason, HasGenericParams, PathSource,
36 PatternSource, UnnecessaryQualification,
37};
38pub use macros::registered_lint_tools_ast;
39use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
40use rustc_arena::{DroplessArena, TypedArena};
41use rustc_ast::node_id::NodeMap;
42use rustc_ast::{
43 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
44 GenericArg, GenericArgs, Generics, NodeId, Path, attr,
45};
46use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
47use rustc_data_structures::intern::Interned;
48use rustc_data_structures::steal::Steal;
49use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, Lock, RwLock, WorkerLocal};
50use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
51use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
52use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
53use rustc_feature::{BUILTIN_ATTRIBUTES, Features};
54use rustc_hir::attrs::StrippedCfgItem;
55use rustc_hir::def::Namespace::{self, *};
56use rustc_hir::def::{self, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
57use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
58use rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};
59use rustc_hir::{PrimTy, TraitCandidate, find_attr};
60use rustc_index::bit_set::DenseBitSet;
61use rustc_lint_defs::builtin::PRIVATE_MACRO_USE;
62use rustc_metadata::creader::CStore;
63use rustc_middle::middle::privacy::EffectiveVisibilities;
64use rustc_middle::middle::resolve::{
65 AmbigModChild, DelegationInfo, DelegationInherentFnKind, DocLinkResMap, MainDefinition,
66 ModChild, PartialRes, PerOwnerResolverData, Reexport, ResolverAstLowering, ResolverGlobalCtxt,
67};
68use rustc_middle::query::Providers;
69use rustc_middle::ty::{self, RegisteredTools, TyCtxt, TyCtxtFeed, Visibility};
70use rustc_span::def_id::{LocalModId, ModId};
71use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
72use rustc_span::{DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug, sym};
73use rustc_structures::CrateType;
74use smallvec::{SmallVec, smallvec};
75use tracing::{debug, instrument};
76
77use crate::diagnostics::impls::{
78 ImportSuggestion, LabelSuggestion, OnUnknownData, StructCtor, Suggestion,
79};
80use crate::imports::{ImportResolution, NameResolutionRef};
81use crate::ref_mut::speculative::SpeculativeFlag;
82use crate::ref_mut::{CmCell, CmRef, CmRefCell};
83
84mod build_reduced_graph;
85mod check_unused;
86mod def_collector;
87mod diagnostics;
88mod effective_visibilities;
89mod ident;
90mod imports;
91mod late;
92mod macros;
93pub mod rustdoc;
94
95type Res = def::Res<NodeId>;
96
97#[derive(#[automatically_derived]
impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Determinacy { }
#[automatically_derived]
impl ::core::clone::Clone for Determinacy {
#[inline]
fn clone(&self) -> Determinacy { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Determinacy { }
#[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]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for Scope<'ra> { }
#[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::ToolAttributePrelude =>
::core::fmt::Formatter::write_str(f, "ToolAttributePrelude"),
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 ToolAttributePrelude,
138 StdLibPrelude,
140 BuiltinTypes,
142}
143
144#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for ScopeSet<'ra> { }
#[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]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for ParentScope<'ra> { }
#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
#[inline]
fn clone(&self) -> ParentScope<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
let _: ::core::clone::AssertParamIsClone<&'ra [ast::Path]>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ParentScope<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "ParentScope",
"module", &self.module, "expansion", &self.expansion,
"macro_rules", &self.macro_rules, "derives", &&self.derives)
}
}Debug)]
165struct ParentScope<'ra> {
166 module: Module<'ra>,
167 expansion: LocalExpnId,
168 macro_rules: MacroRulesScopeRef<'ra>,
169 derives: &'ra [ast::Path],
170}
171
172impl<'ra> ParentScope<'ra> {
173 fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
176 ParentScope {
177 module: module.to_module(),
178 expansion: LocalExpnId::ROOT,
179 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
180 derives: &[],
181 }
182 }
183}
184
185#[derive(#[automatically_derived]
impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InvocationParent {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"InvocationParent", "parent_def", &self.parent_def,
"impl_trait_context", &self.impl_trait_context, "in_attr",
&self.in_attr, "owner", &&self.owner)
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvocationParent { }
#[automatically_derived]
impl ::core::clone::Clone for InvocationParent {
#[inline]
fn clone(&self) -> InvocationParent {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<NodeId>;
*self
}
}Clone)]
186struct InvocationParent {
187 parent_def: LocalDefId,
188 impl_trait_context: ImplTraitContext,
189 in_attr: bool,
190 owner: NodeId,
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 owner: CRATE_NODE_ID,
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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImplTraitContext { }
#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Used { }
#[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::marker::StructuralPartialEq for Used { }
#[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)]
224enum Used {
225 Scope,
226 Other,
227}
228
229#[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)]
230struct BindingError {
231 name: Ident,
232 origin: Vec<(Span, ast::Pat)>,
233 target: Vec<ast::Pat>,
234 could_be_path: bool,
235}
236
237#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ResolutionError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ResolutionError::GenericParamsFromOuterItem {
outer_res: __self_0,
has_generic_params: __self_1,
def_kind: __self_2,
inner_item: __self_3,
current_self_ty: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"GenericParamsFromOuterItem", "outer_res", __self_0,
"has_generic_params", __self_1, "def_kind", __self_2,
"inner_item", __self_3, "current_self_ty", &__self_4),
ResolutionError::NameAlreadyUsedInParameterList(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NameAlreadyUsedInParameterList", __self_0, &__self_1),
ResolutionError::MethodNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::TypeNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::ConstNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::VariableNotBoundInPattern(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableNotBoundInPattern", __self_0, &__self_1),
ResolutionError::VariableBoundWithDifferentMode(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableBoundWithDifferentMode", __self_0, &__self_1),
ResolutionError::IdentifierBoundMoreThanOnceInParameterList(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInParameterList", &__self_0),
ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
ResolutionError::UndeclaredLabel {
name: __self_0, suggestion: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UndeclaredLabel", "name", __self_0, "suggestion",
&__self_1),
ResolutionError::FailedToResolve {
segment: __self_0,
label: __self_1,
suggestion: __self_2,
help: __self_3,
module: __self_4,
message: __self_5 } => {
let names: &'static _ =
&["segment", "label", "suggestion", "help", "module",
"message"];
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,
"FailedToResolve", names, values)
}
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem =>
::core::fmt::Formatter::write_str(f,
"CannotCaptureDynamicEnvironmentInFnItem"),
ResolutionError::AttemptToUseNonConstantValueInConstant {
ident: __self_0,
suggestion: __self_1,
current: __self_2,
type_span: __self_3,
requires_type: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"AttemptToUseNonConstantValueInConstant", "ident", __self_0,
"suggestion", __self_1, "current", __self_2, "type_span",
__self_3, "requires_type", &__self_4),
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::SelfInConstParam =>
::core::fmt::Formatter::write_str(f, "SelfInConstParam"),
ResolutionError::ParamInNonTrivialAnonConst {
is_gca: __self_0, name: __self_1, param_kind: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ParamInNonTrivialAnonConst", "is_gca", __self_0, "name",
__self_1, "param_kind", &__self_2),
ResolutionError::ParamInEnumDiscriminant {
name: __self_0, param_kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ParamInEnumDiscriminant", "name", __self_0, "param_kind",
&__self_1),
ResolutionError::ForwardDeclaredSelf(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ForwardDeclaredSelf", &__self_0),
ResolutionError::UnreachableLabel {
name: __self_0,
definition_span: __self_1,
suggestion: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"UnreachableLabel", "name", __self_0, "definition_span",
__self_1, "suggestion", &__self_2),
ResolutionError::TraitImplMismatch {
name: __self_0,
kind: __self_1,
trait_path: __self_2,
trait_item_span: __self_3,
code: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"TraitImplMismatch", "name", __self_0, "kind", __self_1,
"trait_path", __self_2, "trait_item_span", __self_3, "code",
&__self_4),
ResolutionError::TraitImplDuplicate {
name: __self_0, trait_item_span: __self_1, old_span: __self_2
} =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TraitImplDuplicate", "name", __self_0, "trait_item_span",
__self_1, "old_span", &__self_2),
ResolutionError::InvalidAsmSym =>
::core::fmt::Formatter::write_str(f, "InvalidAsmSym"),
ResolutionError::LowercaseSelf =>
::core::fmt::Formatter::write_str(f, "LowercaseSelf"),
ResolutionError::BindingInNeverPattern =>
::core::fmt::Formatter::write_str(f, "BindingInNeverPattern"),
}
}
}Debug)]
238enum ResolutionError<'ra> {
239 GenericParamsFromOuterItem {
241 outer_res: Res,
242 has_generic_params: HasGenericParams,
243 def_kind: DefKind,
244 inner_item: Option<(Span, Span, ast::ItemKind)>,
246 current_self_ty: Option<String>,
247 },
248 NameAlreadyUsedInParameterList(Ident, Span),
251 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
253 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
255 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
257 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
259 VariableBoundWithDifferentMode(Ident, Span),
261 IdentifierBoundMoreThanOnceInParameterList(Ident),
263 IdentifierBoundMoreThanOnceInSamePattern(Ident),
265 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
267 FailedToResolve {
269 segment: Symbol,
270 label: String,
271 suggestion: Option<Suggestion>,
272 help: Option<String>,
273 module: Option<ModuleOrUniformRoot<'ra>>,
274 message: String,
275 },
276 CannotCaptureDynamicEnvironmentInFnItem,
278 AttemptToUseNonConstantValueInConstant {
280 ident: Ident,
281 suggestion: &'static str,
282 current: &'static str,
283 type_span: Option<Span>,
284 requires_type: ConstantRequiresType,
285 },
286 BindingShadowsSomethingUnacceptable {
288 shadowing_binding: PatternSource,
289 name: Symbol,
290 participle: &'static str,
291 article: &'static str,
292 shadowed_binding: Res,
293 shadowed_binding_span: Span,
294 },
295 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
297 ParamInTyOfConstParam { name: Symbol },
301 SelfInConstParam,
303 ParamInNonTrivialAnonConst {
307 is_gca: bool,
308 name: Symbol,
309 param_kind: ParamKindInNonTrivialAnonConst,
310 },
311 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
315 ForwardDeclaredSelf(ForwardGenericParamBanReason),
317 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
319 TraitImplMismatch {
321 name: Ident,
322 kind: &'static str,
323 trait_path: String,
324 trait_item_span: Span,
325 code: ErrCode,
326 },
327 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
329 InvalidAsmSym,
331 LowercaseSelf,
333 BindingInNeverPattern,
335}
336
337#[derive(#[automatically_derived]
impl ::core::fmt::Debug for VisResolutionError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
VisResolutionError::Relative2018(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Relative2018", __self_0, &__self_1),
VisResolutionError::AncestorOnly(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AncestorOnly", &__self_0),
VisResolutionError::FailedToResolve {
span: __self_0,
segment: __self_1,
label: __self_2,
suggestion: __self_3,
help: __self_4,
message: __self_5 } => {
let names: &'static _ =
&["span", "segment", "label", "suggestion", "help",
"message"];
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,
"FailedToResolve", names, values)
}
VisResolutionError::ExpectedFound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"ExpectedFound", __self_0, __self_1, &__self_2),
VisResolutionError::Indeterminate(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Indeterminate", &__self_0),
VisResolutionError::ModuleOnly(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ModuleOnly", &__self_0),
}
}
}Debug)]
338enum VisResolutionError {
339 Relative2018(Span, ast::Path),
340 AncestorOnly(Span),
341 FailedToResolve {
342 span: Span,
343 segment: Symbol,
344 label: String,
345 suggestion: Option<Suggestion>,
346 help: Option<String>,
347 message: String,
348 },
349 ExpectedFound(Span, String, Res),
350 Indeterminate(Span),
351 ModuleOnly(Span),
352}
353
354#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Segment { }
#[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)]
357struct Segment {
358 ident: Ident,
359 id: Option<NodeId>,
360 has_generic_args: bool,
362 has_lifetime_args: bool,
364 args_span: Span,
365}
366
367impl Segment {
368 fn from_path(path: &Path) -> Vec<Segment> {
369 path.segments.iter().map(|s| s.into()).collect()
370 }
371
372 fn from_ident(ident: Ident) -> Segment {
373 Segment {
374 ident,
375 id: None,
376 has_generic_args: false,
377 has_lifetime_args: false,
378 args_span: DUMMY_SP,
379 }
380 }
381
382 fn names_to_string(segments: &[Segment]) -> String {
383 names_to_string(segments.iter().map(|seg| seg.ident.name))
384 }
385}
386
387impl<'a> From<&'a ast::PathSegment> for Segment {
388 fn from(seg: &'a ast::PathSegment) -> Segment {
389 let has_generic_args = seg.args.is_some();
390 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
391 match args {
392 GenericArgs::AngleBracketed(args) => {
393 let found_lifetimes = args
394 .args
395 .iter()
396 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
397 (args.span, found_lifetimes)
398 }
399 GenericArgs::Parenthesized(args) => (args.span, true),
400 GenericArgs::ParenthesizedElided(span) => (*span, true),
401 }
402 } else {
403 (DUMMY_SP, false)
404 };
405 Segment {
406 ident: seg.ident,
407 id: Some(seg.id),
408 has_generic_args,
409 has_lifetime_args,
410 args_span,
411 }
412 }
413}
414
415#[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]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for LateDecl<'ra> { }
#[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)]
417enum LateDecl<'ra> {
418 Decl(Decl<'ra>),
420 RibDef(Res),
423}
424
425impl<'ra> LateDecl<'ra> {
426 fn res(self) -> Res {
427 match self {
428 LateDecl::Decl(binding) => binding.res(),
429 LateDecl::RibDef(res) => res,
430 }
431 }
432}
433
434#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for ModuleOrUniformRoot<'ra> { }
#[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::marker::StructuralPartialEq for ModuleOrUniformRoot<'ra> { }
#[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)]
435enum ModuleOrUniformRoot<'ra> {
436 Module(Module<'ra>),
438
439 ModuleAndExternPrelude(Module<'ra>),
443
444 ExternPrelude,
447
448 CurrentScope,
452
453 OpenModule(Symbol),
457}
458
459#[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,
help: __self_3,
is_error_from_last_segment: __self_4,
module: __self_5,
segment: __self_6,
error_implied_by_parse_error: __self_7,
message: __self_8,
note: __self_9 } => {
let names: &'static _ =
&["span", "label", "suggestion", "help",
"is_error_from_last_segment", "module", "segment",
"error_implied_by_parse_error", "message", "note"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, __self_6, __self_7, __self_8, &__self_9];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Failed", names, values)
}
}
}
}Debug)]
460enum PathResult<'ra> {
461 Module(ModuleOrUniformRoot<'ra>),
462 NonModule(PartialRes),
463 Indeterminate,
464 Failed {
465 span: Span,
466 label: String,
467 suggestion: Option<Suggestion>,
468 help: Option<String>,
469 is_error_from_last_segment: bool,
470 module: Option<ModuleOrUniformRoot<'ra>>,
484 segment: Ident,
486 error_implied_by_parse_error: bool,
487 message: String,
488 note: Option<String>,
489 },
490}
491
492impl<'ra> PathResult<'ra> {
493 fn failed(
494 ident: Ident,
495 is_error_from_last_segment: bool,
496 finalize: bool,
497 error_implied_by_parse_error: bool,
498 module: Option<ModuleOrUniformRoot<'ra>>,
499 label_and_suggestion_and_note: impl FnOnce() -> (
500 String,
501 String,
502 Option<Suggestion>,
503 Option<String>,
504 Option<String>,
505 ),
506 ) -> PathResult<'ra> {
507 let (message, label, suggestion, note, help) = if finalize {
508 label_and_suggestion_and_note()
509 } else {
510 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find `{0}` in this scope",
ident))
})format!("cannot find `{ident}` in this scope"), String::new(), None, None, None)
512 };
513 PathResult::Failed {
514 span: ident.span,
515 segment: ident,
516 label,
517 suggestion,
518 help,
519 is_error_from_last_segment,
520 module,
521 error_implied_by_parse_error,
522 message,
523 note,
524 }
525 }
526}
527
528#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleKind::Block =>
::core::fmt::Formatter::write_str(f, "Block"),
ModuleKind::Def(__self_0, __self_1, __self_2, __self_3) =>
::core::fmt::Formatter::debug_tuple_field4_finish(f, "Def",
__self_0, __self_1, __self_2, &__self_3),
}
}
}Debug)]
529enum ModuleKind {
530 Block,
543 Def(DefKind, DefId, NodeId, Option<Symbol>),
553}
554
555impl ModuleKind {
556 fn opt_def_id(&self) -> Option<DefId> {
557 match self {
558 ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
559 _ => None,
560 }
561 }
562
563 fn def_id(&self) -> DefId {
564 self.opt_def_id().expect("`Module::def_id` is called on a block module")
565 }
566
567 fn is_local(&self) -> bool {
568 match self {
569 ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
570 ModuleKind::Block => true,
571 }
572 }
573}
574
575#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IdentKey { }
#[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::marker::StructuralPartialEq for IdentKey { }
#[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)]
586struct IdentKey {
587 name: Symbol,
588 ctxt: Macros20NormalizedSyntaxContext,
589}
590
591impl IdentKey {
592 #[inline]
593 fn new(ident: Ident) -> IdentKey {
594 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
595 }
596
597 #[inline]
598 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
599 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
600 (IdentKey { name: ident.name, ctxt }, def)
601 }
602
603 #[inline]
604 fn with_root_ctxt(name: Symbol) -> Self {
605 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
606 IdentKey { name, ctxt }
607 }
608
609 #[inline]
610 fn orig(self, orig_ident_span: Span) -> Ident {
611 Ident::new(self.name, orig_ident_span)
612 }
613}
614
615#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingKey { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BindingKey { }
#[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::marker::StructuralPartialEq for BindingKey { }
#[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)]
620struct BindingKey {
621 ident: IdentKey,
624 ns: Namespace,
625 disambiguator: u32,
631}
632
633impl BindingKey {
634 fn new(ident: IdentKey, ns: Namespace) -> Self {
635 BindingKey { ident, ns, disambiguator: 0 }
636 }
637
638 fn new_disambiguated(
639 ident: IdentKey,
640 ns: Namespace,
641 disambiguator: impl FnOnce() -> u32,
642 ) -> BindingKey {
643 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
644 BindingKey { ident, ns, disambiguator }
645 }
646}
647
648type ResolutionTable<'ra> = FxIndexMap<BindingKey, NameResolutionRef<'ra>>;
649
650enum Resolutions<'ra> {
651 Local(CmRefCell<ResolutionTable<'ra>>),
652 Extern(OnceLock<ResolutionTable<'ra>>),
653}
654
655impl<'ra> Resolutions<'ra> {
656 fn new(local: bool) -> Self {
657 if local {
658 Resolutions::Local(Default::default())
659 } else {
660 Resolutions::Extern(Default::default())
661 }
662 }
663}
664
665struct ModuleData<'ra> {
677 parent: Option<Module<'ra>>,
679 kind: ModuleKind,
681
682 lazy_resolutions: Resolutions<'ra>,
685 underscore_disambiguator: CmCell<u32>,
687
688 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
690
691 no_implicit_prelude: bool,
693
694 glob_importers: CmRefCell<Vec<Import<'ra>>>,
695 globs: CmRefCell<Vec<Import<'ra>>>,
696
697 traits: CmRefCell<
699 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
700 >,
701
702 span: Span,
704
705 expansion: ExpnId,
706
707 self_decl: Option<Decl<'ra>>,
710}
711
712#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for Module<'ra> { }
#[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::marker::StructuralPartialEq for Module<'ra> { }
#[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)]
715#[rustc_pass_by_value]
716struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
717
718#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for LocalModule<'ra> { }
#[automatically_derived]
impl<'ra> ::core::clone::Clone for LocalModule<'ra> {
#[inline]
fn clone(&self) -> LocalModule<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LocalModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::marker::StructuralPartialEq for LocalModule<'ra> { }
#[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for LocalModule<'ra> {
#[inline]
fn eq(&self, other: &LocalModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for LocalModule<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
}
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for LocalModule<'ra> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
720#[rustc_pass_by_value]
721struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
722
723#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for ExternModule<'ra> { }
#[automatically_derived]
impl<'ra> ::core::clone::Clone for ExternModule<'ra> {
#[inline]
fn clone(&self) -> ExternModule<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ExternModule<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::marker::StructuralPartialEq for ExternModule<'ra> { }
#[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ExternModule<'ra> {
#[inline]
fn eq(&self, other: &ExternModule<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for ExternModule<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Interned<'ra, ModuleData<'ra>>>;
}
}Eq, #[automatically_derived]
impl<'ra> ::core::hash::Hash for ExternModule<'ra> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
725#[rustc_pass_by_value]
726struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
727
728impl<'ra> ModuleData<'ra> {
729 fn new(
730 parent: Option<Module<'ra>>,
731 kind: ModuleKind,
732 expansion: ExpnId,
733 span: Span,
734 no_implicit_prelude: bool,
735 vis: Visibility<ModId>,
736 arenas: &'ra ResolverArenas<'ra>,
737 ) -> Self {
738 let lazy_resolutions = Resolutions::new(kind.is_local());
739 let self_decl = match kind {
740 ModuleKind::Def(def_kind, def_id, ..) => {
741 let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
742 Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
743 }
744 ModuleKind::Block => None,
745 };
746 ModuleData {
747 parent,
748 kind,
749 lazy_resolutions,
750 underscore_disambiguator: CmCell::new(0),
751 unexpanded_invocations: Default::default(),
752 no_implicit_prelude,
753 glob_importers: CmRefCell::new(Vec::new()),
754 globs: CmRefCell::new(Vec::new()),
755 traits: CmRefCell::new(None),
756 span,
757 expansion,
758 self_decl,
759 }
760 }
761
762 fn name(&self) -> Option<Symbol> {
764 match self.kind {
765 ModuleKind::Block => None,
766 ModuleKind::Def(.., name) => name,
767 }
768 }
769
770 fn opt_def_id(&self) -> Option<DefId> {
771 self.kind.opt_def_id()
772 }
773
774 fn def_id(&self) -> DefId {
775 self.kind.def_id()
776 }
777
778 fn is_local(&self) -> bool {
779 self.kind.is_local()
780 }
781
782 fn has_unexpanded_invocations<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
783 !self.unexpanded_invocations.borrow_checked(r).is_empty()
784 }
785
786 fn res(&self) -> Option<Res> {
787 match self.kind {
788 ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
789 _ => None,
790 }
791 }
792
793 fn def_kind(&self) -> Option<DefKind> {
794 match self.kind {
795 ModuleKind::Def(def_kind, ..) => Some(def_kind),
796 ModuleKind::Block => None,
797 }
798 }
799}
800
801impl<'ra> Module<'ra> {
802 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
803 self,
804 resolver: &R,
805 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
806 ) {
807 for (key, name_resolution) in resolver.as_ref().resolutions(self).iter() {
808 let name_resolution = name_resolution.borrow_checked(resolver.as_ref());
809 if let Some(decl) = name_resolution.best_decl() {
810 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
811 }
812 }
813 }
814
815 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
816 self,
817 resolver: &mut R,
818 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
819 ) {
820 for (key, name_resolution) in resolver.as_mut().resolutions(self).iter() {
821 let name_resolution = name_resolution.borrow(resolver.as_mut());
822 if let Some(decl) = name_resolution.best_decl() {
823 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
824 }
825 }
826 }
827
828 fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {
830 let mut traits = self.traits.borrow_mut_checked(resolver);
831 if traits.is_none() {
832 let mut collected_traits = Vec::new();
833 self.for_each_child(resolver, |r, ident, _, ns, mut decl| {
834 if ns != TypeNS {
835 return;
836 }
837
838 let ambiguous = decl.is_ambiguity_recursive();
839 let mut try_record_trait = |decl: Decl<'ra>| {
840 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = decl.res() {
841 collected_traits.push((
842 ident.name,
843 decl,
844 r.as_ref().get_module(def_id),
845 ambiguous,
846 ));
847 true
848 } else {
849 false
850 }
851 };
852 while !try_record_trait(decl)
856 && let Some((_, ambig_decl)) = decl.descent_to_ambiguity()
857 {
858 decl = ambig_decl;
859 }
860 });
861 *traits = Some(collected_traits.into_boxed_slice());
862 }
863 }
864
865 fn is_normal(self) -> bool {
867 self.def_kind() == Some(DefKind::Mod)
868 }
869
870 fn is_trait(self) -> bool {
871 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind() {
Some(DefKind::Trait) => true,
_ => false,
}matches!(self.def_kind(), Some(DefKind::Trait))
872 }
873
874 fn nearest_item_scope(self) -> Module<'ra> {
875 match self.def_kind() {
876 Some(DefKind::Enum | DefKind::Trait) => {
877 self.parent.expect("enum or trait module without a parent")
878 }
879 _ => self,
880 }
881 }
882
883 fn nearest_parent_mod(self) -> ModId {
886 match self.kind {
887 ModuleKind::Def(DefKind::Mod, def_id, _, _) => ModId::new_unchecked(def_id),
888 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
889 }
890 }
891
892 fn nearest_parent_mod_node_id(self) -> NodeId {
895 match self.kind {
896 ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
897 _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
898 }
899 }
900
901 fn is_ancestor_of(self, mut other: Self) -> bool {
902 while self != other {
903 if let Some(parent) = other.parent {
904 other = parent;
905 } else {
906 return false;
907 }
908 }
909 true
910 }
911
912 #[track_caller]
913 fn expect_local(self) -> LocalModule<'ra> {
914 match self.kind {
915 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
916 bug_impl(Some(self.span),
format_args!("unexpected extern module: {0:?}", self), Location::caller())span_bug!(self.span, "unexpected extern module: {self:?}")
917 }
918 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
919 }
920 }
921
922 #[track_caller]
923 fn expect_extern(self) -> ExternModule<'ra> {
924 match self.kind {
925 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
926 ModuleKind::Def(..) | ModuleKind::Block => {
927 bug_impl(Some(self.span),
format_args!("unexpected local module: {0:?}", self), Location::caller())span_bug!(self.span, "unexpected local module: {self:?}")
928 }
929 }
930 }
931}
932
933impl<'ra> LocalModule<'ra> {
934 fn new(
935 parent: Option<LocalModule<'ra>>,
936 kind: ModuleKind,
937 vis: Visibility<ModId>,
938 expn_id: ExpnId,
939 span: Span,
940 no_implicit_prelude: bool,
941 arenas: &'ra ResolverArenas<'ra>,
942 ) -> LocalModule<'ra> {
943 if !kind.is_local() {
::core::panicking::panic("assertion failed: kind.is_local()")
};assert!(kind.is_local());
944 let parent = parent.map(|m| m.to_module());
945 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
946 LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
948 }
949
950 fn to_module(self) -> Module<'ra> {
951 Module(self.0)
952 }
953}
954
955impl<'ra> ExternModule<'ra> {
956 fn new(
957 parent: Option<ExternModule<'ra>>,
958 kind: ModuleKind,
959 vis: Visibility<ModId>,
960 expn_id: ExpnId,
961 span: Span,
962 no_implicit_prelude: bool,
963 arenas: &'ra ResolverArenas<'ra>,
964 ) -> ExternModule<'ra> {
965 if !!kind.is_local() {
::core::panicking::panic("assertion failed: !kind.is_local()")
};assert!(!kind.is_local());
966 let parent = parent.map(|m| m.to_module());
967 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
968 ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
970 }
971
972 fn to_module(self) -> Module<'ra> {
973 Module(self.0)
974 }
975}
976
977impl<'ra> std::ops::Deref for Module<'ra> {
978 type Target = ModuleData<'ra>;
979
980 fn deref(&self) -> &Self::Target {
981 &self.0
982 }
983}
984
985impl<'ra> std::ops::Deref for LocalModule<'ra> {
986 type Target = ModuleData<'ra>;
987
988 fn deref(&self) -> &Self::Target {
989 &self.0
990 }
991}
992
993impl<'ra> std::ops::Deref for ExternModule<'ra> {
994 type Target = ModuleData<'ra>;
995
996 fn deref(&self) -> &Self::Target {
997 &self.0
998 }
999}
1000
1001impl<'ra> fmt::Debug for Module<'ra> {
1002 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1003 match self.res() {
1004 None => f.write_fmt(format_args!("block"))write!(f, "block"),
1005 Some(res) => f.write_fmt(format_args!("{0:?}", res))write!(f, "{:?}", res),
1006 }
1007 }
1008}
1009
1010impl<'ra> fmt::Debug for LocalModule<'ra> {
1011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 self.to_module().fmt(f)
1013 }
1014}
1015
1016#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclData<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["kind", "ambiguity", "expansion", "span", "initial_vis",
"ambiguity_vis_max", "ambiguity_vis_min", "parent_module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.ambiguity, &self.expansion, &self.span,
&self.initial_vis, &self.ambiguity_vis_max,
&self.ambiguity_vis_min, &&self.parent_module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DeclData",
names, values)
}
}Debug)]
1018struct DeclData<'ra> {
1019 kind: DeclKind<'ra>,
1020 ambiguity: CmCell<Option<(Decl<'ra>, bool )>>,
1021 expansion: LocalExpnId,
1022 span: Span,
1023 initial_vis: Visibility<ModId>,
1024 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
1027 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
1030 parent_module: Option<Module<'ra>>,
1031}
1032
1033type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
1036
1037#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclKind<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DeclKind::Def(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
&__self_0),
DeclKind::Import { source_decl: __self_0, import: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Import", "source_decl", __self_0, "import", &__self_1),
}
}
}Debug)]
1039enum DeclKind<'ra> {
1040 Def(Res),
1043 Import { source_decl: Decl<'ra>, import: Import<'ra> },
1045}
1046
1047impl<'ra> DeclKind<'ra> {
1048 fn is_import(&self) -> bool {
1050 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
1051 }
1052}
1053
1054#[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)]
1055struct PrivacyError<'ra> {
1056 ident: Ident,
1057 decl: Decl<'ra>,
1058 dedup_span: Span,
1059 outermost_res: Option<(Res, Ident)>,
1060 parent_scope: ParentScope<'ra>,
1061 single_nested: bool,
1063 source: Option<ast::Expr>,
1064}
1065
1066#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for UseError<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["err", "candidates", "node_id", "instead", "suggestion", "path",
"is_call"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.err, &self.candidates, &self.node_id, &self.instead,
&self.suggestion, &self.path, &&self.is_call];
::core::fmt::Formatter::debug_struct_fields_finish(f, "UseError",
names, values)
}
}Debug)]
1067struct UseError<'a> {
1068 err: Diag<'a>,
1069 candidates: Vec<ImportSuggestion>,
1071 node_id: NodeId,
1073 instead: bool,
1075 suggestion: Option<(Span, &'static str, String, Applicability)>,
1077 path: Vec<Segment>,
1080 is_call: bool,
1082}
1083
1084#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for DelayedVisResolutionError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DelayedVisResolutionError", "vis", &self.vis, "parent_scope",
&self.parent_scope, "error", &&self.error)
}
}Debug)]
1085struct DelayedVisResolutionError<'ra> {
1086 vis: ast::Visibility,
1087 parent_scope: ParentScope<'ra>,
1088 error: VisResolutionError,
1089}
1090
1091#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AmbiguityKind { }
#[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::marker::StructuralPartialEq for AmbiguityKind { }
#[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)]
1092enum AmbiguityKind {
1093 BuiltinAttr,
1094 DeriveHelper,
1095 MacroRulesVsModularized,
1096 GlobVsOuter,
1097 GlobVsGlob,
1098 GlobVsExpanded,
1099 MoreExpandedVsOuter,
1100}
1101
1102impl AmbiguityKind {
1103 fn descr(self) -> &'static str {
1104 match self {
1105 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1106 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1107 AmbiguityKind::MacroRulesVsModularized => {
1108 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1109 }
1110 AmbiguityKind::GlobVsOuter => {
1111 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1112 }
1113 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1114 AmbiguityKind::GlobVsExpanded => {
1115 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1116 }
1117 AmbiguityKind::MoreExpandedVsOuter => {
1118 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1119 }
1120 }
1121 }
1122}
1123
1124#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AmbiguityWarning { }
#[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::marker::StructuralPartialEq for AmbiguityWarning { }
#[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)]
1125enum AmbiguityWarning {
1126 GlobImport,
1127 PanicImport,
1128}
1129
1130struct AmbiguityError<'ra> {
1131 kind: AmbiguityKind,
1132 ambig_vis: Option<(Visibility, Visibility)>,
1133 ident: Ident,
1134 b1: Decl<'ra>,
1135 b2: Decl<'ra>,
1136 scope1: Scope<'ra>,
1137 scope2: Scope<'ra>,
1138 warning: Option<AmbiguityWarning>,
1139}
1140
1141impl<'ra> DeclData<'ra> {
1142 fn vis(&self) -> Visibility<ModId> {
1143 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1145 }
1146
1147 fn min_vis(&self) -> Visibility<ModId> {
1148 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1150 }
1151
1152 fn res(&self) -> Res {
1153 match self.kind {
1154 DeclKind::Def(res) => res,
1155 DeclKind::Import { source_decl, .. } => source_decl.res(),
1156 }
1157 }
1158
1159 fn import_source(&self) -> Decl<'ra> {
1160 match self.kind {
1161 DeclKind::Import { source_decl, .. } => source_decl,
1162 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1163 }
1164 }
1165
1166 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1167 match self.ambiguity.get() {
1168 Some((ambig_binding, _)) => Some((self, ambig_binding)),
1169 None => match self.kind {
1170 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1171 _ => None,
1172 },
1173 }
1174 }
1175
1176 fn is_ambiguity_recursive(&self) -> bool {
1177 self.ambiguity.get().is_some()
1178 || match self.kind {
1179 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1180 _ => false,
1181 }
1182 }
1183
1184 fn is_possibly_imported_variant(&self) -> bool {
1185 match self.kind {
1186 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1187 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1188 true
1189 }
1190 DeclKind::Def(..) => false,
1191 }
1192 }
1193
1194 fn is_extern_crate(&self) -> bool {
1195 match self.kind {
1196 DeclKind::Import { import, .. } => {
1197 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1198 }
1199 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1200 _ => false,
1201 }
1202 }
1203
1204 fn is_import(&self) -> bool {
1205 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1206 }
1207
1208 fn is_import_user_facing(&self) -> bool {
1211 #[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, .. }
1212 if !matches!(import.kind, ImportKind::MacroExport))
1213 }
1214
1215 fn is_glob_import(&self) -> bool {
1216 match self.kind {
1217 DeclKind::Import { import, .. } => import.is_glob(),
1218 _ => false,
1219 }
1220 }
1221
1222 fn is_assoc_item(&self) -> bool {
1223 #[allow(non_exhaustive_omitted_patterns)] match self.res() {
Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) =>
true,
_ => false,
}matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
1224 }
1225
1226 fn macro_kinds(&self) -> Option<MacroKinds> {
1227 self.res().macro_kinds()
1228 }
1229
1230 fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {
1231 let mut reexport_chain = SmallVec::new();
1232 let mut next_binding = self;
1233 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1234 reexport_chain.push(import.simplify());
1235 next_binding = source_decl;
1236 }
1237 reexport_chain
1238 }
1239
1240 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1247 let self_parent_expansion = self.expansion;
1251 let other_parent_expansion = decl.expansion;
1252 let certainly_before_other_or_simultaneously =
1253 other_parent_expansion.is_descendant_of(self_parent_expansion);
1254 let certainly_before_invoc_or_simultaneously =
1255 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1256 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1257 }
1258
1259 fn determined<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
1265 match &self.kind {
1266 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1267 !import.parent_scope.module.has_unexpanded_invocations(r)
1268 && source_decl.determined(r)
1269 }
1270 _ => true,
1271 }
1272 }
1273}
1274
1275#[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)]
1276struct ExternPreludeEntry<'ra> {
1277 item_decl: Option<(Decl<'ra>, Span, bool)>,
1281 flag_decl: Option<
1283 Lock<(
1284 PendingDecl<'ra>,
1285 bool,
1286 bool,
1287 )>,
1288 >,
1289}
1290
1291impl ExternPreludeEntry<'_> {
1292 fn introduced_by_item(&self) -> bool {
1293 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1294 }
1295
1296 fn flag() -> Self {
1297 ExternPreludeEntry {
1298 item_decl: None,
1299 flag_decl: Some(Lock::new((PendingDecl::Pending, false, false))),
1300 }
1301 }
1302
1303 fn open_flag() -> Self {
1304 ExternPreludeEntry {
1305 item_decl: None,
1306 flag_decl: Some(Lock::new((PendingDecl::Pending, false, true))),
1307 }
1308 }
1309
1310 fn span(&self) -> Span {
1311 match self.item_decl {
1312 Some((_, span, _)) => span,
1313 None => DUMMY_SP,
1314 }
1315 }
1316}
1317
1318struct DeriveData {
1319 resolutions: Vec<DeriveResolution>,
1320 helper_attrs: Vec<(usize, IdentKey, Span)>,
1321 has_derive_copy: bool,
1324 has_derive_ord: bool,
1325}
1326
1327pub struct ResolverOutputs<'tcx> {
1328 pub global_ctxt: ResolverGlobalCtxt,
1329 pub ast_lowering: ResolverAstLowering<'tcx>,
1330}
1331
1332#[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)]
1333struct DelegationFnSig {
1334 pub has_self: bool,
1335}
1336
1337pub struct Resolver<'ra, 'tcx> {
1341 tcx: TyCtxt<'tcx>,
1342
1343 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1345
1346 graph_root: LocalModule<'ra>,
1347
1348 speculative_flag: SpeculativeFlag,
1350
1351 prelude: Option<Module<'ra>> = None,
1352 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1353
1354 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1356 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1357
1358 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1361
1362 determined_imports: Vec<Import<'ra>> = Vec::new(),
1364
1365 indeterminate_imports: Vec<(Import<'ra>, Option<ImportResolution<'ra>>, usize)> = Vec::new(),
1367
1368 pat_span_map: NodeMap<Span> = Default::default(),
1371
1372 partial_res_map: NodeMap<PartialRes> = Default::default(),
1374 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1376
1377 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1379 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1380 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1381
1382 block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1397 empty_module: LocalModule<'ra>,
1401 local_modules: Vec<LocalModule<'ra>>,
1403 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1405 extern_module_map: RwLock<FxIndexMap<DefId, ExternModule<'ra>>>,
1407
1408 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1410 glob_error: Option<ErrorGuaranteed> = None,
1411 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1412 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1413 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1414
1415 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1417 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1419 issue_145575_hack_applied: bool = false,
1420 delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),
1422 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1424
1425 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1426 dummy_decl: Decl<'ra>,
1427 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1428 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1429 registered_attr_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1430 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1431 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1432 registered_attr_tools: &'tcx RegisteredTools,
1433 registered_lint_tools: &'tcx RegisteredTools,
1434 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1435 local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),
1437 extern_macro_map: RwLock<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
1439 dummy_ext_bang: &'ra Arc<SyntaxExtension>,
1440 dummy_ext_derive: &'ra Arc<SyntaxExtension>,
1441 non_macro_attr: &'ra Arc<SyntaxExtension>,
1442 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1443 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1444 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1445 unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)>,
1447 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1448 single_segment_macro_resolutions:
1450 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1451 multi_segment_macro_resolutions:
1452 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1453 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1454 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1458 containers_deriving_ord: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1459 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1462 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1465 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1467 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1469 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1472
1473 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1475
1476 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1477
1478 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1479
1480 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1484
1485 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1488
1489 lint_buffer: LintBuffer,
1490
1491 next_node_id: NodeId = CRATE_NODE_ID,
1492
1493 owners: NodeMap<PerOwnerResolverData<'tcx>>,
1495
1496 current_owner: PerOwnerResolverData<'tcx>,
1498
1499 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1500
1501 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1503 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1507
1508 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1510 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1512 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1513 delegation_infos: FxIndexMap<LocalDefId, DelegationInfo>,
1514 delegation_inherent_fn_map: FxIndexMap<LocalDefId, FxIndexMap<Ident, DelegationInherentFnKind>>,
1515
1516 main_def: Option<MainDefinition> = None,
1517 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1518 proc_macros: Vec<LocalDefId> = Vec::new(),
1521 confused_type_with_std_module: FxIndexMap<Span, Span>,
1522
1523 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1525
1526 effective_visibilities: EffectiveVisibilities,
1527 macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>>,
1528
1529 doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap>,
1530 doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>>,
1531 all_macro_rules: UnordSet<Symbol> = Default::default(),
1532
1533 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1535 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1538 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1541
1542 current_crate_outer_attr_insert_span: Span,
1545
1546 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1547
1548 all_crate_macros_already_registered: bool = false,
1551
1552 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1556
1557 on_unknown_data: FxHashMap<LocalDefId, OnUnknownData> = default::fx_hash_map(),
1559 features: &'tcx Features,
1560}
1561
1562#[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)]
1565pub struct ResolverArenas<'ra> {
1566 modules: TypedArena<ModuleData<'ra>>,
1567 imports: TypedArena<ImportData<'ra>>,
1568 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1569 ast_paths: TypedArena<ast::Path>,
1570 macros: TypedArena<Arc<SyntaxExtension>>,
1571 dropless: DroplessArena,
1572}
1573
1574impl<'ra> ResolverArenas<'ra> {
1575 fn new_def_decl(
1576 &'ra self,
1577 res: Res,
1578 vis: Visibility<ModId>,
1579 span: Span,
1580 expansion: LocalExpnId,
1581 parent_module: Option<Module<'ra>>,
1582 ) -> Decl<'ra> {
1583 self.alloc_decl(DeclData {
1584 kind: DeclKind::Def(res),
1585 ambiguity: CmCell::new(None),
1586 initial_vis: vis,
1587 ambiguity_vis_max: CmCell::new(None),
1588 ambiguity_vis_min: CmCell::new(None),
1589 span,
1590 expansion,
1591 parent_module,
1592 })
1593 }
1594
1595 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1596 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1597 }
1598
1599 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1600 Interned::new_unchecked(self.dropless.alloc(data))
1602 }
1603 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1604 Interned::new_unchecked(self.imports.alloc(import))
1606 }
1607 fn alloc_name_resolution(&'ra self, resolution: NameResolution<'ra>) -> NameResolutionRef<'ra> {
1608 Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution)))
1610 }
1611 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1612 self.dropless.alloc(RwLock::new(scope))
1613 }
1614 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1615 self.dropless.alloc(decl)
1616 }
1617 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1618 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1619 }
1620 fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
1621 self.macros.alloc(Arc::new(ext))
1622 }
1623 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1624 self.dropless.alloc_from_iter(spans)
1625 }
1626}
1627
1628impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1629 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1630 self
1631 }
1632}
1633
1634impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1635 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1636 self
1637 }
1638}
1639
1640impl<'tcx> Resolver<'_, 'tcx> {
1641 fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
1645 self.owners[&owner].def_id
1646 }
1647
1648 fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
1652 self.owners[&owner].node_id_to_def_id[&id]
1653 }
1654
1655 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1657 self.current_owner.node_id_to_def_id.get(&node).copied()
1658 }
1659
1660 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1662 self.opt_local_def_id(node).unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
node));
}panic!("no entry for node id: `{node:?}`"))
1663 }
1664
1665 fn create_def(
1667 &mut self,
1668 parent: LocalDefId,
1669 node_id: ast::NodeId,
1670 name: Option<Symbol>,
1671 def_kind: DefKind,
1672 expn_id: ExpnId,
1673 span: Span,
1674 is_owner: bool,
1675 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1676 if !!self.current_owner.node_id_to_def_id.contains_key(&node_id) {
{
::core::panicking::panic_fmt(format_args!("adding a def for node-id {0:?}, name {1:?}, data {2:?} but a previous def exists: {3:?}",
node_id, name, def_kind,
self.tcx.definitions_untracked().def_key(self.current_owner.node_id_to_def_id[&node_id])));
}
};assert!(
1677 !self.current_owner.node_id_to_def_id.contains_key(&node_id),
1678 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1679 node_id,
1680 name,
1681 def_kind,
1682 self.tcx
1683 .definitions_untracked()
1684 .def_key(self.current_owner.node_id_to_def_id[&node_id]),
1685 );
1686
1687 let disambiguator = self.disambiguators.get_or_create(parent);
1688
1689 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1691 let def_id = feed.def_id();
1692
1693 if expn_id != ExpnId::root() {
1695 self.expn_that_defined.insert(def_id, expn_id);
1696 }
1697
1698 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);
1700 let _id = self.tcx.untracked().source_span.push(span);
1701 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);
1702
1703 if node_id != ast::DUMMY_NODE_ID && !is_owner {
1707 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:1707",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1707u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
def_id, node_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1708 self.current_owner.node_id_to_def_id.insert(node_id, def_id);
1709 }
1710
1711 feed
1712 }
1713
1714 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1715 if let Some(def_id) = def_id.as_local() {
1716 self.item_generics_num_lifetimes[&def_id]
1717 } else {
1718 self.tcx.generics_of(def_id).own_counts().lifetimes
1719 }
1720 }
1721
1722 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1723 if let Some(def_id) = def_id.as_local() {
1724 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1725 } else {
1726 let required = self
1727 .tcx
1728 .generics_of(def_id)
1729 .own_params
1730 .iter()
1731 .filter_map(|param| match param.kind {
1732 ty::GenericParamDefKind::Lifetime => Some("'_"),
1733 ty::GenericParamDefKind::Type { has_default, .. }
1734 | ty::GenericParamDefKind::Const { has_default } => {
1735 if has_default {
1736 None
1737 } else {
1738 Some("_")
1739 }
1740 }
1741 })
1742 .collect::<Vec<_>>();
1743
1744 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1745 }
1746 }
1747
1748 pub fn tcx(&self) -> TyCtxt<'tcx> {
1749 self.tcx
1750 }
1751
1752 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1759 self.owners
1760 .items()
1761 .flat_map(|(_, data)| {
1762 data.node_id_to_def_id
1763 .items()
1764 .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
1765 })
1766 .filter(|(_, v)| **v == def_id)
1767 .map(|(k, _)| *k)
1768 .get_only()
1769 .unwrap()
1770 }
1771}
1772
1773impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1774 pub fn new(
1775 tcx: TyCtxt<'tcx>,
1776 attrs: &[ast::Attribute],
1777 crate_span: Span,
1778 current_crate_outer_attr_insert_span: Span,
1779 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1780 ) -> Resolver<'ra, 'tcx> {
1781 let root_def_id = CRATE_DEF_ID.to_def_id();
1782 let graph_root = LocalModule::new(
1783 None,
1784 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1785 Visibility::Public,
1786 ExpnId::root(),
1787 crate_span,
1788 attr::contains_name(attrs, sym::no_implicit_prelude),
1789 arenas,
1790 );
1791 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];
1792 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1793 let empty_module = LocalModule::new(
1794 None,
1795 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1796 Visibility::Public,
1797 ExpnId::root(),
1798 DUMMY_SP,
1799 true,
1800 arenas,
1801 );
1802
1803 let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
1804 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1805
1806 crate_feed.def_kind(DefKind::Mod);
1807 let mut owners = NodeMap::default();
1808 owners.insert(CRATE_NODE_ID, owner_data);
1809
1810 let mut invocation_parents = FxHashMap::default();
1811 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1812
1813 let extern_prelude = build_extern_prelude(tcx, attrs);
1814 let registered_attr_tools = tcx.registered_attr_tools(());
1815 let registered_lint_tools = tcx.registered_lint_tools(());
1816 let edition = tcx.sess.edition();
1817
1818 let mut resolver = Resolver {
1819 tcx,
1820
1821 graph_root,
1824 speculative_flag: SpeculativeFlag::default(),
1826 extern_prelude,
1827
1828 empty_module,
1829 local_modules,
1830 local_module_map,
1831 extern_module_map: Default::default(),
1832
1833 glob_map: Default::default(),
1834 maybe_unused_trait_imports: Default::default(),
1835
1836 arenas,
1837 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1838 builtin_type_decls: PrimTy::ALL
1839 .iter()
1840 .map(|prim_ty| {
1841 let res = Res::PrimTy(*prim_ty);
1842 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1843 (prim_ty.name(), decl)
1844 })
1845 .collect(),
1846 builtin_attr_decls: BUILTIN_ATTRIBUTES
1847 .iter()
1848 .map(|builtin_attr| {
1849 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));
1850 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1851 (*builtin_attr, decl)
1852 })
1853 .collect(),
1854 registered_attr_tool_decls: registered_attr_tools
1855 .iter()
1856 .map(|&ident| {
1857 let res = Res::ToolMod;
1858 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1859 (IdentKey::new(ident), decl)
1860 })
1861 .collect(),
1862 registered_attr_tools,
1863 registered_lint_tools,
1864 macro_use_prelude: Default::default(),
1865 extern_macro_map: Default::default(),
1866 dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
1867 dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
1868 non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
1869 unused_macros: Default::default(),
1870 unused_macro_rules: Default::default(),
1871 single_segment_macro_resolutions: Default::default(),
1872 multi_segment_macro_resolutions: Default::default(),
1873 lint_buffer: LintBuffer::default(),
1874 owners,
1875 current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
1876 invocation_parents,
1877 trait_impls: Default::default(),
1878 confused_type_with_std_module: Default::default(),
1879 stripped_cfg_items: Default::default(),
1880 effective_visibilities: Default::default(),
1881 macro_reachable_adts: Default::default(),
1882 doc_link_resolutions: Default::default(),
1883 doc_link_traits_in_scope: Default::default(),
1884 current_crate_outer_attr_insert_span,
1885 disambiguators: Default::default(),
1886 delegation_infos: Default::default(),
1887 delegation_inherent_fn_map: Default::default(),
1888 features: tcx.features(),
1889 ..
1890 };
1891
1892 if let Some(directive) = OnUnknownData::from_attrs(&resolver, attrs) {
1893 resolver.on_unknown_data.insert(CRATE_DEF_ID, directive);
1894 }
1895
1896 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1897 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1898 resolver.feed_visibility(crate_feed, Visibility::Public);
1899
1900 resolver
1901 }
1902
1903 fn new_local_module(
1904 &mut self,
1905 parent: Option<LocalModule<'ra>>,
1906 kind: ModuleKind,
1907 expn_id: ExpnId,
1908 span: Span,
1909 no_implicit_prelude: bool,
1910 ) -> LocalModule<'ra> {
1911 let vis =
1912 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1913 let module =
1914 LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
1915 self.local_modules.push(module);
1916 if let Some(def_id) = module.opt_def_id() {
1917 self.local_module_map.insert(def_id.expect_local(), module);
1918 }
1919 module
1920 }
1921
1922 fn next_node_id(&mut self) -> NodeId {
1923 let start = self.next_node_id;
1924 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1925 self.next_node_id = ast::NodeId::from_u32(next);
1926 start
1927 }
1928
1929 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1930 let start = self.next_node_id;
1931 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1932 self.next_node_id = ast::NodeId::from_usize(end);
1933 start..self.next_node_id
1934 }
1935
1936 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1937 &mut self.lint_buffer
1938 }
1939
1940 pub fn arenas() -> ResolverArenas<'ra> {
1941 Default::default()
1942 }
1943
1944 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1945 feed.visibility(vis.to_mod_id());
1946 self.visibilities_for_hashing.push((feed.def_id(), vis));
1947 }
1948
1949 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1950 let proc_macros = self.proc_macros;
1951 let expn_that_defined = self.expn_that_defined;
1952 let extern_crate_map = self.extern_crate_map;
1953 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1954 let glob_map = self.glob_map;
1955 let main_def = self.main_def;
1956 let confused_type_with_std_module = self.confused_type_with_std_module;
1957 let effective_visibilities = self.effective_visibilities;
1958
1959 let stripped_cfg_items = self
1960 .stripped_cfg_items
1961 .into_iter()
1962 .filter_map(|item| {
1963 let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
1964 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
1965 })
1966 .collect();
1967 let disambiguators = self
1968 .disambiguators
1969 .into_items()
1970 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
1971 .collect();
1972
1973 let global_ctxt = ResolverGlobalCtxt {
1974 expn_that_defined,
1975 visibilities_for_hashing: self.visibilities_for_hashing,
1976 effective_visibilities,
1977 macro_reachable_adts: self.macro_reachable_adts,
1978 extern_crate_map,
1979 module_children: self.module_children,
1980 ambig_module_children: self.ambig_module_children,
1981 glob_map,
1982 maybe_unused_trait_imports,
1983 main_def,
1984 trait_impls: self.trait_impls,
1985 proc_macros,
1986 confused_type_with_std_module,
1987 doc_link_resolutions: self.doc_link_resolutions,
1988 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1989 all_macro_rules: self.all_macro_rules,
1990 stripped_cfg_items,
1991 delegation_infos: self.delegation_infos,
1992 delegation_inherent_fn_map: self.delegation_inherent_fn_map,
1993 };
1994 let ast_lowering = ResolverAstLowering {
1995 partial_res_map: self.partial_res_map,
1996 next_node_id: self.next_node_id,
1997 owners: self.owners,
1998 lint_buffer: Steal::new(self.lint_buffer),
1999 disambiguators,
2000 };
2001 ResolverOutputs { global_ctxt, ast_lowering }
2002 }
2003
2004 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
2005 CStore::from_tcx(self.tcx)
2006 }
2007
2008 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
2009 CStore::from_tcx_mut(self.tcx)
2010 }
2011
2012 fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
2013 match macro_kind {
2014 MacroKind::Bang => self.dummy_ext_bang,
2015 MacroKind::Derive => self.dummy_ext_derive,
2016 MacroKind::Attr => self.non_macro_attr,
2017 }
2018 }
2019
2020 fn cm(&self) -> CmResolver<'_, 'ra, 'tcx> {
2022 CmResolver::Ref(self)
2023 }
2024
2025 fn cm_mut(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
2028 if !!self.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("can\'t mutably borrow speculative resolver"));
}
};assert!(
2029 !self.speculative_flag.is_speculative(),
2030 "can't mutably borrow speculative resolver"
2031 );
2032 CmResolver::Mut(self)
2033 }
2034
2035 fn per_ns<F: FnMut(&Self, Namespace)>(&self, mut f: F) {
2037 f(self, TypeNS);
2038 f(self, ValueNS);
2039 f(self, MacroNS);
2040 }
2041
2042 fn per_ns_mut<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2043 f(self, TypeNS);
2044 f(self, ValueNS);
2045 f(self, MacroNS);
2046 }
2047
2048 fn is_builtin_macro(&self, res: Res) -> bool {
2049 self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
2050 }
2051
2052 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2053 self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
2054 }
2055
2056 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2057 loop {
2058 match ctxt.outer_expn_data().macro_def_id {
2059 Some(def_id) => return def_id,
2060 None => ctxt.remove_mark(),
2061 };
2062 }
2063 }
2064
2065 pub fn resolve_crate(&mut self, krate: &Crate) {
2067 self.tcx.sess.time("resolve_crate", || {
2068 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2069 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2070 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2071 });
2072 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2073 self.tcx
2074 .sess
2075 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2076 let (use_items, use_injections) =
2077 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2078 self.tcx.sess.time("resolve_main", || self.resolve_main());
2079 self.tcx.sess.time("resolve_check_unused", || self.check_unused(use_items));
2080 self.tcx
2081 .sess
2082 .time("resolve_report_errors", || self.report_errors(krate, use_injections));
2083 self.tcx
2084 .sess
2085 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2086 });
2087
2088 self.tcx.untracked().freeze_cstore();
2090 }
2091
2092 fn traits_in_scope(
2093 &mut self,
2094 current_trait: Option<Module<'ra>>,
2095 parent_scope: &ParentScope<'ra>,
2096 sp: Span,
2097 assoc_item: Option<(Symbol, Namespace)>,
2098 ) -> &'tcx [TraitCandidate<'tcx>] {
2099 let mut found_traits = Vec::new();
2100
2101 if let Some(module) = current_trait {
2102 if self.trait_may_have_item(Some(module), assoc_item) {
2103 let def_id = module.def_id();
2104 found_traits.push(TraitCandidate {
2105 def_id,
2106 import_ids: &[],
2107 lint_ambiguous: false,
2108 });
2109 }
2110 }
2111
2112 let scope_set = ScopeSet::All(TypeNS);
2113 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2114 let cmr = self.cm_mut();
2115 cmr.visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2116 match scope {
2117 Scope::ModuleNonGlobs(module, _) => {
2118 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2119 }
2120 Scope::ModuleGlobs(..) => {
2121 }
2123 Scope::StdLibPrelude => {
2124 if let Some(module) = this.prelude {
2125 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2126 }
2127 }
2128 Scope::ExternPreludeItems
2129 | Scope::ExternPreludeFlags
2130 | Scope::ToolAttributePrelude
2131 | Scope::BuiltinTypes => {}
2132 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2133 }
2134 ControlFlow::<()>::Continue(())
2135 });
2136
2137 self.tcx.hir_arena.alloc_slice(&found_traits)
2138 }
2139
2140 fn traits_in_module(
2141 &mut self,
2142 module: Module<'ra>,
2143 assoc_item: Option<(Symbol, Namespace)>,
2144 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2145 ) {
2146 module.ensure_traits(self);
2147 let traits = module.traits.borrow(self);
2148 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2149 traits.as_ref().unwrap().iter()
2150 {
2151 if self.trait_may_have_item(trait_module, assoc_item) {
2152 let def_id = trait_binding.res().def_id();
2153 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2154 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2155 }
2156 }
2157 }
2158
2159 fn trait_may_have_item(
2165 &self,
2166 trait_module: Option<Module<'ra>>,
2167 assoc_item: Option<(Symbol, Namespace)>,
2168 ) -> bool {
2169 match (trait_module, assoc_item) {
2170 (Some(trait_module), Some((name, ns))) => self
2171 .resolutions(trait_module)
2172 .iter()
2173 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2174 _ => true,
2175 }
2176 }
2177
2178 fn find_transitive_imports(
2179 &mut self,
2180 mut kind: &DeclKind<'_>,
2181 trait_name: Symbol,
2182 ) -> &'tcx [LocalDefId] {
2183 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2184 while let DeclKind::Import { import, source_decl, .. } = kind {
2185 if let Some(def_id) = import.def_id() {
2186 self.maybe_unused_trait_imports.insert(def_id);
2187 import_ids.push(def_id);
2188 }
2189 self.add_to_glob_map(*import, trait_name);
2190 kind = &source_decl.kind;
2191 }
2192
2193 self.tcx.hir_arena.alloc_slice(&import_ids)
2194 }
2195
2196 fn resolutions(&self, module: Module<'ra>) -> CmRef<'ra, ResolutionTable<'ra>> {
2197 match &module.0.0.lazy_resolutions {
2198 Resolutions::Local(local_res) => local_res.borrow_checked(self),
2199 Resolutions::Extern(extern_res) => {
2200 CmRef::Untracked(
2203 extern_res
2205 .get_or_init(|| self.build_reduced_graph_external(module.expect_extern())),
2206 )
2207 }
2208 }
2209 }
2210
2211 fn resolutions_mut(&mut self, module: Module<'ra>) -> RefMut<'ra, ResolutionTable<'ra>> {
2212 match &module.0.0.lazy_resolutions {
2213 Resolutions::Local(local_res) => local_res.borrow_mut(self),
2214 Resolutions::Extern(_) => {
2215 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Attempted to mutably borrow an extenral resolution table")));
}unreachable!("Attempted to mutably borrow an extenral resolution table")
2218 }
2219 }
2220 }
2221
2222 fn resolution(
2223 &self,
2224 module: Module<'ra>,
2225 key: BindingKey,
2226 ) -> Option<CmRef<'ra, NameResolution<'ra>>> {
2227 self.resolutions(module).get(&key).map(|resolution| resolution.0.borrow_checked(self))
2228 }
2229
2230 #[track_caller]
2231 fn resolution_or_default(
2232 &mut self,
2233 module: Module<'ra>,
2234 key: BindingKey,
2235 orig_ident_span: Span,
2236 ) -> NameResolutionRef<'ra> {
2237 *self.resolutions_mut(module).entry(key).or_insert_with(|| {
2238 self.arenas.alloc_name_resolution(NameResolution::new(orig_ident_span))
2239 })
2240 }
2241
2242 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2244 for ambiguity_error in &self.ambiguity_errors {
2245 if ambiguity_error.kind == ambi.kind
2247 && ambiguity_error.ident == ambi.ident
2248 && ambiguity_error.ident.span == ambi.ident.span
2249 && ambiguity_error.b1.span == ambi.b1.span
2250 && ambiguity_error.b2.span == ambi.b2.span
2251 {
2252 return true;
2253 }
2254 }
2255 false
2256 }
2257
2258 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2259 if let Some((b2, warning)) = used_decl.ambiguity.get() {
2260 let ambiguity_error = AmbiguityError {
2261 kind: AmbiguityKind::GlobVsGlob,
2262 ambig_vis: None,
2263 ident,
2264 b1: used_decl,
2265 b2,
2266 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2267 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2268 warning: if warning { Some(AmbiguityWarning::GlobImport) } else { None },
2269 };
2270 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2271 self.ambiguity_errors.push(ambiguity_error);
2273 }
2274 }
2275 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2276 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2277 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2280 let empty_module = self.empty_module;
2281 let arenas = self.arenas;
2282 self.cm()
2283 .maybe_resolve_ident_in_module(
2284 ModuleOrUniformRoot::Module(prelude),
2285 ident,
2286 MacroNS,
2287 &ParentScope::module(empty_module, arenas),
2288 None,
2289 )
2290 .is_ok()
2291 });
2292 if !found_in_stdlib_prelude {
2293 self.lint_buffer().buffer_lint(
2294 PRIVATE_MACRO_USE,
2295 import.root_id,
2296 ident.span,
2297 diagnostics::MacroIsPrivate { ident },
2298 );
2299 }
2300 }
2301 if used == Used::Scope
2304 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2305 && let Some((item_decl, _, false)) = entry.item_decl
2306 && item_decl == used_decl
2307 {
2308 return;
2309 }
2310 let old_used = self.import_use_map.entry(import).or_insert(used);
2311 if *old_used < used {
2312 *old_used = used;
2313 }
2314 if let Some(id) = import.id() {
2315 self.used_imports.insert(id);
2316 }
2317 self.add_to_glob_map(import, ident.name);
2318 self.record_use(ident, source_decl, Used::Other);
2319 }
2320 }
2321
2322 #[inline]
2323 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2324 if let ImportKind::Glob { def_id, .. } = import.kind {
2325 self.glob_map.entry(def_id).or_default().insert(name);
2326 }
2327 }
2328
2329 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2330 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2330",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2330u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?})",
ident) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_crate_root({:?})", ident);
2331 let mut ctxt = ident.span.ctxt();
2332 let mark = if ident.name == kw::DollarCrate {
2333 ctxt = ctxt.normalize_to_macro_rules();
2340 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2340",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2340u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
2341 "resolve_crate_root: marks={:?}",
2342 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2343 );
2344 let mut iter = ctxt.marks().into_iter().rev().peekable();
2345 let mut result = None;
2346 while let Some(&(mark, transparency)) = iter.peek() {
2348 if transparency == Transparency::Opaque {
2349 result = Some(mark);
2350 iter.next();
2351 } else {
2352 break;
2353 }
2354 }
2355 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2355",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2355u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2356 "resolve_crate_root: found opaque mark {:?} {:?}",
2357 result,
2358 result.map(|r| r.expn_data())
2359 );
2360 for (mark, transparency) in iter {
2362 if transparency == Transparency::SemiOpaque {
2363 result = Some(mark);
2364 } else {
2365 break;
2366 }
2367 }
2368 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2368",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2368u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
2369 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2370 result,
2371 result.map(|r| r.expn_data())
2372 );
2373 result
2374 } else {
2375 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2375",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2375u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2376 ctxt = ctxt.normalize_to_macros_2_0();
2377 ctxt.adjust(ExpnId::root())
2378 };
2379 let module = match mark {
2380 Some(def) => self.expn_def_scope(def),
2381 None => {
2382 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2382",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2382u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
ident, ident.span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2383 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2384 ident, ident.span
2385 );
2386 return self.graph_root.to_module();
2387 }
2388 };
2389 let module = self.expect_module(
2390 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2391 );
2392 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2392",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2392u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): got module {1:?} ({2:?}) (ident.span = {3:?})",
ident, module, module.name(), ident.span) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2393 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2394 ident,
2395 module,
2396 module.name(),
2397 ident.span
2398 );
2399 module
2400 }
2401
2402 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2403 let mut module = self.expect_module(module.nearest_parent_mod().to_def_id());
2404 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2405 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2406 module = self.expect_module(parent.nearest_parent_mod().to_def_id());
2407 }
2408 module
2409 }
2410
2411 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2412 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2412",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2412u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(recording res) recording {0:?} for {1}",
resolution, node_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2413 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2414 {
::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)");
2415 }
2416 }
2417
2418 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2419 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs:2419",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2419u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
node, span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2420 self.pat_span_map.insert(node, span);
2421 }
2422
2423 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2424 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2425 }
2426
2427 fn disambiguate_macro_rules_vs_modularized(
2428 &self,
2429 macro_rules: Decl<'ra>,
2430 modularized: Decl<'ra>,
2431 ) -> bool {
2432 let macro_rules = macro_rules.parent_module.unwrap();
2440 let modularized = modularized.parent_module.unwrap();
2441 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2442 && modularized.is_ancestor_of(macro_rules)
2443 }
2444
2445 fn extern_prelude_get_item<'r>(
2446 mut self: CmResolver<'r, 'ra, 'tcx>,
2447 ident: IdentKey,
2448 orig_ident_span: Span,
2449 finalize: bool,
2450 ) -> Option<Decl<'ra>> {
2451 let entry = self.extern_prelude.get(&ident);
2452 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2453 if finalize {
2454 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2455 }
2456 decl
2457 })
2458 }
2459
2460 fn extern_prelude_get_flag(
2461 &self,
2462 ident: IdentKey,
2463 orig_ident_span: Span,
2464 finalize: bool,
2465 ) -> Option<Decl<'ra>> {
2466 let entry = self.extern_prelude.get(&ident);
2467 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2468 let mut flag_decl = flag_decl.lock(); let (pending_decl, finalized, is_open) = *flag_decl;
2470 let decl = match pending_decl {
2471 PendingDecl::Ready(decl) => {
2472 if finalize && !finalized && !is_open {
2473 self.cstore_mut().process_path_extern(
2474 self.tcx,
2475 ident.name,
2476 orig_ident_span,
2477 );
2478 }
2479 decl
2480 }
2481 PendingDecl::Pending => {
2482 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2483 if is_open {
2484 let res = Res::OpenMod(ident.name);
2485 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2486 } else {
2487 let crate_id = if finalize {
2488 self.cstore_mut().process_path_extern(
2489 self.tcx,
2490 ident.name,
2491 orig_ident_span,
2492 )
2493 } else {
2494 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2495 };
2496 crate_id.map(|crate_id| {
2497 let def_id = crate_id.as_def_id();
2498 let res = Res::Def(DefKind::Mod, def_id);
2499 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2500 })
2501 }
2502 }
2503 };
2504 *flag_decl = (PendingDecl::Ready(decl), finalize || finalized, is_open);
2505 decl.or_else(|| finalize.then_some(self.dummy_decl))
2506 })
2507 }
2508
2509 fn resolve_rustdoc_path(
2514 &self,
2515 path_str: &str,
2516 ns: Namespace,
2517 parent_scope: ParentScope<'ra>,
2518 ) -> Option<Res> {
2519 let segments: Result<Vec<_>, ()> = path_str
2520 .split("::")
2521 .enumerate()
2522 .map(|(i, s)| {
2523 let sym = if s.is_empty() {
2524 if i == 0 {
2525 kw::PathRoot
2527 } else {
2528 return Err(()); }
2530 } else {
2531 Symbol::intern(s)
2532 };
2533 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2534 })
2535 .collect();
2536 let Ok(segments) = segments else { return None };
2537
2538 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2539 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2540 PathResult::NonModule(path_res) => {
2541 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(..), _)))
2542 }
2543 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2544 None
2545 }
2546 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2547 bug_impl(None, format_args!("got invalid path_result: {0:?}", path_result),
Location::caller())bug!("got invalid path_result: {path_result:?}")
2548 }
2549 }
2550 }
2551
2552 fn def_span(&self, def_id: DefId) -> Span {
2554 match def_id.as_local() {
2555 Some(def_id) => self.tcx.source_span(def_id),
2556 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2558 }
2559 }
2560
2561 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2562 match def_id.as_local() {
2563 Some(def_id) => self.field_names.get(&def_id).cloned(),
2564 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2565 self.tcx.def_kind(def_id),
2566 DefKind::Struct | DefKind::Union | DefKind::Variant
2567 ) =>
2568 {
2569 Some(
2570 self.tcx
2571 .associated_item_def_ids(def_id)
2572 .iter()
2573 .map(|&def_id| {
2574 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2575 })
2576 .collect(),
2577 )
2578 }
2579 _ => None,
2580 }
2581 }
2582
2583 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2584 match def_id.as_local() {
2585 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2586 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2587 self.tcx.def_kind(def_id),
2588 DefKind::Struct | DefKind::Union | DefKind::Variant
2589 ) =>
2590 {
2591 Some(
2592 self.tcx
2593 .associated_item_def_ids(def_id)
2594 .iter()
2595 .filter_map(|&def_id| {
2596 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2597 })
2598 .collect(),
2599 )
2600 }
2601 _ => None,
2602 }
2603 }
2604
2605 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2609 let ExprKind::Path(None, path) = &expr.kind else {
2610 return None;
2611 };
2612 if path.segments.last().unwrap().args.is_some() {
2615 return None;
2616 }
2617
2618 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2619
2620 if def_id.is_local() {
2624 return None;
2625 }
2626
2627 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcLegacyConstGenerics {
fn_indexes, .. }) => {
break 'done Some(fn_indexes);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
2628 self.tcx, def_id,
2630 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2631 )
2632 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2633 }
2634
2635 fn resolve_main(&mut self) {
2636 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2637 if !any_exe {
2639 return;
2640 }
2641
2642 let module = self.graph_root;
2643 let ident = Ident::with_dummy_span(sym::main);
2644 let parent_scope = &ParentScope::module(module, self.arenas);
2645
2646 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2647 ModuleOrUniformRoot::Module(module.to_module()),
2648 ident,
2649 ValueNS,
2650 parent_scope,
2651 None,
2652 ) else {
2653 return;
2654 };
2655
2656 let res = name_binding.res();
2657 let is_import = name_binding.is_import();
2658 let span = name_binding.span;
2659 if let Res::Def(DefKind::Fn, _) = res {
2660 self.record_use(ident, name_binding, Used::Other);
2661 }
2662 self.main_def = Some(MainDefinition { res, is_import, span });
2663 }
2664}
2665
2666fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2667 this: &mut R,
2668 owner: NodeId,
2669 work: impl FnOnce(&mut R) -> T,
2670) -> T {
2671 let tables = this.as_mut().owners.remove(&owner).unwrap();
2672 with_owner_tables(this, owner, tables, work)
2673}
2674
2675{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("with_owner_tables",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2675u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("owner")
}> =
::tracing::__macro_support::FieldName::new("owner");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("tables")
}> =
::tracing::__macro_support::FieldName::new("tables");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&owner)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tables)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: T = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !!this.as_mut().owners.contains_key(&owner) {
::core::panicking::panic("assertion failed: !this.as_mut().owners.contains_key(&owner)")
};
};
let resolver = this.as_mut();
let old_owner = mem::replace(&mut resolver.current_owner, tables);
let ret = work(this);
let resolver = this.as_mut();
let overwritten =
resolver.owners.insert(owner,
mem::replace(&mut resolver.current_owner, old_owner));
if !overwritten.is_none() {
::core::panicking::panic("assertion failed: overwritten.is_none()")
};
ret
}
}
}#[instrument(level = "debug", skip(this, work))]
2676fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2677 this: &mut R,
2678 owner: NodeId,
2679 tables: PerOwnerResolverData<'tcx>,
2680 work: impl FnOnce(&mut R) -> T,
2681) -> T {
2682 debug_assert!(!this.as_mut().owners.contains_key(&owner));
2683 let resolver = this.as_mut();
2684 let old_owner = mem::replace(&mut resolver.current_owner, tables);
2685 let ret = work(this);
2686 let resolver = this.as_mut();
2687 let overwritten =
2688 resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2689 assert!(overwritten.is_none());
2690 ret
2691}
2692
2693fn build_extern_prelude<'tcx, 'ra>(
2694 tcx: TyCtxt<'tcx>,
2695 attrs: &[ast::Attribute],
2696) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2697 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2698 .sess
2699 .opts
2700 .externs
2701 .iter()
2702 .filter_map(|(name, entry)| {
2703 if entry.add_prelude
2706 && let sym = Symbol::intern(name)
2707 && sym.can_be_raw()
2708 {
2709 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2710 } else {
2711 None
2712 }
2713 })
2714 .collect();
2715
2716 let missing_open_bases: Vec<IdentKey> = extern_prelude
2722 .keys()
2723 .filter_map(|ident| {
2724 let (base, _) = ident.name.as_str().split_once("::")?;
2725 let base_sym = Symbol::intern(base);
2726 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2727 })
2728 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2729 .collect();
2730
2731 extern_prelude.extend(
2732 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2733 );
2734
2735 if !attr::contains_name(attrs, sym::no_core) {
2737 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2738
2739 if !attr::contains_name(attrs, sym::no_std) {
2740 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2741 }
2742 }
2743
2744 extern_prelude
2745}
2746
2747fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2748 let mut result = String::new();
2749 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2750 if i > 0 {
2751 result.push_str("::");
2752 }
2753 if Ident::with_dummy_span(name).is_raw_guess() {
2754 result.push_str("r#");
2755 }
2756 result.push_str(name.as_str());
2757 }
2758 result
2759}
2760
2761fn path_names_to_string(path: &Path) -> String {
2762 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2763}
2764
2765fn module_to_string(mut module: Module<'_>) -> Option<String> {
2767 let mut names = Vec::new();
2768 while let Some(parent) = module.parent {
2769 names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2770 module = parent;
2771 }
2772 if names.is_empty() {
2773 return None;
2774 }
2775 Some(names_to_string(names.iter().rev().copied()))
2776}
2777
2778#[derive(#[automatically_derived]
impl ::core::marker::Copy for Stage { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Stage { }
#[automatically_derived]
impl ::core::clone::Clone for Stage {
#[inline]
fn clone(&self) -> Stage { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Stage { }
#[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)]
2779enum Stage {
2780 Early,
2784 Late,
2787}
2788
2789#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImportSummary { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImportSummary { }
#[automatically_derived]
impl ::core::clone::Clone for ImportSummary {
#[inline]
fn clone(&self) -> ImportSummary {
let _: ::core::clone::AssertParamIsClone<Visibility>;
let _: ::core::clone::AssertParamIsClone<LocalModId>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ImportSummary {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f, "ImportSummary",
"vis", &self.vis, "nearest_parent_mod", &self.nearest_parent_mod,
"is_single", &self.is_single, "priv_macro_use",
&self.priv_macro_use, "span", &&self.span)
}
}Debug)]
2792struct ImportSummary {
2793 vis: Visibility,
2794 nearest_parent_mod: LocalModId,
2795 is_single: bool,
2796 priv_macro_use: bool,
2797 span: Span,
2798}
2799
2800#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Finalize { }
#[automatically_derived]
impl ::core::clone::Clone for Finalize {
#[inline]
fn clone(&self) -> Finalize {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Used>;
let _: ::core::clone::AssertParamIsClone<Stage>;
let _: ::core::clone::AssertParamIsClone<Option<ImportSummary>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["node_id", "path_span", "root_span", "report_private", "used",
"stage", "import"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.node_id, &self.path_span, &self.root_span,
&self.report_private, &self.used, &self.stage,
&&self.import];
::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
names, values)
}
}Debug)]
2802struct Finalize {
2803 node_id: NodeId,
2805 path_span: Span,
2808 root_span: Span,
2811 report_private: bool = true,
2814 used: Used = Used::Other,
2816 stage: Stage = Stage::Early,
2818 import: Option<ImportSummary> = None,
2820}
2821
2822impl Finalize {
2823 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2824 Finalize::with_root_span(node_id, path_span, path_span)
2825 }
2826
2827 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2828 Finalize { node_id, path_span, root_span, .. }
2829 }
2830}
2831
2832pub fn provide(providers: &mut Providers) {
2833 providers.registered_attr_tools = macros::registered_attr_tools;
2834 providers.registered_lint_tools = macros::registered_lint_tools;
2835}
2836
2837type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2843
2844mod ref_mut {
2845 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2846 use std::fmt;
2847 use std::ops::Deref;
2848
2849 use crate::Resolver;
2850
2851 pub(crate) enum RefOrMut<'a, T> {
2853 Ref(&'a T),
2854 Mut(&'a mut T),
2855 }
2856
2857 impl<'a, T> Deref for RefOrMut<'a, T> {
2858 type Target = T;
2859
2860 fn deref(&self) -> &Self::Target {
2861 match self {
2862 RefOrMut::Ref(r) => r,
2863 RefOrMut::Mut(r) => r,
2864 }
2865 }
2866 }
2867
2868 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2869 fn as_ref(&self) -> &T {
2870 &*self
2871 }
2872 }
2873
2874 impl<'a, T> RefOrMut<'a, T> {
2875 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2877 match self {
2878 RefOrMut::Ref(r) => RefOrMut::Ref(r),
2879 RefOrMut::Mut(r) => RefOrMut::Mut(r),
2880 }
2881 }
2882
2883 #[track_caller]
2889 pub(crate) fn get_mut(&mut self) -> &mut T {
2890 match self {
2891 RefOrMut::Ref(_) => {
::core::panicking::panic_fmt(format_args!("can\'t mutably borrow an immutable reference"));
}panic!("can't mutably borrow an immutable reference"),
2892 RefOrMut::Mut(r) => r,
2893 }
2894 }
2895 }
2896
2897 #[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)]
2899 pub(crate) struct CmCell<T>(Cell<T>);
2900
2901 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2903 f.debug_tuple("CmCell").field(&self.get()).finish()
2904 }
2905 }
2906
2907 impl<T: Copy> Clone for CmCell<T> {
2908 fn clone(&self) -> CmCell<T> {
2909 CmCell::new(self.get())
2910 }
2911 }
2912
2913 impl<T: Copy> CmCell<T> {
2914 pub(crate) const fn get(&self) -> T {
2915 self.0.get()
2916 }
2917
2918 pub(crate) fn update<'ra, 'tcx>(
2919 &self,
2920 r: &mut Resolver<'ra, 'tcx>,
2921 f: impl FnOnce(T) -> T,
2922 ) {
2923 let old = self.get();
2924 self.set(f(old), r);
2925 }
2926 }
2927
2928 impl<T> CmCell<T> {
2929 pub(crate) const fn new(value: T) -> CmCell<T> {
2930 CmCell(Cell::new(value))
2931 }
2932
2933 pub(crate) fn set<'ra, 'tcx>(&self, val: T, _: &mut Resolver<'ra, 'tcx>) {
2934 self.0.set(val);
2935 }
2936
2937 pub(crate) fn set_checked<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
2938 if !!r.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("Cannot mutate `CmCell` during speculative resolution"));
}
};assert!(
2939 !r.speculative_flag.is_speculative(),
2940 "Cannot mutate `CmCell` during speculative resolution"
2941 );
2942 self.0.set(val);
2943 }
2944
2945 pub(crate) fn into_inner(self) -> T {
2946 self.0.into_inner()
2947 }
2948 }
2949
2950 pub(crate) enum CmRef<'b, T> {
2951 Tracked(Ref<'b, T>),
2953 Untracked(&'b T),
2955 }
2956
2957 impl<'b, T> Deref for CmRef<'b, T> {
2958 type Target = T;
2959
2960 fn deref(&self) -> &Self::Target {
2961 match self {
2962 CmRef::Tracked(r) => r,
2963 CmRef::Untracked(r) => r,
2964 }
2965 }
2966 }
2967
2968 pub(crate) mod speculative {
2969 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for SpeculativeFlag {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SpeculativeFlag", &&self.0)
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpeculativeFlag { }
#[automatically_derived]
impl ::core::clone::Clone for SpeculativeFlag {
#[inline]
fn clone(&self) -> SpeculativeFlag {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SpeculativeFlag { }Copy, #[automatically_derived]
impl ::core::default::Default for SpeculativeFlag {
#[inline]
fn default() -> SpeculativeFlag {
SpeculativeFlag(::core::default::Default::default())
}
}Default)]
2970 pub(crate) struct SpeculativeFlag(bool);
2971
2972 impl SpeculativeFlag {
2973 pub(crate) unsafe fn set(&mut self, value: bool) {
2980 self.0 = value;
2981 }
2982
2983 pub(crate) fn is_speculative(&self) -> bool {
2984 self.0
2985 }
2986 }
2987 }
2988
2989 #[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)]
2991 pub(crate) struct CmRefCell<T>(RefCell<T>);
2992
2993 impl<T> CmRefCell<T> {
2994 pub(crate) fn new(value: T) -> CmRefCell<T> {
2995 CmRefCell(RefCell::new(value))
2996 }
2997
2998 #[track_caller]
2999 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &mut Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
3000 self.try_borrow_mut(r).unwrap()
3001 }
3002
3003 #[track_caller]
3004 pub(crate) fn borrow_mut_checked<'ra, 'tcx>(
3005 &self,
3006 r: &Resolver<'ra, 'tcx>,
3007 ) -> RefMut<'_, T> {
3008 self.try_borrow_mut_checked(r).unwrap()
3009 }
3010
3011 #[track_caller]
3012 pub(crate) fn try_borrow_mut_checked<'ra, 'tcx>(
3013 &self,
3014 r: &Resolver<'ra, 'tcx>,
3015 ) -> Result<RefMut<'_, T>, BorrowMutError> {
3016 if !!r.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("Cannot mutate `CmRefCell` state/value during speculative resolution"));
}
};assert!(
3017 !r.speculative_flag.is_speculative(),
3018 "Cannot mutate `CmRefCell` state/value during speculative resolution"
3019 );
3020 self.0.try_borrow_mut()
3021 }
3022
3023 #[track_caller]
3024 pub(crate) fn try_borrow_mut<'ra, 'tcx>(
3025 &self,
3026 _: &mut Resolver<'ra, 'tcx>,
3027 ) -> Result<RefMut<'_, T>, BorrowMutError> {
3028 self.0.try_borrow_mut()
3029 }
3030
3031 pub(crate) fn borrow<'ra, 'tcx>(&self, _: &mut Resolver<'ra, 'tcx>) -> Ref<'_, T> {
3032 self.0.borrow()
3033 }
3034
3035 pub(crate) fn borrow_checked<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> CmRef<'_, T> {
3036 if r.speculative_flag.is_speculative() {
3037 CmRef::Untracked(unsafe { self.0.try_borrow_unguarded().unwrap() })
3055 } else {
3056 CmRef::Tracked(self.0.borrow())
3057 }
3058 }
3059 }
3060
3061 impl<T: Default> CmRefCell<T> {
3062 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
3063 if r.speculative_flag.is_speculative() {
3064 {
::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");
3065 }
3066 self.0.take()
3067 }
3068 }
3069}
3070
3071mod hygiene {
3072 use rustc_span::{ExpnId, SyntaxContext};
3073
3074 #[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Macros20NormalizedSyntaxContext {
}
#[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::marker::StructuralPartialEq for Macros20NormalizedSyntaxContext {
}
#[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)]
3077 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
3078
3079 impl Macros20NormalizedSyntaxContext {
3080 #[inline]
3081 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3082 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
3083 }
3084
3085 #[inline]
3086 pub(crate) fn new_adjusted(
3087 mut ctxt: SyntaxContext,
3088 expn_id: ExpnId,
3089 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
3090 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
3091 (Macros20NormalizedSyntaxContext(ctxt), def)
3092 }
3093
3094 #[inline]
3095 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3096 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());
3097 Macros20NormalizedSyntaxContext(ctxt)
3098 }
3099
3100 #[inline]
3102 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
3103 let ret = f(&mut self.0);
3104 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());
3105 ret
3106 }
3107 }
3108
3109 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3110 type Target = SyntaxContext;
3111 fn deref(&self) -> &Self::Target {
3112 &self.0
3113 }
3114 }
3115}