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