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(register_tool)]
20#![feature(rustc_attrs)]
21#![recursion_limit = "256"]
22#![register_tool(lint)]
23use std::cell::RefMut;
26use std::collections::BTreeSet;
27use std::ops::ControlFlow;
28use std::sync::{Arc, OnceLock};
29use std::{fmt, mem};
30
31use diagnostics::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
32use effective_visibilities::EffectiveVisibilitiesVisitor;
33use hygiene::Macros20NormalizedSyntaxContext;
34use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
35use late::{
36 ConstantRequiresType, ForwardGenericParamBanReason, HasGenericParams, PathSource,
37 PatternSource, UnnecessaryQualification,
38};
39pub use macros::registered_lint_tools_ast;
40use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
41use rustc_arena::{DroplessArena, TypedArena};
42use rustc_ast::node_id::NodeMap;
43use rustc_ast::{
44 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, DUMMY_NODE_ID, Expr, ExprKind,
45 GenericArg, GenericArgs, Generics, NodeId, Path, attr,
46};
47use rustc_attr_ir::{LanguageItems, StrippedCfgItem, find_attr};
48use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
49use rustc_data_structures::intern::Interned;
50use rustc_data_structures::steal::Steal;
51use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard, Lock, RwLock, WorkerLocal};
52use rustc_data_structures::unord::{UnordItems, UnordMap, UnordSet};
53use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
54use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
55use rustc_feature::{BUILTIN_ATTRIBUTES, Features};
56use rustc_hir::def::Namespace::{self, *};
57use rustc_hir::def::{self, CtorOf, DefKind, MacroKinds, NonMacroAttrKind, PerNS};
58use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
59use rustc_hir::definitions::{PerParentDisambiguatorState, PerParentDisambiguatorsMap};
60use rustc_hir::{PrimTy, TraitCandidate};
61use rustc_index::bit_set::DenseBitSet;
62use rustc_lint_defs::builtin::PRIVATE_MACRO_USE;
63use rustc_metadata::creader::CStore;
64use rustc_middle::middle::privacy::EffectiveVisibilities;
65use rustc_middle::middle::resolve::{
66 AmbigModChild, DelegationInfo, DelegationInherentFnKind, DocLinkResMap, MainDefinition,
67 ModChild, PartialRes, PerOwnerResolverData, Reexport, ResolverAstLowering, ResolverGlobalCtxt,
68};
69use rustc_middle::query::Providers;
70use rustc_middle::ty::{self, RegisteredTools, TyCtxt, TyCtxtFeed, Visibility};
71use rustc_span::def_id::{LocalModId, ModId};
72use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
73use rustc_span::{DUMMY_SP, Ident, OrdSpan, Span, Symbol, bug, kw, span_bug, sym};
74use rustc_structures::CrateType;
75use smallvec::{SmallVec, smallvec};
76use tracing::{debug, instrument};
77
78use crate::diagnostics::impls::{
79 ImportSuggestion, LabelSuggestion, OnUnknownData, StructCtor, Suggestion,
80};
81use crate::imports::{ImportResolution, NameResolutionRef};
82use crate::ref_mut::speculative::SpeculativeFlag;
83use crate::ref_mut::{CmCell, CmRef, CmRefCell};
84
85mod build_reduced_graph;
86mod check_unused;
87mod def_collector;
88mod diagnostics;
89mod effective_visibilities;
90mod ident;
91mod imports;
92mod late;
93mod macros;
94pub mod rustdoc;
95
96type Res = def::Res<NodeId>;
97
98#[derive(#[automatically_derived]impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Determinacy {
}
#[automatically_derived]impl ::core::clone::Clone for Determinacy {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
Determinacy {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Determinacy {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for Determinacy {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Determinacy::Determined => "Determined",
Determinacy::Undetermined => "Undetermined",
})
}
}Debug)]
99enum Determinacy {
100 Determined,
101 Undetermined,
102}
103
104impl Determinacy {
105 fn determined(determined: bool) -> Determinacy {
106 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
107 }
108}
109
110#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'ra>
::core::clone::TrivialClone for Scope<'ra> {
}
#[automatically_derived]impl<'ra> ::core::clone::Clone for Scope<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::DeriveHelpers(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"DeriveHelpers", &__self_0),
Self::DeriveHelpersCompat =>
::core::fmt::Formatter::write_str(f, "DeriveHelpersCompat"),
Self::MacroRules(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"MacroRules", &__self_0),
Self::ModuleNonGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ModuleNonGlobs", __self_0, &__self_1),
Self::ModuleGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ModuleGlobs", __self_0, &__self_1),
Self::MacroUsePrelude =>
::core::fmt::Formatter::write_str(f, "MacroUsePrelude"),
Self::BuiltinAttrs =>
::core::fmt::Formatter::write_str(f, "BuiltinAttrs"),
Self::ExternPreludeItems =>
::core::fmt::Formatter::write_str(f, "ExternPreludeItems"),
Self::ExternPreludeFlags =>
::core::fmt::Formatter::write_str(f, "ExternPreludeFlags"),
Self::ToolAttributePrelude =>
::core::fmt::Formatter::write_str(f, "ToolAttributePrelude"),
Self::StdLibPrelude =>
::core::fmt::Formatter::write_str(f, "StdLibPrelude"),
Self::BuiltinTypes =>
::core::fmt::Formatter::write_str(f, "BuiltinTypes"),
}
}
}Debug)]
112enum Scope<'ra> {
113 DeriveHelpers(LocalExpnId),
115 DeriveHelpersCompat,
119 MacroRules(MacroRulesScopeRef<'ra>),
121 ModuleNonGlobs(Module<'ra>, Option<NodeId>),
125 ModuleGlobs(Module<'ra>, Option<NodeId>),
129 MacroUsePrelude,
131 BuiltinAttrs,
133 ExternPreludeItems,
135 ExternPreludeFlags,
137 ToolAttributePrelude,
139 StdLibPrelude,
141 BuiltinTypes,
143}
144
145#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::All(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "All",
&__self_0),
Self::Module(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Module", __self_0, &__self_1),
Self::ModuleAndExternPrelude(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ModuleAndExternPrelude", __self_0, &__self_1),
Self::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
Self::Macro(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Macro",
&__self_0),
}
}
}Debug)]
148enum ScopeSet<'ra> {
149 All(Namespace),
151 Module(Namespace, Module<'ra>),
153 ModuleAndExternPrelude(Namespace, Module<'ra>),
155 ExternPrelude,
157 Macro(MacroKind),
159}
160
161#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'ra>
::core::clone::TrivialClone for ParentScope<'ra> {
}
#[automatically_derived]impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ParentScope module expansion macro_rules derives", &self.module,
&self.expansion, &self.macro_rules, &&self.derives)
}
}Debug)]
166struct ParentScope<'ra> {
167 module: Module<'ra>,
168 expansion: LocalExpnId,
169 macro_rules: MacroRulesScopeRef<'ra>,
170 derives: &'ra [ast::Path],
171}
172
173impl<'ra> ParentScope<'ra> {
174 fn module(module: LocalModule<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
177 ParentScope {
178 module: module.to_module(),
179 expansion: LocalExpnId::ROOT,
180 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
181 derives: &[],
182 }
183 }
184}
185
186#[derive(#[automatically_derived]impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]impl ::core::fmt::Debug for InvocationParent {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"InvocationParent parent_def impl_trait_context in_attr owner",
&self.parent_def, &self.impl_trait_context, &self.in_attr,
&&self.owner)
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for InvocationParent {
}
#[automatically_derived]impl ::core::clone::Clone for InvocationParent {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<NodeId>;
*self
}
}Clone)]
187struct InvocationParent {
188 parent_def: LocalDefId,
189 impl_trait_context: ImplTraitContext,
190 in_attr: bool,
191 owner: NodeId,
192}
193
194impl InvocationParent {
195 const ROOT: Self = Self {
196 parent_def: CRATE_DEF_ID,
197 impl_trait_context: ImplTraitContext::Existential,
198 in_attr: false,
199 owner: CRATE_NODE_ID,
200 };
201}
202
203#[derive(#[automatically_derived]impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ImplTraitContext {
#[inline]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone)]
204enum ImplTraitContext {
205 Existential,
206 Universal,
207 InBinding,
208}
209
210#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Used {
}
#[automatically_derived]impl ::core::clone::Clone for Used {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::PartialOrd for Used {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other))
}
}PartialOrd, #[automatically_derived]impl ::core::fmt::Debug for Used {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Used::Scope => "Scope", Used::Other => "Other", })
}
}Debug)]
225enum Used {
226 Scope,
227 Other,
228}
229
230#[derive(#[automatically_derived]impl ::core::fmt::Debug for BindingError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"BindingError name origin target could_be_path", &self.name,
&self.origin, &self.target, &&self.could_be_path)
}
}Debug)]
231struct BindingError {
232 name: Ident,
233 origin: Vec<(Span, ast::Pat)>,
234 target: Vec<ast::Pat>,
235 could_be_path: bool,
236}
237
238#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for ResolutionError<'ra>
{
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::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 has_generic_params def_kind inner_item current_self_ty",
__self_0, __self_1, __self_2, __self_3, &__self_4),
Self::NameAlreadyUsedInParameterList(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"NameAlreadyUsedInParameterList", __self_0, &__self_1),
Self::MethodNotMemberOfTrait(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
Self::TypeNotMemberOfTrait(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
Self::ConstNotMemberOfTrait(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
Self::VariableNotBoundInPattern(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"VariableNotBoundInPattern", __self_0, &__self_1),
Self::VariableBoundWithDifferentMode(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"VariableBoundWithDifferentMode", __self_0, &__self_1),
Self::IdentifierBoundMoreThanOnceInParameterList(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"IdentifierBoundMoreThanOnceInParameterList", &__self_0),
Self::IdentifierBoundMoreThanOnceInSamePattern(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
Self::UndeclaredLabel { name: __self_0, suggestion: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UndeclaredLabel name suggestion", __self_0, &__self_1),
Self::FailedToResolve {
segment: __self_0,
label: __self_1,
suggestion: __self_2,
help: __self_3,
module: __self_4,
message: __self_5 } =>
::core::fmt::Formatter::debug_struct_fields_finish(f,
"FailedToResolve segment label suggestion help module message",
&[__self_0, __self_1, __self_2, __self_3, __self_4,
&__self_5]),
Self::CannotCaptureDynamicEnvironmentInFnItem {
suggest_closure: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CannotCaptureDynamicEnvironmentInFnItem suggest_closure",
&__self_0),
Self::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 suggestion current type_span requires_type",
__self_0, __self_1, __self_2, __self_3, &__self_4),
Self::BindingShadowsSomethingUnacceptable {
shadowing_binding: __self_0,
name: __self_1,
participle: __self_2,
article: __self_3,
shadowed_binding: __self_4,
shadowed_binding_span: __self_5 } =>
::core::fmt::Formatter::debug_struct_fields_finish(f,
"BindingShadowsSomethingUnacceptable shadowing_binding name participle article shadowed_binding shadowed_binding_span",
&[__self_0, __self_1, __self_2, __self_3, __self_4,
&__self_5]),
Self::ForwardDeclaredGenericParam(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ForwardDeclaredGenericParam", __self_0, &__self_1),
Self::ParamInTyOfConstParam { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ParamInTyOfConstParam name", &__self_0),
Self::SelfInConstParam =>
::core::fmt::Formatter::write_str(f, "SelfInConstParam"),
Self::ParamInNonTrivialAnonConst {
is_gca_const_items: __self_0,
name: __self_1,
param_kind: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ParamInNonTrivialAnonConst is_gca_const_items name param_kind",
__self_0, __self_1, &__self_2),
Self::ParamInEnumDiscriminant {
name: __self_0, param_kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ParamInEnumDiscriminant name param_kind", __self_0,
&__self_1),
Self::ForwardDeclaredSelf(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ForwardDeclaredSelf", &__self_0),
Self::UnreachableLabel {
name: __self_0,
definition_span: __self_1,
suggestion: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"UnreachableLabel name definition_span suggestion",
__self_0, __self_1, &__self_2),
Self::TraitImplMismatch {
name: __self_0,
kind: __self_1,
trait_path: __self_2,
trait_item_span: __self_3,
code: __self_4,
trait_span: __self_5,
impl_span: __self_6 } =>
::core::fmt::Formatter::debug_struct_fields_finish(f,
"TraitImplMismatch name kind trait_path trait_item_span code trait_span impl_span",
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, &__self_6]),
Self::TraitImplDuplicate {
name: __self_0,
trait_item_span: __self_1,
old_span: __self_2,
trait_span: __self_3,
impl_span: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"TraitImplDuplicate name trait_item_span old_span trait_span impl_span",
__self_0, __self_1, __self_2, __self_3, &__self_4),
Self::InvalidAsmSym =>
::core::fmt::Formatter::write_str(f, "InvalidAsmSym"),
Self::LowercaseSelf =>
::core::fmt::Formatter::write_str(f, "LowercaseSelf"),
Self::BindingInNeverPattern =>
::core::fmt::Formatter::write_str(f, "BindingInNeverPattern"),
Self::CannotUseInnerLocalInMoveExpr {
move_expr_span: __self_0,
ident: __self_1,
scope_span: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CannotUseInnerLocalInMoveExpr move_expr_span ident scope_span",
__self_0, __self_1, &__self_2),
}
}
}Debug)]
239enum ResolutionError<'ra> {
240 GenericParamsFromOuterItem {
242 outer_res: Res,
243 has_generic_params: HasGenericParams,
244 def_kind: DefKind,
245 inner_item: Option<(Span, Span, ast::ItemKind)>,
247 current_self_ty: Option<String>,
248 },
249 NameAlreadyUsedInParameterList(Ident, Span),
252 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
254 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
256 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
258 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
260 VariableBoundWithDifferentMode(Ident, Span),
262 IdentifierBoundMoreThanOnceInParameterList(Ident),
264 IdentifierBoundMoreThanOnceInSamePattern(Ident),
266 UndeclaredLabel {
268 name: Symbol,
269 suggestion: Option<LabelSuggestion>,
270 },
271 FailedToResolve {
273 segment: Symbol,
274 label: String,
275 suggestion: Option<Suggestion>,
276 help: Option<String>,
277 module: Option<ModuleOrUniformRoot<'ra>>,
278 message: String,
279 },
280 CannotCaptureDynamicEnvironmentInFnItem {
282 suggest_closure: bool,
283 },
284 AttemptToUseNonConstantValueInConstant {
286 ident: Ident,
287 suggestion: &'static str,
288 current: &'static str,
289 type_span: Option<Span>,
290 requires_type: ConstantRequiresType,
291 },
292 BindingShadowsSomethingUnacceptable {
294 shadowing_binding: PatternSource,
295 name: Symbol,
296 participle: &'static str,
297 article: &'static str,
298 shadowed_binding: Res,
299 shadowed_binding_span: Span,
300 },
301 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
303 ParamInTyOfConstParam {
307 name: Symbol,
308 },
309 SelfInConstParam,
311 ParamInNonTrivialAnonConst {
315 is_gca_const_items: bool,
316 name: Symbol,
317 param_kind: ParamKindInNonTrivialAnonConst,
318 },
319 ParamInEnumDiscriminant {
323 name: Symbol,
324 param_kind: ParamKindInEnumDiscriminant,
325 },
326 ForwardDeclaredSelf(ForwardGenericParamBanReason),
328 UnreachableLabel {
330 name: Symbol,
331 definition_span: Span,
332 suggestion: Option<LabelSuggestion>,
333 },
334 TraitImplMismatch {
336 name: Ident,
337 kind: &'static str,
338 trait_path: String,
339 trait_item_span: Span,
340 code: ErrCode,
341 trait_span: Span,
342 impl_span: Span,
343 },
344 TraitImplDuplicate {
346 name: Ident,
347 trait_item_span: Span,
348 old_span: Span,
349 trait_span: Span,
350 impl_span: Span,
351 },
352 InvalidAsmSym,
354 LowercaseSelf,
356 BindingInNeverPattern,
358 CannotUseInnerLocalInMoveExpr {
359 move_expr_span: Span,
360 ident: Ident,
361 scope_span: Span,
362 },
363}
364
365#[derive(#[automatically_derived]impl ::core::fmt::Debug for VisResolutionError {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Relative2018(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Relative2018", __self_0, &__self_1),
Self::AncestorOnly(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AncestorOnly", &__self_0),
Self::FailedToResolve {
span: __self_0,
segment: __self_1,
label: __self_2,
suggestion: __self_3,
help: __self_4,
message: __self_5 } =>
::core::fmt::Formatter::debug_struct_fields_finish(f,
"FailedToResolve span segment label suggestion help message",
&[__self_0, __self_1, __self_2, __self_3, __self_4,
&__self_5]),
Self::ExpectedFound(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"ExpectedFound", __self_0, __self_1, &__self_2),
Self::Indeterminate(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Indeterminate", &__self_0),
Self::ModuleOnly(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ModuleOnly", &__self_0),
}
}
}Debug)]
366enum VisResolutionError {
367 Relative2018(Span, ast::Path),
368 AncestorOnly(Span),
369 FailedToResolve {
370 span: Span,
371 segment: Symbol,
372 label: String,
373 suggestion: Option<Suggestion>,
374 help: Option<String>,
375 message: String,
376 },
377 ExpectedFound(Span, String, Res),
378 Indeterminate(Span),
379 ModuleOnly(Span),
380}
381
382#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Segment {
}
#[automatically_derived]impl ::core::clone::Clone for Segment {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"Segment ident id has_generic_args has_lifetime_args args_span",
&self.ident, &self.id, &self.has_generic_args,
&self.has_lifetime_args, &&self.args_span)
}
}Debug)]
385struct Segment {
386 ident: Ident,
387 id: Option<NodeId>,
388 has_generic_args: bool,
390 has_lifetime_args: bool,
392 args_span: Span,
393}
394
395impl Segment {
396 fn from_path(path: &Path) -> Vec<Segment> {
397 path.segments.iter().map(|s| s.into()).collect()
398 }
399
400 fn from_ident(ident: Ident) -> Segment {
401 Segment {
402 ident,
403 id: None,
404 has_generic_args: false,
405 has_lifetime_args: false,
406 args_span: DUMMY_SP,
407 }
408 }
409
410 fn names_to_string(segments: &[Segment]) -> String {
411 names_to_string(segments.iter().map(|seg| seg.ident.name))
412 }
413}
414
415impl<'a> From<&'a ast::PathSegment> for Segment {
416 fn from(seg: &'a ast::PathSegment) -> Segment {
417 let has_generic_args = seg.args.is_some();
418 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
419 match args {
420 GenericArgs::AngleBracketed(args) => {
421 let found_lifetimes = args
422 .args
423 .iter()
424 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
425 (args.span, found_lifetimes)
426 }
427 GenericArgs::Parenthesized(args) => (args.span, true),
428 GenericArgs::ParenthesizedElided(span) => (*span, true),
429 }
430 } else {
431 (DUMMY_SP, false)
432 };
433 Segment {
434 ident: seg.ident,
435 id: Some(seg.id),
436 has_generic_args,
437 has_lifetime_args,
438 args_span,
439 }
440 }
441}
442
443#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for LateDecl<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Decl(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Decl",
&__self_0),
Self::RibDef(__self_0) =>
::core::fmt::Formatter::debug_struct_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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Res>;
*self
}
}Clone)]
445enum LateDecl<'ra> {
446 Decl(Decl<'ra>),
448 RibDef(Res),
451}
452
453impl<'ra> LateDecl<'ra> {
454 fn res(self) -> Res {
455 match self {
456 LateDecl::Decl(binding) => binding.res(),
457 LateDecl::RibDef(res) => res,
458 }
459 }
460}
461
462#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Module(__self_0), Self::Module(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::ModuleAndExternPrelude(__self_0),
Self::ModuleAndExternPrelude(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::OpenModule(__self_0), Self::OpenModule(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl<'ra> ::core::fmt::Debug for
ModuleOrUniformRoot<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Module(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Module", &__self_0),
Self::ModuleAndExternPrelude(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ModuleAndExternPrelude", &__self_0),
Self::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
Self::CurrentScope =>
::core::fmt::Formatter::write_str(f, "CurrentScope"),
Self::OpenModule(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"OpenModule", &__self_0),
}
}
}Debug)]
463enum ModuleOrUniformRoot<'ra> {
464 Module(Module<'ra>),
466
467 ModuleAndExternPrelude(Module<'ra>),
471
472 ExternPrelude,
475
476 CurrentScope,
480
481 OpenModule(Symbol),
485}
486
487#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Module(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Module", &__self_0),
Self::NonModule(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"NonModule", &__self_0),
Self::Indeterminate =>
::core::fmt::Formatter::write_str(f, "Indeterminate"),
Self::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 } =>
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Failed span label suggestion help is_error_from_last_segment module segment error_implied_by_parse_error message note",
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, __self_6, __self_7, __self_8, &__self_9]),
}
}
}Debug)]
488enum PathResult<'ra> {
489 Module(ModuleOrUniformRoot<'ra>),
490 NonModule(PartialRes),
491 Indeterminate,
492 Failed {
493 span: Span,
494 label: String,
495 suggestion: Option<Suggestion>,
496 help: Option<String>,
497 is_error_from_last_segment: bool,
498 module: Option<ModuleOrUniformRoot<'ra>>,
512 segment: Ident,
514 error_implied_by_parse_error: bool,
515 message: String,
516 note: Option<String>,
517 },
518}
519
520impl<'ra> PathResult<'ra> {
521 fn failed(
522 ident: Ident,
523 is_error_from_last_segment: bool,
524 finalize: bool,
525 error_implied_by_parse_error: bool,
526 module: Option<ModuleOrUniformRoot<'ra>>,
527 label_and_suggestion_and_note: impl FnOnce() -> (
528 String,
529 String,
530 Option<Suggestion>,
531 Option<String>,
532 Option<String>,
533 ),
534 ) -> PathResult<'ra> {
535 let (message, label, suggestion, note, help) = if finalize {
536 label_and_suggestion_and_note()
537 } else {
538 (::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)
540 };
541 PathResult::Failed {
542 span: ident.span,
543 segment: ident,
544 label,
545 suggestion,
546 help,
547 is_error_from_last_segment,
548 module,
549 error_implied_by_parse_error,
550 message,
551 note,
552 }
553 }
554}
555
556#[derive(#[automatically_derived]impl ::core::fmt::Debug for ModuleKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Block => ::core::fmt::Formatter::write_str(f, "Block"),
Self::Def(__self_0, __self_1, __self_2, __self_3) =>
::core::fmt::Formatter::debug_struct_field4_finish(f, "Def",
__self_0, __self_1, __self_2, &__self_3),
}
}
}Debug)]
557enum ModuleKind {
558 Block,
571 Def(DefKind, DefId, NodeId, Option<Symbol>),
581}
582
583impl ModuleKind {
584 fn opt_def_id(&self) -> Option<DefId> {
585 match self {
586 ModuleKind::Def(_, def_id, _, _) => Some(*def_id),
587 _ => None,
588 }
589 }
590
591 fn def_id(&self) -> DefId {
592 self.opt_def_id().expect("`Module::def_id` is called on a block module")
593 }
594
595 fn is_local(&self) -> bool {
596 match self {
597 ModuleKind::Def(_, def_id, ..) => def_id.is_local(),
598 ModuleKind::Block => true,
599 }
600 }
601}
602
603#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for IdentKey {
}
#[automatically_derived]impl ::core::clone::Clone for IdentKey {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"IdentKey name ctxt", &self.name, &&self.ctxt)
}
}Debug)]
614struct IdentKey {
615 name: Symbol,
616 ctxt: Macros20NormalizedSyntaxContext,
617}
618
619impl IdentKey {
620 #[inline]
621 fn new(ident: Ident) -> IdentKey {
622 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
623 }
624
625 #[inline]
626 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
627 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
628 (IdentKey { name: ident.name, ctxt }, def)
629 }
630
631 #[inline]
632 fn with_root_ctxt(name: Symbol) -> Self {
633 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
634 IdentKey { name, ctxt }
635 }
636
637 #[inline]
638 fn orig(self, orig_ident_span: Span) -> Ident {
639 Ident::new(self.name, orig_ident_span)
640 }
641}
642
643#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"BindingKey ident ns disambiguator", &self.ident, &self.ns,
&&self.disambiguator)
}
}Debug)]
648struct BindingKey {
649 ident: IdentKey,
652 ns: Namespace,
653 disambiguator: u32,
659}
660
661impl BindingKey {
662 fn new(ident: IdentKey, ns: Namespace) -> Self {
663 BindingKey { ident, ns, disambiguator: 0 }
664 }
665
666 fn new_disambiguated(
667 ident: IdentKey,
668 ns: Namespace,
669 disambiguator: impl FnOnce() -> u32,
670 ) -> BindingKey {
671 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
672 BindingKey { ident, ns, disambiguator }
673 }
674}
675
676type ResolutionTable<'ra> = FxIndexMap<BindingKey, NameResolutionRef<'ra>>;
677
678enum Resolutions<'ra> {
679 Local(CmRefCell<ResolutionTable<'ra>>),
680 Extern(OnceLock<ResolutionTable<'ra>>),
681}
682
683impl<'ra> Resolutions<'ra> {
684 fn new(local: bool) -> Self {
685 if local {
686 Resolutions::Local(Default::default())
687 } else {
688 Resolutions::Extern(Default::default())
689 }
690 }
691}
692
693struct ModuleData<'ra> {
705 parent: Option<Module<'ra>>,
707 kind: ModuleKind,
709
710 lazy_resolutions: Resolutions<'ra>,
713 underscore_disambiguator: CmCell<u32>,
715
716 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
718
719 no_implicit_prelude: bool,
721
722 glob_importers: CmRefCell<Vec<Import<'ra>>>,
723 globs: CmRefCell<Vec<Import<'ra>>>,
724
725 traits: CmRefCell<
727 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
728 >,
729
730 span: Span,
732
733 expansion: ExpnId,
734
735 self_decl: Option<Decl<'ra>>,
738}
739
740#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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)]
743#[cfg_attr(bootstrap, rustc_pass_by_value)]
744#[cfg_attr(not(bootstrap), lint::pass_by_value)]
745struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
746
747#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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)]
749#[cfg_attr(bootstrap, rustc_pass_by_value)]
750#[cfg_attr(not(bootstrap), lint::pass_by_value)]
751struct LocalModule<'ra>(Interned<'ra, ModuleData<'ra>>);
752
753#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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)]
755#[cfg_attr(bootstrap, rustc_pass_by_value)]
756#[cfg_attr(not(bootstrap), lint::pass_by_value)]
757struct ExternModule<'ra>(Interned<'ra, ModuleData<'ra>>);
758
759impl<'ra> ModuleData<'ra> {
760 fn new(
761 parent: Option<Module<'ra>>,
762 kind: ModuleKind,
763 expansion: ExpnId,
764 span: Span,
765 no_implicit_prelude: bool,
766 vis: Visibility<ModId>,
767 arenas: &'ra ResolverArenas<'ra>,
768 ) -> Self {
769 let lazy_resolutions = Resolutions::new(kind.is_local());
770 let self_decl = match kind {
771 ModuleKind::Def(def_kind, def_id, ..) => {
772 let expn_id = expansion.as_local().unwrap_or(LocalExpnId::ROOT);
773 Some(arenas.new_def_decl(Res::Def(def_kind, def_id), vis, span, expn_id, parent))
774 }
775 ModuleKind::Block => None,
776 };
777 ModuleData {
778 parent,
779 kind,
780 lazy_resolutions,
781 underscore_disambiguator: CmCell::new(0),
782 unexpanded_invocations: Default::default(),
783 no_implicit_prelude,
784 glob_importers: CmRefCell::new(Vec::new()),
785 globs: CmRefCell::new(Vec::new()),
786 traits: CmRefCell::new(None),
787 span,
788 expansion,
789 self_decl,
790 }
791 }
792
793 fn name(&self) -> Option<Symbol> {
795 match self.kind {
796 ModuleKind::Block => None,
797 ModuleKind::Def(.., name) => name,
798 }
799 }
800
801 fn opt_def_id(&self) -> Option<DefId> {
802 self.kind.opt_def_id()
803 }
804
805 fn def_id(&self) -> DefId {
806 self.kind.def_id()
807 }
808
809 fn is_local(&self) -> bool {
810 self.kind.is_local()
811 }
812
813 fn has_unexpanded_invocations<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
814 !self.unexpanded_invocations.borrow_checked(r).is_empty()
815 }
816
817 fn res(&self) -> Option<Res> {
818 match self.kind {
819 ModuleKind::Def(kind, def_id, _, _) => Some(Res::Def(kind, def_id)),
820 _ => None,
821 }
822 }
823
824 fn def_kind(&self) -> Option<DefKind> {
825 match self.kind {
826 ModuleKind::Def(def_kind, ..) => Some(def_kind),
827 ModuleKind::Block => None,
828 }
829 }
830}
831
832impl<'ra> Module<'ra> {
833 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
834 self,
835 resolver: &R,
836 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
837 ) {
838 for (key, name_resolution) in resolver.as_ref().resolutions(self).iter() {
839 let name_resolution = name_resolution.borrow_checked(resolver.as_ref());
840 if let Some(decl) = name_resolution.best_decl() {
841 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
842 }
843 }
844 }
845
846 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
847 self,
848 resolver: &mut R,
849 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
850 ) {
851 for (key, name_resolution) in resolver.as_mut().resolutions(self).iter() {
852 let name_resolution = name_resolution.borrow(resolver.as_mut());
853 if let Some(decl) = name_resolution.best_decl() {
854 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
855 }
856 }
857 }
858
859 fn ensure_traits<'tcx>(self, resolver: &Resolver<'ra, 'tcx>) {
861 let mut traits = self.traits.borrow_mut_checked(resolver);
862 if traits.is_none() {
863 let mut collected_traits = Vec::new();
864 self.for_each_child(resolver, |r, ident, _, ns, mut decl| {
865 if ns != TypeNS {
866 return;
867 }
868
869 let ambiguous = decl.is_ambiguity_recursive();
870 let mut try_record_trait = |decl: Decl<'ra>| {
871 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = decl.res() {
872 collected_traits.push((
873 ident.name,
874 decl,
875 r.as_ref().get_module(def_id),
876 ambiguous,
877 ));
878 true
879 } else {
880 false
881 }
882 };
883 while !try_record_trait(decl)
887 && let Some((_, ambig_decl)) = decl.descent_to_ambiguity()
888 {
889 decl = ambig_decl;
890 }
891 });
892 *traits = Some(collected_traits.into_boxed_slice());
893 }
894 }
895
896 fn is_normal(self) -> bool {
898 self.def_kind() == Some(DefKind::Mod)
899 }
900
901 fn is_trait(self) -> bool {
902 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind() {
Some(DefKind::Trait) => true,
_ => false,
}matches!(self.def_kind(), Some(DefKind::Trait))
903 }
904
905 fn nearest_item_scope(self) -> Module<'ra> {
906 match self.def_kind() {
907 Some(DefKind::Enum | DefKind::Trait) => {
908 self.parent.expect("enum or trait module without a parent")
909 }
910 _ => self,
911 }
912 }
913
914 fn nearest_parent_mod(self) -> ModId {
917 match self.kind {
918 ModuleKind::Def(DefKind::Mod, def_id, _, _) => ModId::new_unchecked(def_id),
919 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
920 }
921 }
922
923 fn nearest_parent_mod_node_id(self) -> NodeId {
926 match self.kind {
927 ModuleKind::Def(DefKind::Mod, _, node_id, _) => node_id,
928 _ => self.parent.expect("non-root module without parent").nearest_parent_mod_node_id(),
929 }
930 }
931
932 fn is_ancestor_of(self, mut other: Self) -> bool {
933 while self != other {
934 if let Some(parent) = other.parent {
935 other = parent;
936 } else {
937 return false;
938 }
939 }
940 true
941 }
942
943 #[track_caller]
944 fn expect_local(self) -> LocalModule<'ra> {
945 match self.kind {
946 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => {
947 ::rustc_span::macros::bug_impl(Some(self.span),
format_args!("unexpected extern module: {0:?}", self), Location::caller())span_bug!(self.span, "unexpected extern module: {self:?}")
948 }
949 ModuleKind::Def(..) | ModuleKind::Block => LocalModule(self.0),
950 }
951 }
952
953 #[track_caller]
954 fn expect_extern(self) -> ExternModule<'ra> {
955 match self.kind {
956 ModuleKind::Def(_, def_id, _, _) if !def_id.is_local() => ExternModule(self.0),
957 ModuleKind::Def(..) | ModuleKind::Block => {
958 ::rustc_span::macros::bug_impl(Some(self.span),
format_args!("unexpected local module: {0:?}", self), Location::caller())span_bug!(self.span, "unexpected local module: {self:?}")
959 }
960 }
961 }
962}
963
964impl<'ra> LocalModule<'ra> {
965 fn new(
966 parent: Option<LocalModule<'ra>>,
967 kind: ModuleKind,
968 vis: Visibility<ModId>,
969 expn_id: ExpnId,
970 span: Span,
971 no_implicit_prelude: bool,
972 arenas: &'ra ResolverArenas<'ra>,
973 ) -> LocalModule<'ra> {
974 if !kind.is_local() {
::core::panicking::panic("assertion failed: kind.is_local()")
};assert!(kind.is_local());
975 let parent = parent.map(|m| m.to_module());
976 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
977 LocalModule(Interned::new_unchecked(arenas.modules.alloc(data)))
979 }
980
981 fn to_module(self) -> Module<'ra> {
982 Module(self.0)
983 }
984}
985
986impl<'ra> ExternModule<'ra> {
987 fn new(
988 parent: Option<ExternModule<'ra>>,
989 kind: ModuleKind,
990 vis: Visibility<ModId>,
991 expn_id: ExpnId,
992 span: Span,
993 no_implicit_prelude: bool,
994 arenas: &'ra ResolverArenas<'ra>,
995 ) -> ExternModule<'ra> {
996 if !!kind.is_local() {
::core::panicking::panic("assertion failed: !kind.is_local()")
};assert!(!kind.is_local());
997 let parent = parent.map(|m| m.to_module());
998 let data = ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude, vis, arenas);
999 ExternModule(Interned::new_unchecked(arenas.modules.alloc(data)))
1001 }
1002
1003 fn to_module(self) -> Module<'ra> {
1004 Module(self.0)
1005 }
1006}
1007
1008impl<'ra> std::ops::Deref for Module<'ra> {
1009 type Target = ModuleData<'ra>;
1010
1011 fn deref(&self) -> &Self::Target {
1012 &self.0
1013 }
1014}
1015
1016impl<'ra> std::ops::Deref for LocalModule<'ra> {
1017 type Target = ModuleData<'ra>;
1018
1019 fn deref(&self) -> &Self::Target {
1020 &self.0
1021 }
1022}
1023
1024impl<'ra> std::ops::Deref for ExternModule<'ra> {
1025 type Target = ModuleData<'ra>;
1026
1027 fn deref(&self) -> &Self::Target {
1028 &self.0
1029 }
1030}
1031
1032impl<'ra> fmt::Debug for Module<'ra> {
1033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1034 match self.res() {
1035 None => f.write_fmt(format_args!("block"))write!(f, "block"),
1036 Some(res) => f.write_fmt(format_args!("{0:?}", res))write!(f, "{:?}", res),
1037 }
1038 }
1039}
1040
1041impl<'ra> fmt::Debug for LocalModule<'ra> {
1042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043 self.to_module().fmt(f)
1044 }
1045}
1046
1047#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for DeclData<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"DeclData kind ambiguity expansion span initial_vis ambiguity_vis_max ambiguity_vis_min parent_module",
&[&self.kind, &self.ambiguity, &self.expansion, &self.span,
&self.initial_vis, &self.ambiguity_vis_max,
&self.ambiguity_vis_min, &&self.parent_module])
}
}Debug)]
1049struct DeclData<'ra> {
1050 kind: DeclKind<'ra>,
1051 ambiguity: CmCell<Option<(Decl<'ra>, bool )>>,
1052 expansion: LocalExpnId,
1053 span: Span,
1054 initial_vis: Visibility<ModId>,
1055 ambiguity_vis_max: CmCell<Option<Decl<'ra>>>,
1058 ambiguity_vis_min: CmCell<Option<Decl<'ra>>>,
1061 parent_module: Option<Module<'ra>>,
1062}
1063
1064type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
1067
1068#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for DeclKind<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Def(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Def",
__self_0, &__self_1),
Self::Import { source_decl: __self_0, import: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Import source_decl import", __self_0, &__self_1),
}
}
}Debug)]
1070enum DeclKind<'ra> {
1071 Def(Res, &'ra [Reexport]),
1076 Import { source_decl: Decl<'ra>, import: Import<'ra> },
1078}
1079
1080impl<'ra> DeclKind<'ra> {
1081 fn is_import(&self) -> bool {
1083 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
1084 }
1085}
1086
1087#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for PrivacyError<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"PrivacyError ident decl dedup_span outermost_res parent_scope single_nested source",
&[&self.ident, &self.decl, &self.dedup_span, &self.outermost_res,
&self.parent_scope, &self.single_nested, &&self.source])
}
}Debug)]
1088struct PrivacyError<'ra> {
1089 ident: Ident,
1090 decl: Decl<'ra>,
1091 dedup_span: Span,
1092 outermost_res: Option<(Res, Ident)>,
1093 parent_scope: ParentScope<'ra>,
1094 single_nested: bool,
1096 source: Option<ast::Expr>,
1097}
1098
1099#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for UseError<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"UseError err candidates node_id instead suggestion path is_call",
&[&self.err, &self.candidates, &self.node_id, &self.instead,
&self.suggestion, &self.path, &&self.is_call])
}
}Debug)]
1100struct UseError<'a> {
1101 err: Diag<'a>,
1102 candidates: Vec<ImportSuggestion>,
1104 node_id: NodeId,
1106 instead: bool,
1108 suggestion: Option<(Span, &'static str, String, Applicability)>,
1110 path: Vec<Segment>,
1113 is_call: bool,
1115}
1116
1117#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for
DelayedVisResolutionError<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"DelayedVisResolutionError vis parent_scope error", &self.vis,
&self.parent_scope, &&self.error)
}
}Debug)]
1118struct DelayedVisResolutionError<'ra> {
1119 vis: ast::Visibility,
1120 parent_scope: ParentScope<'ra>,
1121 error: VisResolutionError,
1122}
1123
1124#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AmbiguityKind {
}
#[automatically_derived]impl ::core::clone::Clone for AmbiguityKind {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for AmbiguityKind {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_c_like_enum_write_str(f,
"BuiltinAttr DeriveHelper MacroRulesVsModularized GlobVsOuter GlobVsGlob GlobVsExpanded MoreExpandedVsOuter",
match self {
AmbiguityKind::BuiltinAttr => 0usize,
AmbiguityKind::DeriveHelper => 12usize,
AmbiguityKind::MacroRulesVsModularized => 25usize,
AmbiguityKind::GlobVsOuter => 49usize,
AmbiguityKind::GlobVsGlob => 61usize,
AmbiguityKind::GlobVsExpanded => 72usize,
AmbiguityKind::MoreExpandedVsOuter => 87usize,
})
}
}Debug)]
1125enum AmbiguityKind {
1126 BuiltinAttr,
1127 DeriveHelper,
1128 MacroRulesVsModularized,
1129 GlobVsOuter,
1130 GlobVsGlob,
1131 GlobVsExpanded,
1132 MoreExpandedVsOuter,
1133}
1134
1135impl AmbiguityKind {
1136 fn descr(self) -> &'static str {
1137 match self {
1138 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
1139 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
1140 AmbiguityKind::MacroRulesVsModularized => {
1141 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
1142 }
1143 AmbiguityKind::GlobVsOuter => {
1144 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
1145 }
1146 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
1147 AmbiguityKind::GlobVsExpanded => {
1148 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
1149 }
1150 AmbiguityKind::MoreExpandedVsOuter => {
1151 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
1152 }
1153 }
1154 }
1155}
1156
1157#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AmbiguityWarning {
}
#[automatically_derived]impl ::core::clone::Clone for AmbiguityWarning {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *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: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1158enum AmbiguityWarning {
1159 GlobImport,
1160 PanicImport,
1161}
1162
1163struct AmbiguityError<'ra> {
1164 kind: AmbiguityKind,
1165 ambig_vis: Option<(Visibility, Visibility)>,
1166 ident: Ident,
1167 b1: Decl<'ra>,
1168 b2: Decl<'ra>,
1169 scope1: Scope<'ra>,
1170 scope2: Scope<'ra>,
1171 warning: Option<AmbiguityWarning>,
1172}
1173
1174impl<'ra> DeclData<'ra> {
1175 fn vis(&self) -> Visibility<ModId> {
1176 self.ambiguity_vis_max.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1178 }
1179
1180 fn min_vis(&self) -> Visibility<ModId> {
1181 self.ambiguity_vis_min.get().map(|d| d.vis()).unwrap_or_else(|| self.initial_vis)
1183 }
1184
1185 fn res(&self) -> Res {
1186 match self.kind {
1187 DeclKind::Def(res, ..) => res,
1188 DeclKind::Import { source_decl, .. } => source_decl.res(),
1189 }
1190 }
1191
1192 fn import_source(&self) -> Decl<'ra> {
1193 match self.kind {
1194 DeclKind::Import { source_decl, .. } => source_decl,
1195 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1196 }
1197 }
1198
1199 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
1200 match self.ambiguity.get() {
1201 Some((ambig_binding, _)) => Some((self, ambig_binding)),
1202 None => match self.kind {
1203 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1204 _ => None,
1205 },
1206 }
1207 }
1208
1209 fn is_ambiguity_recursive(&self) -> bool {
1210 self.ambiguity.get().is_some()
1211 || match self.kind {
1212 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1213 _ => false,
1214 }
1215 }
1216
1217 fn is_possibly_imported_variant(&self) -> bool {
1218 match self.kind {
1219 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1220 DeclKind::Def(
1221 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
1222 _,
1223 ) => true,
1224 DeclKind::Def(..) => false,
1225 }
1226 }
1227
1228 fn is_extern_crate(&self) -> bool {
1229 match self.kind {
1230 DeclKind::Import { import, .. } => {
1231 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1232 }
1233 DeclKind::Def(Res::Def(_, def_id), _) => def_id.is_crate_root(),
1234 _ => false,
1235 }
1236 }
1237
1238 fn is_import(&self) -> bool {
1239 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1240 }
1241
1242 fn is_import_user_facing(&self) -> bool {
1245 #[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, .. }
1246 if !matches!(import.kind, ImportKind::MacroExport))
1247 }
1248
1249 fn is_glob_import(&self) -> bool {
1250 match self.kind {
1251 DeclKind::Import { import, .. } => import.is_glob(),
1252 _ => false,
1253 }
1254 }
1255
1256 fn is_assoc_item(&self) -> bool {
1257 #[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, _))
1258 }
1259
1260 fn macro_kinds(&self) -> Option<MacroKinds> {
1261 self.res().macro_kinds()
1262 }
1263
1264 fn reexport_chain(self: Decl<'ra>) -> SmallVec<[Reexport; 2]> {
1265 let mut full_reexport_chain: SmallVec<[Reexport; 2]> = SmallVec::new();
1266 let mut next_binding = self;
1267 loop {
1268 match next_binding.kind {
1269 DeclKind::Import { source_decl, import, .. } => {
1270 full_reexport_chain.push(import.simplify());
1271 next_binding = source_decl;
1272 }
1273 DeclKind::Def(_, reexport_chain) => {
1274 full_reexport_chain.extend(reexport_chain.iter().copied());
1275 break;
1276 }
1277 }
1278 }
1279 full_reexport_chain
1280 }
1281
1282 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1289 let self_parent_expansion = self.expansion;
1293 let other_parent_expansion = decl.expansion;
1294 let certainly_before_other_or_simultaneously =
1295 other_parent_expansion.is_descendant_of(self_parent_expansion);
1296 let certainly_before_invoc_or_simultaneously =
1297 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1298 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1299 }
1300
1301 fn determined<'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> bool {
1307 match &self.kind {
1308 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1309 !import.parent_scope.module.has_unexpanded_invocations(r)
1310 && source_decl.determined(r)
1311 }
1312 _ => true,
1313 }
1314 }
1315}
1316
1317#[derive(#[automatically_derived]impl<'ra> ::core::fmt::Debug for
ExternPreludeEntry<'ra> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ExternPreludeEntry item_decl flag_decl", &self.item_decl,
&&self.flag_decl)
}
}Debug)]
1318struct ExternPreludeEntry<'ra> {
1319 item_decl: Option<(Decl<'ra>, Span, bool)>,
1323 flag_decl: Option<
1325 Lock<(
1326 PendingDecl<'ra>,
1327 bool,
1328 bool,
1329 )>,
1330 >,
1331}
1332
1333impl ExternPreludeEntry<'_> {
1334 fn introduced_by_item(&self) -> bool {
1335 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1336 }
1337
1338 fn flag() -> Self {
1339 ExternPreludeEntry {
1340 item_decl: None,
1341 flag_decl: Some(Lock::new((PendingDecl::Pending, false, false))),
1342 }
1343 }
1344
1345 fn open_flag() -> Self {
1346 ExternPreludeEntry {
1347 item_decl: None,
1348 flag_decl: Some(Lock::new((PendingDecl::Pending, false, true))),
1349 }
1350 }
1351
1352 fn span(&self) -> Span {
1353 match self.item_decl {
1354 Some((_, span, _)) => span,
1355 None => DUMMY_SP,
1356 }
1357 }
1358}
1359
1360struct DeriveData {
1361 resolutions: Vec<DeriveResolution>,
1362 helper_attrs: Vec<(usize, IdentKey, Span)>,
1363 has_derive_copy: bool,
1366 has_derive_ord: bool,
1367}
1368
1369pub struct ResolverOutputs<'tcx> {
1370 pub global_ctxt: ResolverGlobalCtxt,
1371 pub ast_lowering: ResolverAstLowering<'tcx>,
1372}
1373
1374#[derive(#[automatically_derived]impl ::core::fmt::Debug for DelegationFnSig {
#[inline]
#[rustc_trivial_field_reads]
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)]
1375struct DelegationFnSig {
1376 pub has_self: bool,
1377}
1378
1379pub struct Resolver<'ra, 'tcx> {
1383 tcx: TyCtxt<'tcx>,
1384
1385 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1387
1388 graph_root: LocalModule<'ra>,
1389
1390 speculative_flag: SpeculativeFlag,
1392
1393 prelude: Option<Module<'ra>> = None,
1394 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1395
1396 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1398 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1399
1400 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1403
1404 determined_imports: Vec<Import<'ra>> = Vec::new(),
1406
1407 indeterminate_imports: Vec<(Import<'ra>, Option<ImportResolution<'ra>>, usize)> = Vec::new(),
1409
1410 pat_span_map: NodeMap<Span> = Default::default(),
1413
1414 partial_res_map: NodeMap<PartialRes> = Default::default(),
1416 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1418
1419 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1421 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1422 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1423
1424 block_map: NodeMap<LocalModule<'ra>> = Default::default(),
1439 empty_module: LocalModule<'ra>,
1443 local_modules: Vec<LocalModule<'ra>>,
1445 local_module_map: FxIndexMap<LocalDefId, LocalModule<'ra>>,
1447 extern_module_map: RwLock<FxIndexMap<DefId, ExternModule<'ra>>>,
1449
1450 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>> = default::fx_index_map(),
1452 glob_error: Option<ErrorGuaranteed> = None,
1453 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1454 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1455 maybe_unused_trait_imports: FxIndexSet<LocalDefId> = default::fx_index_set(),
1456
1457 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1459 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1461 issue_145575_hack_applied: bool = false,
1462 delayed_vis_resolution_errors: Vec<DelayedVisResolutionError<'ra>> = Vec::new(),
1464 macro_expanded_macro_export_errors: BTreeSet<(OrdSpan, OrdSpan)> = BTreeSet::new(),
1466
1467 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1468 dummy_decl: Decl<'ra>,
1469 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1470 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1471 registered_attr_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1472 macro_names: FxHashMap<IdentKey, LocalDefId> = default::fx_hash_map(),
1473 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1474 registered_attr_tools: &'tcx RegisteredTools,
1475 registered_lint_tools: &'tcx RegisteredTools,
1476 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>> = default::fx_index_map(),
1477 local_macro_map: FxHashMap<LocalDefId, &'ra Arc<SyntaxExtension>> = default::fx_hash_map(),
1479 extern_macro_map: RwLock<FxHashMap<DefId, &'ra Arc<SyntaxExtension>>>,
1481 dummy_ext_bang: &'ra Arc<SyntaxExtension>,
1482 dummy_ext_derive: &'ra Arc<SyntaxExtension>,
1483 non_macro_attr: &'ra Arc<SyntaxExtension>,
1484 local_macro_def_scopes: FxHashMap<LocalDefId, LocalModule<'ra>> = default::fx_hash_map(),
1485 ast_transform_scopes: FxHashMap<LocalExpnId, LocalModule<'ra>> = default::fx_hash_map(),
1486 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident, Option<DefId>)> = default::fx_index_map(),
1487 macro_use_mods: FxIndexSet<NodeId> = default::fx_index_set(),
1488 unused_macro_rules: FxIndexMap<NodeId, (LocalDefId, DenseBitSet<usize>)> = default::fx_index_map(),
1490 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1491 single_segment_macro_resolutions:
1493 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1494 multi_segment_macro_resolutions:
1495 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1496 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1497 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1501 containers_deriving_ord: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1502 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1505 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1508 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1510 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1512 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1515
1516 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1518
1519 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1520
1521 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1522
1523 struct_ctors: LocalDefIdMap<StructCtor> = Default::default(),
1527
1528 struct_generics: LocalDefIdMap<Generics> = Default::default(),
1531
1532 lint_buffer: LintBuffer,
1533
1534 next_node_id: NodeId = CRATE_NODE_ID,
1535
1536 owners: NodeMap<PerOwnerResolverData<'tcx>>,
1538
1539 current_owner: PerOwnerResolverData<'tcx>,
1541
1542 disambiguators: LocalDefIdMap<PerParentDisambiguatorState>,
1543
1544 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1546 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1550
1551 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1553 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1555 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1556 delegation_infos: FxIndexMap<LocalDefId, DelegationInfo> = default::fx_index_map(),
1557 delegation_inherent_fn_map: FxIndexMap<LocalDefId, FxIndexMap<Ident, DelegationInherentFnKind>> = default::fx_index_map(),
1558
1559 main_def: Option<MainDefinition> = None,
1560 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>> = default::fx_index_map(),
1561 proc_macros: Vec<LocalDefId> = Vec::new(),
1564 paths_matching_assoc_types: UnordSet<Span> = Default::default(),
1565 confused_type_with_std_module: FxIndexMap<Span, Span> = default::fx_index_map(),
1566
1567 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1569
1570 effective_visibilities: EffectiveVisibilities = Default::default(),
1571 macro_reachable_adts: FxIndexMap<LocalDefId, FxIndexSet<LocalDefId>> = default::fx_index_map(),
1572
1573 doc_link_resolutions: FxIndexMap<LocalModId, DocLinkResMap> = default::fx_index_map(),
1574 doc_link_traits_in_scope: FxIndexMap<LocalModId, Vec<DefId>> = default::fx_index_map(),
1575 all_macro_rules: UnordSet<Symbol> = Default::default(),
1576
1577 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1579 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1582 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1585
1586 current_crate_outer_attr_insert_span: Span,
1589
1590 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1591
1592 all_crate_macros_already_registered: bool = false,
1595
1596 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1600
1601 raise_fatal_after_resolve: bool = false,
1605
1606 on_unknown_data: FxHashMap<LocalDefId, OnUnknownData> = default::fx_hash_map(),
1608 features: &'tcx Features,
1609
1610 lang_items: LanguageItems,
1611}
1612
1613#[derive(#[automatically_derived]impl<'ra> ::core::default::Default for
ResolverArenas<'ra> {
#[inline]
fn default() -> Self {
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)]
1616pub struct ResolverArenas<'ra> {
1617 modules: TypedArena<ModuleData<'ra>>,
1618 imports: TypedArena<ImportData<'ra>>,
1619 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1620 ast_paths: TypedArena<ast::Path>,
1621 macros: TypedArena<Arc<SyntaxExtension>>,
1622 dropless: DroplessArena,
1623}
1624
1625impl<'ra> ResolverArenas<'ra> {
1626 fn new_def_decl(
1627 &'ra self,
1628 res: Res,
1629 vis: Visibility<ModId>,
1630 span: Span,
1631 expansion: LocalExpnId,
1632 parent_module: Option<Module<'ra>>,
1633 ) -> Decl<'ra> {
1634 self.alloc_decl(DeclData {
1635 kind: DeclKind::Def(res, &[]),
1636 ambiguity: CmCell::new(None),
1637 initial_vis: vis,
1638 ambiguity_vis_max: CmCell::new(None),
1639 ambiguity_vis_min: CmCell::new(None),
1640 span,
1641 expansion,
1642 parent_module,
1643 })
1644 }
1645
1646 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1647 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1648 }
1649
1650 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1651 Interned::new_unchecked(self.dropless.alloc(data))
1653 }
1654 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1655 Interned::new_unchecked(self.imports.alloc(import))
1657 }
1658 fn alloc_name_resolution(&'ra self, resolution: NameResolution<'ra>) -> NameResolutionRef<'ra> {
1659 Interned::new_unchecked(self.name_resolutions.alloc(CmRefCell::new(resolution)))
1661 }
1662 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1663 self.dropless.alloc(RwLock::new(scope))
1664 }
1665 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1666 self.dropless.alloc(decl)
1667 }
1668 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1669 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1670 }
1671 fn alloc_macro(&'ra self, ext: SyntaxExtension) -> &'ra Arc<SyntaxExtension> {
1672 self.macros.alloc(Arc::new(ext))
1673 }
1674 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1675 self.dropless.alloc_from_iter(spans)
1676 }
1677}
1678
1679impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1680 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1681 self
1682 }
1683}
1684
1685impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1686 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1687 self
1688 }
1689}
1690
1691impl<'tcx> Resolver<'_, 'tcx> {
1692 fn owner_def_id(&self, owner: NodeId) -> LocalDefId {
1696 self.owners[&owner].def_id
1697 }
1698
1699 fn child_def_id(&self, owner: NodeId, id: NodeId) -> LocalDefId {
1703 self.owners[&owner].node_id_to_def_id[&id]
1704 }
1705
1706 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1708 self.current_owner.node_id_to_def_id.get(&node).copied()
1709 }
1710
1711 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1713 self.opt_local_def_id(node).unwrap_or_else(|| {
1714 {
::core::panicking::panic_fmt(format_args!("no entry for node id `{2:?}` in owner {0:?}, available: {1:#?}",
self.current_owner.def_id, self.current_owner.node_id_to_def_id,
node));
}panic!(
1715 "no entry for node id `{node:?}` in owner {:?}, available: {:#?}",
1716 self.current_owner.def_id, self.current_owner.node_id_to_def_id
1717 )
1718 })
1719 }
1720
1721 fn create_def(
1723 &mut self,
1724 parent: LocalDefId,
1725 node_id: ast::NodeId,
1726 name: Option<Symbol>,
1727 def_kind: DefKind,
1728 expn_id: ExpnId,
1729 span: Span,
1730 is_owner: bool,
1731 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1732 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!(
1733 !self.current_owner.node_id_to_def_id.contains_key(&node_id),
1734 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1735 node_id,
1736 name,
1737 def_kind,
1738 self.tcx
1739 .definitions_untracked()
1740 .def_key(self.current_owner.node_id_to_def_id[&node_id]),
1741 );
1742
1743 let disambiguator = self.disambiguators.get_or_create(parent);
1744
1745 let feed = self.tcx.create_def(parent, name, def_kind, None, disambiguator);
1747 let def_id = feed.def_id();
1748
1749 if expn_id != ExpnId::root() {
1751 self.expn_that_defined.insert(def_id, expn_id);
1752 }
1753
1754 if true {
{
match (&span.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.parent(), None);
1756 let _id = self.tcx.untracked().source_span.push(span);
1757 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);
1758
1759 if node_id != ast::DUMMY_NODE_ID && !is_owner {
1763 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:1763",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1763u32),
::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);
1764 self.current_owner.node_id_to_def_id.insert(node_id, def_id);
1765 }
1766
1767 feed
1768 }
1769
1770 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1771 if let Some(def_id) = def_id.as_local() {
1772 self.item_generics_num_lifetimes[&def_id]
1773 } else {
1774 self.tcx.generics_of(def_id).own_counts().lifetimes
1775 }
1776 }
1777
1778 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1779 if let Some(def_id) = def_id.as_local() {
1780 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1781 } else {
1782 let required = self
1783 .tcx
1784 .generics_of(def_id)
1785 .own_params
1786 .iter()
1787 .filter_map(|param| match param.kind {
1788 ty::GenericParamDefKind::Lifetime => Some("'_"),
1789 ty::GenericParamDefKind::Type { has_default, .. }
1790 | ty::GenericParamDefKind::Const { has_default, arg_pos: _ } => {
1791 if has_default {
1792 None
1793 } else {
1794 Some("_")
1795 }
1796 }
1797 })
1798 .collect::<Vec<_>>();
1799
1800 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1801 }
1802 }
1803
1804 pub fn tcx(&self) -> TyCtxt<'tcx> {
1805 self.tcx
1806 }
1807
1808 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1815 self.owners
1816 .items()
1817 .flat_map(|(_, data)| {
1818 data.node_id_to_def_id
1819 .items()
1820 .chain(UnordItems::new([(&data.id, &data.def_id)].into_iter()))
1821 })
1822 .filter(|(_, v)| **v == def_id)
1823 .map(|(k, _)| *k)
1824 .get_only()
1825 .unwrap()
1826 }
1827}
1828
1829impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1830 pub fn new(
1831 tcx: TyCtxt<'tcx>,
1832 attrs: &[ast::Attribute],
1833 crate_span: Span,
1834 current_crate_outer_attr_insert_span: Span,
1835 arenas: &'ra WorkerLocal<ResolverArenas<'ra>>,
1836 ) -> Resolver<'ra, 'tcx> {
1837 let root_def_id = CRATE_DEF_ID.to_def_id();
1838 let graph_root = LocalModule::new(
1839 None,
1840 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1841 Visibility::Public,
1842 ExpnId::root(),
1843 crate_span,
1844 attr::contains_name(attrs, sym::no_implicit_prelude),
1845 arenas,
1846 );
1847 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];
1848 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1849 let empty_module = LocalModule::new(
1850 None,
1851 ModuleKind::Def(DefKind::Mod, root_def_id, CRATE_NODE_ID, None),
1852 Visibility::Public,
1853 ExpnId::root(),
1854 DUMMY_SP,
1855 true,
1856 arenas,
1857 );
1858
1859 let owner_data = PerOwnerResolverData::new(CRATE_NODE_ID, CRATE_DEF_ID);
1860 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1861
1862 crate_feed.def_kind(DefKind::Mod);
1863 let mut owners = NodeMap::default();
1864 owners.insert(CRATE_NODE_ID, owner_data);
1865
1866 let mut invocation_parents = FxHashMap::default();
1867 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1868
1869 let extern_prelude = build_extern_prelude(tcx, attrs);
1870 let registered_attr_tools = tcx.registered_attr_tools(());
1871 let registered_lint_tools = tcx.registered_lint_tools(());
1872 let edition = tcx.sess.edition();
1873
1874 let mut resolver = Resolver {
1875 tcx,
1876
1877 graph_root,
1880 speculative_flag: SpeculativeFlag::default(),
1882 extern_prelude,
1883
1884 empty_module,
1885 local_modules,
1886 local_module_map,
1887 extern_module_map: Default::default(),
1888
1889 arenas,
1890 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1891 builtin_type_decls: PrimTy::ALL
1892 .iter()
1893 .map(|prim_ty| {
1894 let res = Res::PrimTy(*prim_ty);
1895 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1896 (prim_ty.name(), decl)
1897 })
1898 .collect(),
1899 builtin_attr_decls: BUILTIN_ATTRIBUTES
1900 .iter()
1901 .map(|builtin_attr| {
1902 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(*builtin_attr));
1903 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1904 (*builtin_attr, decl)
1905 })
1906 .collect(),
1907 registered_attr_tool_decls: registered_attr_tools
1908 .iter()
1909 .map(|(&tool, _)| {
1910 let res = Res::ToolMod;
1911 let decl = arenas.new_pub_def_decl(res, tool.span, LocalExpnId::ROOT);
1912 (IdentKey::new(tool), decl)
1913 })
1914 .collect(),
1915 registered_attr_tools,
1916 registered_lint_tools,
1917 extern_macro_map: Default::default(),
1918 dummy_ext_bang: arenas.alloc_macro(SyntaxExtension::dummy_bang(edition)),
1919 dummy_ext_derive: arenas.alloc_macro(SyntaxExtension::dummy_derive(edition)),
1920 non_macro_attr: arenas.alloc_macro(SyntaxExtension::non_macro_attr(edition)),
1921 single_segment_macro_resolutions: Default::default(),
1922 multi_segment_macro_resolutions: Default::default(),
1923 lint_buffer: LintBuffer::default(),
1924 owners,
1925 current_owner: PerOwnerResolverData::new(DUMMY_NODE_ID, CRATE_DEF_ID),
1926 invocation_parents,
1927 current_crate_outer_attr_insert_span,
1928 disambiguators: Default::default(),
1929 features: tcx.features(),
1930 lang_items: LanguageItems::new(),
1931 ..
1932 };
1933
1934 if let Some(directive) = OnUnknownData::from_attrs(&resolver, attrs) {
1935 resolver.on_unknown_data.insert(CRATE_DEF_ID, directive);
1936 }
1937
1938 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1939 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1940 resolver.feed_visibility(crate_feed, Visibility::Public);
1941
1942 resolver
1943 }
1944
1945 fn new_local_module(
1946 &mut self,
1947 parent: Option<LocalModule<'ra>>,
1948 kind: ModuleKind,
1949 expn_id: ExpnId,
1950 span: Span,
1951 no_implicit_prelude: bool,
1952 ) -> LocalModule<'ra> {
1953 let vis =
1954 kind.opt_def_id().map_or(Visibility::Public, |def_id| self.tcx.visibility(def_id));
1955 let module =
1956 LocalModule::new(parent, kind, vis, expn_id, span, no_implicit_prelude, self.arenas);
1957 self.local_modules.push(module);
1958 if let Some(def_id) = module.opt_def_id() {
1959 self.local_module_map.insert(def_id.expect_local(), module);
1960 }
1961 module
1962 }
1963
1964 fn next_node_id(&mut self) -> NodeId {
1965 let start = self.next_node_id;
1966 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1967 self.next_node_id = ast::NodeId::from_u32(next);
1968 start
1969 }
1970
1971 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1972 let start = self.next_node_id;
1973 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1974 self.next_node_id = ast::NodeId::from_usize(end);
1975 start..self.next_node_id
1976 }
1977
1978 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1979 &mut self.lint_buffer
1980 }
1981
1982 pub fn arenas() -> ResolverArenas<'ra> {
1983 Default::default()
1984 }
1985
1986 fn feed_visibility(&mut self, feed: TyCtxtFeed<'tcx, LocalDefId>, vis: Visibility) {
1987 feed.visibility(vis.to_mod_id());
1988 self.visibilities_for_hashing.push((feed.def_id(), vis));
1989 }
1990
1991 pub fn into_outputs(self) -> ResolverOutputs<'tcx> {
1992 let proc_macros = self.proc_macros;
1993 let expn_that_defined = self.expn_that_defined;
1994 let extern_crate_map = self.extern_crate_map;
1995 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1996 let glob_map = self.glob_map;
1997 let main_def = self.main_def;
1998 let confused_type_with_std_module = self.confused_type_with_std_module;
1999 let paths_matching_assoc_types = self.paths_matching_assoc_types;
2000 let effective_visibilities = self.effective_visibilities;
2001 let lang_items = self.lang_items;
2002
2003 let stripped_cfg_items = self
2004 .stripped_cfg_items
2005 .into_iter()
2006 .filter_map(|item| {
2007 let parent_scope = self.owners.get(&item.parent_scope)?.def_id.to_def_id();
2008 Some(StrippedCfgItem { parent_scope, ident: item.ident, cfg: item.cfg })
2009 })
2010 .collect();
2011 let disambiguators = self
2012 .disambiguators
2013 .into_items()
2014 .map(|(def_id, disamb)| (def_id, Steal::new(disamb)))
2015 .collect();
2016
2017 let global_ctxt = ResolverGlobalCtxt {
2018 expn_that_defined,
2019 visibilities_for_hashing: self.visibilities_for_hashing,
2020 effective_visibilities,
2021 macro_reachable_adts: self.macro_reachable_adts,
2022 extern_crate_map,
2023 module_children: self.module_children,
2024 ambig_module_children: self.ambig_module_children,
2025 glob_map,
2026 maybe_unused_trait_imports,
2027 main_def,
2028 trait_impls: self.trait_impls,
2029 proc_macros,
2030 confused_type_with_std_module,
2031 paths_matching_assoc_types,
2032 doc_link_resolutions: self.doc_link_resolutions,
2033 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
2034 all_macro_rules: self.all_macro_rules,
2035 stripped_cfg_items,
2036 delegation_infos: self.delegation_infos,
2037 delegation_inherent_fn_map: self.delegation_inherent_fn_map,
2038 lang_items,
2039 };
2040 let ast_lowering = ResolverAstLowering {
2041 partial_res_map: self.partial_res_map,
2042 next_node_id: self.next_node_id,
2043 owners: self.owners,
2044 lint_buffer: Steal::new(self.lint_buffer),
2045 disambiguators,
2046 };
2047 ResolverOutputs { global_ctxt, ast_lowering }
2048 }
2049
2050 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
2051 CStore::from_tcx(self.tcx)
2052 }
2053
2054 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
2055 CStore::from_tcx_mut(self.tcx)
2056 }
2057
2058 fn dummy_ext(&self, macro_kind: MacroKind) -> &'ra Arc<SyntaxExtension> {
2059 match macro_kind {
2060 MacroKind::Bang => self.dummy_ext_bang,
2061 MacroKind::Derive => self.dummy_ext_derive,
2062 MacroKind::Attr => self.non_macro_attr,
2063 }
2064 }
2065
2066 fn cm(&self) -> CmResolver<'_, 'ra, 'tcx> {
2068 CmResolver::Ref(self)
2069 }
2070
2071 fn cm_mut(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
2074 if !!self.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("can\'t mutably borrow speculative resolver"));
}
};assert!(
2075 !self.speculative_flag.is_speculative(),
2076 "can't mutably borrow speculative resolver"
2077 );
2078 CmResolver::Mut(self)
2079 }
2080
2081 fn per_ns<F: FnMut(&Self, Namespace)>(&self, mut f: F) {
2083 f(self, TypeNS);
2084 f(self, ValueNS);
2085 f(self, MacroNS);
2086 }
2087
2088 fn per_ns_mut<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
2089 f(self, TypeNS);
2090 f(self, ValueNS);
2091 f(self, MacroNS);
2092 }
2093
2094 fn is_builtin_macro(&self, res: Res) -> bool {
2095 self.get_macro(res).is_some_and(|ext| ext.builtin_name.is_some())
2096 }
2097
2098 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
2099 self.get_macro(res).is_some_and(|ext| ext.builtin_name == Some(symbol))
2100 }
2101
2102 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
2103 loop {
2104 match ctxt.outer_expn_data().macro_def_id {
2105 Some(def_id) => return def_id,
2106 None => ctxt.remove_mark(),
2107 };
2108 }
2109 }
2110
2111 pub fn resolve_crate(&mut self, krate: &Crate) {
2113 self.tcx.sess.time("resolve_crate", || {
2114 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
2115 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
2116 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
2117 });
2118 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
2119 self.tcx
2120 .sess
2121 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
2122 let (use_items, use_injections) =
2123 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
2124 self.tcx.sess.time("resolve_main", || self.resolve_main());
2125 self.tcx.sess.time("resolve_check_unused", || self.check_unused(use_items));
2126 self.tcx
2127 .sess
2128 .time("resolve_report_errors", || self.report_errors(krate, use_injections));
2129 self.tcx
2130 .sess
2131 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
2132
2133 self.tcx.sess.time("finalize_lang_items", || self.finalize_lang_items());
2134 });
2135
2136 self.tcx.untracked().freeze_cstore();
2138 if self.raise_fatal_after_resolve {
2139 rustc_errors::FatalError.raise();
2140 }
2141 }
2142
2143 fn traits_in_scope(
2144 &mut self,
2145 current_trait: Option<Module<'ra>>,
2146 parent_scope: &ParentScope<'ra>,
2147 sp: Span,
2148 assoc_item: Option<(Symbol, Namespace)>,
2149 ) -> &'tcx [TraitCandidate<'tcx>] {
2150 let mut found_traits = Vec::new();
2151
2152 if let Some(module) = current_trait {
2153 if self.trait_may_have_item(Some(module), assoc_item) {
2154 let def_id = module.def_id();
2155 found_traits.push(TraitCandidate {
2156 def_id,
2157 import_ids: &[],
2158 lint_ambiguous: false,
2159 });
2160 }
2161 }
2162
2163 let scope_set = ScopeSet::All(TypeNS);
2164 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
2165 let cmr = self.cm_mut();
2166 cmr.visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
2167 match scope {
2168 Scope::ModuleNonGlobs(module, _) => {
2169 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2170 }
2171 Scope::ModuleGlobs(..) => {
2172 }
2174 Scope::StdLibPrelude => {
2175 if let Some(module) = this.prelude {
2176 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
2177 }
2178 }
2179 Scope::ExternPreludeItems
2180 | Scope::ExternPreludeFlags
2181 | Scope::ToolAttributePrelude
2182 | Scope::BuiltinTypes => {}
2183 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
2184 }
2185 ControlFlow::<()>::Continue(())
2186 });
2187
2188 self.tcx.hir_arena.alloc_slice(&found_traits)
2189 }
2190
2191 fn traits_in_module(
2192 &mut self,
2193 module: Module<'ra>,
2194 assoc_item: Option<(Symbol, Namespace)>,
2195 found_traits: &mut Vec<TraitCandidate<'tcx>>,
2196 ) {
2197 module.ensure_traits(self);
2198 let traits = module.traits.borrow(self);
2199 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2200 traits.as_ref().unwrap().iter()
2201 {
2202 if self.trait_may_have_item(trait_module, assoc_item) {
2203 let def_id = trait_binding.res().def_id();
2204 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2205 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2206 }
2207 }
2208 }
2209
2210 fn trait_may_have_item(
2216 &self,
2217 trait_module: Option<Module<'ra>>,
2218 assoc_item: Option<(Symbol, Namespace)>,
2219 ) -> bool {
2220 match (trait_module, assoc_item) {
2221 (Some(trait_module), Some((name, ns))) => self
2222 .resolutions(trait_module)
2223 .iter()
2224 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2225 _ => true,
2226 }
2227 }
2228
2229 fn find_transitive_imports(
2230 &mut self,
2231 mut kind: &DeclKind<'_>,
2232 trait_name: Symbol,
2233 ) -> &'tcx [LocalDefId] {
2234 let mut import_ids: SmallVec<[LocalDefId; 1]> = ::smallvec::SmallVec::new()smallvec![];
2235 while let DeclKind::Import { import, source_decl, .. } = kind {
2236 if let Some(def_id) = import.def_id() {
2237 self.maybe_unused_trait_imports.insert(def_id);
2238 import_ids.push(def_id);
2239 }
2240 self.add_to_glob_map(*import, trait_name);
2241 kind = &source_decl.kind;
2242 }
2243
2244 self.tcx.hir_arena.alloc_slice(&import_ids)
2245 }
2246
2247 fn resolutions(&self, module: Module<'ra>) -> CmRef<'ra, ResolutionTable<'ra>> {
2248 match &module.0.0.lazy_resolutions {
2249 Resolutions::Local(local_res) => local_res.borrow_checked(self),
2250 Resolutions::Extern(extern_res) => {
2251 CmRef::Untracked(
2254 extern_res
2256 .get_or_init(|| self.build_reduced_graph_external(module.expect_extern())),
2257 )
2258 }
2259 }
2260 }
2261
2262 fn resolutions_mut(&mut self, module: Module<'ra>) -> RefMut<'ra, ResolutionTable<'ra>> {
2263 match &module.0.0.lazy_resolutions {
2264 Resolutions::Local(local_res) => local_res.borrow_mut(self),
2265 Resolutions::Extern(_) => {
2266 {
::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")
2269 }
2270 }
2271 }
2272
2273 fn resolution(
2274 &self,
2275 module: Module<'ra>,
2276 key: BindingKey,
2277 ) -> Option<CmRef<'ra, NameResolution<'ra>>> {
2278 self.resolutions(module).get(&key).map(|resolution| resolution.0.borrow_checked(self))
2279 }
2280
2281 #[track_caller]
2282 fn resolution_or_default(
2283 &mut self,
2284 module: Module<'ra>,
2285 key: BindingKey,
2286 orig_ident_span: Span,
2287 ) -> NameResolutionRef<'ra> {
2288 *self.resolutions_mut(module).entry(key).or_insert_with(|| {
2289 self.arenas.alloc_name_resolution(NameResolution::new(orig_ident_span))
2290 })
2291 }
2292
2293 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2295 for ambiguity_error in &self.ambiguity_errors {
2296 if ambiguity_error.kind == ambi.kind
2298 && ambiguity_error.ident == ambi.ident
2299 && ambiguity_error.ident.span == ambi.ident.span
2300 && ambiguity_error.b1.span == ambi.b1.span
2301 && ambiguity_error.b2.span == ambi.b2.span
2302 {
2303 return true;
2304 }
2305 }
2306 false
2307 }
2308
2309 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2310 if let Some((b2, warning)) = used_decl.ambiguity.get() {
2311 let ambiguity_error = AmbiguityError {
2312 kind: AmbiguityKind::GlobVsGlob,
2313 ambig_vis: None,
2314 ident,
2315 b1: used_decl,
2316 b2,
2317 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2318 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2319 warning: if warning { Some(AmbiguityWarning::GlobImport) } else { None },
2320 };
2321 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2322 self.ambiguity_errors.push(ambiguity_error);
2324 }
2325 }
2326 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2327 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2328 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2331 let empty_module = self.empty_module;
2332 let arenas = self.arenas;
2333 self.cm()
2334 .maybe_resolve_ident_in_module(
2335 ModuleOrUniformRoot::Module(prelude),
2336 ident,
2337 MacroNS,
2338 &ParentScope::module(empty_module, arenas),
2339 None,
2340 )
2341 .is_ok()
2342 });
2343 if !found_in_stdlib_prelude {
2344 self.lint_buffer().buffer_lint(
2345 PRIVATE_MACRO_USE,
2346 import.root_id,
2347 ident.span,
2348 diagnostics::MacroIsPrivate { ident },
2349 );
2350 }
2351 }
2352 if used == Used::Scope
2355 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2356 && let Some((item_decl, _, false)) = entry.item_decl
2357 && item_decl == used_decl
2358 {
2359 return;
2360 }
2361 let old_used = self.import_use_map.entry(import).or_insert(used);
2362 if *old_used < used {
2363 *old_used = used;
2364 }
2365 if let Some(id) = import.id() {
2366 self.used_imports.insert(id);
2367 }
2368 self.add_to_glob_map(import, ident.name);
2369 self.record_use(ident, source_decl, Used::Other);
2370 }
2371 }
2372
2373 #[inline]
2374 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2375 if let ImportKind::Glob { def_id, .. } = import.kind {
2376 self.glob_map.entry(def_id).or_default().insert(name);
2377 }
2378 }
2379
2380 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2381 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2381",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2381u32),
::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);
2382 let mut ctxt = ident.span.ctxt();
2383 let mark = if ident.name == kw::DollarCrate {
2384 ctxt = ctxt.normalize_to_macro_rules();
2391 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2391",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2391u32),
::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!(
2392 "resolve_crate_root: marks={:?}",
2393 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2394 );
2395 let mut iter = ctxt.marks().into_iter().rev().peekable();
2396 let mut result = None;
2397 while let Some(&(mark, transparency)) = iter.peek() {
2399 if transparency == Transparency::Opaque {
2400 result = Some(mark);
2401 iter.next();
2402 } else {
2403 break;
2404 }
2405 }
2406 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2406",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2406u32),
::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!(
2407 "resolve_crate_root: found opaque mark {:?} {:?}",
2408 result,
2409 result.map(|r| r.expn_data())
2410 );
2411 for (mark, transparency) in iter {
2413 if transparency == Transparency::SemiOpaque {
2414 result = Some(mark);
2415 } else {
2416 break;
2417 }
2418 }
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/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2419",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/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!("resolve_crate_root: found semi-opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2420 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2421 result,
2422 result.map(|r| r.expn_data())
2423 );
2424 result
2425 } else {
2426 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2426",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2426u32),
::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");
2427 ctxt = ctxt.normalize_to_macros_2_0();
2428 ctxt.adjust(ExpnId::root())
2429 };
2430 let module = match mark {
2431 Some(def) => self.expn_def_scope(def),
2432 None => {
2433 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2433",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2433u32),
::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!(
2434 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2435 ident, ident.span
2436 );
2437 return self.graph_root.to_module();
2438 }
2439 };
2440 let module = self.expect_module(
2441 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2442 );
2443 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2443",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2443u32),
::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!(
2444 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2445 ident,
2446 module,
2447 module.name(),
2448 ident.span
2449 );
2450 module
2451 }
2452
2453 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2454 let mut module = self.expect_module(module.nearest_parent_mod().to_def_id());
2455 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2456 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2457 module = self.expect_module(parent.nearest_parent_mod().to_def_id());
2458 }
2459 module
2460 }
2461
2462 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2463 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2463",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2463u32),
::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);
2464 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2465 {
::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)");
2466 }
2467 }
2468
2469 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2470 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs:2470",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2470u32),
::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);
2471 self.pat_span_map.insert(node, span);
2472 }
2473
2474 fn is_accessible_from(&self, vis: Visibility<impl Into<ModId>>, module: Module<'ra>) -> bool {
2475 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2476 }
2477
2478 fn disambiguate_macro_rules_vs_modularized(
2479 &self,
2480 macro_rules: Decl<'ra>,
2481 modularized: Decl<'ra>,
2482 ) -> bool {
2483 let macro_rules = macro_rules.parent_module.unwrap();
2491 let modularized = modularized.parent_module.unwrap();
2492 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2493 && modularized.is_ancestor_of(macro_rules)
2494 }
2495
2496 fn extern_prelude_get_item<'r>(
2497 mut self: CmResolver<'r, 'ra, 'tcx>,
2498 ident: IdentKey,
2499 orig_ident_span: Span,
2500 finalize: bool,
2501 ) -> Option<Decl<'ra>> {
2502 let entry = self.extern_prelude.get(&ident);
2503 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2504 if finalize {
2505 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2506 }
2507 decl
2508 })
2509 }
2510
2511 fn extern_prelude_get_flag(
2512 &self,
2513 ident: IdentKey,
2514 orig_ident_span: Span,
2515 finalize: bool,
2516 ) -> Option<Decl<'ra>> {
2517 let entry = self.extern_prelude.get(&ident);
2518 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2519 let mut flag_decl = flag_decl.lock(); let (pending_decl, finalized, is_open) = *flag_decl;
2521 let decl = match pending_decl {
2522 PendingDecl::Ready(decl) => {
2523 if finalize && !finalized && !is_open {
2524 self.cstore_mut().process_path_extern(
2525 self.tcx,
2526 ident.name,
2527 orig_ident_span,
2528 );
2529 }
2530 decl
2531 }
2532 PendingDecl::Pending => {
2533 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2534 if is_open {
2535 let res = Res::OpenMod(ident.name);
2536 Some(self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT))
2537 } else {
2538 let crate_id = if finalize {
2539 self.cstore_mut().process_path_extern(
2540 self.tcx,
2541 ident.name,
2542 orig_ident_span,
2543 )
2544 } else {
2545 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2546 };
2547 crate_id.map(|crate_id| {
2548 let def_id = crate_id.as_def_id();
2549 let res = Res::Def(DefKind::Mod, def_id);
2550 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2551 })
2552 }
2553 }
2554 };
2555 *flag_decl = (PendingDecl::Ready(decl), finalize || finalized, is_open);
2556 decl.or_else(|| finalize.then_some(self.dummy_decl))
2557 })
2558 }
2559
2560 fn resolve_rustdoc_path(
2565 &self,
2566 path_str: &str,
2567 ns: Namespace,
2568 parent_scope: ParentScope<'ra>,
2569 ) -> Option<Res> {
2570 let segments: Result<Vec<_>, ()> = path_str
2571 .split("::")
2572 .enumerate()
2573 .map(|(i, s)| {
2574 let sym = if s.is_empty() {
2575 if i == 0 {
2576 kw::PathRoot
2578 } else {
2579 return Err(()); }
2581 } else {
2582 Symbol::intern(s)
2583 };
2584 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2585 })
2586 .collect();
2587 let Ok(segments) = segments else { return None };
2588
2589 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2590 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2591 PathResult::NonModule(path_res) => {
2592 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(..), _)))
2593 }
2594 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2595 None
2596 }
2597 path_result @ (PathResult::Module(..) | PathResult::Indeterminate) => {
2598 ::rustc_span::macros::bug_impl(None,
format_args!("got invalid path_result: {0:?}", path_result),
Location::caller())bug!("got invalid path_result: {path_result:?}")
2599 }
2600 }
2601 }
2602
2603 fn def_span(&self, def_id: DefId) -> Span {
2605 match def_id.as_local() {
2606 Some(def_id) => self.tcx.source_span(def_id),
2607 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2609 }
2610 }
2611
2612 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2613 match def_id.as_local() {
2614 Some(def_id) => self.field_names.get(&def_id).cloned(),
2615 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2616 self.tcx.def_kind(def_id),
2617 DefKind::Struct | DefKind::Union | DefKind::Variant
2618 ) =>
2619 {
2620 Some(
2621 self.tcx
2622 .associated_item_def_ids(def_id)
2623 .iter()
2624 .map(|&def_id| {
2625 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2626 })
2627 .collect(),
2628 )
2629 }
2630 _ => None,
2631 }
2632 }
2633
2634 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2635 match def_id.as_local() {
2636 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2637 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2638 self.tcx.def_kind(def_id),
2639 DefKind::Struct | DefKind::Union | DefKind::Variant
2640 ) =>
2641 {
2642 Some(
2643 self.tcx
2644 .associated_item_def_ids(def_id)
2645 .iter()
2646 .filter_map(|&def_id| {
2647 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2648 })
2649 .collect(),
2650 )
2651 }
2652 _ => None,
2653 }
2654 }
2655
2656 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2660 let ExprKind::Path(None, path) = &expr.kind else {
2661 return None;
2662 };
2663 if path.segments.last().unwrap().args.is_some() {
2666 return None;
2667 }
2668
2669 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2670
2671 if def_id.is_local() {
2675 return None;
2676 }
2677
2678 {
{
'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::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
2679 self.tcx, def_id,
2681 RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2682 )
2683 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2684 }
2685
2686 fn resolve_main(&mut self) {
2687 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2688 if !any_exe {
2690 return;
2691 }
2692
2693 let module = self.graph_root;
2694 let ident = Ident::with_dummy_span(sym::main);
2695 let parent_scope = &ParentScope::module(module, self.arenas);
2696
2697 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2698 ModuleOrUniformRoot::Module(module.to_module()),
2699 ident,
2700 ValueNS,
2701 parent_scope,
2702 None,
2703 ) else {
2704 return;
2705 };
2706
2707 let res = name_binding.res();
2708 let is_import = name_binding.is_import();
2709 let span = name_binding.span;
2710 if let Res::Def(DefKind::Fn, _) = res {
2711 self.record_use(ident, name_binding, Used::Other);
2712 }
2713 self.main_def = Some(MainDefinition { res, is_import, span });
2714 }
2715
2716 fn finalize_lang_items(&mut self) {
2717 for &cnum in self.tcx.used_crates(()) {
2719 for &(def_id, lang_item) in self.tcx.defined_lang_items(cnum).iter() {
2720 late::collect_item(self.tcx, &mut self.lang_items, lang_item, def_id, None);
2721 }
2722 }
2723 late::weak_lang_items::check_crate(self.tcx, &mut self.lang_items);
2724 }
2725}
2726
2727fn with_owner<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2728 this: &mut R,
2729 owner: NodeId,
2730 work: impl FnOnce(&mut R) -> T,
2731) -> T {
2732 let tables = this.as_mut().owners.remove(&owner).unwrap();
2733 with_owner_tables(this, owner, tables, work)
2734}
2735
2736{}
#[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/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2736u32),
::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))]
2737fn with_owner_tables<'ra, 'tcx, R: AsMut<Resolver<'ra, 'tcx>>, T>(
2738 this: &mut R,
2739 owner: NodeId,
2740 tables: PerOwnerResolverData<'tcx>,
2741 work: impl FnOnce(&mut R) -> T,
2742) -> T {
2743 debug_assert!(!this.as_mut().owners.contains_key(&owner));
2744 let resolver = this.as_mut();
2745 let old_owner = mem::replace(&mut resolver.current_owner, tables);
2746 let ret = work(this);
2747 let resolver = this.as_mut();
2748 let overwritten =
2749 resolver.owners.insert(owner, mem::replace(&mut resolver.current_owner, old_owner));
2750 assert!(overwritten.is_none());
2751 ret
2752}
2753
2754fn build_extern_prelude<'tcx, 'ra>(
2755 tcx: TyCtxt<'tcx>,
2756 attrs: &[ast::Attribute],
2757) -> FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> {
2758 let mut extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>> = tcx
2759 .sess
2760 .opts
2761 .externs
2762 .iter()
2763 .filter_map(|(name, entry)| {
2764 if entry.add_prelude
2767 && let sym = Symbol::intern(name)
2768 && sym.can_be_raw()
2769 {
2770 Some((IdentKey::with_root_ctxt(sym), ExternPreludeEntry::flag()))
2771 } else {
2772 None
2773 }
2774 })
2775 .collect();
2776
2777 let missing_open_bases: Vec<IdentKey> = extern_prelude
2783 .keys()
2784 .filter_map(|ident| {
2785 let (base, _) = ident.name.as_str().split_once("::")?;
2786 let base_sym = Symbol::intern(base);
2787 base_sym.can_be_raw().then(|| IdentKey::with_root_ctxt(base_sym))
2788 })
2789 .filter(|base_ident| !extern_prelude.contains_key(base_ident))
2790 .collect();
2791
2792 extern_prelude.extend(
2793 missing_open_bases.into_iter().map(|ident| (ident, ExternPreludeEntry::open_flag())),
2794 );
2795
2796 if !attr::contains_name(attrs, sym::no_core) {
2798 extern_prelude.insert(IdentKey::with_root_ctxt(sym::core), ExternPreludeEntry::flag());
2799
2800 if !attr::contains_name(attrs, sym::no_std) {
2801 extern_prelude.insert(IdentKey::with_root_ctxt(sym::std), ExternPreludeEntry::flag());
2802 }
2803 }
2804
2805 extern_prelude
2806}
2807
2808fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2809 let mut result = String::new();
2810 for (i, name) in names.enumerate().filter(|(_, name)| *name != kw::PathRoot) {
2811 if i > 0 {
2812 result.push_str("::");
2813 }
2814 if Ident::with_dummy_span(name).is_raw_guess() {
2815 result.push_str("r#");
2816 }
2817 result.push_str(name.as_str());
2818 }
2819 result
2820}
2821
2822fn path_names_to_string(path: &Path) -> String {
2823 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2824}
2825
2826fn module_to_string(mut module: Module<'_>) -> Option<String> {
2828 let mut names = Vec::new();
2829 while let Some(parent) = module.parent {
2830 names.push(module.name().unwrap_or(sym::opaque_module_name_placeholder));
2831 module = parent;
2832 }
2833 if names.is_empty() {
2834 return None;
2835 }
2836 Some(names_to_string(names.iter().rev().copied()))
2837}
2838
2839#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Stage { }
#[automatically_derived]impl ::core::cmp::PartialEq for Stage {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for Stage {
#[inline]
#[rustc_trivial_field_reads]
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)]
2840enum Stage {
2841 Early,
2845 Late,
2848}
2849
2850#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"ImportSummary vis nearest_parent_mod is_single priv_macro_use span",
&self.vis, &self.nearest_parent_mod, &self.is_single,
&self.priv_macro_use, &&self.span)
}
}Debug)]
2853struct ImportSummary {
2854 vis: Visibility,
2855 nearest_parent_mod: LocalModId,
2856 is_single: bool,
2857 priv_macro_use: bool,
2858 span: Span,
2859}
2860
2861#[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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Finalize node_id path_span root_span report_private used stage import",
&[&self.node_id, &self.path_span, &self.root_span,
&self.report_private, &self.used, &self.stage,
&&self.import])
}
}Debug)]
2863struct Finalize {
2864 node_id: NodeId,
2866 path_span: Span,
2869 root_span: Span,
2872 report_private: bool = true,
2875 used: Used = Used::Other,
2877 stage: Stage = Stage::Early,
2879 import: Option<ImportSummary> = None,
2881}
2882
2883impl Finalize {
2884 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2885 Finalize::with_root_span(node_id, path_span, path_span)
2886 }
2887
2888 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2889 Finalize { node_id, path_span, root_span, .. }
2890 }
2891}
2892
2893pub fn provide(providers: &mut Providers) {
2894 providers.registered_attr_tools = macros::registered_attr_tools;
2895 providers.registered_lint_tools = macros::registered_lint_tools;
2896}
2897
2898type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2904
2905mod ref_mut {
2906 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2907 use std::fmt;
2908 use std::ops::Deref;
2909
2910 use crate::Resolver;
2911
2912 pub(crate) enum RefOrMut<'a, T> {
2914 Ref(&'a T),
2915 Mut(&'a mut T),
2916 }
2917
2918 impl<'a, T> Deref for RefOrMut<'a, T> {
2919 type Target = T;
2920
2921 fn deref(&self) -> &Self::Target {
2922 match self {
2923 RefOrMut::Ref(r) => r,
2924 RefOrMut::Mut(r) => r,
2925 }
2926 }
2927 }
2928
2929 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2930 fn as_ref(&self) -> &T {
2931 &*self
2932 }
2933 }
2934
2935 impl<'a, T> RefOrMut<'a, T> {
2936 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2938 match self {
2939 RefOrMut::Ref(r) => RefOrMut::Ref(r),
2940 RefOrMut::Mut(r) => RefOrMut::Mut(r),
2941 }
2942 }
2943
2944 #[track_caller]
2950 pub(crate) fn get_mut(&mut self) -> &mut T {
2951 match self {
2952 RefOrMut::Ref(_) => {
::core::panicking::panic_fmt(format_args!("can\'t mutably borrow an immutable reference"));
}panic!("can't mutably borrow an immutable reference"),
2953 RefOrMut::Mut(r) => r,
2954 }
2955 }
2956 }
2957
2958 #[derive(#[automatically_derived]impl<T: ::core::default::Default>
::core::default::Default for CmCell<T> {
#[inline]
fn default() -> Self { CmCell(::core::default::Default::default()) }
}Default)]
2960 pub(crate) struct CmCell<T>(Cell<T>);
2961
2962 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2963 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2964 f.debug_tuple("CmCell").field(&self.get()).finish()
2965 }
2966 }
2967
2968 impl<T: Copy> Clone for CmCell<T> {
2969 fn clone(&self) -> CmCell<T> {
2970 CmCell::new(self.get())
2971 }
2972 }
2973
2974 impl<T: Copy> CmCell<T> {
2975 pub(crate) const fn get(&self) -> T {
2976 self.0.get()
2977 }
2978
2979 pub(crate) fn update<'ra, 'tcx>(
2980 &self,
2981 r: &mut Resolver<'ra, 'tcx>,
2982 f: impl FnOnce(T) -> T,
2983 ) {
2984 let old = self.get();
2985 self.set(f(old), r);
2986 }
2987 }
2988
2989 impl<T> CmCell<T> {
2990 pub(crate) const fn new(value: T) -> CmCell<T> {
2991 CmCell(Cell::new(value))
2992 }
2993
2994 pub(crate) fn set<'ra, 'tcx>(&self, val: T, _: &mut Resolver<'ra, 'tcx>) {
2995 self.0.set(val);
2996 }
2997
2998 pub(crate) fn set_checked<'ra, 'tcx>(&self, val: T, r: &Resolver<'ra, 'tcx>) {
2999 if !!r.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("Cannot mutate `CmCell` during speculative resolution"));
}
};assert!(
3000 !r.speculative_flag.is_speculative(),
3001 "Cannot mutate `CmCell` during speculative resolution"
3002 );
3003 self.0.set(val);
3004 }
3005
3006 pub(crate) fn into_inner(self) -> T {
3007 self.0.into_inner()
3008 }
3009 }
3010
3011 pub(crate) enum CmRef<'b, T> {
3012 Tracked(Ref<'b, T>),
3014 Untracked(&'b T),
3016 }
3017
3018 impl<'b, T> Deref for CmRef<'b, T> {
3019 type Target = T;
3020
3021 fn deref(&self) -> &Self::Target {
3022 match self {
3023 CmRef::Tracked(r) => r,
3024 CmRef::Untracked(r) => r,
3025 }
3026 }
3027 }
3028
3029 pub(crate) mod speculative {
3030 #[derive(#[automatically_derived]impl ::core::fmt::Debug for SpeculativeFlag {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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() -> Self {
SpeculativeFlag(::core::default::Default::default())
}
}Default)]
3031 pub(crate) struct SpeculativeFlag(bool);
3032
3033 impl SpeculativeFlag {
3034 pub(crate) unsafe fn set(&mut self, value: bool) {
3041 self.0 = value;
3042 }
3043
3044 pub(crate) fn is_speculative(&self) -> bool {
3045 self.0
3046 }
3047 }
3048 }
3049
3050 #[derive(#[automatically_derived]impl<T: ::core::default::Default>
::core::default::Default for CmRefCell<T> {
#[inline]
fn default() -> Self { CmRefCell(::core::default::Default::default()) }
}Default)]
3052 pub(crate) struct CmRefCell<T>(RefCell<T>);
3053
3054 impl<T> CmRefCell<T> {
3055 pub(crate) fn new(value: T) -> CmRefCell<T> {
3056 CmRefCell(RefCell::new(value))
3057 }
3058
3059 #[track_caller]
3060 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &mut Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
3061 self.try_borrow_mut(r).unwrap()
3062 }
3063
3064 #[track_caller]
3065 pub(crate) fn borrow_mut_checked<'ra, 'tcx>(
3066 &self,
3067 r: &Resolver<'ra, 'tcx>,
3068 ) -> RefMut<'_, T> {
3069 self.try_borrow_mut_checked(r).unwrap()
3070 }
3071
3072 #[track_caller]
3073 pub(crate) fn try_borrow_mut_checked<'ra, 'tcx>(
3074 &self,
3075 r: &Resolver<'ra, 'tcx>,
3076 ) -> Result<RefMut<'_, T>, BorrowMutError> {
3077 if !!r.speculative_flag.is_speculative() {
{
::core::panicking::panic_fmt(format_args!("Cannot mutate `CmRefCell` state/value during speculative resolution"));
}
};assert!(
3078 !r.speculative_flag.is_speculative(),
3079 "Cannot mutate `CmRefCell` state/value during speculative resolution"
3080 );
3081 self.0.try_borrow_mut()
3082 }
3083
3084 #[track_caller]
3085 pub(crate) fn try_borrow_mut<'ra, 'tcx>(
3086 &self,
3087 _: &mut Resolver<'ra, 'tcx>,
3088 ) -> Result<RefMut<'_, T>, BorrowMutError> {
3089 self.0.try_borrow_mut()
3090 }
3091
3092 pub(crate) fn borrow<'ra, 'tcx>(&self, _: &mut Resolver<'ra, 'tcx>) -> Ref<'_, T> {
3093 self.0.borrow()
3094 }
3095
3096 pub(crate) fn borrow_checked<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> CmRef<'_, T> {
3097 if r.speculative_flag.is_speculative() {
3098 CmRef::Untracked(unsafe { self.0.try_borrow_unguarded().unwrap() })
3116 } else {
3117 CmRef::Tracked(self.0.borrow())
3118 }
3119 }
3120 }
3121
3122 impl<T: Default> CmRefCell<T> {
3123 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
3124 if r.speculative_flag.is_speculative() {
3125 {
::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");
3126 }
3127 self.0.take()
3128 }
3129 }
3130}
3131
3132mod hygiene {
3133 use rustc_span::{ExpnId, SyntaxContext};
3134
3135 #[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Macros20NormalizedSyntaxContext {
}
#[automatically_derived]impl ::core::clone::Clone for
Macros20NormalizedSyntaxContext {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
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: &Self) -> 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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Macros20NormalizedSyntaxContext", &&self.0)
}
}Debug)]
3138 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
3139
3140 impl Macros20NormalizedSyntaxContext {
3141 #[inline]
3142 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3143 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
3144 }
3145
3146 #[inline]
3147 pub(crate) fn new_adjusted(
3148 mut ctxt: SyntaxContext,
3149 expn_id: ExpnId,
3150 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
3151 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
3152 (Macros20NormalizedSyntaxContext(ctxt), def)
3153 }
3154
3155 #[inline]
3156 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
3157 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());
3158 Macros20NormalizedSyntaxContext(ctxt)
3159 }
3160
3161 #[inline]
3163 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
3164 let ret = f(&mut self.0);
3165 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());
3166 ret
3167 }
3168 }
3169
3170 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
3171 type Target = SyntaxContext;
3172 fn deref(&self) -> &Self::Target {
3173 &self.0
3174 }
3175 }
3176}