1#![allow(internal_features)]
11#![cfg_attr(bootstrap, feature(assert_matches))]
12#![cfg_attr(bootstrap, feature(ptr_as_ref_unchecked))]
13#![feature(arbitrary_self_types)]
14#![feature(box_patterns)]
15#![feature(const_default)]
16#![feature(const_trait_impl)]
17#![feature(control_flow_into_value)]
18#![feature(default_field_values)]
19#![feature(if_let_guard)]
20#![feature(iter_intersperse)]
21#![feature(rustc_attrs)]
22#![feature(trim_prefix_suffix)]
23#![recursion_limit = "256"]
24use std::cell::Ref;
27use std::collections::BTreeSet;
28use std::fmt::{self};
29use std::ops::ControlFlow;
30use std::sync::Arc;
31
32use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
33use effective_visibilities::EffectiveVisibilitiesVisitor;
34use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
35use hygiene::Macros20NormalizedSyntaxContext;
36use imports::{Import, ImportData, ImportKind, NameResolution, PendingDecl};
37use late::{
38 ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
39 UnnecessaryQualification,
40};
41use macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
42use rustc_arena::{DroplessArena, TypedArena};
43use rustc_ast::node_id::NodeMap;
44use rustc_ast::{
45 self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
46 NodeId, Path, attr,
47};
48use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, default};
49use rustc_data_structures::intern::Interned;
50use rustc_data_structures::steal::Steal;
51use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
52use rustc_data_structures::unord::{UnordMap, UnordSet};
53use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
54use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
55use rustc_feature::BUILTIN_ATTRIBUTES;
56use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
57use rustc_hir::def::Namespace::{self, *};
58use rustc_hir::def::{
59 self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
60 PerNS,
61};
62use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
63use rustc_hir::definitions::DisambiguatorState;
64use rustc_hir::{PrimTy, TraitCandidate, find_attr};
65use rustc_index::bit_set::DenseBitSet;
66use rustc_metadata::creader::CStore;
67use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
68use rustc_middle::middle::privacy::EffectiveVisibilities;
69use rustc_middle::query::Providers;
70use rustc_middle::ty::{
71 self, DelegationFnSig, DelegationInfo, Feed, MainDefinition, RegisteredTools,
72 ResolverAstLowering, ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
73};
74use rustc_session::config::CrateType;
75use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
76use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
77use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
78use smallvec::{SmallVec, smallvec};
79use tracing::debug;
80
81type Res = def::Res<NodeId>;
82
83mod build_reduced_graph;
84mod check_unused;
85mod def_collector;
86mod diagnostics;
87mod effective_visibilities;
88mod errors;
89mod ident;
90mod imports;
91mod late;
92mod macros;
93pub mod rustdoc;
94
95pub use macros::registered_tools_ast;
96
97use crate::ref_mut::{CmCell, CmRefCell};
98
99#[derive(#[automatically_derived]
impl ::core::marker::Copy for Determinacy { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Determinacy {
#[inline]
fn clone(&self) -> Determinacy { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Determinacy {
#[inline]
fn eq(&self, other: &Determinacy) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Determinacy {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Determinacy::Determined => "Determined",
Determinacy::Undetermined => "Undetermined",
})
}
}Debug)]
100enum Determinacy {
101 Determined,
102 Undetermined,
103}
104
105impl Determinacy {
106 fn determined(determined: bool) -> Determinacy {
107 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
108 }
109}
110
111#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Scope<'ra> {
#[inline]
fn clone(&self) -> Scope<'ra> {
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Scope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for Scope<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Scope::DeriveHelpers(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DeriveHelpers", &__self_0),
Scope::DeriveHelpersCompat =>
::core::fmt::Formatter::write_str(f, "DeriveHelpersCompat"),
Scope::MacroRules(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MacroRules", &__self_0),
Scope::ModuleNonGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleNonGlobs", __self_0, &__self_1),
Scope::ModuleGlobs(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleGlobs", __self_0, &__self_1),
Scope::MacroUsePrelude =>
::core::fmt::Formatter::write_str(f, "MacroUsePrelude"),
Scope::BuiltinAttrs =>
::core::fmt::Formatter::write_str(f, "BuiltinAttrs"),
Scope::ExternPreludeItems =>
::core::fmt::Formatter::write_str(f, "ExternPreludeItems"),
Scope::ExternPreludeFlags =>
::core::fmt::Formatter::write_str(f, "ExternPreludeFlags"),
Scope::ToolPrelude =>
::core::fmt::Formatter::write_str(f, "ToolPrelude"),
Scope::StdLibPrelude =>
::core::fmt::Formatter::write_str(f, "StdLibPrelude"),
Scope::BuiltinTypes =>
::core::fmt::Formatter::write_str(f, "BuiltinTypes"),
}
}
}Debug)]
113enum Scope<'ra> {
114 DeriveHelpers(LocalExpnId),
116 DeriveHelpersCompat,
120 MacroRules(MacroRulesScopeRef<'ra>),
122 ModuleNonGlobs(Module<'ra>, Option<NodeId>),
126 ModuleGlobs(Module<'ra>, Option<NodeId>),
130 MacroUsePrelude,
132 BuiltinAttrs,
134 ExternPreludeItems,
136 ExternPreludeFlags,
138 ToolPrelude,
140 StdLibPrelude,
142 BuiltinTypes,
144}
145
146#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ScopeSet<'ra> {
#[inline]
fn clone(&self) -> ScopeSet<'ra> {
let _: ::core::clone::AssertParamIsClone<Namespace>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<MacroKind>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ScopeSet<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ScopeSet<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ScopeSet::All(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
&__self_0),
ScopeSet::Module(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Module",
__self_0, &__self_1),
ScopeSet::ModuleAndExternPrelude(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ModuleAndExternPrelude", __self_0, &__self_1),
ScopeSet::ExternPrelude =>
::core::fmt::Formatter::write_str(f, "ExternPrelude"),
ScopeSet::Macro(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Macro",
&__self_0),
}
}
}Debug)]
149enum ScopeSet<'ra> {
150 All(Namespace),
152 Module(Namespace, Module<'ra>),
154 ModuleAndExternPrelude(Namespace, Module<'ra>),
156 ExternPrelude,
158 Macro(MacroKind),
160}
161
162#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentScope<'ra> {
#[inline]
fn clone(&self) -> ParentScope<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<LocalExpnId>;
let _: ::core::clone::AssertParamIsClone<MacroRulesScopeRef<'ra>>;
let _: ::core::clone::AssertParamIsClone<&'ra [ast::Path]>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentScope<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for ParentScope<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "ParentScope",
"module", &self.module, "expansion", &self.expansion,
"macro_rules", &self.macro_rules, "derives", &&self.derives)
}
}Debug)]
167struct ParentScope<'ra> {
168 module: Module<'ra>,
169 expansion: LocalExpnId,
170 macro_rules: MacroRulesScopeRef<'ra>,
171 derives: &'ra [ast::Path],
172}
173
174impl<'ra> ParentScope<'ra> {
175 fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
178 ParentScope {
179 module,
180 expansion: LocalExpnId::ROOT,
181 macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
182 derives: &[],
183 }
184 }
185}
186
187#[derive(#[automatically_derived]
impl ::core::marker::Copy for InvocationParent { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InvocationParent {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"InvocationParent", "parent_def", &self.parent_def,
"impl_trait_context", &self.impl_trait_context, "in_attr",
&self.in_attr, "const_arg_context", &&self.const_arg_context)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for InvocationParent {
#[inline]
fn clone(&self) -> InvocationParent {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _: ::core::clone::AssertParamIsClone<ImplTraitContext>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<ConstArgContext>;
*self
}
}Clone)]
188struct InvocationParent {
189 parent_def: LocalDefId,
190 impl_trait_context: ImplTraitContext,
191 in_attr: bool,
192 const_arg_context: ConstArgContext,
193}
194
195impl InvocationParent {
196 const ROOT: Self = Self {
197 parent_def: CRATE_DEF_ID,
198 impl_trait_context: ImplTraitContext::Existential,
199 in_attr: false,
200 const_arg_context: ConstArgContext::NonDirect,
201 };
202}
203
204#[derive(#[automatically_derived]
impl ::core::marker::Copy for ImplTraitContext { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ImplTraitContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ImplTraitContext::Existential => "Existential",
ImplTraitContext::Universal => "Universal",
ImplTraitContext::InBinding => "InBinding",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ImplTraitContext {
#[inline]
fn clone(&self) -> ImplTraitContext { *self }
}Clone)]
205enum ImplTraitContext {
206 Existential,
207 Universal,
208 InBinding,
209}
210
211#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstArgContext { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstArgContext {
#[inline]
fn clone(&self) -> ConstArgContext { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstArgContext {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ConstArgContext::Direct => "Direct",
ConstArgContext::NonDirect => "NonDirect",
})
}
}Debug)]
212enum ConstArgContext {
213 Direct,
214 NonDirect,
216}
217
218#[derive(#[automatically_derived]
impl ::core::clone::Clone for Used {
#[inline]
fn clone(&self) -> Used { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Used { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Used {
#[inline]
fn eq(&self, other: &Used) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Used {
#[inline]
fn partial_cmp(&self, other: &Used)
-> ::core::option::Option<::core::cmp::Ordering> {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
}
}PartialOrd, #[automatically_derived]
impl ::core::fmt::Debug for Used {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Used::Scope => "Scope", Used::Other => "Other", })
}
}Debug)]
233enum Used {
234 Scope,
235 Other,
236}
237
238#[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)]
239struct BindingError {
240 name: Ident,
241 origin: Vec<(Span, ast::Pat)>,
242 target: Vec<ast::Pat>,
243 could_be_path: bool,
244}
245
246#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ResolutionError<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ResolutionError::GenericParamsFromOuterItem {
outer_res: __self_0,
has_generic_params: __self_1,
def_kind: __self_2,
inner_item: __self_3,
current_self_ty: __self_4 } =>
::core::fmt::Formatter::debug_struct_field5_finish(f,
"GenericParamsFromOuterItem", "outer_res", __self_0,
"has_generic_params", __self_1, "def_kind", __self_2,
"inner_item", __self_3, "current_self_ty", &__self_4),
ResolutionError::NameAlreadyUsedInParameterList(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NameAlreadyUsedInParameterList", __self_0, &__self_1),
ResolutionError::MethodNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"MethodNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::TypeNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"TypeNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::ConstNotMemberOfTrait(__self_0, __self_1,
__self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f,
"ConstNotMemberOfTrait", __self_0, __self_1, &__self_2),
ResolutionError::VariableNotBoundInPattern(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableNotBoundInPattern", __self_0, &__self_1),
ResolutionError::VariableBoundWithDifferentMode(__self_0,
__self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VariableBoundWithDifferentMode", __self_0, &__self_1),
ResolutionError::IdentifierBoundMoreThanOnceInParameterList(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInParameterList", &__self_0),
ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(__self_0)
=>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IdentifierBoundMoreThanOnceInSamePattern", &__self_0),
ResolutionError::UndeclaredLabel {
name: __self_0, suggestion: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"UndeclaredLabel", "name", __self_0, "suggestion",
&__self_1),
ResolutionError::SelfImportsOnlyAllowedWithin {
root: __self_0, span_with_rename: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SelfImportsOnlyAllowedWithin", "root", __self_0,
"span_with_rename", &__self_1),
ResolutionError::SelfImportCanOnlyAppearOnceInTheList =>
::core::fmt::Formatter::write_str(f,
"SelfImportCanOnlyAppearOnceInTheList"),
ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix =>
::core::fmt::Formatter::write_str(f,
"SelfImportOnlyInImportListWithNonEmptyPrefix"),
ResolutionError::FailedToResolve {
segment: __self_0,
label: __self_1,
suggestion: __self_2,
module: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"FailedToResolve", "segment", __self_0, "label", __self_1,
"suggestion", __self_2, "module", &__self_3),
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem =>
::core::fmt::Formatter::write_str(f,
"CannotCaptureDynamicEnvironmentInFnItem"),
ResolutionError::AttemptToUseNonConstantValueInConstant {
ident: __self_0,
suggestion: __self_1,
current: __self_2,
type_span: __self_3 } =>
::core::fmt::Formatter::debug_struct_field4_finish(f,
"AttemptToUseNonConstantValueInConstant", "ident", __self_0,
"suggestion", __self_1, "current", __self_2, "type_span",
&__self_3),
ResolutionError::BindingShadowsSomethingUnacceptable {
shadowing_binding: __self_0,
name: __self_1,
participle: __self_2,
article: __self_3,
shadowed_binding: __self_4,
shadowed_binding_span: __self_5 } => {
let names: &'static _ =
&["shadowing_binding", "name", "participle", "article",
"shadowed_binding", "shadowed_binding_span"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
&__self_5];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"BindingShadowsSomethingUnacceptable", names, values)
}
ResolutionError::ForwardDeclaredGenericParam(__self_0, __self_1)
=>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ForwardDeclaredGenericParam", __self_0, &__self_1),
ResolutionError::ParamInTyOfConstParam { name: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"ParamInTyOfConstParam", "name", &__self_0),
ResolutionError::ParamInNonTrivialAnonConst {
name: __self_0, param_kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ParamInNonTrivialAnonConst", "name", __self_0,
"param_kind", &__self_1),
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)]
247enum ResolutionError<'ra> {
248 GenericParamsFromOuterItem {
250 outer_res: Res,
251 has_generic_params: HasGenericParams,
252 def_kind: DefKind,
253 inner_item: Option<(Span, ast::ItemKind)>,
254 current_self_ty: Option<String>,
255 },
256 NameAlreadyUsedInParameterList(Ident, Span),
259 MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
261 TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
263 ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
265 VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
267 VariableBoundWithDifferentMode(Ident, Span),
269 IdentifierBoundMoreThanOnceInParameterList(Ident),
271 IdentifierBoundMoreThanOnceInSamePattern(Ident),
273 UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
275 SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
277 SelfImportCanOnlyAppearOnceInTheList,
279 SelfImportOnlyInImportListWithNonEmptyPrefix,
281 FailedToResolve {
283 segment: Option<Symbol>,
284 label: String,
285 suggestion: Option<Suggestion>,
286 module: Option<ModuleOrUniformRoot<'ra>>,
287 },
288 CannotCaptureDynamicEnvironmentInFnItem,
290 AttemptToUseNonConstantValueInConstant {
292 ident: Ident,
293 suggestion: &'static str,
294 current: &'static str,
295 type_span: Option<Span>,
296 },
297 BindingShadowsSomethingUnacceptable {
299 shadowing_binding: PatternSource,
300 name: Symbol,
301 participle: &'static str,
302 article: &'static str,
303 shadowed_binding: Res,
304 shadowed_binding_span: Span,
305 },
306 ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
308 ParamInTyOfConstParam { name: Symbol },
312 ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
316 ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
320 ForwardDeclaredSelf(ForwardGenericParamBanReason),
322 UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
324 TraitImplMismatch {
326 name: Ident,
327 kind: &'static str,
328 trait_path: String,
329 trait_item_span: Span,
330 code: ErrCode,
331 },
332 TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
334 InvalidAsmSym,
336 LowercaseSelf,
338 BindingInNeverPattern,
340}
341
342enum VisResolutionError<'a> {
343 Relative2018(Span, &'a ast::Path),
344 AncestorOnly(Span),
345 FailedToResolve(Span, String, Option<Suggestion>),
346 ExpectedFound(Span, String, Res),
347 Indeterminate(Span),
348 ModuleOnly(Span),
349}
350
351#[derive(#[automatically_derived]
impl ::core::clone::Clone for Segment {
#[inline]
fn clone(&self) -> Segment {
let _: ::core::clone::AssertParamIsClone<Ident>;
let _: ::core::clone::AssertParamIsClone<Option<NodeId>>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Segment { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Segment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f, "Segment",
"ident", &self.ident, "id", &self.id, "has_generic_args",
&self.has_generic_args, "has_lifetime_args",
&self.has_lifetime_args, "args_span", &&self.args_span)
}
}Debug)]
354struct Segment {
355 ident: Ident,
356 id: Option<NodeId>,
357 has_generic_args: bool,
360 has_lifetime_args: bool,
362 args_span: Span,
363}
364
365impl Segment {
366 fn from_path(path: &Path) -> Vec<Segment> {
367 path.segments.iter().map(|s| s.into()).collect()
368 }
369
370 fn from_ident(ident: Ident) -> Segment {
371 Segment {
372 ident,
373 id: None,
374 has_generic_args: false,
375 has_lifetime_args: false,
376 args_span: DUMMY_SP,
377 }
378 }
379
380 fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
381 Segment {
382 ident,
383 id: Some(id),
384 has_generic_args: false,
385 has_lifetime_args: false,
386 args_span: DUMMY_SP,
387 }
388 }
389
390 fn names_to_string(segments: &[Segment]) -> String {
391 names_to_string(segments.iter().map(|seg| seg.ident.name))
392 }
393}
394
395impl<'a> From<&'a ast::PathSegment> for Segment {
396 fn from(seg: &'a ast::PathSegment) -> Segment {
397 let has_generic_args = seg.args.is_some();
398 let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
399 match args {
400 GenericArgs::AngleBracketed(args) => {
401 let found_lifetimes = args
402 .args
403 .iter()
404 .any(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) => true,
_ => false,
}matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
405 (args.span, found_lifetimes)
406 }
407 GenericArgs::Parenthesized(args) => (args.span, true),
408 GenericArgs::ParenthesizedElided(span) => (*span, true),
409 }
410 } else {
411 (DUMMY_SP, false)
412 };
413 Segment {
414 ident: seg.ident,
415 id: Some(seg.id),
416 has_generic_args,
417 has_lifetime_args,
418 args_span,
419 }
420 }
421}
422
423#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for LateDecl<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LateDecl::Decl(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Decl",
&__self_0),
LateDecl::RibDef(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "RibDef",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl<'ra> ::core::marker::Copy for LateDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for LateDecl<'ra> {
#[inline]
fn clone(&self) -> LateDecl<'ra> {
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Res>;
*self
}
}Clone)]
425enum LateDecl<'ra> {
426 Decl(Decl<'ra>),
428 RibDef(Res),
431}
432
433impl<'ra> LateDecl<'ra> {
434 fn res(self) -> Res {
435 match self {
436 LateDecl::Decl(binding) => binding.res(),
437 LateDecl::RibDef(res) => res,
438 }
439 }
440}
441
442#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for ModuleOrUniformRoot<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ModuleOrUniformRoot<'ra> {
#[inline]
fn clone(&self) -> ModuleOrUniformRoot<'ra> {
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
let _: ::core::clone::AssertParamIsClone<Module<'ra>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for ModuleOrUniformRoot<'ra> {
#[inline]
fn eq(&self, other: &ModuleOrUniformRoot<'ra>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ModuleOrUniformRoot::Module(__self_0),
ModuleOrUniformRoot::Module(__arg1_0)) =>
__self_0 == __arg1_0,
(ModuleOrUniformRoot::ModuleAndExternPrelude(__self_0),
ModuleOrUniformRoot::ModuleAndExternPrelude(__arg1_0)) =>
__self_0 == __arg1_0,
_ => 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"),
}
}
}Debug)]
443enum ModuleOrUniformRoot<'ra> {
444 Module(Module<'ra>),
446
447 ModuleAndExternPrelude(Module<'ra>),
451
452 ExternPrelude,
455
456 CurrentScope,
460}
461
462#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for PathResult<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PathResult::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
PathResult::NonModule(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NonModule", &__self_0),
PathResult::Indeterminate =>
::core::fmt::Formatter::write_str(f, "Indeterminate"),
PathResult::Failed {
span: __self_0,
label: __self_1,
suggestion: __self_2,
is_error_from_last_segment: __self_3,
module: __self_4,
segment_name: __self_5,
error_implied_by_parse_error: __self_6 } => {
let names: &'static _ =
&["span", "label", "suggestion",
"is_error_from_last_segment", "module", "segment_name",
"error_implied_by_parse_error"];
let values: &[&dyn ::core::fmt::Debug] =
&[__self_0, __self_1, __self_2, __self_3, __self_4,
__self_5, &__self_6];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"Failed", names, values)
}
}
}
}Debug)]
463enum PathResult<'ra> {
464 Module(ModuleOrUniformRoot<'ra>),
465 NonModule(PartialRes),
466 Indeterminate,
467 Failed {
468 span: Span,
469 label: String,
470 suggestion: Option<Suggestion>,
471 is_error_from_last_segment: bool,
472 module: Option<ModuleOrUniformRoot<'ra>>,
486 segment_name: Symbol,
488 error_implied_by_parse_error: bool,
489 },
490}
491
492impl<'ra> PathResult<'ra> {
493 fn failed(
494 ident: Ident,
495 is_error_from_last_segment: bool,
496 finalize: bool,
497 error_implied_by_parse_error: bool,
498 module: Option<ModuleOrUniformRoot<'ra>>,
499 label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
500 ) -> PathResult<'ra> {
501 let (label, suggestion) =
502 if finalize { label_and_suggestion() } else { (String::new(), None) };
503 PathResult::Failed {
504 span: ident.span,
505 segment_name: ident.name,
506 label,
507 suggestion,
508 is_error_from_last_segment,
509 module,
510 error_implied_by_parse_error,
511 }
512 }
513}
514
515#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ModuleKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ModuleKind::Block =>
::core::fmt::Formatter::write_str(f, "Block"),
ModuleKind::Def(__self_0, __self_1, __self_2) =>
::core::fmt::Formatter::debug_tuple_field3_finish(f, "Def",
__self_0, __self_1, &__self_2),
}
}
}Debug)]
516enum ModuleKind {
517 Block,
530 Def(DefKind, DefId, Option<Symbol>),
540}
541
542impl ModuleKind {
543 fn name(&self) -> Option<Symbol> {
545 match *self {
546 ModuleKind::Block => None,
547 ModuleKind::Def(.., name) => name,
548 }
549 }
550}
551
552#[derive(#[automatically_derived]
impl ::core::clone::Clone for IdentKey {
#[inline]
fn clone(&self) -> IdentKey {
let _: ::core::clone::AssertParamIsClone<Symbol>;
let _:
::core::clone::AssertParamIsClone<Macros20NormalizedSyntaxContext>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IdentKey { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for IdentKey {
#[inline]
fn eq(&self, other: &IdentKey) -> bool {
self.name == other.name && self.ctxt == other.ctxt
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IdentKey {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_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)]
563struct IdentKey {
564 name: Symbol,
565 ctxt: Macros20NormalizedSyntaxContext,
566}
567
568impl IdentKey {
569 #[inline]
570 fn new(ident: Ident) -> IdentKey {
571 IdentKey { name: ident.name, ctxt: Macros20NormalizedSyntaxContext::new(ident.span.ctxt()) }
572 }
573
574 #[inline]
575 fn new_adjusted(ident: Ident, expn_id: ExpnId) -> (IdentKey, Option<ExpnId>) {
576 let (ctxt, def) = Macros20NormalizedSyntaxContext::new_adjusted(ident.span.ctxt(), expn_id);
577 (IdentKey { name: ident.name, ctxt }, def)
578 }
579
580 #[inline]
581 fn with_root_ctxt(name: Symbol) -> Self {
582 let ctxt = Macros20NormalizedSyntaxContext::new_unchecked(SyntaxContext::root());
583 IdentKey { name, ctxt }
584 }
585
586 #[inline]
587 fn orig(self, orig_ident_span: Span) -> Ident {
588 Ident::new(self.name, orig_ident_span)
589 }
590}
591
592#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingKey {
#[inline]
fn clone(&self) -> BindingKey {
let _: ::core::clone::AssertParamIsClone<IdentKey>;
let _: ::core::clone::AssertParamIsClone<Namespace>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for BindingKey {
#[inline]
fn eq(&self, other: &BindingKey) -> bool {
self.disambiguator == other.disambiguator && self.ident == other.ident
&& self.ns == other.ns
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BindingKey {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_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)]
597struct BindingKey {
598 ident: IdentKey,
601 ns: Namespace,
602 disambiguator: u32,
608}
609
610impl BindingKey {
611 fn new(ident: IdentKey, ns: Namespace) -> Self {
612 BindingKey { ident, ns, disambiguator: 0 }
613 }
614
615 fn new_disambiguated(
616 ident: IdentKey,
617 ns: Namespace,
618 disambiguator: impl FnOnce() -> u32,
619 ) -> BindingKey {
620 let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
621 BindingKey { ident, ns, disambiguator }
622 }
623}
624
625type Resolutions<'ra> = CmRefCell<FxIndexMap<BindingKey, &'ra CmRefCell<NameResolution<'ra>>>>;
626
627struct ModuleData<'ra> {
639 parent: Option<Module<'ra>>,
641 kind: ModuleKind,
643
644 lazy_resolutions: Resolutions<'ra>,
647 populate_on_access: CacheCell<bool>,
649 underscore_disambiguator: CmCell<u32>,
651
652 unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
654
655 no_implicit_prelude: bool,
657
658 glob_importers: CmRefCell<Vec<Import<'ra>>>,
659 globs: CmRefCell<Vec<Import<'ra>>>,
660
661 traits: CmRefCell<
663 Option<Box<[(Symbol, Decl<'ra>, Option<Module<'ra>>, bool )]>>,
664 >,
665
666 span: Span,
668
669 expansion: ExpnId,
670
671 self_decl: Option<Decl<'ra>>,
674}
675
676#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for Module<'ra> {
#[inline]
fn clone(&self) -> Module<'ra> {
let _:
::core::clone::AssertParamIsClone<Interned<'ra,
ModuleData<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for Module<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for Module<'ra> {
#[inline]
fn eq(&self, other: &Module<'ra>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl<'ra> ::core::cmp::Eq for Module<'ra> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_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)]
679#[rustc_pass_by_value]
680struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
681
682impl std::hash::Hash for ModuleData<'_> {
687 fn hash<H>(&self, _: &mut H)
688 where
689 H: std::hash::Hasher,
690 {
691 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
692 }
693}
694
695impl<'ra> ModuleData<'ra> {
696 fn new(
697 parent: Option<Module<'ra>>,
698 kind: ModuleKind,
699 expansion: ExpnId,
700 span: Span,
701 no_implicit_prelude: bool,
702 self_decl: Option<Decl<'ra>>,
703 ) -> Self {
704 let is_foreign = match kind {
705 ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
706 ModuleKind::Block => false,
707 };
708 ModuleData {
709 parent,
710 kind,
711 lazy_resolutions: Default::default(),
712 populate_on_access: CacheCell::new(is_foreign),
713 underscore_disambiguator: CmCell::new(0),
714 unexpanded_invocations: Default::default(),
715 no_implicit_prelude,
716 glob_importers: CmRefCell::new(Vec::new()),
717 globs: CmRefCell::new(Vec::new()),
718 traits: CmRefCell::new(None),
719 span,
720 expansion,
721 self_decl,
722 }
723 }
724}
725
726impl<'ra> Module<'ra> {
727 fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
728 self,
729 resolver: &R,
730 mut f: impl FnMut(&R, IdentKey, Span, Namespace, Decl<'ra>),
731 ) {
732 for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
733 let name_resolution = name_resolution.borrow();
734 if let Some(decl) = name_resolution.best_decl() {
735 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
736 }
737 }
738 }
739
740 fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
741 self,
742 resolver: &mut R,
743 mut f: impl FnMut(&mut R, IdentKey, Span, Namespace, Decl<'ra>),
744 ) {
745 for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
746 let name_resolution = name_resolution.borrow();
747 if let Some(decl) = name_resolution.best_decl() {
748 f(resolver, key.ident, name_resolution.orig_ident_span, key.ns, decl);
749 }
750 }
751 }
752
753 fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
755 let mut traits = self.traits.borrow_mut(resolver.as_ref());
756 if traits.is_none() {
757 let mut collected_traits = Vec::new();
758 self.for_each_child(resolver, |r, ident, _, ns, binding| {
759 if ns != TypeNS {
760 return;
761 }
762 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
763 collected_traits.push((
764 ident.name,
765 binding,
766 r.as_ref().get_module(def_id),
767 binding.is_ambiguity_recursive(),
768 ));
769 }
770 });
771 *traits = Some(collected_traits.into_boxed_slice());
772 }
773 }
774
775 fn res(self) -> Option<Res> {
776 match self.kind {
777 ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
778 _ => None,
779 }
780 }
781
782 fn def_id(self) -> DefId {
783 self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
784 }
785
786 fn opt_def_id(self) -> Option<DefId> {
787 match self.kind {
788 ModuleKind::Def(_, def_id, _) => Some(def_id),
789 _ => None,
790 }
791 }
792
793 fn is_normal(self) -> bool {
795 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Mod, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
796 }
797
798 fn is_trait(self) -> bool {
799 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ModuleKind::Def(DefKind::Trait, _, _) => true,
_ => false,
}matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
800 }
801
802 fn nearest_item_scope(self) -> Module<'ra> {
803 match self.kind {
804 ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
805 self.parent.expect("enum or trait module without a parent")
806 }
807 _ => self,
808 }
809 }
810
811 fn nearest_parent_mod(self) -> DefId {
814 match self.kind {
815 ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
816 _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
817 }
818 }
819
820 fn is_ancestor_of(self, mut other: Self) -> bool {
821 while self != other {
822 if let Some(parent) = other.parent {
823 other = parent;
824 } else {
825 return false;
826 }
827 }
828 true
829 }
830}
831
832impl<'ra> std::ops::Deref for Module<'ra> {
833 type Target = ModuleData<'ra>;
834
835 fn deref(&self) -> &Self::Target {
836 &self.0
837 }
838}
839
840impl<'ra> fmt::Debug for Module<'ra> {
841 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842 match self.kind {
843 ModuleKind::Block => f.write_fmt(format_args!("block"))write!(f, "block"),
844 ModuleKind::Def(..) => f.write_fmt(format_args!("{0:?}", self.res()))write!(f, "{:?}", self.res()),
845 }
846 }
847}
848
849#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for DeclData<'ra> {
#[inline]
fn clone(&self) -> DeclData<'ra> {
DeclData {
kind: ::core::clone::Clone::clone(&self.kind),
ambiguity: ::core::clone::Clone::clone(&self.ambiguity),
warn_ambiguity: ::core::clone::Clone::clone(&self.warn_ambiguity),
expansion: ::core::clone::Clone::clone(&self.expansion),
span: ::core::clone::Clone::clone(&self.span),
vis: ::core::clone::Clone::clone(&self.vis),
parent_module: ::core::clone::Clone::clone(&self.parent_module),
}
}
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclData<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["kind", "ambiguity", "warn_ambiguity", "expansion", "span",
"vis", "parent_module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.ambiguity, &self.warn_ambiguity,
&self.expansion, &self.span, &self.vis,
&&self.parent_module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DeclData",
names, values)
}
}Debug)]
851struct DeclData<'ra> {
852 kind: DeclKind<'ra>,
853 ambiguity: CmCell<Option<Decl<'ra>>>,
854 warn_ambiguity: CmCell<bool>,
857 expansion: LocalExpnId,
858 span: Span,
859 vis: CmCell<Visibility<DefId>>,
860 parent_module: Option<Module<'ra>>,
861}
862
863type Decl<'ra> = Interned<'ra, DeclData<'ra>>;
866
867impl std::hash::Hash for DeclData<'_> {
872 fn hash<H>(&self, _: &mut H)
873 where
874 H: std::hash::Hasher,
875 {
876 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
877 }
878}
879
880#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for DeclKind<'ra> {
#[inline]
fn clone(&self) -> DeclKind<'ra> {
let _: ::core::clone::AssertParamIsClone<Res>;
let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
let _: ::core::clone::AssertParamIsClone<Import<'ra>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for DeclKind<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for DeclKind<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DeclKind::Def(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Def",
&__self_0),
DeclKind::Import { source_decl: __self_0, import: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Import", "source_decl", __self_0, "import", &__self_1),
}
}
}Debug)]
882enum DeclKind<'ra> {
883 Def(Res),
886 Import { source_decl: Decl<'ra>, import: Import<'ra> },
888}
889
890impl<'ra> DeclKind<'ra> {
891 fn is_import(&self) -> bool {
893 #[allow(non_exhaustive_omitted_patterns)] match *self {
DeclKind::Import { .. } => true,
_ => false,
}matches!(*self, DeclKind::Import { .. })
894 }
895}
896
897#[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)]
898struct PrivacyError<'ra> {
899 ident: Ident,
900 decl: Decl<'ra>,
901 dedup_span: Span,
902 outermost_res: Option<(Res, Ident)>,
903 parent_scope: ParentScope<'ra>,
904 single_nested: bool,
906 source: Option<ast::Expr>,
907}
908
909#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for UseError<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["err", "candidates", "def_id", "instead", "suggestion", "path",
"is_call"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.err, &self.candidates, &self.def_id, &self.instead,
&self.suggestion, &self.path, &&self.is_call];
::core::fmt::Formatter::debug_struct_fields_finish(f, "UseError",
names, values)
}
}Debug)]
910struct UseError<'a> {
911 err: Diag<'a>,
912 candidates: Vec<ImportSuggestion>,
914 def_id: DefId,
916 instead: bool,
918 suggestion: Option<(Span, &'static str, String, Applicability)>,
920 path: Vec<Segment>,
923 is_call: bool,
925}
926
927#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityKind {
#[inline]
fn clone(&self) -> AmbiguityKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityKind {
#[inline]
fn eq(&self, other: &AmbiguityKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for AmbiguityKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AmbiguityKind::BuiltinAttr => "BuiltinAttr",
AmbiguityKind::DeriveHelper => "DeriveHelper",
AmbiguityKind::MacroRulesVsModularized =>
"MacroRulesVsModularized",
AmbiguityKind::GlobVsOuter => "GlobVsOuter",
AmbiguityKind::GlobVsGlob => "GlobVsGlob",
AmbiguityKind::GlobVsExpanded => "GlobVsExpanded",
AmbiguityKind::MoreExpandedVsOuter => "MoreExpandedVsOuter",
})
}
}Debug)]
928enum AmbiguityKind {
929 BuiltinAttr,
930 DeriveHelper,
931 MacroRulesVsModularized,
932 GlobVsOuter,
933 GlobVsGlob,
934 GlobVsExpanded,
935 MoreExpandedVsOuter,
936}
937
938impl AmbiguityKind {
939 fn descr(self) -> &'static str {
940 match self {
941 AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
942 AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
943 AmbiguityKind::MacroRulesVsModularized => {
944 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
945 }
946 AmbiguityKind::GlobVsOuter => {
947 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
948 }
949 AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
950 AmbiguityKind::GlobVsExpanded => {
951 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
952 }
953 AmbiguityKind::MoreExpandedVsOuter => {
954 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
955 }
956 }
957 }
958}
959
960#[derive(#[automatically_derived]
impl ::core::clone::Clone for AmbiguityWarning {
#[inline]
fn clone(&self) -> AmbiguityWarning { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AmbiguityWarning { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AmbiguityWarning {
#[inline]
fn eq(&self, other: &AmbiguityWarning) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
961enum AmbiguityWarning {
962 GlobImport,
963 PanicImport,
964}
965
966struct AmbiguityError<'ra> {
967 kind: AmbiguityKind,
968 ambig_vis: Option<(Visibility, Visibility)>,
969 ident: Ident,
970 b1: Decl<'ra>,
971 b2: Decl<'ra>,
972 scope1: Scope<'ra>,
973 scope2: Scope<'ra>,
974 warning: Option<AmbiguityWarning>,
975}
976
977impl<'ra> DeclData<'ra> {
978 fn vis(&self) -> Visibility<DefId> {
979 self.vis.get()
980 }
981
982 fn res(&self) -> Res {
983 match self.kind {
984 DeclKind::Def(res) => res,
985 DeclKind::Import { source_decl, .. } => source_decl.res(),
986 }
987 }
988
989 fn import_source(&self) -> Decl<'ra> {
990 match self.kind {
991 DeclKind::Import { source_decl, .. } => source_decl,
992 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
993 }
994 }
995
996 fn descent_to_ambiguity(self: Decl<'ra>) -> Option<(Decl<'ra>, Decl<'ra>)> {
997 match self.ambiguity.get() {
998 Some(ambig_binding) => Some((self, ambig_binding)),
999 None => match self.kind {
1000 DeclKind::Import { source_decl, .. } => source_decl.descent_to_ambiguity(),
1001 _ => None,
1002 },
1003 }
1004 }
1005
1006 fn is_ambiguity_recursive(&self) -> bool {
1007 self.ambiguity.get().is_some()
1008 || match self.kind {
1009 DeclKind::Import { source_decl, .. } => source_decl.is_ambiguity_recursive(),
1010 _ => false,
1011 }
1012 }
1013
1014 fn warn_ambiguity_recursive(&self) -> bool {
1015 self.warn_ambiguity.get()
1016 || match self.kind {
1017 DeclKind::Import { source_decl, .. } => source_decl.warn_ambiguity_recursive(),
1018 _ => false,
1019 }
1020 }
1021
1022 fn is_possibly_imported_variant(&self) -> bool {
1023 match self.kind {
1024 DeclKind::Import { source_decl, .. } => source_decl.is_possibly_imported_variant(),
1025 DeclKind::Def(Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _)) => {
1026 true
1027 }
1028 DeclKind::Def(..) => false,
1029 }
1030 }
1031
1032 fn is_extern_crate(&self) -> bool {
1033 match self.kind {
1034 DeclKind::Import { import, .. } => {
1035 #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::ExternCrate { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::ExternCrate { .. })
1036 }
1037 DeclKind::Def(Res::Def(_, def_id)) => def_id.is_crate_root(),
1038 _ => false,
1039 }
1040 }
1041
1042 fn is_import(&self) -> bool {
1043 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
DeclKind::Import { .. } => true,
_ => false,
}matches!(self.kind, DeclKind::Import { .. })
1044 }
1045
1046 fn is_import_user_facing(&self) -> bool {
1049 #[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, .. }
1050 if !matches!(import.kind, ImportKind::MacroExport))
1051 }
1052
1053 fn is_glob_import(&self) -> bool {
1054 match self.kind {
1055 DeclKind::Import { import, .. } => import.is_glob(),
1056 _ => false,
1057 }
1058 }
1059
1060 fn is_assoc_item(&self) -> bool {
1061 #[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, _))
1062 }
1063
1064 fn macro_kinds(&self) -> Option<MacroKinds> {
1065 self.res().macro_kinds()
1066 }
1067
1068 fn reexport_chain(self: Decl<'ra>, r: &Resolver<'_, '_>) -> SmallVec<[Reexport; 2]> {
1069 let mut reexport_chain = SmallVec::new();
1070 let mut next_binding = self;
1071 while let DeclKind::Import { source_decl, import, .. } = next_binding.kind {
1072 reexport_chain.push(import.simplify(r));
1073 next_binding = source_decl;
1074 }
1075 reexport_chain
1076 }
1077
1078 fn may_appear_after(&self, invoc_parent_expansion: LocalExpnId, decl: Decl<'_>) -> bool {
1085 let self_parent_expansion = self.expansion;
1089 let other_parent_expansion = decl.expansion;
1090 let certainly_before_other_or_simultaneously =
1091 other_parent_expansion.is_descendant_of(self_parent_expansion);
1092 let certainly_before_invoc_or_simultaneously =
1093 invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1094 !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1095 }
1096
1097 fn determined(&self) -> bool {
1101 match &self.kind {
1102 DeclKind::Import { source_decl, import, .. } if import.is_glob() => {
1103 import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1104 && source_decl.determined()
1105 }
1106 _ => true,
1107 }
1108 }
1109}
1110
1111struct ExternPreludeEntry<'ra> {
1112 item_decl: Option<(Decl<'ra>, Span, bool)>,
1116 flag_decl: Option<CacheCell<(PendingDecl<'ra>, bool)>>,
1118}
1119
1120impl ExternPreludeEntry<'_> {
1121 fn introduced_by_item(&self) -> bool {
1122 #[allow(non_exhaustive_omitted_patterns)] match self.item_decl {
Some((.., true)) => true,
_ => false,
}matches!(self.item_decl, Some((.., true)))
1123 }
1124
1125 fn flag() -> Self {
1126 ExternPreludeEntry {
1127 item_decl: None,
1128 flag_decl: Some(CacheCell::new((PendingDecl::Pending, false))),
1129 }
1130 }
1131
1132 fn span(&self) -> Span {
1133 match self.item_decl {
1134 Some((_, span, _)) => span,
1135 None => DUMMY_SP,
1136 }
1137 }
1138}
1139
1140struct DeriveData {
1141 resolutions: Vec<DeriveResolution>,
1142 helper_attrs: Vec<(usize, IdentKey, Span)>,
1143 has_derive_copy: bool,
1144}
1145
1146struct MacroData {
1147 ext: Arc<SyntaxExtension>,
1148 nrules: usize,
1149 macro_rules: bool,
1150}
1151
1152impl MacroData {
1153 fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1154 MacroData { ext, nrules: 0, macro_rules: false }
1155 }
1156}
1157
1158pub struct ResolverOutputs {
1159 pub global_ctxt: ResolverGlobalCtxt,
1160 pub ast_lowering: ResolverAstLowering,
1161}
1162
1163pub struct Resolver<'ra, 'tcx> {
1167 tcx: TyCtxt<'tcx>,
1168
1169 expn_that_defined: UnordMap<LocalDefId, ExpnId> = Default::default(),
1171
1172 graph_root: Module<'ra>,
1173
1174 assert_speculative: bool,
1176
1177 prelude: Option<Module<'ra>> = None,
1178 extern_prelude: FxIndexMap<IdentKey, ExternPreludeEntry<'ra>>,
1179
1180 field_names: LocalDefIdMap<Vec<Ident>> = Default::default(),
1182 field_defaults: LocalDefIdMap<Vec<Symbol>> = Default::default(),
1183
1184 field_visibility_spans: FxHashMap<DefId, Vec<Span>> = default::fx_hash_map(),
1187
1188 determined_imports: Vec<Import<'ra>> = Vec::new(),
1190
1191 indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1193
1194 pat_span_map: NodeMap<Span> = Default::default(),
1197
1198 partial_res_map: NodeMap<PartialRes> = Default::default(),
1200 import_res_map: NodeMap<PerNS<Option<Res>>> = Default::default(),
1202 import_use_map: FxHashMap<Import<'ra>, Used> = default::fx_hash_map(),
1204 label_res_map: NodeMap<NodeId> = Default::default(),
1206 lifetimes_res_map: NodeMap<LifetimeRes> = Default::default(),
1208 extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>> = Default::default(),
1210
1211 extern_crate_map: UnordMap<LocalDefId, CrateNum> = Default::default(),
1213 module_children: LocalDefIdMap<Vec<ModChild>> = Default::default(),
1214 ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>> = Default::default(),
1215 trait_map: NodeMap<Vec<TraitCandidate>> = Default::default(),
1216
1217 block_map: NodeMap<Module<'ra>> = Default::default(),
1232 empty_module: Module<'ra>,
1236 local_modules: Vec<Module<'ra>>,
1238 local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1240 extern_module_map: CacheRefCell<FxIndexMap<DefId, Module<'ra>>>,
1242
1243 glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1245 glob_error: Option<ErrorGuaranteed> = None,
1246 visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1247 used_imports: FxHashSet<NodeId> = default::fx_hash_set(),
1248 maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1249
1250 privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1252 ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1254 issue_145575_hack_applied: bool = false,
1255 use_injections: Vec<UseError<'tcx>> = Vec::new(),
1257 macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1259
1260 inaccessible_ctor_reexport: FxHashMap<Span, Span> = default::fx_hash_map(),
1264
1265 arenas: &'ra ResolverArenas<'ra>,
1266 dummy_decl: Decl<'ra>,
1267 builtin_type_decls: FxHashMap<Symbol, Decl<'ra>>,
1268 builtin_attr_decls: FxHashMap<Symbol, Decl<'ra>>,
1269 registered_tool_decls: FxHashMap<IdentKey, Decl<'ra>>,
1270 macro_names: FxHashSet<IdentKey> = default::fx_hash_set(),
1271 builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind> = default::fx_hash_map(),
1272 registered_tools: &'tcx RegisteredTools,
1273 macro_use_prelude: FxIndexMap<Symbol, Decl<'ra>>,
1274 local_macro_map: FxHashMap<LocalDefId, &'ra MacroData> = default::fx_hash_map(),
1276 extern_macro_map: CacheRefCell<FxHashMap<DefId, &'ra MacroData>>,
1278 dummy_ext_bang: Arc<SyntaxExtension>,
1279 dummy_ext_derive: Arc<SyntaxExtension>,
1280 non_macro_attr: &'ra MacroData,
1281 local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>> = default::fx_hash_map(),
1282 ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>> = default::fx_hash_map(),
1283 unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1284 unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1286 proc_macro_stubs: FxHashSet<LocalDefId> = default::fx_hash_set(),
1287 single_segment_macro_resolutions:
1289 CmRefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<Decl<'ra>>, Option<Span>)>>,
1290 multi_segment_macro_resolutions:
1291 CmRefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1292 builtin_attrs: Vec<(Ident, ParentScope<'ra>)> = Vec::new(),
1293 containers_deriving_copy: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1297 invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>> = default::fx_hash_map(),
1300 output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1303 macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>> = default::fx_hash_map(),
1305 helper_attrs: FxHashMap<LocalExpnId, Vec<(IdentKey, Span, Decl<'ra>)>> = default::fx_hash_map(),
1307 derive_data: FxHashMap<LocalExpnId, DeriveData> = default::fx_hash_map(),
1310
1311 name_already_seen: FxHashMap<Symbol, Span> = default::fx_hash_map(),
1313
1314 potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1315
1316 potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1317
1318 struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)> = Default::default(),
1322
1323 lint_buffer: LintBuffer,
1324
1325 next_node_id: NodeId = CRATE_NODE_ID,
1326
1327 node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1328
1329 disambiguator: DisambiguatorState = DisambiguatorState::new(),
1330
1331 placeholder_field_indices: FxHashMap<NodeId, usize> = default::fx_hash_map(),
1333 invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1337
1338 item_generics_num_lifetimes: FxHashMap<LocalDefId, usize> = default::fx_hash_map(),
1340 item_required_generic_args_suggestions: FxHashMap<LocalDefId, String> = default::fx_hash_map(),
1342 delegation_fn_sigs: LocalDefIdMap<DelegationFnSig> = Default::default(),
1343 delegation_infos: LocalDefIdMap<DelegationInfo> = Default::default(),
1344
1345 main_def: Option<MainDefinition> = None,
1346 trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1347 proc_macros: Vec<LocalDefId> = Vec::new(),
1350 confused_type_with_std_module: FxIndexMap<Span, Span>,
1351 lifetime_elision_allowed: FxHashSet<NodeId> = default::fx_hash_set(),
1353
1354 stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1356
1357 effective_visibilities: EffectiveVisibilities,
1358 doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1359 doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1360 all_macro_rules: UnordSet<Symbol> = Default::default(),
1361
1362 glob_delegation_invoc_ids: FxHashSet<LocalExpnId> = default::fx_hash_set(),
1364 impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>> = default::fx_hash_map(),
1367 impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>> = default::fx_hash_map(),
1370
1371 current_crate_outer_attr_insert_span: Span,
1374
1375 mods_with_parse_errors: FxHashSet<DefId> = default::fx_hash_set(),
1376
1377 all_crate_macros_already_registered: bool = false,
1380
1381 impl_trait_names: FxHashMap<NodeId, Symbol> = default::fx_hash_map(),
1385}
1386
1387#[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)]
1390pub struct ResolverArenas<'ra> {
1391 modules: TypedArena<ModuleData<'ra>>,
1392 imports: TypedArena<ImportData<'ra>>,
1393 name_resolutions: TypedArena<CmRefCell<NameResolution<'ra>>>,
1394 ast_paths: TypedArena<ast::Path>,
1395 macros: TypedArena<MacroData>,
1396 dropless: DroplessArena,
1397}
1398
1399impl<'ra> ResolverArenas<'ra> {
1400 fn new_def_decl(
1401 &'ra self,
1402 res: Res,
1403 vis: Visibility<DefId>,
1404 span: Span,
1405 expansion: LocalExpnId,
1406 parent_module: Option<Module<'ra>>,
1407 ) -> Decl<'ra> {
1408 self.alloc_decl(DeclData {
1409 kind: DeclKind::Def(res),
1410 ambiguity: CmCell::new(None),
1411 warn_ambiguity: CmCell::new(false),
1412 vis: CmCell::new(vis),
1413 span,
1414 expansion,
1415 parent_module,
1416 })
1417 }
1418
1419 fn new_pub_def_decl(&'ra self, res: Res, span: Span, expn_id: LocalExpnId) -> Decl<'ra> {
1420 self.new_def_decl(res, Visibility::Public, span, expn_id, None)
1421 }
1422
1423 fn new_module(
1424 &'ra self,
1425 parent: Option<Module<'ra>>,
1426 kind: ModuleKind,
1427 expn_id: ExpnId,
1428 span: Span,
1429 no_implicit_prelude: bool,
1430 ) -> Module<'ra> {
1431 let self_decl = match kind {
1432 ModuleKind::Def(def_kind, def_id, _) => {
1433 Some(self.new_pub_def_decl(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT))
1434 }
1435 ModuleKind::Block => None,
1436 };
1437 Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1438 parent,
1439 kind,
1440 expn_id,
1441 span,
1442 no_implicit_prelude,
1443 self_decl,
1444 ))))
1445 }
1446 fn alloc_decl(&'ra self, data: DeclData<'ra>) -> Decl<'ra> {
1447 Interned::new_unchecked(self.dropless.alloc(data))
1448 }
1449 fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1450 Interned::new_unchecked(self.imports.alloc(import))
1451 }
1452 fn alloc_name_resolution(
1453 &'ra self,
1454 orig_ident_span: Span,
1455 ) -> &'ra CmRefCell<NameResolution<'ra>> {
1456 self.name_resolutions.alloc(CmRefCell::new(NameResolution::new(orig_ident_span)))
1457 }
1458 fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1459 self.dropless.alloc(CacheCell::new(scope))
1460 }
1461 fn alloc_macro_rules_decl(&'ra self, decl: MacroRulesDecl<'ra>) -> &'ra MacroRulesDecl<'ra> {
1462 self.dropless.alloc(decl)
1463 }
1464 fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1465 self.ast_paths.alloc_from_iter(paths.iter().cloned())
1466 }
1467 fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1468 self.macros.alloc(macro_data)
1469 }
1470 fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1471 self.dropless.alloc_from_iter(spans)
1472 }
1473}
1474
1475impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1476 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1477 self
1478 }
1479}
1480
1481impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1482 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1483 self
1484 }
1485}
1486
1487impl<'tcx> Resolver<'_, 'tcx> {
1488 fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1489 self.opt_feed(node).map(|f| f.key())
1490 }
1491
1492 fn local_def_id(&self, node: NodeId) -> LocalDefId {
1493 self.feed(node).key()
1494 }
1495
1496 fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1497 self.node_id_to_def_id.get(&node).copied()
1498 }
1499
1500 fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1501 self.opt_feed(node).unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("no entry for node id: `{0:?}`",
node));
}panic!("no entry for node id: `{node:?}`"))
1502 }
1503
1504 fn local_def_kind(&self, node: NodeId) -> DefKind {
1505 self.tcx.def_kind(self.local_def_id(node))
1506 }
1507
1508 fn create_def(
1510 &mut self,
1511 parent: LocalDefId,
1512 node_id: ast::NodeId,
1513 name: Option<Symbol>,
1514 def_kind: DefKind,
1515 expn_id: ExpnId,
1516 span: Span,
1517 ) -> TyCtxtFeed<'tcx, LocalDefId> {
1518 if !!self.node_id_to_def_id.contains_key(&node_id) {
{
::core::panicking::panic_fmt(format_args!("adding a def for node-id {0:?}, name {1:?}, data {2:?} but a previous def exists: {3:?}",
node_id, name, def_kind,
self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key())));
}
};assert!(
1519 !self.node_id_to_def_id.contains_key(&node_id),
1520 "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1521 node_id,
1522 name,
1523 def_kind,
1524 self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1525 );
1526
1527 let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1529 let def_id = feed.def_id();
1530
1531 if expn_id != ExpnId::root() {
1533 self.expn_that_defined.insert(def_id, expn_id);
1534 }
1535
1536 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);
1538 let _id = self.tcx.untracked().source_span.push(span);
1539 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);
1540
1541 if node_id != ast::DUMMY_NODE_ID {
1545 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:1545",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1545u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("create_def: def_id_to_node_id[{0:?}] <-> {1:?}",
def_id, node_id) as &dyn Value))])
});
} else { ; }
};debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1546 self.node_id_to_def_id.insert(node_id, feed.downgrade());
1547 }
1548
1549 feed
1550 }
1551
1552 fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1553 if let Some(def_id) = def_id.as_local() {
1554 self.item_generics_num_lifetimes[&def_id]
1555 } else {
1556 self.tcx.generics_of(def_id).own_counts().lifetimes
1557 }
1558 }
1559
1560 fn item_required_generic_args_suggestion(&self, def_id: DefId) -> String {
1561 if let Some(def_id) = def_id.as_local() {
1562 self.item_required_generic_args_suggestions.get(&def_id).cloned().unwrap_or_default()
1563 } else {
1564 let required = self
1565 .tcx
1566 .generics_of(def_id)
1567 .own_params
1568 .iter()
1569 .filter_map(|param| match param.kind {
1570 ty::GenericParamDefKind::Lifetime => Some("'_"),
1571 ty::GenericParamDefKind::Type { has_default, .. }
1572 | ty::GenericParamDefKind::Const { has_default } => {
1573 if has_default {
1574 None
1575 } else {
1576 Some("_")
1577 }
1578 }
1579 })
1580 .collect::<Vec<_>>();
1581
1582 if required.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", ")) }
1583 }
1584 }
1585
1586 pub fn tcx(&self) -> TyCtxt<'tcx> {
1587 self.tcx
1588 }
1589
1590 fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1595 self.node_id_to_def_id
1596 .items()
1597 .filter(|(_, v)| v.key() == def_id)
1598 .map(|(k, _)| *k)
1599 .get_only()
1600 .unwrap()
1601 }
1602}
1603
1604impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1605 pub fn new(
1606 tcx: TyCtxt<'tcx>,
1607 attrs: &[ast::Attribute],
1608 crate_span: Span,
1609 current_crate_outer_attr_insert_span: Span,
1610 arenas: &'ra ResolverArenas<'ra>,
1611 ) -> Resolver<'ra, 'tcx> {
1612 let root_def_id = CRATE_DEF_ID.to_def_id();
1613 let graph_root = arenas.new_module(
1614 None,
1615 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1616 ExpnId::root(),
1617 crate_span,
1618 attr::contains_name(attrs, sym::no_implicit_prelude),
1619 );
1620 let local_modules = <[_]>::into_vec(::alloc::boxed::box_new([graph_root]))vec![graph_root];
1621 let local_module_map = FxIndexMap::from_iter([(CRATE_DEF_ID, graph_root)]);
1622 let empty_module = arenas.new_module(
1623 None,
1624 ModuleKind::Def(DefKind::Mod, root_def_id, None),
1625 ExpnId::root(),
1626 DUMMY_SP,
1627 true,
1628 );
1629
1630 let mut node_id_to_def_id = NodeMap::default();
1631 let crate_feed = tcx.create_local_crate_def_id(crate_span);
1632
1633 crate_feed.def_kind(DefKind::Mod);
1634 let crate_feed = crate_feed.downgrade();
1635 node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1636
1637 let mut invocation_parents = FxHashMap::default();
1638 invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1639
1640 let mut extern_prelude: FxIndexMap<_, _> = tcx
1641 .sess
1642 .opts
1643 .externs
1644 .iter()
1645 .filter_map(|(name, entry)| {
1646 if entry.add_prelude
1649 && let name = Symbol::intern(name)
1650 && name.can_be_raw()
1651 {
1652 let ident = IdentKey::with_root_ctxt(name);
1653 Some((ident, ExternPreludeEntry::flag()))
1654 } else {
1655 None
1656 }
1657 })
1658 .collect();
1659
1660 if !attr::contains_name(attrs, sym::no_core) {
1661 let ident = IdentKey::with_root_ctxt(sym::core);
1662 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1663 if !attr::contains_name(attrs, sym::no_std) {
1664 let ident = IdentKey::with_root_ctxt(sym::std);
1665 extern_prelude.insert(ident, ExternPreludeEntry::flag());
1666 }
1667 }
1668
1669 let registered_tools = tcx.registered_tools(());
1670 let edition = tcx.sess.edition();
1671
1672 let mut resolver = Resolver {
1673 tcx,
1674
1675 graph_root,
1678 assert_speculative: false, extern_prelude,
1680
1681 empty_module,
1682 local_modules,
1683 local_module_map,
1684 extern_module_map: Default::default(),
1685
1686 glob_map: Default::default(),
1687 maybe_unused_trait_imports: Default::default(),
1688
1689 arenas,
1690 dummy_decl: arenas.new_pub_def_decl(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1691 builtin_type_decls: PrimTy::ALL
1692 .iter()
1693 .map(|prim_ty| {
1694 let res = Res::PrimTy(*prim_ty);
1695 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1696 (prim_ty.name(), decl)
1697 })
1698 .collect(),
1699 builtin_attr_decls: BUILTIN_ATTRIBUTES
1700 .iter()
1701 .map(|builtin_attr| {
1702 let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1703 let decl = arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT);
1704 (builtin_attr.name, decl)
1705 })
1706 .collect(),
1707 registered_tool_decls: registered_tools
1708 .iter()
1709 .map(|&ident| {
1710 let res = Res::ToolMod;
1711 let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT);
1712 (IdentKey::new(ident), decl)
1713 })
1714 .collect(),
1715 registered_tools,
1716 macro_use_prelude: Default::default(),
1717 extern_macro_map: Default::default(),
1718 dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1719 dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1720 non_macro_attr: arenas
1721 .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1722 unused_macros: Default::default(),
1723 unused_macro_rules: Default::default(),
1724 single_segment_macro_resolutions: Default::default(),
1725 multi_segment_macro_resolutions: Default::default(),
1726 lint_buffer: LintBuffer::default(),
1727 node_id_to_def_id,
1728 invocation_parents,
1729 trait_impls: Default::default(),
1730 confused_type_with_std_module: Default::default(),
1731 stripped_cfg_items: Default::default(),
1732 effective_visibilities: Default::default(),
1733 doc_link_resolutions: Default::default(),
1734 doc_link_traits_in_scope: Default::default(),
1735 current_crate_outer_attr_insert_span,
1736 ..
1737 };
1738
1739 let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1740 resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1741 resolver.feed_visibility(crate_feed, Visibility::Public);
1742
1743 resolver
1744 }
1745
1746 fn new_local_module(
1747 &mut self,
1748 parent: Option<Module<'ra>>,
1749 kind: ModuleKind,
1750 expn_id: ExpnId,
1751 span: Span,
1752 no_implicit_prelude: bool,
1753 ) -> Module<'ra> {
1754 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1755 self.local_modules.push(module);
1756 if let Some(def_id) = module.opt_def_id() {
1757 self.local_module_map.insert(def_id.expect_local(), module);
1758 }
1759 module
1760 }
1761
1762 fn new_extern_module(
1763 &self,
1764 parent: Option<Module<'ra>>,
1765 kind: ModuleKind,
1766 expn_id: ExpnId,
1767 span: Span,
1768 no_implicit_prelude: bool,
1769 ) -> Module<'ra> {
1770 let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1771 self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1772 module
1773 }
1774
1775 fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1776 let mac = self.arenas.alloc_macro(macro_data);
1777 self.local_macro_map.insert(def_id, mac);
1778 mac
1779 }
1780
1781 fn next_node_id(&mut self) -> NodeId {
1782 let start = self.next_node_id;
1783 let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1784 self.next_node_id = ast::NodeId::from_u32(next);
1785 start
1786 }
1787
1788 fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1789 let start = self.next_node_id;
1790 let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1791 self.next_node_id = ast::NodeId::from_usize(end);
1792 start..self.next_node_id
1793 }
1794
1795 pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1796 &mut self.lint_buffer
1797 }
1798
1799 pub fn arenas() -> ResolverArenas<'ra> {
1800 Default::default()
1801 }
1802
1803 fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1804 let feed = feed.upgrade(self.tcx);
1805 feed.visibility(vis.to_def_id());
1806 self.visibilities_for_hashing.push((feed.def_id(), vis));
1807 }
1808
1809 pub fn into_outputs(self) -> ResolverOutputs {
1810 let proc_macros = self.proc_macros;
1811 let expn_that_defined = self.expn_that_defined;
1812 let extern_crate_map = self.extern_crate_map;
1813 let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1814 let glob_map = self.glob_map;
1815 let main_def = self.main_def;
1816 let confused_type_with_std_module = self.confused_type_with_std_module;
1817 let effective_visibilities = self.effective_visibilities;
1818
1819 let stripped_cfg_items = self
1820 .stripped_cfg_items
1821 .into_iter()
1822 .filter_map(|item| {
1823 let parent_module =
1824 self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1825 Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1826 })
1827 .collect();
1828
1829 let global_ctxt = ResolverGlobalCtxt {
1830 expn_that_defined,
1831 visibilities_for_hashing: self.visibilities_for_hashing,
1832 effective_visibilities,
1833 extern_crate_map,
1834 module_children: self.module_children,
1835 ambig_module_children: self.ambig_module_children,
1836 glob_map,
1837 maybe_unused_trait_imports,
1838 main_def,
1839 trait_impls: self.trait_impls,
1840 proc_macros,
1841 confused_type_with_std_module,
1842 doc_link_resolutions: self.doc_link_resolutions,
1843 doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1844 all_macro_rules: self.all_macro_rules,
1845 stripped_cfg_items,
1846 };
1847 let ast_lowering = ty::ResolverAstLowering {
1848 partial_res_map: self.partial_res_map,
1849 import_res_map: self.import_res_map,
1850 label_res_map: self.label_res_map,
1851 lifetimes_res_map: self.lifetimes_res_map,
1852 extra_lifetime_params_map: self.extra_lifetime_params_map,
1853 next_node_id: self.next_node_id,
1854 node_id_to_def_id: self
1855 .node_id_to_def_id
1856 .into_items()
1857 .map(|(k, f)| (k, f.key()))
1858 .collect(),
1859 trait_map: self.trait_map,
1860 lifetime_elision_allowed: self.lifetime_elision_allowed,
1861 lint_buffer: Steal::new(self.lint_buffer),
1862 delegation_fn_sigs: self.delegation_fn_sigs,
1863 delegation_infos: self.delegation_infos,
1864 };
1865 ResolverOutputs { global_ctxt, ast_lowering }
1866 }
1867
1868 fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1869 CStore::from_tcx(self.tcx)
1870 }
1871
1872 fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1873 CStore::from_tcx_mut(self.tcx)
1874 }
1875
1876 fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1877 match macro_kind {
1878 MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1879 MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1880 MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1881 }
1882 }
1883
1884 fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1889 CmResolver::new(self, !self.assert_speculative)
1890 }
1891
1892 fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1894 f(self, TypeNS);
1895 f(self, ValueNS);
1896 f(self, MacroNS);
1897 }
1898
1899 fn per_ns_cm<'r, F: FnMut(CmResolver<'_, 'ra, 'tcx>, Namespace)>(
1900 mut self: CmResolver<'r, 'ra, 'tcx>,
1901 mut f: F,
1902 ) {
1903 f(self.reborrow(), TypeNS);
1904 f(self.reborrow(), ValueNS);
1905 f(self, MacroNS);
1906 }
1907
1908 fn is_builtin_macro(&self, res: Res) -> bool {
1909 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1910 }
1911
1912 fn is_specific_builtin_macro(&self, res: Res, symbol: Symbol) -> bool {
1913 self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name == Some(symbol))
1914 }
1915
1916 fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1917 loop {
1918 match ctxt.outer_expn_data().macro_def_id {
1919 Some(def_id) => return def_id,
1920 None => ctxt.remove_mark(),
1921 };
1922 }
1923 }
1924
1925 pub fn resolve_crate(&mut self, krate: &Crate) {
1927 self.tcx.sess.time("resolve_crate", || {
1928 self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1929 let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1930 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1931 });
1932 self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1933 self.tcx
1934 .sess
1935 .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1936 self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1937 self.tcx.sess.time("resolve_main", || self.resolve_main());
1938 self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1939 self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1940 self.tcx
1941 .sess
1942 .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1943 });
1944
1945 self.tcx.untracked().cstore.freeze();
1947 }
1948
1949 fn traits_in_scope(
1950 &mut self,
1951 current_trait: Option<Module<'ra>>,
1952 parent_scope: &ParentScope<'ra>,
1953 sp: Span,
1954 assoc_item: Option<(Symbol, Namespace)>,
1955 ) -> Vec<TraitCandidate> {
1956 let mut found_traits = Vec::new();
1957
1958 if let Some(module) = current_trait {
1959 if self.trait_may_have_item(Some(module), assoc_item) {
1960 let def_id = module.def_id();
1961 found_traits.push(TraitCandidate {
1962 def_id,
1963 import_ids: ::smallvec::SmallVec::new()smallvec![],
1964 lint_ambiguous: false,
1965 });
1966 }
1967 }
1968
1969 let scope_set = ScopeSet::All(TypeNS);
1970 let ctxt = Macros20NormalizedSyntaxContext::new(sp.ctxt());
1971 self.cm().visit_scopes(scope_set, parent_scope, ctxt, sp, None, |mut this, scope, _, _| {
1972 match scope {
1973 Scope::ModuleNonGlobs(module, _) => {
1974 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1975 }
1976 Scope::ModuleGlobs(..) => {
1977 }
1979 Scope::StdLibPrelude => {
1980 if let Some(module) = this.prelude {
1981 this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1982 }
1983 }
1984 Scope::ExternPreludeItems
1985 | Scope::ExternPreludeFlags
1986 | Scope::ToolPrelude
1987 | Scope::BuiltinTypes => {}
1988 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1989 }
1990 ControlFlow::<()>::Continue(())
1991 });
1992
1993 found_traits
1994 }
1995
1996 fn traits_in_module(
1997 &mut self,
1998 module: Module<'ra>,
1999 assoc_item: Option<(Symbol, Namespace)>,
2000 found_traits: &mut Vec<TraitCandidate>,
2001 ) {
2002 module.ensure_traits(self);
2003 let traits = module.traits.borrow();
2004 for &(trait_name, trait_binding, trait_module, lint_ambiguous) in
2005 traits.as_ref().unwrap().iter()
2006 {
2007 if self.trait_may_have_item(trait_module, assoc_item) {
2008 let def_id = trait_binding.res().def_id();
2009 let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name);
2010 found_traits.push(TraitCandidate { def_id, import_ids, lint_ambiguous });
2011 }
2012 }
2013 }
2014
2015 fn trait_may_have_item(
2021 &self,
2022 trait_module: Option<Module<'ra>>,
2023 assoc_item: Option<(Symbol, Namespace)>,
2024 ) -> bool {
2025 match (trait_module, assoc_item) {
2026 (Some(trait_module), Some((name, ns))) => self
2027 .resolutions(trait_module)
2028 .borrow()
2029 .iter()
2030 .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
2031 _ => true,
2032 }
2033 }
2034
2035 fn find_transitive_imports(
2036 &mut self,
2037 mut kind: &DeclKind<'_>,
2038 trait_name: Symbol,
2039 ) -> SmallVec<[LocalDefId; 1]> {
2040 let mut import_ids = ::smallvec::SmallVec::new()smallvec![];
2041 while let DeclKind::Import { import, source_decl, .. } = kind {
2042 if let Some(node_id) = import.id() {
2043 let def_id = self.local_def_id(node_id);
2044 self.maybe_unused_trait_imports.insert(def_id);
2045 import_ids.push(def_id);
2046 }
2047 self.add_to_glob_map(*import, trait_name);
2048 kind = &source_decl.kind;
2049 }
2050 import_ids
2051 }
2052
2053 fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
2054 if module.populate_on_access.get() {
2055 module.populate_on_access.set(false);
2056 self.build_reduced_graph_external(module);
2057 }
2058 &module.0.0.lazy_resolutions
2059 }
2060
2061 fn resolution(
2062 &self,
2063 module: Module<'ra>,
2064 key: BindingKey,
2065 ) -> Option<Ref<'ra, NameResolution<'ra>>> {
2066 self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
2067 }
2068
2069 fn resolution_or_default(
2070 &self,
2071 module: Module<'ra>,
2072 key: BindingKey,
2073 orig_ident_span: Span,
2074 ) -> &'ra CmRefCell<NameResolution<'ra>> {
2075 self.resolutions(module)
2076 .borrow_mut_unchecked()
2077 .entry(key)
2078 .or_insert_with(|| self.arenas.alloc_name_resolution(orig_ident_span))
2079 }
2080
2081 fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2083 for ambiguity_error in &self.ambiguity_errors {
2084 if ambiguity_error.kind == ambi.kind
2086 && ambiguity_error.ident == ambi.ident
2087 && ambiguity_error.ident.span == ambi.ident.span
2088 && ambiguity_error.b1.span == ambi.b1.span
2089 && ambiguity_error.b2.span == ambi.b2.span
2090 {
2091 return true;
2092 }
2093 }
2094 false
2095 }
2096
2097 fn record_use(&mut self, ident: Ident, used_decl: Decl<'ra>, used: Used) {
2098 self.record_use_inner(ident, used_decl, used, used_decl.warn_ambiguity.get());
2099 }
2100
2101 fn record_use_inner(
2102 &mut self,
2103 ident: Ident,
2104 used_decl: Decl<'ra>,
2105 used: Used,
2106 warn_ambiguity: bool,
2107 ) {
2108 if let Some(b2) = used_decl.ambiguity.get() {
2109 let ambiguity_error = AmbiguityError {
2110 kind: AmbiguityKind::GlobVsGlob,
2111 ambig_vis: None,
2112 ident,
2113 b1: used_decl,
2114 b2,
2115 scope1: Scope::ModuleGlobs(used_decl.parent_module.unwrap(), None),
2116 scope2: Scope::ModuleGlobs(b2.parent_module.unwrap(), None),
2117 warning: if warn_ambiguity { Some(AmbiguityWarning::GlobImport) } else { None },
2118 };
2119 if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2120 self.ambiguity_errors.push(ambiguity_error);
2122 }
2123 }
2124 if let DeclKind::Import { import, source_decl } = used_decl.kind {
2125 if let ImportKind::MacroUse { warn_private: true } = import.kind {
2126 let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2129 let empty_module = self.empty_module;
2130 let arenas = self.arenas;
2131 self.cm()
2132 .maybe_resolve_ident_in_module(
2133 ModuleOrUniformRoot::Module(prelude),
2134 ident,
2135 MacroNS,
2136 &ParentScope::module(empty_module, arenas),
2137 None,
2138 )
2139 .is_ok()
2140 });
2141 if !found_in_stdlib_prelude {
2142 self.lint_buffer().buffer_lint(
2143 PRIVATE_MACRO_USE,
2144 import.root_id,
2145 ident.span,
2146 errors::MacroIsPrivate { ident },
2147 );
2148 }
2149 }
2150 if used == Used::Scope
2153 && let Some(entry) = self.extern_prelude.get(&IdentKey::new(ident))
2154 && let Some((item_decl, _, false)) = entry.item_decl
2155 && item_decl == used_decl
2156 {
2157 return;
2158 }
2159 let old_used = self.import_use_map.entry(import).or_insert(used);
2160 if *old_used < used {
2161 *old_used = used;
2162 }
2163 if let Some(id) = import.id() {
2164 self.used_imports.insert(id);
2165 }
2166 self.add_to_glob_map(import, ident.name);
2167 self.record_use_inner(
2168 ident,
2169 source_decl,
2170 Used::Other,
2171 warn_ambiguity || source_decl.warn_ambiguity.get(),
2172 );
2173 }
2174 }
2175
2176 #[inline]
2177 fn add_to_glob_map(&mut self, import: Import<'_>, name: Symbol) {
2178 if let ImportKind::Glob { id, .. } = import.kind {
2179 let def_id = self.local_def_id(id);
2180 self.glob_map.entry(def_id).or_default().insert(name);
2181 }
2182 }
2183
2184 fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2185 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2185",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2185u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?})",
ident) as &dyn Value))])
});
} else { ; }
};debug!("resolve_crate_root({:?})", ident);
2186 let mut ctxt = ident.span.ctxt();
2187 let mark = if ident.name == kw::DollarCrate {
2188 ctxt = ctxt.normalize_to_macro_rules();
2195 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2195",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2195u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: marks={0:?}",
ctxt.marks().into_iter().map(|(i, t)|
(i.expn_data(), t)).collect::<Vec<_>>()) as &dyn Value))])
});
} else { ; }
};debug!(
2196 "resolve_crate_root: marks={:?}",
2197 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2198 );
2199 let mut iter = ctxt.marks().into_iter().rev().peekable();
2200 let mut result = None;
2201 while let Some(&(mark, transparency)) = iter.peek() {
2203 if transparency == Transparency::Opaque {
2204 result = Some(mark);
2205 iter.next();
2206 } else {
2207 break;
2208 }
2209 }
2210 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2210",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2210u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as &dyn Value))])
});
} else { ; }
};debug!(
2211 "resolve_crate_root: found opaque mark {:?} {:?}",
2212 result,
2213 result.map(|r| r.expn_data())
2214 );
2215 for (mark, transparency) in iter {
2217 if transparency == Transparency::SemiOpaque {
2218 result = Some(mark);
2219 } else {
2220 break;
2221 }
2222 }
2223 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2223",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2223u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: found semi-opaque mark {0:?} {1:?}",
result, result.map(|r| r.expn_data())) as &dyn Value))])
});
} else { ; }
};debug!(
2224 "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2225 result,
2226 result.map(|r| r.expn_data())
2227 );
2228 result
2229 } else {
2230 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2230",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2230u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root: not DollarCrate")
as &dyn Value))])
});
} else { ; }
};debug!("resolve_crate_root: not DollarCrate");
2231 ctxt = ctxt.normalize_to_macros_2_0();
2232 ctxt.adjust(ExpnId::root())
2233 };
2234 let module = match mark {
2235 Some(def) => self.expn_def_scope(def),
2236 None => {
2237 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2237",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2237u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): found no mark (ident.span = {1:?})",
ident, ident.span) as &dyn Value))])
});
} else { ; }
};debug!(
2238 "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2239 ident, ident.span
2240 );
2241 return self.graph_root;
2242 }
2243 };
2244 let module = self.expect_module(
2245 module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2246 );
2247 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2247",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2247u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("resolve_crate_root({0:?}): got module {1:?} ({2:?}) (ident.span = {3:?})",
ident, module, module.kind.name(), ident.span) as
&dyn Value))])
});
} else { ; }
};debug!(
2248 "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2249 ident,
2250 module,
2251 module.kind.name(),
2252 ident.span
2253 );
2254 module
2255 }
2256
2257 fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2258 let mut module = self.expect_module(module.nearest_parent_mod());
2259 while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2260 let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2261 module = self.expect_module(parent.nearest_parent_mod());
2262 }
2263 module
2264 }
2265
2266 fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2267 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2267",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2267u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(recording res) recording {0:?} for {1}",
resolution, node_id) as &dyn Value))])
});
} else { ; }
};debug!("(recording res) recording {:?} for {}", resolution, node_id);
2268 if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2269 {
::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)");
2270 }
2271 }
2272
2273 fn record_pat_span(&mut self, node: NodeId, span: Span) {
2274 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/lib.rs:2274",
"rustc_resolve", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2274u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(recording pat) recording {0:?} for {1:?}",
node, span) as &dyn Value))])
});
} else { ; }
};debug!("(recording pat) recording {:?} for {:?}", node, span);
2275 self.pat_span_map.insert(node, span);
2276 }
2277
2278 fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2279 vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2280 }
2281
2282 fn disambiguate_macro_rules_vs_modularized(
2283 &self,
2284 macro_rules: Decl<'ra>,
2285 modularized: Decl<'ra>,
2286 ) -> bool {
2287 let macro_rules = macro_rules.parent_module.unwrap();
2295 let modularized = modularized.parent_module.unwrap();
2296 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2297 && modularized.is_ancestor_of(macro_rules)
2298 }
2299
2300 fn extern_prelude_get_item<'r>(
2301 mut self: CmResolver<'r, 'ra, 'tcx>,
2302 ident: IdentKey,
2303 orig_ident_span: Span,
2304 finalize: bool,
2305 ) -> Option<Decl<'ra>> {
2306 let entry = self.extern_prelude.get(&ident);
2307 entry.and_then(|entry| entry.item_decl).map(|(decl, ..)| {
2308 if finalize {
2309 self.get_mut().record_use(ident.orig(orig_ident_span), decl, Used::Scope);
2310 }
2311 decl
2312 })
2313 }
2314
2315 fn extern_prelude_get_flag(
2316 &self,
2317 ident: IdentKey,
2318 orig_ident_span: Span,
2319 finalize: bool,
2320 ) -> Option<Decl<'ra>> {
2321 let entry = self.extern_prelude.get(&ident);
2322 entry.and_then(|entry| entry.flag_decl.as_ref()).and_then(|flag_decl| {
2323 let (pending_decl, finalized) = flag_decl.get();
2324 let decl = match pending_decl {
2325 PendingDecl::Ready(decl) => {
2326 if finalize && !finalized {
2327 self.cstore_mut().process_path_extern(
2328 self.tcx,
2329 ident.name,
2330 orig_ident_span,
2331 );
2332 }
2333 decl
2334 }
2335 PendingDecl::Pending => {
2336 if true {
if !!finalized {
::core::panicking::panic("assertion failed: !finalized")
};
};debug_assert!(!finalized);
2337 let crate_id = if finalize {
2338 self.cstore_mut().process_path_extern(self.tcx, ident.name, orig_ident_span)
2339 } else {
2340 self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2341 };
2342 crate_id.map(|crate_id| {
2343 let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2344 self.arenas.new_pub_def_decl(res, DUMMY_SP, LocalExpnId::ROOT)
2345 })
2346 }
2347 };
2348 flag_decl.set((PendingDecl::Ready(decl), finalize || finalized));
2349 decl.or_else(|| finalize.then_some(self.dummy_decl))
2350 })
2351 }
2352
2353 fn resolve_rustdoc_path(
2358 &mut self,
2359 path_str: &str,
2360 ns: Namespace,
2361 parent_scope: ParentScope<'ra>,
2362 ) -> Option<Res> {
2363 let segments: Result<Vec<_>, ()> = path_str
2364 .split("::")
2365 .enumerate()
2366 .map(|(i, s)| {
2367 let sym = if s.is_empty() {
2368 if i == 0 {
2369 kw::PathRoot
2371 } else {
2372 return Err(()); }
2374 } else {
2375 Symbol::intern(s)
2376 };
2377 Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2378 })
2379 .collect();
2380 let Ok(segments) = segments else { return None };
2381
2382 match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2383 PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2384 PathResult::NonModule(path_res) => {
2385 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(..), _)))
2386 }
2387 PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2388 None
2389 }
2390 PathResult::Module(..) | PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2391 }
2392 }
2393
2394 fn def_span(&self, def_id: DefId) -> Span {
2396 match def_id.as_local() {
2397 Some(def_id) => self.tcx.source_span(def_id),
2398 None => self.cstore().def_span_untracked(self.tcx(), def_id),
2400 }
2401 }
2402
2403 fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2404 match def_id.as_local() {
2405 Some(def_id) => self.field_names.get(&def_id).cloned(),
2406 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2407 self.tcx.def_kind(def_id),
2408 DefKind::Struct | DefKind::Union | DefKind::Variant
2409 ) =>
2410 {
2411 Some(
2412 self.tcx
2413 .associated_item_def_ids(def_id)
2414 .iter()
2415 .map(|&def_id| {
2416 Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2417 })
2418 .collect(),
2419 )
2420 }
2421 _ => None,
2422 }
2423 }
2424
2425 fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2426 match def_id.as_local() {
2427 Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2428 None if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(def_id) {
DefKind::Struct | DefKind::Union | DefKind::Variant => true,
_ => false,
}matches!(
2429 self.tcx.def_kind(def_id),
2430 DefKind::Struct | DefKind::Union | DefKind::Variant
2431 ) =>
2432 {
2433 Some(
2434 self.tcx
2435 .associated_item_def_ids(def_id)
2436 .iter()
2437 .filter_map(|&def_id| {
2438 self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2439 })
2440 .collect(),
2441 )
2442 }
2443 _ => None,
2444 }
2445 }
2446
2447 fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2451 let ExprKind::Path(None, path) = &expr.kind else {
2452 return None;
2453 };
2454 if path.segments.last().unwrap().args.is_some() {
2457 return None;
2458 }
2459
2460 let def_id = self.partial_res_map.get(&expr.id)?.full_res()?.opt_def_id()?;
2461
2462 if def_id.is_local() {
2466 return None;
2467 }
2468
2469 {
'done:
{
for i in self.tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcLegacyConstGenerics {
fn_indexes, .. }) => {
break 'done Some(fn_indexes);
}
_ => {}
}
}
None
}
}find_attr!(
2470 self.tcx.get_all_attrs(def_id),
2472 AttributeKind::RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes
2473 )
2474 .map(|fn_indexes| fn_indexes.iter().map(|(num, _)| *num).collect())
2475 }
2476
2477 fn resolve_main(&mut self) {
2478 let any_exe = self.tcx.crate_types().contains(&CrateType::Executable);
2479 if !any_exe {
2481 return;
2482 }
2483
2484 let module = self.graph_root;
2485 let ident = Ident::with_dummy_span(sym::main);
2486 let parent_scope = &ParentScope::module(module, self.arenas);
2487
2488 let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2489 ModuleOrUniformRoot::Module(module),
2490 ident,
2491 ValueNS,
2492 parent_scope,
2493 None,
2494 ) else {
2495 return;
2496 };
2497
2498 let res = name_binding.res();
2499 let is_import = name_binding.is_import();
2500 let span = name_binding.span;
2501 if let Res::Def(DefKind::Fn, _) = res {
2502 self.record_use(ident, name_binding, Used::Other);
2503 }
2504 self.main_def = Some(MainDefinition { res, is_import, span });
2505 }
2506}
2507
2508fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2509 let mut result = String::new();
2510 for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2511 if i > 0 {
2512 result.push_str("::");
2513 }
2514 if Ident::with_dummy_span(name).is_raw_guess() {
2515 result.push_str("r#");
2516 }
2517 result.push_str(name.as_str());
2518 }
2519 result
2520}
2521
2522fn path_names_to_string(path: &Path) -> String {
2523 names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2524}
2525
2526fn module_to_string(mut module: Module<'_>) -> Option<String> {
2528 let mut names = Vec::new();
2529 loop {
2530 if let ModuleKind::Def(.., name) = module.kind {
2531 if let Some(parent) = module.parent {
2532 names.push(name.unwrap());
2534 module = parent
2535 } else {
2536 break;
2537 }
2538 } else {
2539 names.push(sym::opaque_module_name_placeholder);
2540 let Some(parent) = module.parent else {
2541 return None;
2542 };
2543 module = parent;
2544 }
2545 }
2546 if names.is_empty() {
2547 return None;
2548 }
2549 Some(names_to_string(names.iter().rev().copied()))
2550}
2551
2552#[derive(#[automatically_derived]
impl ::core::marker::Copy for Stage { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Stage {
#[inline]
fn clone(&self) -> Stage { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Stage {
#[inline]
fn eq(&self, other: &Stage) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for Stage {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Stage::Early => "Early", Stage::Late => "Late", })
}
}Debug)]
2553enum Stage {
2554 Early,
2558 Late,
2561}
2562
2563#[derive(#[automatically_derived]
impl ::core::marker::Copy for Finalize { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Finalize {
#[inline]
fn clone(&self) -> Finalize {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Used>;
let _: ::core::clone::AssertParamIsClone<Stage>;
let _: ::core::clone::AssertParamIsClone<Option<Visibility>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Finalize {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["node_id", "path_span", "root_span", "report_private", "used",
"stage", "import_vis"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.node_id, &self.path_span, &self.root_span,
&self.report_private, &self.used, &self.stage,
&&self.import_vis];
::core::fmt::Formatter::debug_struct_fields_finish(f, "Finalize",
names, values)
}
}Debug)]
2565struct Finalize {
2566 node_id: NodeId,
2568 path_span: Span,
2571 root_span: Span,
2574 report_private: bool = true,
2577 used: Used = Used::Other,
2579 stage: Stage = Stage::Early,
2581 import_vis: Option<Visibility> = None,
2583}
2584
2585impl Finalize {
2586 fn new(node_id: NodeId, path_span: Span) -> Finalize {
2587 Finalize::with_root_span(node_id, path_span, path_span)
2588 }
2589
2590 fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2591 Finalize { node_id, path_span, root_span, .. }
2592 }
2593}
2594
2595pub fn provide(providers: &mut Providers) {
2596 providers.registered_tools = macros::registered_tools;
2597}
2598
2599type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2605
2606use std::cell::{Cell as CacheCell, RefCell as CacheRefCell};
2610
2611mod ref_mut {
2614 use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2615 use std::fmt;
2616 use std::ops::Deref;
2617
2618 use crate::Resolver;
2619
2620 pub(crate) struct RefOrMut<'a, T> {
2622 p: &'a mut T,
2623 mutable: bool,
2624 }
2625
2626 impl<'a, T> Deref for RefOrMut<'a, T> {
2627 type Target = T;
2628
2629 fn deref(&self) -> &Self::Target {
2630 self.p
2631 }
2632 }
2633
2634 impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2635 fn as_ref(&self) -> &T {
2636 self.p
2637 }
2638 }
2639
2640 impl<'a, T> RefOrMut<'a, T> {
2641 pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2642 RefOrMut { p, mutable }
2643 }
2644
2645 pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2647 RefOrMut { p: self.p, mutable: self.mutable }
2648 }
2649
2650 #[track_caller]
2655 pub(crate) fn get_mut(&mut self) -> &mut T {
2656 match self.mutable {
2657 false => {
::core::panicking::panic_fmt(format_args!("Can\'t mutably borrow speculative resolver"));
}panic!("Can't mutably borrow speculative resolver"),
2658 true => self.p,
2659 }
2660 }
2661
2662 pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2665 self.p
2666 }
2667 }
2668
2669 #[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)]
2671 pub(crate) struct CmCell<T>(Cell<T>);
2672
2673 impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2675 f.debug_tuple("CmCell").field(&self.get()).finish()
2676 }
2677 }
2678
2679 impl<T: Copy> Clone for CmCell<T> {
2680 fn clone(&self) -> CmCell<T> {
2681 CmCell::new(self.get())
2682 }
2683 }
2684
2685 impl<T: Copy> CmCell<T> {
2686 pub(crate) const fn get(&self) -> T {
2687 self.0.get()
2688 }
2689
2690 pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2691 where
2692 T: Copy,
2693 {
2694 let old = self.get();
2695 self.set_unchecked(f(old));
2696 }
2697 }
2698
2699 impl<T> CmCell<T> {
2700 pub(crate) const fn new(value: T) -> CmCell<T> {
2701 CmCell(Cell::new(value))
2702 }
2703
2704 pub(crate) fn set_unchecked(&self, val: T) {
2705 self.0.set(val);
2706 }
2707
2708 pub(crate) fn into_inner(self) -> T {
2709 self.0.into_inner()
2710 }
2711 }
2712
2713 #[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)]
2715 pub(crate) struct CmRefCell<T>(RefCell<T>);
2716
2717 impl<T> CmRefCell<T> {
2718 pub(crate) const fn new(value: T) -> CmRefCell<T> {
2719 CmRefCell(RefCell::new(value))
2720 }
2721
2722 #[track_caller]
2723 pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2724 self.0.borrow_mut()
2725 }
2726
2727 #[track_caller]
2728 pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2729 if r.assert_speculative {
2730 {
::core::panicking::panic_fmt(format_args!("Not allowed to mutably borrow a CmRefCell during speculative resolution"));
};panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2731 }
2732 self.borrow_mut_unchecked()
2733 }
2734
2735 #[track_caller]
2736 pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2737 self.0.try_borrow_mut()
2738 }
2739
2740 #[track_caller]
2741 pub(crate) fn borrow(&self) -> Ref<'_, T> {
2742 self.0.borrow()
2743 }
2744 }
2745
2746 impl<T: Default> CmRefCell<T> {
2747 pub(crate) fn take<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> T {
2748 if r.assert_speculative {
2749 {
::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");
2750 }
2751 self.0.take()
2752 }
2753 }
2754}
2755
2756mod hygiene {
2757 use rustc_span::{ExpnId, SyntaxContext};
2758
2759 #[derive(#[automatically_derived]
impl ::core::clone::Clone for Macros20NormalizedSyntaxContext {
#[inline]
fn clone(&self) -> Macros20NormalizedSyntaxContext {
let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Macros20NormalizedSyntaxContext { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for Macros20NormalizedSyntaxContext {
#[inline]
fn eq(&self, other: &Macros20NormalizedSyntaxContext) -> bool {
self.0 == other.0
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Macros20NormalizedSyntaxContext {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_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)]
2762 pub(crate) struct Macros20NormalizedSyntaxContext(SyntaxContext);
2763
2764 impl Macros20NormalizedSyntaxContext {
2765 #[inline]
2766 pub(crate) fn new(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2767 Macros20NormalizedSyntaxContext(ctxt.normalize_to_macros_2_0())
2768 }
2769
2770 #[inline]
2771 pub(crate) fn new_adjusted(
2772 mut ctxt: SyntaxContext,
2773 expn_id: ExpnId,
2774 ) -> (Macros20NormalizedSyntaxContext, Option<ExpnId>) {
2775 let def = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
2776 (Macros20NormalizedSyntaxContext(ctxt), def)
2777 }
2778
2779 #[inline]
2780 pub(crate) fn new_unchecked(ctxt: SyntaxContext) -> Macros20NormalizedSyntaxContext {
2781 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());
2782 Macros20NormalizedSyntaxContext(ctxt)
2783 }
2784
2785 #[inline]
2787 pub(crate) fn update_unchecked<R>(&mut self, f: impl FnOnce(&mut SyntaxContext) -> R) -> R {
2788 let ret = f(&mut self.0);
2789 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());
2790 ret
2791 }
2792 }
2793
2794 impl std::ops::Deref for Macros20NormalizedSyntaxContext {
2795 type Target = SyntaxContext;
2796 fn deref(&self) -> &Self::Target {
2797 &self.0
2798 }
2799 }
2800}