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