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