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