1use std::borrow::Cow;
10use std::collections::hash_map::Entry;
11use std::debug_assert_matches;
12use std::mem::{replace, swap, take};
13use std::ops::{ControlFlow, Range};
14
15use rustc_ast::visit::{
16 AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
17};
18use rustc_ast::*;
19use rustc_data_structures::either::Either;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
21use rustc_data_structures::unord::{UnordMap, UnordSet};
22use rustc_errors::codes::*;
23use rustc_errors::{
24 Applicability, Diag, DiagArgValue, Diagnostic, ErrorGuaranteed, IntoDiagArg, MultiSpan,
25 StashKey, Suggestions, elided_lifetime_in_path_suggestion, pluralize,
26};
27use rustc_hir::def::Namespace::{self, *};
28use rustc_hir::def::{CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS};
29use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId};
30use rustc_hir::{MissingLifetimeKind, PrimTy};
31use rustc_middle::middle::resolve_bound_vars::Set1;
32use rustc_middle::ty::{AssocTag, DelegationInfo, Visibility};
33use rustc_middle::{bug, span_bug};
34use rustc_session::config::{CrateType, ResolveDocLinks};
35use rustc_session::diagnostics::feature_err;
36use rustc_session::lint;
37use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Spanned, Symbol, kw, respan, sym};
38use smallvec::{SmallVec, smallvec};
39use thin_vec::ThinVec;
40use tracing::{debug, instrument, trace};
41
42use crate::{
43 BindingError, BindingKey, Decl, DelegationFnSig, Finalize, IdentKey, LateDecl, LocalModule,
44 Module, ModuleOrUniformRoot, ParentScope, PathResult, Res, ResolutionError, Resolver, Segment,
45 Stage, TyCtxt, UseError, Used, path_names_to_string, rustdoc, with_owner,
46};
47
48mod diagnostics;
49
50use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime};
51
52#[derive(#[automatically_derived]
impl ::core::marker::Copy for BindingInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BindingInfo {
#[inline]
fn clone(&self) -> BindingInfo {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<BindingMode>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BindingInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "BindingInfo",
"span", &self.span, "annotation", &&self.annotation)
}
}Debug)]
53struct BindingInfo {
54 span: Span,
55 annotation: BindingMode,
56}
57
58#[derive(#[automatically_derived]
impl ::core::marker::Copy for PatternSource { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PatternSource {
#[inline]
fn clone(&self) -> PatternSource { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for PatternSource {
#[inline]
fn eq(&self, other: &PatternSource) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PatternSource {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for PatternSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
PatternSource::Match => "Match",
PatternSource::Let => "Let",
PatternSource::For => "For",
PatternSource::FnParam => "FnParam",
})
}
}Debug)]
59pub(crate) enum PatternSource {
60 Match,
61 Let,
62 For,
63 FnParam,
64}
65
66#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsRepeatExpr { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsRepeatExpr {
#[inline]
fn clone(&self) -> IsRepeatExpr { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for IsRepeatExpr {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
IsRepeatExpr::No => "No",
IsRepeatExpr::Yes => "Yes",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for IsRepeatExpr {
#[inline]
fn eq(&self, other: &IsRepeatExpr) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IsRepeatExpr {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
67enum IsRepeatExpr {
68 No,
69 Yes,
70}
71
72struct IsNeverPattern;
73
74#[derive(#[automatically_derived]
impl ::core::marker::Copy for AnonConstKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AnonConstKind {
#[inline]
fn clone(&self) -> AnonConstKind {
let _: ::core::clone::AssertParamIsClone<IsRepeatExpr>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AnonConstKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
AnonConstKind::EnumDiscriminant =>
::core::fmt::Formatter::write_str(f, "EnumDiscriminant"),
AnonConstKind::FieldDefaultValue =>
::core::fmt::Formatter::write_str(f, "FieldDefaultValue"),
AnonConstKind::InlineConst =>
::core::fmt::Formatter::write_str(f, "InlineConst"),
AnonConstKind::ConstArg(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ConstArg", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AnonConstKind {
#[inline]
fn eq(&self, other: &AnonConstKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(AnonConstKind::ConstArg(__self_0),
AnonConstKind::ConstArg(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AnonConstKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<IsRepeatExpr>;
}
}Eq)]
77enum AnonConstKind {
78 EnumDiscriminant,
79 FieldDefaultValue,
80 InlineConst,
81 ConstArg(IsRepeatExpr),
82}
83
84impl PatternSource {
85 fn descr(self) -> &'static str {
86 match self {
87 PatternSource::Match => "match binding",
88 PatternSource::Let => "let binding",
89 PatternSource::For => "for binding",
90 PatternSource::FnParam => "function parameter",
91 }
92 }
93}
94
95impl IntoDiagArg for PatternSource {
96 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
97 DiagArgValue::Str(Cow::Borrowed(self.descr()))
98 }
99}
100
101#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for PatBoundCtx {
#[inline]
fn eq(&self, other: &PatBoundCtx) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
105enum PatBoundCtx {
106 Product,
108 Or,
110}
111
112type PatternBindings = SmallVec<[(PatBoundCtx, FxIndexMap<Ident, Res>); 1]>;
124
125#[derive(#[automatically_derived]
impl ::core::marker::Copy for HasGenericParams { }Copy, #[automatically_derived]
impl ::core::clone::Clone for HasGenericParams {
#[inline]
fn clone(&self) -> HasGenericParams {
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for HasGenericParams {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
HasGenericParams::Yes(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Yes",
&__self_0),
HasGenericParams::No =>
::core::fmt::Formatter::write_str(f, "No"),
}
}
}Debug)]
127pub(crate) enum HasGenericParams {
128 Yes(Span),
129 No,
130}
131
132#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantHasGenerics { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantHasGenerics {
#[inline]
fn clone(&self) -> ConstantHasGenerics {
let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantHasGenerics {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ConstantHasGenerics::Yes =>
::core::fmt::Formatter::write_str(f, "Yes"),
ConstantHasGenerics::No(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "No",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantHasGenerics {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<NoConstantGenericsReason>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantHasGenerics {
#[inline]
fn eq(&self, other: &ConstantHasGenerics) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ConstantHasGenerics::No(__self_0),
ConstantHasGenerics::No(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
134pub(crate) enum ConstantHasGenerics {
135 Yes,
136 No(NoConstantGenericsReason),
137}
138
139impl ConstantHasGenerics {
140 fn force_yes_if(self, b: bool) -> Self {
141 if b { Self::Yes } else { self }
142 }
143}
144
145#[derive(#[automatically_derived]
impl ::core::marker::Copy for NoConstantGenericsReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NoConstantGenericsReason {
#[inline]
fn clone(&self) -> NoConstantGenericsReason { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for NoConstantGenericsReason {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
NoConstantGenericsReason::NonTrivialConstArg =>
"NonTrivialConstArg",
NoConstantGenericsReason::IsEnumDiscriminant =>
"IsEnumDiscriminant",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for NoConstantGenericsReason {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for NoConstantGenericsReason {
#[inline]
fn eq(&self, other: &NoConstantGenericsReason) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
147pub(crate) enum NoConstantGenericsReason {
148 NonTrivialConstArg,
155 IsEnumDiscriminant,
164}
165
166#[derive(#[automatically_derived]
impl ::core::marker::Copy for ConstantItemKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ConstantItemKind {
#[inline]
fn clone(&self) -> ConstantItemKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ConstantItemKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ConstantItemKind::Const => "Const",
ConstantItemKind::Static => "Static",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for ConstantItemKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for ConstantItemKind {
#[inline]
fn eq(&self, other: &ConstantItemKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
167pub(crate) enum ConstantItemKind {
168 Const,
169 Static,
170}
171
172impl ConstantItemKind {
173 pub(crate) fn as_str(&self) -> &'static str {
174 match self {
175 Self::Const => "const",
176 Self::Static => "static",
177 }
178 }
179}
180
181#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RecordPartialRes {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RecordPartialRes::Yes => "Yes",
RecordPartialRes::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RecordPartialRes { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RecordPartialRes {
#[inline]
fn clone(&self) -> RecordPartialRes { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RecordPartialRes {
#[inline]
fn eq(&self, other: &RecordPartialRes) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for RecordPartialRes {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
182enum RecordPartialRes {
183 Yes,
184 No,
185}
186
187#[derive(#[automatically_derived]
impl<'ra> ::core::marker::Copy for RibKind<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::clone::Clone for RibKind<'ra> {
#[inline]
fn clone(&self) -> RibKind<'ra> {
let _: ::core::clone::AssertParamIsClone<Option<LocalModule<'ra>>>;
let _: ::core::clone::AssertParamIsClone<HasGenericParams>;
let _: ::core::clone::AssertParamIsClone<DefKind>;
let _: ::core::clone::AssertParamIsClone<ConstantHasGenerics>;
let _:
::core::clone::AssertParamIsClone<Option<(Ident,
ConstantItemKind)>>;
let _: ::core::clone::AssertParamIsClone<LocalModule<'ra>>;
let _: ::core::clone::AssertParamIsClone<DefId>;
let _:
::core::clone::AssertParamIsClone<ForwardGenericParamBanReason>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for RibKind<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
RibKind::Normal => ::core::fmt::Formatter::write_str(f, "Normal"),
RibKind::Block(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Block",
&__self_0),
RibKind::AssocItem =>
::core::fmt::Formatter::write_str(f, "AssocItem"),
RibKind::FnOrCoroutine =>
::core::fmt::Formatter::write_str(f, "FnOrCoroutine"),
RibKind::Item(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Item",
__self_0, &__self_1),
RibKind::ConstantItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"ConstantItem", __self_0, &__self_1),
RibKind::Module(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Module",
&__self_0),
RibKind::MacroDefinition(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MacroDefinition", &__self_0),
RibKind::ForwardGenericParamBan(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ForwardGenericParamBan", &__self_0),
RibKind::ConstParamTy =>
::core::fmt::Formatter::write_str(f, "ConstParamTy"),
RibKind::InlineAsmSym =>
::core::fmt::Formatter::write_str(f, "InlineAsmSym"),
}
}
}Debug)]
190pub(crate) enum RibKind<'ra> {
191 Normal,
193
194 Block(Option<LocalModule<'ra>>),
200
201 AssocItem,
206
207 FnOrCoroutine,
209
210 Item(HasGenericParams, DefKind),
212
213 ConstantItem(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
218
219 Module(LocalModule<'ra>),
221
222 MacroDefinition(DefId),
224
225 ForwardGenericParamBan(ForwardGenericParamBanReason),
229
230 ConstParamTy,
233
234 InlineAsmSym,
237}
238
239#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForwardGenericParamBanReason { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ForwardGenericParamBanReason {
#[inline]
fn clone(&self) -> ForwardGenericParamBanReason { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ForwardGenericParamBanReason {
#[inline]
fn eq(&self, other: &ForwardGenericParamBanReason) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ForwardGenericParamBanReason {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ForwardGenericParamBanReason {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ForwardGenericParamBanReason::Default => "Default",
ForwardGenericParamBanReason::ConstParamTy => "ConstParamTy",
})
}
}Debug)]
240pub(crate) enum ForwardGenericParamBanReason {
241 Default,
242 ConstParamTy,
243}
244
245impl RibKind<'_> {
246 pub(crate) fn contains_params(&self) -> bool {
249 match self {
250 RibKind::Normal
251 | RibKind::Block(..)
252 | RibKind::FnOrCoroutine
253 | RibKind::ConstantItem(..)
254 | RibKind::Module(_)
255 | RibKind::MacroDefinition(_)
256 | RibKind::InlineAsmSym => false,
257 RibKind::ConstParamTy
258 | RibKind::AssocItem
259 | RibKind::Item(..)
260 | RibKind::ForwardGenericParamBan(_) => true,
261 }
262 }
263
264 fn is_label_barrier(self) -> bool {
266 match self {
267 RibKind::Normal | RibKind::MacroDefinition(..) => false,
268 RibKind::FnOrCoroutine | RibKind::ConstantItem(..) => true,
269 kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected rib kind: {0:?}",
kind))bug!("unexpected rib kind: {kind:?}"),
270 }
271 }
272}
273
274#[derive(#[automatically_derived]
impl<'ra, R: ::core::fmt::Debug> ::core::fmt::Debug for Rib<'ra, R> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "Rib",
"bindings", &self.bindings, "patterns_with_skipped_bindings",
&self.patterns_with_skipped_bindings, "kind", &&self.kind)
}
}Debug)]
287pub(crate) struct Rib<'ra, R = Res> {
288 pub bindings: FxIndexMap<Ident, R>,
289 pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>,
290 pub kind: RibKind<'ra>,
291}
292
293impl<'ra, R> Rib<'ra, R> {
294 fn new(kind: RibKind<'ra>) -> Rib<'ra, R> {
295 Rib {
296 bindings: Default::default(),
297 patterns_with_skipped_bindings: Default::default(),
298 kind,
299 }
300 }
301}
302
303#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeUseSet {
#[inline]
fn clone(&self) -> LifetimeUseSet {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<visit::LifetimeCtxt>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeUseSet { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeUseSet {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LifetimeUseSet::One { use_span: __self_0, use_ctxt: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "One",
"use_span", __self_0, "use_ctxt", &__self_1),
LifetimeUseSet::Many =>
::core::fmt::Formatter::write_str(f, "Many"),
}
}
}Debug)]
304enum LifetimeUseSet {
305 One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
306 Many,
307}
308
309#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeRibKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeRibKind {
#[inline]
fn clone(&self) -> LifetimeRibKind {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<LifetimeBinderKind>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<LifetimeRes>;
let _: ::core::clone::AssertParamIsClone<NoConstantGenericsReason>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeRibKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LifetimeRibKind::Generics {
binder: __self_0, span: __self_1, kind: __self_2 } =>
::core::fmt::Formatter::debug_struct_field3_finish(f,
"Generics", "binder", __self_0, "span", __self_1, "kind",
&__self_2),
LifetimeRibKind::AnonymousCreateParameter {
binder: __self_0, report_in_path: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"AnonymousCreateParameter", "binder", __self_0,
"report_in_path", &__self_1),
LifetimeRibKind::Elided { res: __self_0, error_in_path: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Elided", "res", __self_0, "error_in_path", &__self_1),
LifetimeRibKind::AnonymousReportError =>
::core::fmt::Formatter::write_str(f, "AnonymousReportError"),
LifetimeRibKind::ElisionFailure =>
::core::fmt::Formatter::write_str(f, "ElisionFailure"),
LifetimeRibKind::ConstParamTy =>
::core::fmt::Formatter::write_str(f, "ConstParamTy"),
LifetimeRibKind::ConcreteAnonConst(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ConcreteAnonConst", &__self_0),
LifetimeRibKind::Item =>
::core::fmt::Formatter::write_str(f, "Item"),
LifetimeRibKind::ImplTrait =>
::core::fmt::Formatter::write_str(f, "ImplTrait"),
}
}
}Debug)]
310enum LifetimeRibKind {
311 Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
316
317 AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
334
335 Elided {
337 res: LifetimeRes,
338 error_in_path: bool,
340 },
341
342 AnonymousReportError,
348
349 ElisionFailure,
351
352 ConstParamTy,
357
358 ConcreteAnonConst(NoConstantGenericsReason),
364
365 Item,
367
368 ImplTrait,
370}
371impl LifetimeRibKind {
372 fn elided(res: LifetimeRes) -> LifetimeRibKind {
374 LifetimeRibKind::Elided { res, error_in_path: false }
375 }
376}
377
378#[derive(#[automatically_derived]
impl ::core::marker::Copy for LifetimeBinderKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LifetimeBinderKind {
#[inline]
fn clone(&self) -> LifetimeBinderKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LifetimeBinderKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
LifetimeBinderKind::FnPtrType => "FnPtrType",
LifetimeBinderKind::PolyTrait => "PolyTrait",
LifetimeBinderKind::WhereBound => "WhereBound",
LifetimeBinderKind::Item => "Item",
LifetimeBinderKind::ConstItem => "ConstItem",
LifetimeBinderKind::Function => "Function",
LifetimeBinderKind::Closure => "Closure",
LifetimeBinderKind::ImplBlock => "ImplBlock",
LifetimeBinderKind::ImplAssocType => "ImplAssocType",
})
}
}Debug)]
379enum LifetimeBinderKind {
380 FnPtrType,
381 PolyTrait,
382 WhereBound,
383 Item,
386 ConstItem,
387 Function,
388 Closure,
389 ImplBlock,
390 ImplAssocType,
392}
393
394impl LifetimeBinderKind {
395 fn descr(self) -> &'static str {
396 use LifetimeBinderKind::*;
397 match self {
398 FnPtrType => "type",
399 PolyTrait => "bound",
400 WhereBound => "bound",
401 Item | ConstItem => "item",
402 ImplAssocType => "associated type",
403 ImplBlock => "impl block",
404 Function => "function",
405 Closure => "closure",
406 }
407 }
408}
409
410#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LifetimeRib {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "LifetimeRib",
"kind", &self.kind, "bindings", &&self.bindings)
}
}Debug)]
411struct LifetimeRib {
412 kind: LifetimeRibKind,
413 bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
415}
416
417impl LifetimeRib {
418 fn new(kind: LifetimeRibKind) -> LifetimeRib {
419 LifetimeRib { bindings: Default::default(), kind }
420 }
421}
422
423#[derive(#[automatically_derived]
impl ::core::marker::Copy for AliasPossibility { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AliasPossibility {
#[inline]
fn clone(&self) -> AliasPossibility { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for AliasPossibility {
#[inline]
fn eq(&self, other: &AliasPossibility) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AliasPossibility {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for AliasPossibility {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AliasPossibility::No => "No",
AliasPossibility::Maybe => "Maybe",
})
}
}Debug)]
424pub(crate) enum AliasPossibility {
425 No,
426 Maybe,
427}
428
429#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ResolvingRestrictionKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ResolvingRestrictionKind::Impl => "Impl",
ResolvingRestrictionKind::Mut => "Mut",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for ResolvingRestrictionKind {
#[inline]
fn clone(&self) -> ResolvingRestrictionKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ResolvingRestrictionKind { }Copy)]
431pub(crate) enum ResolvingRestrictionKind {
432 Impl,
433 Mut,
434}
435
436impl IntoDiagArg for ResolvingRestrictionKind {
437 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
438 use std::borrow::Cow;
439 match self {
440 ResolvingRestrictionKind::Impl => DiagArgValue::Str(Cow::Borrowed("impl")),
441 ResolvingRestrictionKind::Mut => DiagArgValue::Str(Cow::Borrowed("mut")),
442 }
443 }
444}
445
446#[derive(#[automatically_derived]
impl<'a, 'ast, 'ra> ::core::marker::Copy for PathSource<'a, 'ast, 'ra> { }Copy, #[automatically_derived]
impl<'a, 'ast, 'ra> ::core::clone::Clone for PathSource<'a, 'ast, 'ra> {
#[inline]
fn clone(&self) -> PathSource<'a, 'ast, 'ra> {
let _: ::core::clone::AssertParamIsClone<AliasPossibility>;
let _: ::core::clone::AssertParamIsClone<Option<&'ast Expr>>;
let _: ::core::clone::AssertParamIsClone<Option<&'a Expr>>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<&'ra [Span]>;
let _: ::core::clone::AssertParamIsClone<Namespace>;
let _:
::core::clone::AssertParamIsClone<&'a PathSource<'a, 'ast,
'ra>>;
*self
}
}Clone, #[automatically_derived]
impl<'a, 'ast, 'ra> ::core::fmt::Debug for PathSource<'a, 'ast, 'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PathSource::Type => ::core::fmt::Formatter::write_str(f, "Type"),
PathSource::Trait(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Trait",
&__self_0),
PathSource::Expr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Expr",
&__self_0),
PathSource::Pat => ::core::fmt::Formatter::write_str(f, "Pat"),
PathSource::Struct(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Struct",
&__self_0),
PathSource::TupleStruct(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"TupleStruct", __self_0, &__self_1),
PathSource::TraitItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"TraitItem", __self_0, &__self_1),
PathSource::Delegation =>
::core::fmt::Formatter::write_str(f, "Delegation"),
PathSource::ExternItemImpl =>
::core::fmt::Formatter::write_str(f, "ExternItemImpl"),
PathSource::PreciseCapturingArg(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"PreciseCapturingArg", &__self_0),
PathSource::ReturnTypeNotation =>
::core::fmt::Formatter::write_str(f, "ReturnTypeNotation"),
PathSource::DefineOpaques =>
::core::fmt::Formatter::write_str(f, "DefineOpaques"),
PathSource::Macro =>
::core::fmt::Formatter::write_str(f, "Macro"),
PathSource::Module =>
::core::fmt::Formatter::write_str(f, "Module"),
}
}
}Debug)]
447pub(crate) enum PathSource<'a, 'ast, 'ra> {
448 Type,
450 Trait(AliasPossibility),
452 Expr(Option<&'ast Expr>),
454 Pat,
456 Struct(Option<&'a Expr>),
458 TupleStruct(Span, &'ra [Span]),
460 TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
465 Delegation,
467 ExternItemImpl,
469 PreciseCapturingArg(Namespace),
471 ReturnTypeNotation,
473 DefineOpaques,
475 Macro,
477 Module,
479}
480
481impl PathSource<'_, '_, '_> {
482 fn namespace(self) -> Namespace {
483 match self {
484 PathSource::Type
485 | PathSource::Trait(_)
486 | PathSource::Struct(_)
487 | PathSource::DefineOpaques
488 | PathSource::Module => TypeNS,
489 PathSource::Expr(..)
490 | PathSource::Pat
491 | PathSource::TupleStruct(..)
492 | PathSource::Delegation
493 | PathSource::ExternItemImpl
494 | PathSource::ReturnTypeNotation => ValueNS,
495 PathSource::TraitItem(ns, _) => ns,
496 PathSource::PreciseCapturingArg(ns) => ns,
497 PathSource::Macro => MacroNS,
498 }
499 }
500
501 fn defer_to_typeck(self) -> bool {
502 match self {
503 PathSource::Type
504 | PathSource::Expr(..)
505 | PathSource::Pat
506 | PathSource::Struct(_)
507 | PathSource::TupleStruct(..)
508 | PathSource::ReturnTypeNotation => true,
509 PathSource::Trait(_)
510 | PathSource::TraitItem(..)
511 | PathSource::DefineOpaques
512 | PathSource::Delegation
513 | PathSource::ExternItemImpl
514 | PathSource::PreciseCapturingArg(..)
515 | PathSource::Macro
516 | PathSource::Module => false,
517 }
518 }
519
520 fn descr_expected(self) -> &'static str {
521 match &self {
522 PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
523 PathSource::Type => "type",
524 PathSource::Trait(_) => "trait",
525 PathSource::Pat => "unit struct, unit variant or constant",
526 PathSource::Struct(_) => "struct, variant or union type",
527 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
528 | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
529 PathSource::TraitItem(ns, _) => match ns {
530 TypeNS => "associated type",
531 ValueNS => "method or associated constant",
532 MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
533 },
534 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
535 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
538 ExprKind::Path(_, path)
540 if let [segment, _] = path.segments.as_slice()
541 && segment.ident.name == kw::PathRoot =>
542 {
543 "external crate"
544 }
545 ExprKind::Path(_, path)
546 if let Some(segment) = path.segments.last()
547 && let Some(c) = segment.ident.to_string().chars().next()
548 && c.is_uppercase() =>
549 {
550 "function, tuple struct or tuple variant"
551 }
552 _ => "function",
553 },
554 _ => "value",
555 },
556 PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
557 PathSource::ExternItemImpl => "function or static",
558 PathSource::PreciseCapturingArg(..) => "type or const parameter",
559 PathSource::Macro => "macro",
560 PathSource::Module => "module",
561 }
562 }
563
564 fn is_call(self) -> bool {
565 #[allow(non_exhaustive_omitted_patterns)] match self {
PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
566 }
567
568 pub(crate) fn is_expected(self, res: Res) -> bool {
569 match self {
570 PathSource::DefineOpaques => {
571 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
true,
_ => false,
}matches!(
572 res,
573 Res::Def(
574 DefKind::Struct
575 | DefKind::Union
576 | DefKind::Enum
577 | DefKind::TyAlias
578 | DefKind::AssocTy,
579 _
580 ) | Res::SelfTyAlias { .. }
581 )
582 }
583 PathSource::Type => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Trait
| DefKind::TraitAlias | DefKind::TyAlias | DefKind::AssocTy |
DefKind::TyParam | DefKind::OpaqueTy | DefKind::ForeignTy, _) |
Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } =>
true,
_ => false,
}matches!(
584 res,
585 Res::Def(
586 DefKind::Struct
587 | DefKind::Union
588 | DefKind::Enum
589 | DefKind::Trait
590 | DefKind::TraitAlias
591 | DefKind::TyAlias
592 | DefKind::AssocTy
593 | DefKind::TyParam
594 | DefKind::OpaqueTy
595 | DefKind::ForeignTy,
596 _,
597 ) | Res::PrimTy(..)
598 | Res::SelfTyParam { .. }
599 | Res::SelfTyAlias { .. }
600 ),
601 PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
602 PathSource::Trait(AliasPossibility::Maybe) => {
603 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
604 }
605 PathSource::Expr(..) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) |
DefKind::Const { .. } | DefKind::Static { .. } | DefKind::Fn |
DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::ConstParam,
_) | Res::Local(..) | Res::SelfCtor(..) => true,
_ => false,
}matches!(
606 res,
607 Res::Def(
608 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
609 | DefKind::Const { .. }
610 | DefKind::Static { .. }
611 | DefKind::Fn
612 | DefKind::AssocFn
613 | DefKind::AssocConst { .. }
614 | DefKind::ConstParam,
615 _,
616 ) | Res::Local(..)
617 | Res::SelfCtor(..)
618 ),
619 PathSource::Pat => {
620 res.expected_in_unit_struct_pat()
621 || #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
_ => false,
}matches!(
622 res,
623 Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
624 )
625 }
626 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
627 PathSource::Struct(_) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Variant |
DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyParam { .. } |
Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(
628 res,
629 Res::Def(
630 DefKind::Struct
631 | DefKind::Union
632 | DefKind::Variant
633 | DefKind::TyAlias
634 | DefKind::AssocTy,
635 _,
636 ) | Res::SelfTyParam { .. }
637 | Res::SelfTyAlias { .. }
638 ),
639 PathSource::TraitItem(ns, _) => match res {
640 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
641 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
642 _ => false,
643 },
644 PathSource::ReturnTypeNotation => match res {
645 Res::Def(DefKind::AssocFn, _) => true,
646 _ => false,
647 },
648 PathSource::Delegation => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Fn | DefKind::AssocFn, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Fn | DefKind::AssocFn, _)),
649 PathSource::ExternItemImpl => {
650 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
DefKind::Static { .. }, _) => true,
_ => false,
}matches!(
651 res,
652 Res::Def(
653 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
654 _
655 )
656 )
657 }
658 PathSource::PreciseCapturingArg(ValueNS) => {
659 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::ConstParam, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
660 }
661 PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(
663 res,
664 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
665 ),
666 PathSource::PreciseCapturingArg(MacroNS) => false,
667 PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Macro(_), _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
668 PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
669 }
670 }
671
672 fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
673 match (self, has_unexpected_resolution) {
674 (PathSource::Trait(_), true) => E0404,
675 (PathSource::Trait(_), false) => E0405,
676 (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
677 (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
678 (PathSource::Struct(_), true) => E0574,
679 (PathSource::Struct(_), false) => E0422,
680 (PathSource::Expr(..), true)
681 | (PathSource::Delegation, true)
682 | (PathSource::ExternItemImpl, true) => E0423,
683 (PathSource::Expr(..), false)
684 | (PathSource::Delegation, false)
685 | (PathSource::ExternItemImpl, false) => E0425,
686 (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
687 (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
688 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
689 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
690 (PathSource::PreciseCapturingArg(..), true) => E0799,
691 (PathSource::PreciseCapturingArg(..), false) => E0800,
692 (PathSource::Macro, _) => E0425,
693 (PathSource::Module, true) => E0577,
698 (PathSource::Module, false) => E0433,
699 }
700 }
701}
702
703#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for MaybeExported<'a> {
#[inline]
fn clone(&self) -> MaybeExported<'a> {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Option<DefId>>;
let _:
::core::clone::AssertParamIsClone<Result<DefId,
&'a ast::Visibility>>;
let _: ::core::clone::AssertParamIsClone<&'a ast::Visibility>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for MaybeExported<'a> { }Copy)]
707enum MaybeExported<'a> {
708 Ok(NodeId),
709 Impl(Option<DefId>),
710 ImplItem(Result<DefId, &'a ast::Visibility>),
711 NestedUse(&'a ast::Visibility),
712}
713
714impl MaybeExported<'_> {
715 fn eval(self, r: &Resolver<'_, '_>) -> bool {
716 let def_id = match self {
717 MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
718 r.current_owner.def_id
719 } else {
720 r.current_owner.node_id_to_def_id[&node_id]
721 }),
722 MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
723 trait_def_id.as_local()
724 }
725 MaybeExported::Impl(None) => return true,
726 MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
727 return vis.kind.is_pub();
728 }
729 };
730 def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
731 }
732}
733
734#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for UnnecessaryQualification<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"UnnecessaryQualification", "decl", &self.decl, "node_id",
&self.node_id, "path_span", &self.path_span, "removal_span",
&&self.removal_span)
}
}Debug)]
736pub(crate) struct UnnecessaryQualification<'ra> {
737 pub decl: LateDecl<'ra>,
738 pub node_id: NodeId,
739 pub path_span: Span,
740 pub removal_span: Span,
741}
742
743#[derive(#[automatically_derived]
impl<'ast> ::core::default::Default for DiagMetadata<'ast> {
#[inline]
fn default() -> DiagMetadata<'ast> {
DiagMetadata {
current_trait_assoc_items: ::core::default::Default::default(),
current_self_type: ::core::default::Default::default(),
current_self_item: ::core::default::Default::default(),
current_item: ::core::default::Default::default(),
currently_processing_generic_args: ::core::default::Default::default(),
current_function: ::core::default::Default::default(),
unused_labels: ::core::default::Default::default(),
current_let_binding: ::core::default::Default::default(),
current_pat: ::core::default::Default::default(),
in_if_condition: ::core::default::Default::default(),
in_assignment: ::core::default::Default::default(),
is_assign_rhs: ::core::default::Default::default(),
in_non_gat_assoc_type: ::core::default::Default::default(),
in_range: ::core::default::Default::default(),
current_trait_object: ::core::default::Default::default(),
current_where_predicate: ::core::default::Default::default(),
in_assoc_ty_binding: ::core::default::Default::default(),
current_type_path: ::core::default::Default::default(),
current_impl_items: ::core::default::Default::default(),
current_impl_item: ::core::default::Default::default(),
currently_processing_impl_trait: ::core::default::Default::default(),
current_elision_failures: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]
impl<'ast> ::core::fmt::Debug for DiagMetadata<'ast> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["current_trait_assoc_items", "current_self_type",
"current_self_item", "current_item",
"currently_processing_generic_args", "current_function",
"unused_labels", "current_let_binding", "current_pat",
"in_if_condition", "in_assignment", "is_assign_rhs",
"in_non_gat_assoc_type", "in_range", "current_trait_object",
"current_where_predicate", "in_assoc_ty_binding",
"current_type_path", "current_impl_items",
"current_impl_item", "currently_processing_impl_trait",
"current_elision_failures"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.current_trait_assoc_items, &self.current_self_type,
&self.current_self_item, &self.current_item,
&self.currently_processing_generic_args,
&self.current_function, &self.unused_labels,
&self.current_let_binding, &self.current_pat,
&self.in_if_condition, &self.in_assignment,
&self.is_assign_rhs, &self.in_non_gat_assoc_type,
&self.in_range, &self.current_trait_object,
&self.current_where_predicate, &self.in_assoc_ty_binding,
&self.current_type_path, &self.current_impl_items,
&self.current_impl_item,
&self.currently_processing_impl_trait,
&&self.current_elision_failures];
::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagMetadata",
names, values)
}
}Debug)]
744pub(crate) struct DiagMetadata<'ast> {
745 current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
747
748 pub(crate) current_self_type: Option<&'ast Ty>,
750
751 current_self_item: Option<NodeId>,
753
754 pub(crate) current_item: Option<&'ast Item>,
756
757 currently_processing_generic_args: bool,
760
761 current_function: Option<(FnKind<'ast>, Span)>,
763
764 unused_labels: FxIndexMap<NodeId, Span>,
767
768 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
770
771 current_pat: Option<&'ast Pat>,
772
773 in_if_condition: Option<&'ast Expr>,
775
776 in_assignment: Option<&'ast Expr>,
778 is_assign_rhs: bool,
779
780 in_non_gat_assoc_type: Option<bool>,
782
783 in_range: Option<(&'ast Expr, &'ast Expr)>,
785
786 current_trait_object: Option<&'ast [ast::GenericBound]>,
789
790 current_where_predicate: Option<&'ast WherePredicate>,
792
793 in_assoc_ty_binding: bool,
795
796 current_type_path: Option<&'ast Ty>,
797
798 current_impl_items: Option<&'ast [Box<AssocItem>]>,
800
801 current_impl_item: Option<&'ast AssocItem>,
803
804 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
806
807 current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,
810}
811
812struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
813 r: &'a mut Resolver<'ra, 'tcx>,
814
815 parent_scope: ParentScope<'ra>,
817
818 ribs: PerNS<Vec<Rib<'ra>>>,
820
821 last_block_rib: Option<Rib<'ra>>,
823
824 label_ribs: Vec<Rib<'ra, NodeId>>,
826
827 lifetime_ribs: Vec<LifetimeRib>,
829
830 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
836
837 current_trait_ref: Option<(Module<'ra>, TraitRef)>,
839
840 diag_metadata: Box<DiagMetadata<'ast>>,
842
843 in_func_body: bool,
849
850 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
852
853 use_injections: Vec<UseError<'tcx>>,
855}
856
857impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
858 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
859 &self.r
860 }
861}
862impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
863 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
864 &mut self.r
865 }
866}
867
868impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
870 fn visit_attribute(&mut self, _: &'ast Attribute) {
871 }
874 fn visit_item(&mut self, item: &'ast Item) {
875 let prev = replace(&mut self.diag_metadata.current_item, Some(item));
876 let old_ignore = replace(&mut self.in_func_body, false);
878 with_owner(self, item.id, |this| {
879 this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
880 });
881 self.in_func_body = old_ignore;
882 self.diag_metadata.current_item = prev;
883 }
884 fn visit_arm(&mut self, arm: &'ast Arm) {
885 self.resolve_arm(arm);
886 }
887 fn visit_block(&mut self, block: &'ast Block) {
888 let old_macro_rules = self.parent_scope.macro_rules;
889 self.resolve_block(block);
890 self.parent_scope.macro_rules = old_macro_rules;
891 }
892 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
893 ::rustc_middle::util::bug::bug_fmt(format_args!("encountered anon const without a manual call to `resolve_anon_const`: {0:#?}",
constant));bug!("encountered anon const without a manual call to `resolve_anon_const`: {constant:#?}");
894 }
895 fn visit_expr(&mut self, expr: &'ast Expr) {
896 self.resolve_expr(expr, None);
897 }
898 fn visit_pat(&mut self, p: &'ast Pat) {
899 let prev = self.diag_metadata.current_pat;
900 self.diag_metadata.current_pat = Some(p);
901
902 if let PatKind::Guard(subpat, _) = &p.kind {
903 self.visit_pat(subpat);
905 } else {
906 visit::walk_pat(self, p);
907 }
908
909 self.diag_metadata.current_pat = prev;
910 }
911 fn visit_local(&mut self, local: &'ast Local) {
912 let local_spans = match local.pat.kind {
913 PatKind::Wild => None,
915 _ => Some((
916 local.pat.span,
917 local.ty.as_ref().map(|ty| ty.span),
918 local.kind.init().map(|init| init.span),
919 )),
920 };
921 let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
922 self.resolve_local(local);
923 self.diag_metadata.current_let_binding = original;
924 }
925 fn visit_ty(&mut self, ty: &'ast Ty) {
926 let prev = self.diag_metadata.current_trait_object;
927 let prev_ty = self.diag_metadata.current_type_path;
928 match &ty.kind {
929 TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
930 let span = self.r.tcx.sess.source_map().start_point(ty.span);
934 self.resolve_elided_lifetime(ty.id, span);
935 visit::walk_ty(self, ty);
936 }
937 TyKind::Path(qself, path) => {
938 self.diag_metadata.current_type_path = Some(ty);
939
940 let source = if let Some(seg) = path.segments.last()
944 && let Some(args) = &seg.args
945 && #[allow(non_exhaustive_omitted_patterns)] match **args {
GenericArgs::ParenthesizedElided(..) => true,
_ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
946 {
947 PathSource::ReturnTypeNotation
948 } else {
949 PathSource::Type
950 };
951
952 self.smart_resolve_path(ty.id, qself, path, source);
953
954 if qself.is_none()
956 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
957 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
958 partial_res.full_res()
959 {
960 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
964 self.with_generic_param_rib(
965 &[],
966 RibKind::Normal,
967 ty.id,
968 LifetimeBinderKind::PolyTrait,
969 span,
970 |this| this.visit_path(path),
971 );
972 } else {
973 visit::walk_ty(self, ty)
974 }
975 }
976 TyKind::ImplicitSelf => {
977 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
978 let res = self
979 .resolve_ident_in_lexical_scope(
980 self_ty,
981 TypeNS,
982 Some(Finalize::new(ty.id, ty.span)),
983 None,
984 )
985 .map_or(Res::Err, |d| d.res());
986 self.r.record_partial_res(ty.id, PartialRes::new(res));
987 visit::walk_ty(self, ty)
988 }
989 TyKind::ImplTrait(..) => {
990 let candidates = self.lifetime_elision_candidates.take();
991 self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
992 self.lifetime_elision_candidates = candidates;
993 }
994 TyKind::TraitObject(bounds, ..) => {
995 self.diag_metadata.current_trait_object = Some(&bounds[..]);
996 visit::walk_ty(self, ty)
997 }
998 TyKind::FnPtr(fn_ptr) => {
999 let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
1000 self.with_generic_param_rib(
1001 &fn_ptr.generic_params,
1002 RibKind::Normal,
1003 ty.id,
1004 LifetimeBinderKind::FnPtrType,
1005 span,
1006 |this| {
1007 this.visit_generic_params(&fn_ptr.generic_params, false);
1008 this.resolve_fn_signature(
1009 ty.id,
1010 false,
1011 fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1014 &fn_ptr.decl.output,
1015 false,
1016 )
1017 },
1018 )
1019 }
1020 TyKind::UnsafeBinder(unsafe_binder) => {
1021 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
1022 self.with_generic_param_rib(
1023 &unsafe_binder.generic_params,
1024 RibKind::Normal,
1025 ty.id,
1026 LifetimeBinderKind::FnPtrType,
1027 span,
1028 |this| {
1029 this.visit_generic_params(&unsafe_binder.generic_params, false);
1030 this.with_lifetime_rib(
1031 LifetimeRibKind::AnonymousReportError,
1034 |this| this.visit_ty(&unsafe_binder.inner_ty),
1035 );
1036 },
1037 )
1038 }
1039 TyKind::Array(element_ty, length) => {
1040 self.visit_ty(element_ty);
1041 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
1042 }
1043 _ => visit::walk_ty(self, ty),
1044 }
1045 self.diag_metadata.current_trait_object = prev;
1046 self.diag_metadata.current_type_path = prev_ty;
1047 }
1048
1049 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1050 match &t.kind {
1051 TyPatKind::Range(start, end, _) => {
1052 if let Some(start) = start {
1053 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1054 }
1055 if let Some(end) = end {
1056 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1057 }
1058 }
1059 TyPatKind::Or(patterns) => {
1060 for pat in patterns {
1061 self.visit_ty_pat(pat)
1062 }
1063 }
1064 TyPatKind::NotNull | TyPatKind::Err(_) => {}
1065 }
1066 }
1067
1068 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1069 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1070 self.with_generic_param_rib(
1071 &tref.bound_generic_params,
1072 RibKind::Normal,
1073 tref.trait_ref.ref_id,
1074 LifetimeBinderKind::PolyTrait,
1075 span,
1076 |this| {
1077 this.visit_generic_params(&tref.bound_generic_params, false);
1078 this.smart_resolve_path(
1079 tref.trait_ref.ref_id,
1080 &None,
1081 &tref.trait_ref.path,
1082 PathSource::Trait(AliasPossibility::Maybe),
1083 );
1084 this.visit_trait_ref(&tref.trait_ref);
1085 },
1086 );
1087 }
1088 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1089 with_owner(self, foreign_item.id, |this| {
1090 this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1091 let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1092 match foreign_item.kind {
1093 ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1094 this.with_generic_param_rib(
1095 &generics.params,
1096 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1097 foreign_item.id,
1098 LifetimeBinderKind::Item,
1099 generics.span,
1100 |this| visit::walk_item(this, foreign_item),
1101 );
1102 }
1103 ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1104 this.with_generic_param_rib(
1105 &generics.params,
1106 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1107 foreign_item.id,
1108 LifetimeBinderKind::Function,
1109 generics.span,
1110 |this| visit::walk_item(this, foreign_item),
1111 );
1112 }
1113 ForeignItemKind::Static(..) => {
1114 this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1115 }
1116 ForeignItemKind::MacCall(..) => {
1117 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1118 }
1119 }
1120 })
1121 }
1122 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1123 let previous_value = self.diag_metadata.current_function;
1124 match fn_kind {
1125 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1128 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1129 self.visit_fn_header(&sig.header);
1130 self.visit_ident(ident);
1131 self.visit_generics(generics);
1132 self.resolve_fn_signature(
1133 fn_id,
1134 sig.decl.has_self(),
1135 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1136 &sig.decl.output,
1137 false,
1138 );
1139 return;
1140 }
1141 FnKind::Fn(..) => {
1142 self.diag_metadata.current_function = Some((fn_kind, sp));
1143 }
1144 FnKind::Closure(..) => {}
1146 };
1147 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1147",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1147u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving function) entering function")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving function) entering function");
1148
1149 if let FnKind::Fn(_, _, f) = fn_kind {
1150 self.resolve_eii(&f.eii_impls);
1151 }
1152
1153 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1155 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1157 match fn_kind {
1158 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1159 this.visit_generics(generics);
1160
1161 let declaration = &sig.decl;
1162 let coro_node_id = sig
1163 .header
1164 .coroutine_kind
1165 .map(|coroutine_kind| coroutine_kind.return_id());
1166
1167 this.resolve_fn_signature(
1168 fn_id,
1169 declaration.has_self(),
1170 declaration
1171 .inputs
1172 .iter()
1173 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1174 &declaration.output,
1175 coro_node_id.is_some(),
1176 );
1177
1178 if let Some(contract) = contract {
1179 this.visit_contract(contract);
1180 }
1181
1182 if let Some(body) = body {
1183 let previous_state = replace(&mut this.in_func_body, true);
1186 this.last_block_rib = None;
1188 this.with_lifetime_rib(
1190 LifetimeRibKind::elided(LifetimeRes::Infer),
1191 |this| this.visit_block(body),
1192 );
1193
1194 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1194",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1194u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving function) leaving function")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving function) leaving function");
1195 this.in_func_body = previous_state;
1196 }
1197 }
1198 FnKind::Closure(binder, _, declaration, body) => {
1199 this.visit_closure_binder(binder);
1200
1201 this.with_lifetime_rib(
1202 match binder {
1203 ClosureBinder::NotPresent => {
1205 LifetimeRibKind::AnonymousCreateParameter {
1206 binder: fn_id,
1207 report_in_path: false,
1208 }
1209 }
1210 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1211 },
1212 |this| this.resolve_params(&declaration.inputs),
1214 );
1215 this.with_lifetime_rib(
1216 match binder {
1217 ClosureBinder::NotPresent => {
1218 LifetimeRibKind::elided(LifetimeRes::Infer)
1219 }
1220 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1221 },
1222 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1223 );
1224
1225 let previous_state = replace(&mut this.in_func_body, true);
1228 this.with_lifetime_rib(
1230 LifetimeRibKind::elided(LifetimeRes::Infer),
1231 |this| this.visit_expr(body),
1232 );
1233
1234 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1234",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1234u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving function) leaving function")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving function) leaving function");
1235 this.in_func_body = previous_state;
1236 }
1237 }
1238 })
1239 });
1240 self.diag_metadata.current_function = previous_value;
1241 }
1242
1243 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1244 self.resolve_lifetime(lifetime, use_ctxt)
1245 }
1246
1247 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1248 match arg {
1249 PreciseCapturingArg::Lifetime(_) => {}
1252
1253 PreciseCapturingArg::Arg(path, id) => {
1254 let mut check_ns = |ns| {
1261 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1262 };
1263 if !check_ns(TypeNS) && check_ns(ValueNS) {
1265 self.smart_resolve_path(
1266 *id,
1267 &None,
1268 path,
1269 PathSource::PreciseCapturingArg(ValueNS),
1270 );
1271 } else {
1272 self.smart_resolve_path(
1273 *id,
1274 &None,
1275 path,
1276 PathSource::PreciseCapturingArg(TypeNS),
1277 );
1278 }
1279 }
1280 }
1281
1282 visit::walk_precise_capturing_arg(self, arg)
1283 }
1284
1285 fn visit_generics(&mut self, generics: &'ast Generics) {
1286 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1287 for p in &generics.where_clause.predicates {
1288 self.visit_where_predicate(p);
1289 }
1290 }
1291
1292 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1293 match b {
1294 ClosureBinder::NotPresent => {}
1295 ClosureBinder::For { generic_params, .. } => {
1296 self.visit_generic_params(
1297 generic_params,
1298 self.diag_metadata.current_self_item.is_some(),
1299 );
1300 }
1301 }
1302 }
1303
1304 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1305 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1305",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1305u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("visit_generic_arg({0:?})",
arg) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("visit_generic_arg({:?})", arg);
1306 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1307 match arg {
1308 GenericArg::Type(ty) => {
1309 if let TyKind::Path(None, ref path) = ty.kind
1315 && path.is_potential_trivial_const_arg()
1318 {
1319 let mut check_ns = |ns| {
1320 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
1321 .is_some()
1322 };
1323 if !check_ns(TypeNS) && check_ns(ValueNS) {
1324 self.resolve_anon_const_manual(
1325 true,
1326 AnonConstKind::ConstArg(IsRepeatExpr::No),
1327 |this| {
1328 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1329 this.visit_path(path);
1330 },
1331 );
1332
1333 self.diag_metadata.currently_processing_generic_args = prev;
1334 return;
1335 }
1336 }
1337
1338 self.visit_ty(ty);
1339 }
1340 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1341 GenericArg::Const(ct) => {
1342 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1343 }
1344 }
1345 self.diag_metadata.currently_processing_generic_args = prev;
1346 }
1347
1348 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1349 self.visit_ident(&constraint.ident);
1350 if let Some(ref gen_args) = constraint.gen_args {
1351 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1353 this.visit_generic_args(gen_args)
1354 });
1355 }
1356 match constraint.kind {
1357 AssocItemConstraintKind::Equality { ref term } => match term {
1358 Term::Ty(ty) => {
1359 let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);
1360 self.visit_ty(ty);
1361 self.diag_metadata.in_assoc_ty_binding = prev;
1362 }
1363 Term::Const(c) => {
1364 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1365 }
1366 },
1367 AssocItemConstraintKind::Bound { ref bounds } => {
1368 for elem in bounds {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_param_bound(elem,
BoundKind::Bound)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1369 }
1370 }
1371 }
1372
1373 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1374 let Some(ref args) = path_segment.args else {
1375 return;
1376 };
1377
1378 match &**args {
1379 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1380 GenericArgs::Parenthesized(p_args) => {
1381 for rib in self.lifetime_ribs.iter().rev() {
1383 match rib.kind {
1384 LifetimeRibKind::Generics {
1387 binder,
1388 kind: LifetimeBinderKind::PolyTrait,
1389 ..
1390 } => {
1391 self.resolve_fn_signature(
1392 binder,
1393 false,
1394 p_args.inputs.iter().map(|ty| (None, &**ty)),
1395 &p_args.output,
1396 false,
1397 );
1398 break;
1399 }
1400 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1403 visit::walk_generic_args(self, args);
1404 break;
1405 }
1406 LifetimeRibKind::AnonymousCreateParameter { .. }
1407 | LifetimeRibKind::AnonymousReportError
1408 | LifetimeRibKind::ImplTrait
1409 | LifetimeRibKind::Elided { .. }
1410 | LifetimeRibKind::ElisionFailure
1411 | LifetimeRibKind::ConcreteAnonConst(_)
1412 | LifetimeRibKind::ConstParamTy => {}
1413 }
1414 }
1415 }
1416 GenericArgs::ParenthesizedElided(_) => {}
1417 }
1418 }
1419
1420 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1421 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1421",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1421u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("visit_where_predicate {0:?}",
p) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("visit_where_predicate {:?}", p);
1422 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1423 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1424 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1425 bounded_ty,
1426 bounds,
1427 bound_generic_params,
1428 ..
1429 }) = &p.kind
1430 {
1431 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1432 this.with_generic_param_rib(
1433 bound_generic_params,
1434 RibKind::Normal,
1435 bounded_ty.id,
1436 LifetimeBinderKind::WhereBound,
1437 span,
1438 |this| {
1439 this.visit_generic_params(bound_generic_params, false);
1440 this.visit_ty(bounded_ty);
1441 for bound in bounds {
1442 this.visit_param_bound(bound, BoundKind::Bound)
1443 }
1444 },
1445 );
1446 } else {
1447 visit::walk_where_predicate(this, p);
1448 }
1449 });
1450 self.diag_metadata.current_where_predicate = previous_value;
1451 }
1452
1453 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1454 for (op, _) in &asm.operands {
1455 match op {
1456 InlineAsmOperand::In { expr, .. }
1457 | InlineAsmOperand::Out { expr: Some(expr), .. }
1458 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1459 InlineAsmOperand::Out { expr: None, .. } => {}
1460 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1461 self.visit_expr(in_expr);
1462 if let Some(out_expr) = out_expr {
1463 self.visit_expr(out_expr);
1464 }
1465 }
1466 InlineAsmOperand::Const { anon_const, .. } => {
1467 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1470 }
1471 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1472 InlineAsmOperand::Label { block } => self.visit_block(block),
1473 }
1474 }
1475 }
1476
1477 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1478 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1480 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1481 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1482 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1483 visit::walk_inline_asm_sym(this, sym);
1484 });
1485 })
1486 });
1487 }
1488
1489 fn visit_variant(&mut self, v: &'ast Variant) {
1490 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1491 self.visit_id(v.id);
1492 for elem in &v.attrs {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(self, visit_attribute, &v.attrs);
1493 self.visit_vis(&v.vis);
1494 self.visit_ident(&v.ident);
1495 self.visit_variant_data(&v.data);
1496 if let Some(discr) = &v.disr_expr {
1497 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1498 }
1499 }
1500
1501 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1502 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1503 let FieldDef {
1504 attrs,
1505 id: _,
1506 span: _,
1507 vis,
1508 ident,
1509 ty,
1510 is_placeholder: _,
1511 default,
1512 mut_restriction,
1513 safety: _,
1514 } = f;
1515 for elem in attrs {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(self, visit_attribute, attrs);
1516 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_vis(vis)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_vis(vis));
1517 self.resolve_restriction_path(&mut_restriction.kind, ResolvingRestrictionKind::Mut);
1518 if let Some(x) = ident {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ident(x)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};visit_opt!(self, visit_ident, ident);
1519 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ty(ty)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_ty(ty));
1520 if let Some(v) = &default {
1521 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1522 }
1523 }
1524}
1525
1526impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1527 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1528 let graph_root = resolver.graph_root;
1531 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1532 let start_rib_kind = RibKind::Module(graph_root);
1533 LateResolutionVisitor {
1534 r: resolver,
1535 parent_scope,
1536 ribs: PerNS {
1537 value_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1538 type_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1539 macro_ns: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Rib::new(start_rib_kind)]))vec![Rib::new(start_rib_kind)],
1540 },
1541 last_block_rib: None,
1542 label_ribs: Vec::new(),
1543 lifetime_ribs: Vec::new(),
1544 lifetime_elision_candidates: None,
1545 current_trait_ref: None,
1546 diag_metadata: Default::default(),
1547 in_func_body: false,
1549 lifetime_uses: Default::default(),
1550 use_injections: Vec::new(),
1551 }
1552 }
1553
1554 fn maybe_resolve_ident_in_lexical_scope(
1555 &mut self,
1556 ident: Ident,
1557 ns: Namespace,
1558 ) -> Option<LateDecl<'ra>> {
1559 self.r.resolve_ident_in_lexical_scope(
1560 ident,
1561 ns,
1562 &self.parent_scope,
1563 None,
1564 &self.ribs[ns],
1565 None,
1566 Some(&self.diag_metadata),
1567 )
1568 }
1569
1570 fn resolve_ident_in_lexical_scope(
1571 &mut self,
1572 ident: Ident,
1573 ns: Namespace,
1574 finalize: Option<Finalize>,
1575 ignore_decl: Option<Decl<'ra>>,
1576 ) -> Option<LateDecl<'ra>> {
1577 self.r.resolve_ident_in_lexical_scope(
1578 ident,
1579 ns,
1580 &self.parent_scope,
1581 finalize,
1582 &self.ribs[ns],
1583 ignore_decl,
1584 Some(&self.diag_metadata),
1585 )
1586 }
1587
1588 fn resolve_path(
1589 &mut self,
1590 path: &[Segment],
1591 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1593 source: PathSource<'_, 'ast, 'ra>,
1594 ) -> PathResult<'ra> {
1595 self.r.cm().resolve_path_with_ribs(
1596 path,
1597 opt_ns,
1598 &self.parent_scope,
1599 Some(source),
1600 finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1601 Some(&self.ribs),
1602 None,
1603 None,
1604 Some(&self.diag_metadata),
1605 )
1606 }
1607
1608 fn with_rib<T>(
1628 &mut self,
1629 ns: Namespace,
1630 kind: RibKind<'ra>,
1631 work: impl FnOnce(&mut Self) -> T,
1632 ) -> T {
1633 self.ribs[ns].push(Rib::new(kind));
1634 let ret = work(self);
1635 self.ribs[ns].pop();
1636 ret
1637 }
1638
1639 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1640 let mut forward_ty_ban_rib =
1646 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1647 let mut forward_const_ban_rib =
1648 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1649 for param in params.iter() {
1650 match param.kind {
1651 GenericParamKind::Type { .. } => {
1652 forward_ty_ban_rib
1653 .bindings
1654 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1655 }
1656 GenericParamKind::Const { .. } => {
1657 forward_const_ban_rib
1658 .bindings
1659 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1660 }
1661 GenericParamKind::Lifetime => {}
1662 }
1663 }
1664
1665 if add_self_upper {
1675 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1677 }
1678
1679 let mut forward_ty_ban_rib_const_param_ty = Rib {
1682 bindings: forward_ty_ban_rib.bindings.clone(),
1683 patterns_with_skipped_bindings: Default::default(),
1684 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1685 };
1686 let mut forward_const_ban_rib_const_param_ty = Rib {
1687 bindings: forward_const_ban_rib.bindings.clone(),
1688 patterns_with_skipped_bindings: Default::default(),
1689 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1690 };
1691 if !self.r.features.generic_const_parameter_types() {
1694 forward_ty_ban_rib_const_param_ty.bindings.clear();
1695 forward_const_ban_rib_const_param_ty.bindings.clear();
1696 }
1697
1698 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1699 for param in params {
1700 match param.kind {
1701 GenericParamKind::Lifetime => {
1702 for bound in ¶m.bounds {
1703 this.visit_param_bound(bound, BoundKind::Bound);
1704 }
1705 }
1706 GenericParamKind::Type { ref default } => {
1707 for bound in ¶m.bounds {
1708 this.visit_param_bound(bound, BoundKind::Bound);
1709 }
1710
1711 if let Some(ty) = default {
1712 this.ribs[TypeNS].push(forward_ty_ban_rib);
1713 this.ribs[ValueNS].push(forward_const_ban_rib);
1714 this.visit_ty(ty);
1715 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1716 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1717 }
1718
1719 let i = &Ident::with_dummy_span(param.ident.name);
1721 forward_ty_ban_rib.bindings.swap_remove(i);
1722 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1723 }
1724 GenericParamKind::Const { ref ty, span: _, ref default } => {
1725 if !param.bounds.is_empty() {
::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1727
1728 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1729 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1730 if this.r.features.generic_const_parameter_types() {
1731 this.visit_ty(ty)
1732 } else {
1733 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1734 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1735 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1736 this.visit_ty(ty)
1737 });
1738 this.ribs[TypeNS].pop().unwrap();
1739 this.ribs[ValueNS].pop().unwrap();
1740 }
1741 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1742 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1743
1744 if let Some(expr) = default {
1745 this.ribs[TypeNS].push(forward_ty_ban_rib);
1746 this.ribs[ValueNS].push(forward_const_ban_rib);
1747 this.resolve_anon_const(
1748 expr,
1749 AnonConstKind::ConstArg(IsRepeatExpr::No),
1750 );
1751 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1752 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1753 }
1754
1755 let i = &Ident::with_dummy_span(param.ident.name);
1757 forward_const_ban_rib.bindings.swap_remove(i);
1758 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1759 }
1760 }
1761 }
1762 })
1763 }
1764
1765 #[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_lifetime_rib",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1765u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
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(&kind)
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;
}
{
self.lifetime_ribs.push(LifetimeRib::new(kind));
let outer_elision_candidates =
self.lifetime_elision_candidates.take();
let ret = work(self);
self.lifetime_elision_candidates = outer_elision_candidates;
self.lifetime_ribs.pop();
ret
}
}
}#[instrument(level = "debug", skip(self, work))]
1766 fn with_lifetime_rib<T>(
1767 &mut self,
1768 kind: LifetimeRibKind,
1769 work: impl FnOnce(&mut Self) -> T,
1770 ) -> T {
1771 self.lifetime_ribs.push(LifetimeRib::new(kind));
1772 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1773 let ret = work(self);
1774 self.lifetime_elision_candidates = outer_elision_candidates;
1775 self.lifetime_ribs.pop();
1776 ret
1777 }
1778
1779 #[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("resolve_lifetime",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1779u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("lifetime")
}> =
::tracing::__macro_support::FieldName::new("lifetime");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_ctxt")
}> =
::tracing::__macro_support::FieldName::new("use_ctxt");
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(&lifetime)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_ctxt)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let ident = lifetime.ident;
if ident.name == kw::StaticLifetime {
self.record_lifetime_use(lifetime.id, LifetimeRes::Static,
LifetimeElisionCandidate::Ignore);
return;
}
if ident.name == kw::UnderscoreLifetime {
return self.resolve_anonymous_lifetime(lifetime, lifetime.id,
false);
}
let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
while let Some(rib) = lifetime_rib_iter.next() {
let normalized_ident = ident.normalize_to_macros_2_0();
if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
self.record_lifetime_use(lifetime.id, res,
LifetimeElisionCandidate::Ignore);
if let LifetimeRes::Param { param, binder } = res {
match self.lifetime_uses.entry(param) {
Entry::Vacant(v) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1805",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1805u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("First use of {0:?} at {1:?}",
res, ident.span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let use_set =
self.lifetime_ribs.iter().rev().find_map(|rib|
match rib.kind {
LifetimeRibKind::Item |
LifetimeRibKind::AnonymousReportError |
LifetimeRibKind::ElisionFailure =>
Some(LifetimeUseSet::Many),
LifetimeRibKind::AnonymousCreateParameter {
binder: anon_binder, .. } =>
Some(if binder == anon_binder {
LifetimeUseSet::One { use_span: ident.span, use_ctxt }
} else { LifetimeUseSet::Many }),
LifetimeRibKind::Elided { res: r, error_in_path } => {
Some(if res == r && !error_in_path {
LifetimeUseSet::One { use_span: ident.span, use_ctxt }
} else { LifetimeUseSet::Many })
}
LifetimeRibKind::Generics { .. } |
LifetimeRibKind::ConstParamTy => None,
LifetimeRibKind::ConcreteAnonConst(_) => {
::rustc_middle::util::bug::span_bug_fmt(ident.span,
format_args!("unexpected rib kind: {0:?}", rib.kind))
}
LifetimeRibKind::ImplTrait => {
if self.r.features.anonymous_lifetime_in_impl_trait() {
None
} else { Some(LifetimeUseSet::Many) }
}
}).unwrap_or(LifetimeUseSet::Many);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1850",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1850u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_ctxt")
}> =
::tracing::__macro_support::FieldName::new("use_ctxt");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_set")
}> =
::tracing::__macro_support::FieldName::new("use_set");
NAME.as_str()
}], ::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(&::tracing::field::debug(&use_ctxt)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_set)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
v.insert(use_set);
}
Entry::Occupied(mut o) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1854",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1854u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("Many uses of {0:?} at {1:?}",
res, ident.span) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
*o.get_mut() = LifetimeUseSet::Many;
}
}
}
return;
}
match rib.kind {
LifetimeRibKind::Item => break,
LifetimeRibKind::ConstParamTy => {
let guar =
self.emit_non_static_lt_in_const_param_ty_error(lifetime);
self.record_lifetime_err(lifetime.id, guar);
return;
}
LifetimeRibKind::ConcreteAnonConst(cause) => {
let guar =
self.emit_forbidden_non_static_lifetime_error(cause,
lifetime);
self.record_lifetime_err(lifetime.id, guar);
return;
}
LifetimeRibKind::AnonymousCreateParameter { .. } |
LifetimeRibKind::Elided { .. } | LifetimeRibKind::Generics {
.. } | LifetimeRibKind::ElisionFailure |
LifetimeRibKind::AnonymousReportError |
LifetimeRibKind::ImplTrait => {}
}
}
let normalized_ident = ident.normalize_to_macros_2_0();
let outer_res =
lifetime_rib_iter.find_map(|rib|
rib.bindings.get_key_value(&normalized_ident).map(|(&outer,
_)| outer));
let guar =
self.emit_undeclared_lifetime_error(lifetime, outer_res);
self.record_lifetime_err(lifetime.id, guar);
}
}
}#[instrument(level = "debug", skip(self))]
1780 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1781 let ident = lifetime.ident;
1782
1783 if ident.name == kw::StaticLifetime {
1784 self.record_lifetime_use(
1785 lifetime.id,
1786 LifetimeRes::Static,
1787 LifetimeElisionCandidate::Ignore,
1788 );
1789 return;
1790 }
1791
1792 if ident.name == kw::UnderscoreLifetime {
1793 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1794 }
1795
1796 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1797 while let Some(rib) = lifetime_rib_iter.next() {
1798 let normalized_ident = ident.normalize_to_macros_2_0();
1799 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1800 self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1801
1802 if let LifetimeRes::Param { param, binder } = res {
1803 match self.lifetime_uses.entry(param) {
1804 Entry::Vacant(v) => {
1805 debug!("First use of {:?} at {:?}", res, ident.span);
1806 let use_set = self
1807 .lifetime_ribs
1808 .iter()
1809 .rev()
1810 .find_map(|rib| match rib.kind {
1811 LifetimeRibKind::Item
1814 | LifetimeRibKind::AnonymousReportError
1815 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1816 LifetimeRibKind::AnonymousCreateParameter {
1819 binder: anon_binder,
1820 ..
1821 } => Some(if binder == anon_binder {
1822 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1823 } else {
1824 LifetimeUseSet::Many
1825 }),
1826 LifetimeRibKind::Elided { res: r, error_in_path } => {
1829 Some(if res == r && !error_in_path {
1830 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1831 } else {
1832 LifetimeUseSet::Many
1833 })
1834 }
1835 LifetimeRibKind::Generics { .. }
1836 | LifetimeRibKind::ConstParamTy => None,
1837 LifetimeRibKind::ConcreteAnonConst(_) => {
1838 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1839 }
1840
1841 LifetimeRibKind::ImplTrait => {
1842 if self.r.features.anonymous_lifetime_in_impl_trait() {
1843 None
1844 } else {
1845 Some(LifetimeUseSet::Many)
1846 }
1847 }
1848 })
1849 .unwrap_or(LifetimeUseSet::Many);
1850 debug!(?use_ctxt, ?use_set);
1851 v.insert(use_set);
1852 }
1853 Entry::Occupied(mut o) => {
1854 debug!("Many uses of {:?} at {:?}", res, ident.span);
1855 *o.get_mut() = LifetimeUseSet::Many;
1856 }
1857 }
1858 }
1859 return;
1860 }
1861
1862 match rib.kind {
1863 LifetimeRibKind::Item => break,
1864 LifetimeRibKind::ConstParamTy => {
1865 let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1866 self.record_lifetime_err(lifetime.id, guar);
1867 return;
1868 }
1869 LifetimeRibKind::ConcreteAnonConst(cause) => {
1870 let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1871 self.record_lifetime_err(lifetime.id, guar);
1872 return;
1873 }
1874 LifetimeRibKind::AnonymousCreateParameter { .. }
1875 | LifetimeRibKind::Elided { .. }
1876 | LifetimeRibKind::Generics { .. }
1877 | LifetimeRibKind::ElisionFailure
1878 | LifetimeRibKind::AnonymousReportError
1879 | LifetimeRibKind::ImplTrait => {}
1880 }
1881 }
1882
1883 let normalized_ident = ident.normalize_to_macros_2_0();
1884 let outer_res = lifetime_rib_iter
1885 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1886
1887 let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1888 self.record_lifetime_err(lifetime.id, guar);
1889 }
1890
1891 #[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("resolve_anonymous_lifetime",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1891u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("lifetime")
}> =
::tracing::__macro_support::FieldName::new("lifetime");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id_for_lint")
}> =
::tracing::__macro_support::FieldName::new("id_for_lint");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("elided")
}> =
::tracing::__macro_support::FieldName::new("elided");
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(&lifetime)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id_for_lint)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&elided 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: () = loop {};
return __tracing_attr_fake_return;
}
{
if true {
{
match (&lifetime.ident.name, &kw::UnderscoreLifetime) {
(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);
}
}
}
};
};
let kind =
if elided {
MissingLifetimeKind::Ampersand
} else { MissingLifetimeKind::Underscore };
let missing_lifetime =
MissingLifetime {
id: lifetime.id,
span: lifetime.ident.span,
kind,
count: 1,
id_for_lint,
};
let elision_candidate =
LifetimeElisionCandidate::Missing(missing_lifetime);
for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:1911",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1911u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rib.kind")
}> =
::tracing::__macro_support::FieldName::new("rib.kind");
NAME.as_str()
}], ::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(&::tracing::field::debug(&rib.kind)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
match rib.kind {
LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
{
let res =
self.create_fresh_lifetime(lifetime.ident, binder, kind);
self.record_lifetime_use(lifetime.id, res,
elision_candidate);
return;
}
LifetimeRibKind::AnonymousReportError => {
let guar =
if elided {
let suggestion =
if self.diag_metadata.in_assoc_ty_binding {
None
} else {
self.lifetime_ribs[i..].iter().rev().find_map(|rib|
{
if let LifetimeRibKind::Generics {
span,
kind: LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound, .. } = rib.kind {
Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
lo: span.shrink_to_lo(),
hi: lifetime.ident.span.shrink_to_hi(),
})
} else { None }
})
};
if !self.in_func_body &&
let Some((module, _)) = &self.current_trait_ref &&
let Some(ty) = &self.diag_metadata.current_self_type &&
Some(true) == self.diag_metadata.in_non_gat_assoc_type &&
let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
module.kind {
if def_id_matches_path(self.r.tcx, trait_id,
&["core", "iter", "traits", "iterator", "Iterator"]) {
self.r.dcx().emit_err(crate::diagnostics::LendingIteratorReportError {
lifetime: lifetime.ident.span,
ty: ty.span,
})
} else {
let decl =
if !trait_id.is_local() &&
let Some(assoc) = self.diag_metadata.current_impl_item &&
let AssocItemKind::Type(_) = assoc.kind &&
let assocs = self.r.tcx.associated_items(trait_id) &&
let Some(ident) = assoc.kind.ident() &&
let Some(assoc) =
assocs.find_by_ident_and_kind(self.r.tcx, ident,
AssocTag::Type, trait_id) {
let mut decl: MultiSpan =
self.r.tcx.def_span(assoc.def_id).into();
decl.push_span_label(self.r.tcx.def_span(trait_id),
String::new());
decl
} else { DUMMY_SP.into() };
let mut err =
self.r.dcx().create_err(crate::diagnostics::AnonymousLifetimeNonGatReportError {
lifetime: lifetime.ident.span,
decl,
});
self.point_at_impl_lifetimes(&mut err, i,
lifetime.ident.span);
err.emit()
}
} else if self.diag_metadata.in_assoc_ty_binding {
let mut err =
self.r.dcx().create_err(crate::diagnostics::ElidedAnonymousLifetimeReportError {
span: lifetime.ident.span,
suggestion,
});
self.suggest_introducing_lifetime_for_assoc_ty_binding(&mut err,
lifetime.ident.span);
err.emit()
} else {
self.r.dcx().emit_err(crate::diagnostics::ElidedAnonymousLifetimeReportError {
span: lifetime.ident.span,
suggestion,
})
}
} else {
self.r.dcx().emit_err(crate::diagnostics::ExplicitAnonymousLifetimeReportError {
span: lifetime.ident.span,
})
};
self.record_lifetime_err(lifetime.id, guar);
return;
}
LifetimeRibKind::Elided { res, .. } => {
self.record_lifetime_use(lifetime.id, res,
elision_candidate);
return;
}
LifetimeRibKind::ElisionFailure => {
self.diag_metadata.current_elision_failures.push((missing_lifetime,
Either::Left(lifetime.id)));
return;
}
LifetimeRibKind::Item => break,
LifetimeRibKind::Generics { .. } |
LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
=> {}
LifetimeRibKind::ConcreteAnonConst(_) => {
::rustc_middle::util::bug::span_bug_fmt(lifetime.ident.span,
format_args!("unexpected rib kind: {0:?}", rib.kind))
}
}
}
let guar =
self.report_missing_lifetime_specifiers([&missing_lifetime],
None);
self.record_lifetime_err(lifetime.id, guar);
}
}
}#[instrument(level = "debug", skip(self))]
1892 fn resolve_anonymous_lifetime(
1893 &mut self,
1894 lifetime: &Lifetime,
1895 id_for_lint: NodeId,
1896 elided: bool,
1897 ) {
1898 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1899
1900 let kind =
1901 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1902 let missing_lifetime = MissingLifetime {
1903 id: lifetime.id,
1904 span: lifetime.ident.span,
1905 kind,
1906 count: 1,
1907 id_for_lint,
1908 };
1909 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1910 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1911 debug!(?rib.kind);
1912 match rib.kind {
1913 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1914 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1915 self.record_lifetime_use(lifetime.id, res, elision_candidate);
1916 return;
1917 }
1918 LifetimeRibKind::AnonymousReportError => {
1919 let guar = if elided {
1920 let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1921 None
1927 } else {
1928 self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1929 if let LifetimeRibKind::Generics {
1933 span,
1934 kind:
1935 LifetimeBinderKind::PolyTrait
1936 | LifetimeBinderKind::WhereBound,
1937 ..
1938 } = rib.kind
1939 {
1940 Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1941 lo: span.shrink_to_lo(),
1942 hi: lifetime.ident.span.shrink_to_hi(),
1943 })
1944 } else {
1945 None
1946 }
1947 })
1948 };
1949 if !self.in_func_body
1952 && let Some((module, _)) = &self.current_trait_ref
1953 && let Some(ty) = &self.diag_metadata.current_self_type
1954 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1955 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1956 module.kind
1957 {
1958 if def_id_matches_path(
1959 self.r.tcx,
1960 trait_id,
1961 &["core", "iter", "traits", "iterator", "Iterator"],
1962 ) {
1963 self.r.dcx().emit_err(
1964 crate::diagnostics::LendingIteratorReportError {
1965 lifetime: lifetime.ident.span,
1966 ty: ty.span,
1967 },
1968 )
1969 } else {
1970 let decl = if !trait_id.is_local()
1971 && let Some(assoc) = self.diag_metadata.current_impl_item
1972 && let AssocItemKind::Type(_) = assoc.kind
1973 && let assocs = self.r.tcx.associated_items(trait_id)
1974 && let Some(ident) = assoc.kind.ident()
1975 && let Some(assoc) = assocs.find_by_ident_and_kind(
1976 self.r.tcx,
1977 ident,
1978 AssocTag::Type,
1979 trait_id,
1980 ) {
1981 let mut decl: MultiSpan =
1982 self.r.tcx.def_span(assoc.def_id).into();
1983 decl.push_span_label(
1984 self.r.tcx.def_span(trait_id),
1985 String::new(),
1986 );
1987 decl
1988 } else {
1989 DUMMY_SP.into()
1990 };
1991 let mut err = self.r.dcx().create_err(
1992 crate::diagnostics::AnonymousLifetimeNonGatReportError {
1993 lifetime: lifetime.ident.span,
1994 decl,
1995 },
1996 );
1997 self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1998 err.emit()
1999 }
2000 } else if self.diag_metadata.in_assoc_ty_binding {
2001 let mut err = self.r.dcx().create_err(
2006 crate::diagnostics::ElidedAnonymousLifetimeReportError {
2007 span: lifetime.ident.span,
2008 suggestion,
2009 },
2010 );
2011 self.suggest_introducing_lifetime_for_assoc_ty_binding(
2012 &mut err,
2013 lifetime.ident.span,
2014 );
2015 err.emit()
2016 } else {
2017 self.r.dcx().emit_err(
2018 crate::diagnostics::ElidedAnonymousLifetimeReportError {
2019 span: lifetime.ident.span,
2020 suggestion,
2021 },
2022 )
2023 }
2024 } else {
2025 self.r.dcx().emit_err(
2026 crate::diagnostics::ExplicitAnonymousLifetimeReportError {
2027 span: lifetime.ident.span,
2028 },
2029 )
2030 };
2031 self.record_lifetime_err(lifetime.id, guar);
2032 return;
2033 }
2034 LifetimeRibKind::Elided { res, .. } => {
2035 self.record_lifetime_use(lifetime.id, res, elision_candidate);
2036 return;
2037 }
2038 LifetimeRibKind::ElisionFailure => {
2039 self.diag_metadata
2040 .current_elision_failures
2041 .push((missing_lifetime, Either::Left(lifetime.id)));
2042 return;
2043 }
2044 LifetimeRibKind::Item => break,
2045 LifetimeRibKind::Generics { .. }
2046 | LifetimeRibKind::ConstParamTy
2047 | LifetimeRibKind::ImplTrait => {}
2048 LifetimeRibKind::ConcreteAnonConst(_) => {
2049 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2051 }
2052 }
2053 }
2054 let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2055 self.record_lifetime_err(lifetime.id, guar);
2056 }
2057
2058 fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2059 let Some((rib, span)) =
2060 self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2061 LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2062 Some((rib, span))
2063 }
2064 _ => None,
2065 })
2066 else {
2067 return;
2068 };
2069 if !rib.bindings.is_empty() {
2070 err.span_label(
2071 span,
2072 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there {0} named lifetime{1} specified on the impl block you could use",
if rib.bindings.len() == 1 { "is a" } else { "are" },
if rib.bindings.len() == 1 { "" } else { "s" }))
})format!(
2073 "there {} named lifetime{} specified on the impl block you could use",
2074 if rib.bindings.len() == 1 { "is a" } else { "are" },
2075 pluralize!(rib.bindings.len()),
2076 ),
2077 );
2078 if rib.bindings.len() == 1 {
2079 err.span_suggestion_verbose(
2080 lifetime.shrink_to_hi(),
2081 "consider using the lifetime from the impl block",
2082 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ",
rib.bindings.keys().next().unwrap()))
})format!("{} ", rib.bindings.keys().next().unwrap()),
2083 Applicability::MaybeIncorrect,
2084 );
2085 }
2086 } else {
2087 struct AnonRefFinder;
2088 impl<'ast> Visitor<'ast> for AnonRefFinder {
2089 type Result = ControlFlow<Span>;
2090
2091 fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2092 if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2093 return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2094 }
2095 visit::walk_ty(self, ty)
2096 }
2097
2098 fn visit_lifetime(
2099 &mut self,
2100 lt: &'ast ast::Lifetime,
2101 _cx: visit::LifetimeCtxt,
2102 ) -> Self::Result {
2103 if lt.ident.name == kw::UnderscoreLifetime {
2104 return ControlFlow::Break(lt.ident.span);
2105 }
2106 visit::walk_lifetime(self, lt)
2107 }
2108 }
2109
2110 if let Some(ty) = &self.diag_metadata.current_self_type
2111 && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2112 {
2113 err.multipart_suggestion(
2114 "add a lifetime to the impl block and use it in the self type and associated \
2115 type",
2116 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, "<'a>".to_string()), (sp, "'a ".to_string()),
(lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2117 (span, "<'a>".to_string()),
2118 (sp, "'a ".to_string()),
2119 (lifetime.shrink_to_hi(), "'a ".to_string()),
2120 ],
2121 Applicability::MaybeIncorrect,
2122 );
2123 } else if let Some(item) = &self.diag_metadata.current_item
2124 && let ItemKind::Impl(impl_) = &item.kind
2125 && let Some(of_trait) = &impl_.of_trait
2126 && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2127 {
2128 err.multipart_suggestion(
2129 "add a lifetime to the impl block and use it in the trait and associated type",
2130 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, "<'a>".to_string()), (sp, "'a".to_string()),
(lifetime.shrink_to_hi(), "'a ".to_string())]))vec![
2131 (span, "<'a>".to_string()),
2132 (sp, "'a".to_string()),
2133 (lifetime.shrink_to_hi(), "'a ".to_string()),
2134 ],
2135 Applicability::MaybeIncorrect,
2136 );
2137 } else {
2138 err.span_label(
2139 span,
2140 "you could add a lifetime on the impl block, if the trait or the self type \
2141 could have one",
2142 );
2143 }
2144 }
2145 }
2146
2147 #[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("resolve_elided_lifetime",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2147u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("anchor_id")
}> =
::tracing::__macro_support::FieldName::new("anchor_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
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(&anchor_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let id = self.r.next_node_id();
let lt =
Lifetime {
id,
ident: Ident::new(kw::UnderscoreLifetime, span),
};
self.record_lifetime_use(anchor_id,
LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
LifetimeElisionCandidate::Ignore);
self.resolve_anonymous_lifetime(<, anchor_id, true);
}
}
}#[instrument(level = "debug", skip(self))]
2148 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2149 let id = self.r.next_node_id();
2150 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2151
2152 self.record_lifetime_use(
2153 anchor_id,
2154 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2155 LifetimeElisionCandidate::Ignore,
2156 );
2157 self.resolve_anonymous_lifetime(<, anchor_id, true);
2158 }
2159
2160 #[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("create_fresh_lifetime",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2160u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ident")
}> =
::tracing::__macro_support::FieldName::new("ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("binder")
}> =
::tracing::__macro_support::FieldName::new("binder");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
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(&ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&binder)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
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: LifetimeRes = loop {};
return __tracing_attr_fake_return;
}
{
if true {
{
match (&ident.name, &kw::UnderscoreLifetime) {
(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);
}
}
}
};
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2168",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2168u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ident.span")
}> =
::tracing::__macro_support::FieldName::new("ident.span");
NAME.as_str()
}], ::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(&::tracing::field::debug(&ident.span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let param = self.r.next_node_id();
let res = LifetimeRes::Fresh { param, kind };
self.record_lifetime_def(param, res);
self.r.current_owner.extra_lifetime_params_map.entry(binder).or_insert_with(Vec::new).push((ident,
param, kind));
res
}
}
}#[instrument(level = "debug", skip(self))]
2161 fn create_fresh_lifetime(
2162 &mut self,
2163 ident: Ident,
2164 binder: NodeId,
2165 kind: MissingLifetimeKind,
2166 ) -> LifetimeRes {
2167 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2168 debug!(?ident.span);
2169
2170 let param = self.r.next_node_id();
2172 let res = LifetimeRes::Fresh { param, kind };
2173 self.record_lifetime_def(param, res);
2174
2175 self.r
2177 .current_owner
2178 .extra_lifetime_params_map
2179 .entry(binder)
2180 .or_insert_with(Vec::new)
2181 .push((ident, param, kind));
2182 res
2183 }
2184
2185 #[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("resolve_elided_lifetimes_in_path",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2185u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("partial_res")
}> =
::tracing::__macro_support::FieldName::new("partial_res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path_span")
}> =
::tracing::__macro_support::FieldName::new("path_span");
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(&partial_res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let proj_start = path.len() - partial_res.unresolved_segments();
for (i, segment) in path.iter().enumerate() {
if segment.has_lifetime_args { continue; }
let Some(segment_id) = segment.id else { continue; };
let type_def_id =
match partial_res.base_res() {
Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start =>
{
self.r.tcx.parent(def_id)
}
Res::Def(DefKind::Variant, def_id) if
i + 2 == proj_start && segment.has_generic_args => {
self.r.tcx.parent(def_id)
}
Res::Def(DefKind::Variant, def_id) if
i + 1 == proj_start &&
!i.checked_sub(1).is_some_and(|i| path[i].has_generic_args)
=> {
self.r.tcx.parent(def_id)
}
Res::Def(DefKind::Struct, def_id) |
Res::Def(DefKind::Union, def_id) |
Res::Def(DefKind::Enum, def_id) |
Res::Def(DefKind::TyAlias, def_id) |
Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => {
def_id
}
_ => continue,
};
let expected_lifetimes =
self.r.item_generics_num_lifetimes(type_def_id);
if expected_lifetimes == 0 { continue; }
let node_ids = self.r.next_node_ids(expected_lifetimes);
self.record_lifetime_use(segment_id,
LifetimeRes::ElidedAnchor {
start: node_ids.start,
end: node_ids.end,
}, LifetimeElisionCandidate::Ignore);
let inferred =
match source {
PathSource::Trait(..) | PathSource::TraitItem(..) |
PathSource::Type | PathSource::PreciseCapturingArg(..) |
PathSource::ReturnTypeNotation | PathSource::Macro |
PathSource::Module => false,
PathSource::Expr(..) | PathSource::Pat |
PathSource::Struct(_) | PathSource::TupleStruct(..) |
PathSource::DefineOpaques | PathSource::Delegation |
PathSource::ExternItemImpl => true,
};
if inferred {
for id in node_ids {
self.record_lifetime_use(id, LifetimeRes::Infer,
LifetimeElisionCandidate::Ignore);
}
continue;
}
let elided_lifetime_span =
if segment.has_generic_args {
segment.args_span.with_hi(segment.args_span.lo() +
BytePos(1))
} else {
segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
};
let ident =
Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
let kind =
if segment.has_generic_args {
MissingLifetimeKind::Comma
} else { MissingLifetimeKind::Brackets };
let missing_lifetime =
MissingLifetime {
id: node_ids.start,
id_for_lint: segment_id,
span: elided_lifetime_span,
kind,
count: expected_lifetimes,
};
let mut should_lint = true;
for rib in self.lifetime_ribs.iter().rev() {
match rib.kind {
LifetimeRibKind::AnonymousCreateParameter {
report_in_path: true, .. } | LifetimeRibKind::Elided {
error_in_path: true, .. } => {
let sess = self.r.tcx.sess;
let subdiag =
elided_lifetime_in_path_suggestion(sess.source_map(),
expected_lifetimes, path_span, !segment.has_generic_args,
elided_lifetime_span);
let guar =
self.r.dcx().emit_err(crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
span: path_span,
subdiag,
});
should_lint = false;
for id in node_ids { self.record_lifetime_err(id, guar); }
break;
}
LifetimeRibKind::AnonymousCreateParameter { binder, .. } =>
{
let mut candidate =
LifetimeElisionCandidate::Missing(missing_lifetime);
for id in node_ids {
let res = self.create_fresh_lifetime(ident, binder, kind);
self.record_lifetime_use(id, res,
replace(&mut candidate, LifetimeElisionCandidate::Ignore));
}
break;
}
LifetimeRibKind::Elided { res, error_in_path: false } => {
let mut candidate =
LifetimeElisionCandidate::Missing(missing_lifetime);
for id in node_ids {
self.record_lifetime_use(id, res,
replace(&mut candidate, LifetimeElisionCandidate::Ignore));
}
break;
}
LifetimeRibKind::ElisionFailure => {
self.diag_metadata.current_elision_failures.push((missing_lifetime,
Either::Right(node_ids)));
break;
}
LifetimeRibKind::AnonymousReportError |
LifetimeRibKind::Item => {
let guar =
self.report_missing_lifetime_specifiers([&missing_lifetime],
None);
for id in node_ids { self.record_lifetime_err(id, guar); }
break;
}
LifetimeRibKind::Generics { .. } |
LifetimeRibKind::ConstParamTy | LifetimeRibKind::ImplTrait
=> {}
LifetimeRibKind::ConcreteAnonConst(_) => {
::rustc_middle::util::bug::span_bug_fmt(elided_lifetime_span,
format_args!("unexpected rib kind: {0:?}", rib.kind))
}
}
}
if should_lint {
let include_angle_bracket = !segment.has_generic_args;
self.r.lint_buffer.dyn_buffer_lint_any(lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
segment_id, elided_lifetime_span,
move |dcx, level, sess|
{
let source_map =
sess.downcast_ref::<rustc_session::Session>().expect("expected a `Session`").source_map();
crate::diagnostics::ElidedLifetimesInPaths {
subdiag: elided_lifetime_in_path_suggestion(source_map,
expected_lifetimes, path_span, include_angle_bracket,
elided_lifetime_span),
}.into_diag(dcx, level)
});
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2186 fn resolve_elided_lifetimes_in_path(
2187 &mut self,
2188 partial_res: PartialRes,
2189 path: &[Segment],
2190 source: PathSource<'_, 'ast, 'ra>,
2191 path_span: Span,
2192 ) {
2193 let proj_start = path.len() - partial_res.unresolved_segments();
2194 for (i, segment) in path.iter().enumerate() {
2195 if segment.has_lifetime_args {
2196 continue;
2197 }
2198 let Some(segment_id) = segment.id else {
2199 continue;
2200 };
2201
2202 let type_def_id = match partial_res.base_res() {
2205 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2206 self.r.tcx.parent(def_id)
2207 }
2208 Res::Def(DefKind::Variant, def_id)
2209 if i + 2 == proj_start && segment.has_generic_args =>
2210 {
2211 self.r.tcx.parent(def_id)
2212 }
2213 Res::Def(DefKind::Variant, def_id)
2214 if i + 1 == proj_start
2215 && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2216 {
2217 self.r.tcx.parent(def_id)
2218 }
2219 Res::Def(DefKind::Struct, def_id)
2220 | Res::Def(DefKind::Union, def_id)
2221 | Res::Def(DefKind::Enum, def_id)
2222 | Res::Def(DefKind::TyAlias, def_id)
2223 | Res::Def(DefKind::Trait, def_id)
2224 if i + 1 == proj_start =>
2225 {
2226 def_id
2227 }
2228 _ => continue,
2229 };
2230
2231 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2232 if expected_lifetimes == 0 {
2233 continue;
2234 }
2235
2236 let node_ids = self.r.next_node_ids(expected_lifetimes);
2237 self.record_lifetime_use(
2238 segment_id,
2239 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2240 LifetimeElisionCandidate::Ignore,
2241 );
2242
2243 let inferred = match source {
2244 PathSource::Trait(..)
2245 | PathSource::TraitItem(..)
2246 | PathSource::Type
2247 | PathSource::PreciseCapturingArg(..)
2248 | PathSource::ReturnTypeNotation
2249 | PathSource::Macro
2250 | PathSource::Module => false,
2251 PathSource::Expr(..)
2252 | PathSource::Pat
2253 | PathSource::Struct(_)
2254 | PathSource::TupleStruct(..)
2255 | PathSource::DefineOpaques
2256 | PathSource::Delegation
2257 | PathSource::ExternItemImpl => true,
2258 };
2259 if inferred {
2260 for id in node_ids {
2263 self.record_lifetime_use(
2264 id,
2265 LifetimeRes::Infer,
2266 LifetimeElisionCandidate::Ignore,
2267 );
2268 }
2269 continue;
2270 }
2271
2272 let elided_lifetime_span = if segment.has_generic_args {
2273 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2275 } else {
2276 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2280 };
2281 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2282
2283 let kind = if segment.has_generic_args {
2284 MissingLifetimeKind::Comma
2285 } else {
2286 MissingLifetimeKind::Brackets
2287 };
2288 let missing_lifetime = MissingLifetime {
2289 id: node_ids.start,
2290 id_for_lint: segment_id,
2291 span: elided_lifetime_span,
2292 kind,
2293 count: expected_lifetimes,
2294 };
2295 let mut should_lint = true;
2296 for rib in self.lifetime_ribs.iter().rev() {
2297 match rib.kind {
2298 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2305 | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2306 let sess = self.r.tcx.sess;
2307 let subdiag = elided_lifetime_in_path_suggestion(
2308 sess.source_map(),
2309 expected_lifetimes,
2310 path_span,
2311 !segment.has_generic_args,
2312 elided_lifetime_span,
2313 );
2314 let guar = self.r.dcx().emit_err(
2315 crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2316 span: path_span,
2317 subdiag,
2318 },
2319 );
2320 should_lint = false;
2321
2322 for id in node_ids {
2323 self.record_lifetime_err(id, guar);
2324 }
2325 break;
2326 }
2327 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2329 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2331 for id in node_ids {
2332 let res = self.create_fresh_lifetime(ident, binder, kind);
2333 self.record_lifetime_use(
2334 id,
2335 res,
2336 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2337 );
2338 }
2339 break;
2340 }
2341 LifetimeRibKind::Elided { res, error_in_path: false } => {
2342 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2343 for id in node_ids {
2344 self.record_lifetime_use(
2345 id,
2346 res,
2347 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2348 );
2349 }
2350 break;
2351 }
2352 LifetimeRibKind::ElisionFailure => {
2353 self.diag_metadata
2354 .current_elision_failures
2355 .push((missing_lifetime, Either::Right(node_ids)));
2356 break;
2357 }
2358 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2363 let guar =
2364 self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2365 for id in node_ids {
2366 self.record_lifetime_err(id, guar);
2367 }
2368 break;
2369 }
2370 LifetimeRibKind::Generics { .. }
2371 | LifetimeRibKind::ConstParamTy
2372 | LifetimeRibKind::ImplTrait => {}
2373 LifetimeRibKind::ConcreteAnonConst(_) => {
2374 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2376 }
2377 }
2378 }
2379
2380 if should_lint {
2381 let include_angle_bracket = !segment.has_generic_args;
2382 self.r.lint_buffer.dyn_buffer_lint_any(
2383 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2384 segment_id,
2385 elided_lifetime_span,
2386 move |dcx, level, sess| {
2387 let source_map = sess
2388 .downcast_ref::<rustc_session::Session>()
2389 .expect("expected a `Session`")
2390 .source_map();
2391 crate::diagnostics::ElidedLifetimesInPaths {
2392 subdiag: elided_lifetime_in_path_suggestion(
2393 source_map,
2394 expected_lifetimes,
2395 path_span,
2396 include_angle_bracket,
2397 elided_lifetime_span,
2398 ),
2399 }
2400 .into_diag(dcx, level)
2401 },
2402 );
2403 }
2404 }
2405 }
2406
2407 #[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("record_lifetime_use",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2408u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id")
}> =
::tracing::__macro_support::FieldName::new("id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("candidate")
}> =
::tracing::__macro_support::FieldName::new("candidate");
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(&id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
self.record_lifetime_def(id, res);
match res {
LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } |
LifetimeRes::Static { .. } => {
if let Some(ref mut candidates) =
self.lifetime_elision_candidates {
candidates.push((res, candidate));
}
}
LifetimeRes::Infer | LifetimeRes::Error(..) |
LifetimeRes::ElidedAnchor { .. } => {}
}
}
}
}#[instrument(level = "debug", skip(self))]
2409 fn record_lifetime_use(
2410 &mut self,
2411 id: NodeId,
2412 res: LifetimeRes,
2413 candidate: LifetimeElisionCandidate,
2414 ) {
2415 self.record_lifetime_def(id, res);
2416
2417 match res {
2418 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2419 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2420 candidates.push((res, candidate));
2421 }
2422 }
2423 LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2424 }
2425 }
2426
2427 #[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("record_lifetime_err",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2429u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id")
}> =
::tracing::__macro_support::FieldName::new("id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("guar")
}> =
::tracing::__macro_support::FieldName::new("guar");
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(&id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&guar)
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: () = loop {};
return __tracing_attr_fake_return;
}
{ self.record_lifetime_def(id, LifetimeRes::Error(guar)); }
}
}#[instrument(level = "debug", skip(self))]
2430 fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2431 self.record_lifetime_def(id, LifetimeRes::Error(guar));
2432 }
2433
2434 #[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("record_lifetime_def",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2435u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("id")
}> =
::tracing::__macro_support::FieldName::new("id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
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(&id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(prev_res) =
self.r.current_owner.lifetimes_res_map.insert(id, res) {
{
::core::panicking::panic_fmt(format_args!("lifetime parameter {0:?} resolved multiple times ({1:?} before, {2:?} now)",
id, prev_res, res));
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2436 fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2437 if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2438 panic!(
2439 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2440 )
2441 }
2442 }
2443
2444 #[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("resolve_fn_signature",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2445u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_id")
}> =
::tracing::__macro_support::FieldName::new("fn_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("has_self")
}> =
::tracing::__macro_support::FieldName::new("has_self");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("output_ty")
}> =
::tracing::__macro_support::FieldName::new("output_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("report_elided_lifetimes_in_path")
}> =
::tracing::__macro_support::FieldName::new("report_elided_lifetimes_in_path");
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(&fn_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&has_self as
&dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&output_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&report_elided_lifetimes_in_path
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let rib =
LifetimeRibKind::AnonymousCreateParameter {
binder: fn_id,
report_in_path: report_elided_lifetimes_in_path,
};
self.with_lifetime_rib(rib,
|this|
{
let elision_lifetime =
this.resolve_fn_params(has_self, inputs);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2461",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2461u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("elision_lifetime")
}> =
::tracing::__macro_support::FieldName::new("elision_lifetime");
NAME.as_str()
}], ::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(&::tracing::field::debug(&elision_lifetime)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let outer_failures =
take(&mut this.diag_metadata.current_elision_failures);
let output_rib =
if let Ok(res) = elision_lifetime.as_ref() {
if fn_id == this.r.current_owner.id {
this.r.current_owner.lifetime_elision_allowed = true;
}
LifetimeRibKind::elided(*res)
} else { LifetimeRibKind::ElisionFailure };
this.with_lifetime_rib(output_rib,
|this| visit::walk_fn_ret_ty(this, output_ty));
let elision_failures =
replace(&mut this.diag_metadata.current_elision_failures,
outer_failures);
if !elision_failures.is_empty() {
let Err(failure_info) =
elision_lifetime else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let guar =
this.report_missing_lifetime_specifiers(elision_failures.iter().map(|(missing_lifetime,
..)| missing_lifetime), Some(failure_info));
let mut record_res =
|lifetime| this.record_lifetime_err(lifetime, guar);
for (_, nodes) in elision_failures {
match nodes {
Either::Left(node_id) => record_res(node_id),
Either::Right(node_ids) => {
for lifetime in node_ids { record_res(lifetime) }
}
}
}
}
});
}
}
}#[instrument(level = "debug", skip(self, inputs))]
2446 fn resolve_fn_signature(
2447 &mut self,
2448 fn_id: NodeId,
2449 has_self: bool,
2450 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2451 output_ty: &'ast FnRetTy,
2452 report_elided_lifetimes_in_path: bool,
2453 ) {
2454 let rib = LifetimeRibKind::AnonymousCreateParameter {
2455 binder: fn_id,
2456 report_in_path: report_elided_lifetimes_in_path,
2457 };
2458 self.with_lifetime_rib(rib, |this| {
2459 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2461 debug!(?elision_lifetime);
2462
2463 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2464 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2465 if fn_id == this.r.current_owner.id {
2466 this.r.current_owner.lifetime_elision_allowed = true;
2467 }
2468 LifetimeRibKind::elided(*res)
2469 } else {
2470 LifetimeRibKind::ElisionFailure
2471 };
2472 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2473 let elision_failures =
2474 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2475 if !elision_failures.is_empty() {
2476 let Err(failure_info) = elision_lifetime else { bug!() };
2477 let guar = this.report_missing_lifetime_specifiers(
2478 elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2479 Some(failure_info),
2480 );
2481 let mut record_res = |lifetime| this.record_lifetime_err(lifetime, guar);
2482 for (_, nodes) in elision_failures {
2483 match nodes {
2484 Either::Left(node_id) => record_res(node_id),
2485 Either::Right(node_ids) => {
2486 for lifetime in node_ids {
2487 record_res(lifetime)
2488 }
2489 }
2490 }
2491 }
2492 }
2493 });
2494 }
2495
2496 fn resolve_fn_params(
2500 &mut self,
2501 has_self: bool,
2502 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2503 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2504 enum Elision {
2505 None,
2507 Self_(LifetimeRes),
2509 Param(LifetimeRes),
2511 Err,
2513 }
2514
2515 let outer_candidates = self.lifetime_elision_candidates.take();
2517
2518 let mut elision_lifetime = Elision::None;
2520 let mut parameter_info = Vec::new();
2522 let mut all_candidates = Vec::new();
2523
2524 let mut bindings = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push((PatBoundCtx::Product, Default::default()));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(PatBoundCtx::Product, Default::default())])))
}
}smallvec![(PatBoundCtx::Product, Default::default())];
2526 for (pat, _) in inputs.clone() {
2527 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2527",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2527u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("resolving bindings in pat = {0:?}",
pat) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolving bindings in pat = {pat:?}");
2528 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
2529 if let Some(pat) = pat {
2530 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2531 }
2532 });
2533 }
2534 self.apply_pattern_bindings(bindings);
2535
2536 for (index, (pat, ty)) in inputs.enumerate() {
2537 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2537",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2537u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("resolving type for pat = {0:?}, ty = {1:?}",
pat, ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolving type for pat = {pat:?}, ty = {ty:?}");
2538 if true {
{
match self.lifetime_elision_candidates {
None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val, "None",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.lifetime_elision_candidates, None);
2540 self.lifetime_elision_candidates = Some(Default::default());
2541 self.visit_ty(ty);
2542 let local_candidates = self.lifetime_elision_candidates.take();
2543
2544 if let Some(candidates) = local_candidates {
2545 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2546 let lifetime_count = distinct.len();
2547 if lifetime_count != 0 {
2548 parameter_info.push(ElisionFnParameter {
2549 index,
2550 ident: if let Some(pat) = pat
2551 && let PatKind::Ident(_, ident, _) = pat.kind
2552 {
2553 Some(ident)
2554 } else {
2555 None
2556 },
2557 lifetime_count,
2558 span: ty.span,
2559 });
2560 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2561 match candidate {
2562 LifetimeElisionCandidate::Ignore => None,
2563 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2564 }
2565 }));
2566 }
2567 if !distinct.is_empty() {
2568 match elision_lifetime {
2569 Elision::None => {
2571 if let Some(res) = distinct.get_only() {
2572 elision_lifetime = Elision::Param(*res)
2574 } else {
2575 elision_lifetime = Elision::Err;
2577 }
2578 }
2579 Elision::Param(_) => elision_lifetime = Elision::Err,
2581 Elision::Self_(_) | Elision::Err => {}
2583 }
2584 }
2585 }
2586
2587 if index == 0 && has_self {
2589 let self_lifetime = self.find_lifetime_for_self(ty);
2590 elision_lifetime = match self_lifetime {
2591 Set1::One(lifetime) => Elision::Self_(lifetime),
2593 Set1::Many => Elision::Err,
2598 Set1::Empty => Elision::None,
2601 }
2602 }
2603 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2603",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2603u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving function / closure) recorded parameter")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving function / closure) recorded parameter");
2604 }
2605
2606 if true {
{
match self.lifetime_elision_candidates {
None => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val, "None",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(self.lifetime_elision_candidates, None);
2608 self.lifetime_elision_candidates = outer_candidates;
2609
2610 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2611 return Ok(res);
2612 }
2613
2614 Err((all_candidates, parameter_info))
2616 }
2617
2618 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2620 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2624 r: &'a Resolver<'ra, 'tcx>,
2625 impl_self: Option<Res>,
2626 lifetime: Set1<LifetimeRes>,
2627 }
2628
2629 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2630 fn visit_ty(&mut self, ty: &'ra Ty) {
2631 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2631",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2631u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("FindReferenceVisitor considering ty={0:?}",
ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("FindReferenceVisitor considering ty={:?}", ty);
2632 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2633 let mut visitor =
2635 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2636 visitor.visit_ty(ty);
2637 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2637",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2637u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("FindReferenceVisitor: SelfVisitor self_found={0:?}",
visitor.self_found) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("FindReferenceVisitor: SelfVisitor self_found={:?}", visitor.self_found);
2638 if visitor.self_found {
2639 let lt_id = if let Some(lt) = lt {
2640 lt.id
2641 } else {
2642 let res = self.r.current_owner.lifetimes_res_map[&ty.id];
2643 let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2644 start
2645 };
2646 let lt_res = self.r.current_owner.lifetimes_res_map[<_id];
2647 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2647",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2647u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("FindReferenceVisitor inserting res={0:?}",
lt_res) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("FindReferenceVisitor inserting res={:?}", lt_res);
2648 self.lifetime.insert(lt_res);
2649 }
2650 }
2651 visit::walk_ty(self, ty)
2652 }
2653
2654 fn visit_expr(&mut self, _: &'ra Expr) {}
2657 }
2658
2659 struct SelfVisitor<'a, 'ra, 'tcx> {
2662 r: &'a Resolver<'ra, 'tcx>,
2663 impl_self: Option<Res>,
2664 self_found: bool,
2665 }
2666
2667 impl SelfVisitor<'_, '_, '_> {
2668 fn is_self_ty(&self, ty: &Ty) -> bool {
2670 match ty.kind {
2671 TyKind::ImplicitSelf => true,
2672 TyKind::Path(None, _) => {
2673 let path_res = self.r.partial_res_map[&ty.id].full_res();
2674 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2675 return true;
2676 }
2677 self.impl_self.is_some() && path_res == self.impl_self
2678 }
2679 _ => false,
2680 }
2681 }
2682 }
2683
2684 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2685 fn visit_ty(&mut self, ty: &'ra Ty) {
2686 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2686",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2686u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("SelfVisitor considering ty={0:?}",
ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("SelfVisitor considering ty={:?}", ty);
2687 if self.is_self_ty(ty) {
2688 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2688",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2688u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("SelfVisitor found Self")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("SelfVisitor found Self");
2689 self.self_found = true;
2690 }
2691 visit::walk_ty(self, ty)
2692 }
2693
2694 fn visit_expr(&mut self, _: &'ra Expr) {}
2697 }
2698
2699 let impl_self = self
2700 .diag_metadata
2701 .current_self_type
2702 .and_then(|ty| {
2703 if let TyKind::Path(None, _) = ty.kind {
2704 self.r.partial_res_map.get(&ty.id)
2705 } else {
2706 None
2707 }
2708 })
2709 .and_then(|res| res.full_res())
2710 .filter(|res| {
2711 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
Res::PrimTy(_) => true,
_ => false,
}matches!(
2715 res,
2716 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2717 )
2718 });
2719 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2720 visitor.visit_ty(ty);
2721 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2721",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2721u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::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!("FindReferenceVisitor found={0:?}",
visitor.lifetime) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2722 visitor.lifetime
2723 }
2724
2725 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2728 let mut suggestion = None;
2729
2730 for i in (0..self.label_ribs.len()).rev() {
2731 let rib = &self.label_ribs[i];
2732
2733 if let RibKind::MacroDefinition(def) = rib.kind
2734 && def == self.r.macro_def(label.span.ctxt())
2737 {
2738 label.span.remove_mark();
2739 }
2740
2741 let ident = label.normalize_to_macro_rules();
2742 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2743 let definition_span = ident.span;
2744 return if self.is_label_valid_from_rib(i) {
2745 Ok((*id, definition_span))
2746 } else {
2747 Err(ResolutionError::UnreachableLabel {
2748 name: label.name,
2749 definition_span,
2750 suggestion,
2751 })
2752 };
2753 }
2754
2755 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2758 }
2759
2760 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2761 }
2762
2763 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2765 let ribs = &self.label_ribs[rib_index + 1..];
2766 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2767 }
2768
2769 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2770 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2770",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2770u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_adt")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_adt");
2771 let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2772 self.with_current_self_item(item, |this| {
2773 this.with_generic_param_rib(
2774 &generics.params,
2775 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2776 item.id,
2777 LifetimeBinderKind::Item,
2778 generics.span,
2779 |this| {
2780 let item_def_id = this.r.current_owner.def_id.to_def_id();
2781 this.with_self_rib(
2782 Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2783 |this| {
2784 visit::walk_item(this, item);
2785 },
2786 );
2787 },
2788 );
2789 });
2790 }
2791
2792 fn future_proof_import(&mut self, use_tree: &UseTree) {
2793 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2794 let ident = segment.ident;
2795 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2796 return;
2797 }
2798
2799 let nss = match use_tree.kind {
2800 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2801 _ => &[TypeNS],
2802 };
2803 let report_error = |this: &Self, ns| {
2804 if this.should_report_errs() {
2805 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2806 this.r.dcx().emit_err(crate::diagnostics::ImportsCannotReferTo {
2807 span: ident.span,
2808 what,
2809 });
2810 }
2811 };
2812
2813 for &ns in nss {
2814 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2815 Some(LateDecl::RibDef(..)) => {
2816 report_error(self, ns);
2817 }
2818 Some(LateDecl::Decl(binding)) => {
2819 if let Some(LateDecl::RibDef(..)) =
2820 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2821 {
2822 report_error(self, ns);
2823 }
2824 }
2825 None => {}
2826 }
2827 }
2828 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2829 for (use_tree, _) in items {
2830 self.future_proof_import(use_tree);
2831 }
2832 }
2833 }
2834
2835 fn resolve_item(&mut self, item: &'ast Item) {
2836 let mod_inner_docs =
2837 #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Mod(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2838 if !mod_inner_docs && !#[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Impl(..) | ItemKind::Use(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
2839 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2840 }
2841
2842 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2842",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2842u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving item) resolving {0:?} ({1:?})",
item.kind.ident(), item.kind) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
2843
2844 let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2845 match &item.kind {
2846 ItemKind::TyAlias(TyAlias { generics, .. }) => {
2847 self.with_generic_param_rib(
2848 &generics.params,
2849 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2850 item.id,
2851 LifetimeBinderKind::Item,
2852 generics.span,
2853 |this| visit::walk_item(this, item),
2854 );
2855 }
2856
2857 ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2858 self.with_generic_param_rib(
2859 &generics.params,
2860 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2861 item.id,
2862 LifetimeBinderKind::Function,
2863 generics.span,
2864 |this| visit::walk_item(this, item),
2865 );
2866 self.resolve_define_opaques(define_opaque);
2867 }
2868
2869 ItemKind::Enum(_, generics, _)
2870 | ItemKind::Struct(_, generics, _)
2871 | ItemKind::Union(_, generics, _) => {
2872 self.resolve_adt(item, generics);
2873 }
2874
2875 ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2876 self.diag_metadata.current_impl_items = Some(impl_items);
2877 self.resolve_implementation(
2878 &item.attrs,
2879 generics,
2880 of_trait.as_deref(),
2881 self_ty,
2882 item.id,
2883 impl_items,
2884 );
2885 self.diag_metadata.current_impl_items = None;
2886 }
2887
2888 ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2889 self.resolve_restriction_path(
2891 &impl_restriction.kind,
2892 ResolvingRestrictionKind::Impl,
2893 );
2894
2895 self.with_generic_param_rib(
2897 &generics.params,
2898 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2899 item.id,
2900 LifetimeBinderKind::Item,
2901 generics.span,
2902 |this| {
2903 let local_def_id = this.r.current_owner.def_id.to_def_id();
2904 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2905 this.visit_generics(generics);
2906 for elem in bounds {
match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_param_bound(elem,
BoundKind::SuperTraits)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2907 this.resolve_trait_items(items);
2908 });
2909 },
2910 );
2911 }
2912
2913 ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2914 self.with_generic_param_rib(
2916 &generics.params,
2917 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2918 item.id,
2919 LifetimeBinderKind::Item,
2920 generics.span,
2921 |this| {
2922 let local_def_id = this.r.current_owner.def_id.to_def_id();
2923 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2924 this.visit_generics(generics);
2925 for elem in bounds {
match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_param_bound(elem,
BoundKind::Bound)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2926 });
2927 },
2928 );
2929 }
2930
2931 ItemKind::Mod(..) => {
2932 let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2933 let orig_module = replace(&mut self.parent_scope.module, module);
2934 self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2935 this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2936 if mod_inner_docs {
2937 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2938 }
2939 let old_macro_rules = this.parent_scope.macro_rules;
2940 visit::walk_item(this, item);
2941 if item.attrs.iter().all(|attr| {
2944 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2945 }) {
2946 this.parent_scope.macro_rules = old_macro_rules;
2947 }
2948 })
2949 });
2950 self.parent_scope.module = orig_module;
2951 }
2952
2953 ItemKind::Static(ast::StaticItem {
2954 ident, ty, expr, define_opaque, eii_impls, ..
2955 }) => {
2956 self.with_static_rib(def_kind, |this| {
2957 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| {
2958 this.visit_ty(ty);
2959 });
2960 if let Some(expr) = expr {
2961 this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2964 }
2965 });
2966 self.resolve_define_opaques(define_opaque);
2967 self.resolve_eii(&eii_impls);
2968 }
2969
2970 ItemKind::Const(ast::ConstItem {
2971 ident,
2972 generics,
2973 ty,
2974 rhs_kind,
2975 define_opaque,
2976 defaultness: _,
2977 }) => {
2978 self.with_generic_param_rib(
2979 &generics.params,
2980 RibKind::Item(
2981 if self.r.features.generic_const_items() {
2982 HasGenericParams::Yes(generics.span)
2983 } else {
2984 HasGenericParams::No
2985 },
2986 def_kind,
2987 ),
2988 item.id,
2989 LifetimeBinderKind::ConstItem,
2990 generics.span,
2991 |this| {
2992 this.visit_generics(generics);
2993
2994 this.with_lifetime_rib(
2995 LifetimeRibKind::elided(LifetimeRes::Static),
2996 |this: &mut LateResolutionVisitor<'a, 'ast, 'ra, 'tcx>| {
2997 if rhs_kind.is_type_const()
2998 && !this.r.features.generic_const_parameter_types()
2999 {
3000 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3001 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3002 this.with_lifetime_rib(
3003 LifetimeRibKind::ConstParamTy,
3004 |this| this.visit_ty(ty),
3005 )
3006 })
3007 });
3008 } else {
3009 this.visit_ty(ty);
3010 }
3011 },
3012 );
3013
3014 this.resolve_const_item_rhs(
3015 rhs_kind,
3016 Some((*ident, ConstantItemKind::Const)),
3017 );
3018 },
3019 );
3020 self.resolve_define_opaques(define_opaque);
3021 }
3022 ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
3023 .with_generic_param_rib(
3024 &[],
3025 RibKind::Item(HasGenericParams::No, def_kind),
3026 item.id,
3027 LifetimeBinderKind::ConstItem,
3028 DUMMY_SP,
3029 |this| {
3030 this.with_lifetime_rib(
3031 LifetimeRibKind::elided(LifetimeRes::Infer),
3032 |this| {
3033 this.with_constant_rib(
3034 IsRepeatExpr::No,
3035 ConstantHasGenerics::Yes,
3036 Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
3037 |this| this.resolve_labeled_block(None, block.id, block),
3038 )
3039 },
3040 );
3041 },
3042 ),
3043
3044 ItemKind::Use(use_tree) => {
3045 let maybe_exported = match use_tree.kind {
3046 UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3047 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3048 };
3049 self.resolve_doc_links(&item.attrs, maybe_exported);
3050
3051 self.future_proof_import(use_tree);
3052 }
3053
3054 ItemKind::MacroDef(_, macro_def) => {
3055 if macro_def.macro_rules {
3058 let def_id = self.r.current_owner.def_id;
3059 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3060 }
3061
3062 if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3063 ¯o_def.eii_declaration
3064 {
3065 self.smart_resolve_path(
3066 item.id,
3067 &None,
3068 extern_item_path,
3069 PathSource::ExternItemImpl,
3070 );
3071 }
3072 }
3073
3074 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3075 visit::walk_item(self, item);
3076 }
3077
3078 ItemKind::Delegation(delegation) => {
3079 let span = delegation.path.segments.last().unwrap().ident.span;
3080 self.with_generic_param_rib(
3081 &[],
3082 RibKind::Item(HasGenericParams::Yes(span), def_kind),
3083 item.id,
3084 LifetimeBinderKind::Function,
3085 span,
3086 |this| this.resolve_delegation(delegation, item.id, false),
3087 );
3088 }
3089
3090 ItemKind::ExternCrate(..) => {}
3091
3092 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3093 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3094 }
3095 }
3096 }
3097
3098 fn with_generic_param_rib<F>(
3099 &mut self,
3100 params: &[GenericParam],
3101 kind: RibKind<'ra>,
3102 binder: NodeId,
3103 generics_kind: LifetimeBinderKind,
3104 generics_span: Span,
3105 f: F,
3106 ) where
3107 F: FnOnce(&mut Self),
3108 {
3109 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3109",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3109u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("with_generic_param_rib")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("with_generic_param_rib");
3110 let lifetime_kind =
3111 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3112
3113 let mut function_type_rib = Rib::new(kind);
3114 let mut function_value_rib = Rib::new(kind);
3115 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3116
3117 if !params.is_empty() {
3119 let mut seen_bindings = FxHashMap::default();
3120 let mut seen_lifetimes = FxHashSet::default();
3122
3123 for ns in [ValueNS, TypeNS] {
3125 for parent_rib in self.ribs[ns].iter().rev() {
3126 if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
RibKind::Module(..) | RibKind::Block(..) => true,
_ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3129 break;
3130 }
3131
3132 seen_bindings
3133 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3134 }
3135 }
3136
3137 for rib in self.lifetime_ribs.iter().rev() {
3139 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3140 if let LifetimeRibKind::Item = rib.kind {
3141 break;
3142 }
3143 }
3144
3145 for param in params {
3146 let ident = param.ident.normalize_to_macros_2_0();
3147 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3147",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3147u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("with_generic_param_rib: {0}",
param.id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("with_generic_param_rib: {}", param.id);
3148
3149 if let GenericParamKind::Lifetime = param.kind
3150 && let Some(&original) = seen_lifetimes.get(&ident)
3151 {
3152 let guar = diagnostics::signal_lifetime_shadowing(
3153 self.r.tcx.sess,
3154 original,
3155 param.ident,
3156 );
3157 self.record_lifetime_err(param.id, guar);
3159 continue;
3160 }
3161
3162 match seen_bindings.entry(ident) {
3163 Entry::Occupied(entry) => {
3164 let span = *entry.get();
3165 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3166 let guar = self.r.report_error(param.ident.span, err);
3167 let rib = match param.kind {
3168 GenericParamKind::Lifetime => {
3169 self.record_lifetime_err(param.id, guar);
3171 continue;
3172 }
3173 GenericParamKind::Type { .. } => &mut function_type_rib,
3174 GenericParamKind::Const { .. } => &mut function_value_rib,
3175 };
3176
3177 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3179 rib.bindings.insert(ident, Res::Err);
3180 continue;
3181 }
3182 Entry::Vacant(entry) => {
3183 entry.insert(param.ident.span);
3184 }
3185 }
3186
3187 if param.ident.name == kw::UnderscoreLifetime {
3188 let is_raw_underscore_lifetime = self
3191 .r
3192 .tcx
3193 .sess
3194 .psess
3195 .raw_identifier_spans
3196 .iter()
3197 .any(|span| span == param.span());
3198
3199 let guar = self
3200 .r
3201 .dcx()
3202 .create_err(crate::diagnostics::UnderscoreLifetimeIsReserved {
3203 span: param.ident.span,
3204 })
3205 .emit_unless_delay(is_raw_underscore_lifetime);
3206 self.record_lifetime_err(param.id, guar);
3208 continue;
3209 }
3210
3211 if param.ident.name == kw::StaticLifetime {
3212 let guar =
3213 self.r.dcx().emit_err(crate::diagnostics::StaticLifetimeIsReserved {
3214 span: param.ident.span,
3215 lifetime: param.ident,
3216 });
3217 self.record_lifetime_err(param.id, guar);
3219 continue;
3220 }
3221
3222 let def_id = self.r.local_def_id(param.id);
3223
3224 let (rib, def_kind) = match param.kind {
3226 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3227 GenericParamKind::Const { .. } => {
3228 (&mut function_value_rib, DefKind::ConstParam)
3229 }
3230 GenericParamKind::Lifetime => {
3231 let res = LifetimeRes::Param { param: def_id, binder };
3232 self.record_lifetime_def(param.id, res);
3233 function_lifetime_rib.bindings.insert(ident, (param.id, res));
3234 continue;
3235 }
3236 };
3237
3238 let res = match kind {
3239 RibKind::Item(..) | RibKind::AssocItem => {
3240 Res::Def(def_kind, def_id.to_def_id())
3241 }
3242 RibKind::Normal => {
3243 if self.r.features.non_lifetime_binders()
3246 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamKind::Type { .. } => true,
_ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3247 {
3248 Res::Def(def_kind, def_id.to_def_id())
3249 } else {
3250 Res::Err
3251 }
3252 }
3253 _ => ::rustc_middle::util::bug::span_bug_fmt(param.ident.span,
format_args!("Unexpected rib kind {0:?}", kind))span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
3254 };
3255 self.r.record_partial_res(param.id, PartialRes::new(res));
3256 rib.bindings.insert(ident, res);
3257 }
3258 }
3259
3260 self.lifetime_ribs.push(function_lifetime_rib);
3261 self.ribs[ValueNS].push(function_value_rib);
3262 self.ribs[TypeNS].push(function_type_rib);
3263
3264 f(self);
3265
3266 self.ribs[TypeNS].pop();
3267 self.ribs[ValueNS].pop();
3268 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3269
3270 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3272 for (_, res) in function_lifetime_rib.bindings.values() {
3273 candidates.retain(|(r, _)| r != res);
3274 }
3275 }
3276
3277 if let LifetimeBinderKind::FnPtrType
3278 | LifetimeBinderKind::WhereBound
3279 | LifetimeBinderKind::Function
3280 | LifetimeBinderKind::ImplBlock = generics_kind
3281 {
3282 self.maybe_report_lifetime_uses(generics_span, params)
3283 }
3284 }
3285
3286 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3287 self.label_ribs.push(Rib::new(kind));
3288 f(self);
3289 self.label_ribs.pop();
3290 }
3291
3292 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3293 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3294 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3295 }
3296
3297 #[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_constant_rib",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3305u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_repeat")
}> =
::tracing::__macro_support::FieldName::new("is_repeat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("may_use_generics")
}> =
::tracing::__macro_support::FieldName::new("may_use_generics");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
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(&is_repeat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&may_use_generics)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let f =
|this: &mut Self|
{
this.with_rib(ValueNS,
RibKind::ConstantItem(may_use_generics, item),
|this|
{
this.with_rib(TypeNS,
RibKind::ConstantItem(may_use_generics.force_yes_if(is_repeat
== IsRepeatExpr::Yes), item),
|this|
{
this.with_label_rib(RibKind::ConstantItem(may_use_generics,
item), f);
})
})
};
if let ConstantHasGenerics::No(cause) = may_use_generics {
self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause),
f)
} else { f(self) }
}
}
}#[instrument(level = "debug", skip(self, f))]
3306 fn with_constant_rib(
3307 &mut self,
3308 is_repeat: IsRepeatExpr,
3309 may_use_generics: ConstantHasGenerics,
3310 item: Option<(Ident, ConstantItemKind)>,
3311 f: impl FnOnce(&mut Self),
3312 ) {
3313 let f = |this: &mut Self| {
3314 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3315 this.with_rib(
3316 TypeNS,
3317 RibKind::ConstantItem(
3318 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3319 item,
3320 ),
3321 |this| {
3322 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3323 },
3324 )
3325 })
3326 };
3327
3328 if let ConstantHasGenerics::No(cause) = may_use_generics {
3329 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3330 } else {
3331 f(self)
3332 }
3333 }
3334
3335 fn with_current_self_type<T>(
3336 &mut self,
3337 self_type: &'ast Ty,
3338 f: impl FnOnce(&mut Self) -> T,
3339 ) -> T {
3340 let previous_value = replace(&mut self.diag_metadata.current_self_type, Some(self_type));
3342 let result = f(self);
3343 self.diag_metadata.current_self_type = previous_value;
3344 result
3345 }
3346
3347 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3348 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3349 let result = f(self);
3350 self.diag_metadata.current_self_item = previous_value;
3351 result
3352 }
3353
3354 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3356 let trait_assoc_items =
3357 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3358
3359 for item in trait_items {
3360 with_owner(self, item.id, |this| this.resolve_trait_item(item));
3361 }
3362
3363 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3364 }
3365
3366 fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3367 let walk_assoc_item =
3368 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3369 this.with_generic_param_rib(
3370 &generics.params,
3371 RibKind::AssocItem,
3372 item.id,
3373 kind,
3374 generics.span,
3375 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3376 );
3377 };
3378
3379 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3380 match &item.kind {
3381 AssocItemKind::Const(ast::ConstItem {
3382 generics, ty, rhs_kind, define_opaque, ..
3383 }) => {
3384 self.with_generic_param_rib(
3385 &generics.params,
3386 RibKind::AssocItem,
3387 item.id,
3388 LifetimeBinderKind::ConstItem,
3389 generics.span,
3390 |this| {
3391 this.with_lifetime_rib(
3392 LifetimeRibKind::Elided {
3393 res: LifetimeRes::Static,
3394 error_in_path: true,
3395 },
3396 |this| {
3397 this.visit_generics(generics);
3398 if rhs_kind.is_type_const()
3399 && !this.r.features.generic_const_parameter_types()
3400 {
3401 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3402 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3403 this.with_lifetime_rib(
3404 LifetimeRibKind::ConstParamTy,
3405 |this| this.visit_ty(ty),
3406 )
3407 })
3408 });
3409 } else {
3410 this.visit_ty(ty);
3411 }
3412
3413 this.resolve_const_item_rhs(rhs_kind, None);
3422 },
3423 )
3424 },
3425 );
3426
3427 self.resolve_define_opaques(define_opaque);
3428 }
3429 AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3430 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3431
3432 self.resolve_define_opaques(define_opaque);
3433 }
3434 AssocItemKind::Delegation(delegation) => {
3435 self.with_generic_param_rib(
3436 &[],
3437 RibKind::AssocItem,
3438 item.id,
3439 LifetimeBinderKind::Function,
3440 delegation.path.segments.last().unwrap().ident.span,
3441 |this| this.resolve_delegation(delegation, item.id, false),
3442 );
3443 }
3444 AssocItemKind::Type(TyAlias { generics, .. }) => self
3445 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3446 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3447 }),
3448 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3449 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3450 }
3451 };
3452 }
3453
3454 fn with_optional_trait_ref<T>(
3456 &mut self,
3457 opt_trait_ref: Option<&TraitRef>,
3458 self_type: &'ast Ty,
3459 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3460 ) -> T {
3461 let mut new_val = None;
3462 let mut new_id = None;
3463 if let Some(trait_ref) = opt_trait_ref {
3464 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3465 self.diag_metadata.currently_processing_impl_trait =
3466 Some((trait_ref.clone(), self_type.clone()));
3467 let res = self.smart_resolve_path_fragment(
3468 &None,
3469 &path,
3470 PathSource::Trait(AliasPossibility::No),
3471 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3472 RecordPartialRes::Yes,
3473 None,
3474 );
3475 self.diag_metadata.currently_processing_impl_trait = None;
3476 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3477 new_id = Some(def_id);
3478 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3479 }
3480 }
3481 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3482 let result = f(self, new_id);
3483 self.current_trait_ref = original_trait_ref;
3484 result
3485 }
3486
3487 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3488 let mut self_type_rib = Rib::new(RibKind::Normal);
3489
3490 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3492 self.ribs[ns].push(self_type_rib);
3493 f(self);
3494 self.ribs[ns].pop();
3495 }
3496
3497 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3498 self.with_self_rib_ns(TypeNS, self_res, f)
3499 }
3500
3501 fn resolve_implementation(
3502 &mut self,
3503 attrs: &[ast::Attribute],
3504 generics: &'ast Generics,
3505 of_trait: Option<&'ast ast::TraitImplHeader>,
3506 self_type: &'ast Ty,
3507 item_id: NodeId,
3508 impl_items: &'ast [Box<AssocItem>],
3509 ) {
3510 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3510",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3510u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation");
3511 self.with_generic_param_rib(
3513 &generics.params,
3514 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3515 item_id,
3516 LifetimeBinderKind::ImplBlock,
3517 generics.span,
3518 |this| {
3519 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3521 this.with_lifetime_rib(
3522 LifetimeRibKind::AnonymousCreateParameter {
3523 binder: item_id,
3524 report_in_path: true
3525 },
3526 |this| {
3527 this.with_optional_trait_ref(
3529 of_trait.map(|t| &t.trait_ref),
3530 self_type,
3531 |this, trait_id| {
3532 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3533
3534 let item_def_id = this.r.current_owner.def_id;
3535
3536 if let Some(trait_id) = trait_id {
3538 this.r
3539 .trait_impls
3540 .entry(trait_id)
3541 .or_default()
3542 .push(item_def_id);
3543 }
3544
3545 let item_def_id = item_def_id.to_def_id();
3546 let res = Res::SelfTyAlias {
3547 alias_to: item_def_id,
3548 is_trait_impl: trait_id.is_some(),
3549 };
3550 this.with_self_rib(res, |this| {
3551 if let Some(of_trait) = of_trait {
3552 visit::walk_trait_ref(this, &of_trait.trait_ref);
3554 }
3555 this.visit_ty(self_type);
3557 this.visit_generics(generics);
3559
3560 this.with_current_self_type(self_type, |this| {
3562 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3563 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3563",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3563u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation with_self_rib_ns(ValueNS, ...)")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
3564 let mut seen_trait_items = Default::default();
3565 for item in impl_items {
3566 with_owner(this, item.id, |this| {
3567 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3568 })
3569 }
3570 });
3571 });
3572 });
3573 },
3574 )
3575 },
3576 );
3577 });
3578 },
3579 );
3580 }
3581
3582 fn resolve_impl_item(
3583 &mut self,
3584 item: &'ast AssocItem,
3585 seen_trait_items: &mut FxHashMap<DefId, Span>,
3586 trait_id: Option<DefId>,
3587 is_in_trait_impl: bool,
3588 ) {
3589 use crate::ResolutionError::*;
3590 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3591 let prev = self.diag_metadata.current_impl_item.take();
3592 self.diag_metadata.current_impl_item = Some(&item);
3593 match &item.kind {
3594 AssocItemKind::Const(ast::ConstItem {
3595 ident,
3596 generics,
3597 ty,
3598 rhs_kind,
3599 define_opaque,
3600 ..
3601 }) => {
3602 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3602",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3602u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation AssocItemKind::Const")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation AssocItemKind::Const");
3603 self.with_generic_param_rib(
3604 &generics.params,
3605 RibKind::AssocItem,
3606 item.id,
3607 LifetimeBinderKind::ConstItem,
3608 generics.span,
3609 |this| {
3610 this.with_lifetime_rib(
3611 LifetimeRibKind::Elided {
3612 res: LifetimeRes::Static,
3613 error_in_path: true,
3614 },
3615 |this| {
3616 this.check_trait_item(
3619 item.id,
3620 *ident,
3621 *ident,
3622 &item.kind,
3623 ValueNS,
3624 item.span,
3625 seen_trait_items,
3626 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3627 );
3628
3629 this.visit_generics(generics);
3630 if rhs_kind.is_type_const()
3631 && !this.r.tcx.features().generic_const_parameter_types()
3632 {
3633 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3634 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3635 this.with_lifetime_rib(
3636 LifetimeRibKind::ConstParamTy,
3637 |this| this.visit_ty(ty),
3638 )
3639 })
3640 });
3641 } else {
3642 this.visit_ty(ty);
3643 }
3644 this.resolve_const_item_rhs(rhs_kind, None);
3650 },
3651 )
3652 },
3653 );
3654 self.resolve_define_opaques(define_opaque);
3655 }
3656 AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3657 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3657",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3657u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation AssocItemKind::Fn")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation AssocItemKind::Fn");
3658 self.with_generic_param_rib(
3660 &generics.params,
3661 RibKind::AssocItem,
3662 item.id,
3663 LifetimeBinderKind::Function,
3664 generics.span,
3665 |this| {
3666 let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3667 Ident::new(sym::pin_drop, ident.span)
3668 } else {
3669 *ident
3670 };
3671 this.check_trait_item(
3674 item.id,
3675 effective_ident,
3676 *ident,
3677 &item.kind,
3678 ValueNS,
3679 item.span,
3680 seen_trait_items,
3681 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3682 );
3683
3684 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3685 },
3686 );
3687
3688 self.resolve_define_opaques(define_opaque);
3689 }
3690 AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3691 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3692 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3692",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3692u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation AssocItemKind::Type")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation AssocItemKind::Type");
3693 self.with_generic_param_rib(
3695 &generics.params,
3696 RibKind::AssocItem,
3697 item.id,
3698 LifetimeBinderKind::ImplAssocType,
3699 generics.span,
3700 |this| {
3701 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3702 this.check_trait_item(
3705 item.id,
3706 *ident,
3707 *ident,
3708 &item.kind,
3709 TypeNS,
3710 item.span,
3711 seen_trait_items,
3712 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3713 );
3714
3715 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3716 });
3717 },
3718 );
3719 self.diag_metadata.in_non_gat_assoc_type = None;
3720 }
3721 AssocItemKind::Delegation(delegation) => {
3722 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3722",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3722u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_implementation AssocItemKind::Delegation")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolve_implementation AssocItemKind::Delegation");
3723 self.with_generic_param_rib(
3724 &[],
3725 RibKind::AssocItem,
3726 item.id,
3727 LifetimeBinderKind::Function,
3728 delegation.path.segments.last().unwrap().ident.span,
3729 |this| {
3730 this.check_trait_item(
3731 item.id,
3732 delegation.ident,
3733 delegation.ident,
3734 &item.kind,
3735 ValueNS,
3736 item.span,
3737 seen_trait_items,
3738 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3739 );
3740
3741 this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3744 },
3745 );
3746 }
3747 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3748 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3749 }
3750 }
3751 self.diag_metadata.current_impl_item = prev;
3752 }
3753
3754 fn check_trait_item<F>(
3755 &mut self,
3756 id: NodeId,
3757 mut ident: Ident,
3758 mut reported_ident: Ident,
3759 kind: &AssocItemKind,
3760 ns: Namespace,
3761 span: Span,
3762 seen_trait_items: &mut FxHashMap<DefId, Span>,
3763 err: F,
3764 ) where
3765 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3766 {
3767 let Some((module, _)) = self.current_trait_ref else {
3769 return;
3770 };
3771 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3772 reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3773 let key = BindingKey::new(IdentKey::new(ident), ns);
3774 let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3775 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3775",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3775u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("decl")
}> =
::tracing::__macro_support::FieldName::new("decl");
NAME.as_str()
}], ::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(&::tracing::field::debug(&decl)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?decl);
3776 if decl.is_none() {
3777 let ns = match ns {
3780 ValueNS => TypeNS,
3781 TypeNS => ValueNS,
3782 _ => ns,
3783 };
3784 let key = BindingKey::new(IdentKey::new(ident), ns);
3785 decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3786 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3786",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3786u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("decl")
}> =
::tracing::__macro_support::FieldName::new("decl");
NAME.as_str()
}], ::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(&::tracing::field::debug(&decl)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?decl);
3787 }
3788
3789 let feed_visibility = |this: &mut Self, def_id| {
3790 let vis = this.r.tcx.visibility(def_id);
3791 let vis = if vis.is_visible_locally() {
3792 vis.expect_local()
3793 } else {
3794 this.r.dcx().span_delayed_bug(
3795 span,
3796 "error should be emitted when an unexpected trait item is used",
3797 );
3798 Visibility::Public
3799 };
3800 this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3804 };
3805
3806 let Some(decl) = decl else {
3807 let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3809 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3810 let path_names = path_names_to_string(path);
3811 self.report_error(span, err(reported_ident, path_names, candidate));
3812 feed_visibility(self, module.def_id());
3813 return;
3814 };
3815
3816 let res = decl.res();
3817 let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3818 feed_visibility(self, id_in_trait);
3819
3820 match seen_trait_items.entry(id_in_trait) {
3821 Entry::Occupied(entry) => {
3822 self.report_error(
3823 span,
3824 ResolutionError::TraitImplDuplicate {
3825 name: ident,
3826 old_span: *entry.get(),
3827 trait_item_span: decl.span,
3828 },
3829 );
3830 return;
3831 }
3832 Entry::Vacant(entry) => {
3833 entry.insert(span);
3834 }
3835 };
3836
3837 match (def_kind, kind) {
3838 (DefKind::AssocTy, AssocItemKind::Type(..))
3839 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3840 | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3841 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3842 self.r.record_partial_res(id, PartialRes::new(res));
3843 return;
3844 }
3845 _ => {}
3846 }
3847
3848 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3850 let (code, kind) = match kind {
3851 AssocItemKind::Const(..) => (E0323, "const"),
3852 AssocItemKind::Fn(..) => (E0324, "method"),
3853 AssocItemKind::Type(..) => (E0325, "type"),
3854 AssocItemKind::Delegation(..) => (E0324, "method"),
3855 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3856 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3857 }
3858 };
3859 let trait_path = path_names_to_string(path);
3860 self.report_error(
3861 span,
3862 ResolutionError::TraitImplMismatch {
3863 name: ident,
3864 kind,
3865 code,
3866 trait_path,
3867 trait_item_span: decl.span,
3868 },
3869 );
3870 }
3871
3872 fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3873 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3874 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3875 this.visit_expr(expr)
3876 });
3877 })
3878 }
3879
3880 fn resolve_const_item_rhs(
3881 &mut self,
3882 rhs_kind: &'ast ConstItemRhsKind,
3883 item: Option<(Ident, ConstantItemKind)>,
3884 ) {
3885 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| match rhs_kind {
3886 ConstItemRhsKind::TypeConst { rhs: Some(anon_const) } => {
3887 this.resolve_anon_const(anon_const, AnonConstKind::ConstArg(IsRepeatExpr::No));
3888 }
3889 ConstItemRhsKind::Body { rhs: Some(expr) } => {
3890 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3891 this.visit_expr(expr)
3892 });
3893 }
3894 _ => (),
3895 })
3896 }
3897
3898 fn resolve_delegation(
3899 &mut self,
3900 delegation: &'ast Delegation,
3901 item_id: NodeId,
3902 is_in_trait_impl: bool,
3903 ) {
3904 self.smart_resolve_path(
3905 delegation.id,
3906 &delegation.qself,
3907 &delegation.path,
3908 PathSource::Delegation,
3909 );
3910
3911 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3914 if let Some(qself) = &delegation.qself {
3915 this.visit_ty(&qself.ty);
3916 }
3917
3918 this.visit_path(&delegation.path);
3919 });
3920
3921 let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
3922 let def_id = self
3923 .r
3924 .partial_res_map
3925 .get(&resolution_node_id)
3926 .and_then(|r| r.expect_full_res().opt_def_id());
3927
3928 let resolution_id = def_id.ok_or_else(|| {
3929 self.r.tcx.dcx().span_delayed_bug(
3930 delegation.path.span,
3931 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LateResolutionVisitor: couldn\'t resolve node {0:?} in delegation item",
resolution_node_id))
})format!(
3932 "LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
3933 ),
3934 )
3935 });
3936
3937 let info = DelegationInfo { resolution_id };
3938 self.r.delegation_infos.insert(self.r.current_owner.def_id, info);
3939
3940 let Some(body) = &delegation.body else { return };
3941 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3942 let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3943 let res = Res::Local(delegation.id);
3944 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3945
3946 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3948 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3949 this.visit_block(body);
3950 });
3951 });
3952 });
3953 }
3954
3955 fn resolve_params(&mut self, params: &'ast [Param]) {
3956 let mut bindings = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push((PatBoundCtx::Product, Default::default()));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(PatBoundCtx::Product, Default::default())])))
}
}smallvec![(PatBoundCtx::Product, Default::default())];
3957 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3958 for Param { pat, .. } in params {
3959 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3960 }
3961 this.apply_pattern_bindings(bindings);
3962 });
3963 for Param { ty, .. } in params {
3964 self.visit_ty(ty);
3965 }
3966 }
3967
3968 fn resolve_local(&mut self, local: &'ast Local) {
3969 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3969",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3969u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("resolving local ({0:?})",
local) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("resolving local ({:?})", local);
3970 if let Some(x) = &local.ty {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_ty(x)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};visit_opt!(self, visit_ty, &local.ty);
3972
3973 if let Some((init, els)) = local.kind.init_else_opt() {
3975 self.visit_expr(init);
3976
3977 if let Some(els) = els {
3979 self.visit_block(els);
3980 }
3981 }
3982
3983 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3985 }
3986
3987 fn compute_and_check_binding_map(
4007 &mut self,
4008 pat: &Pat,
4009 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4010 let mut binding_map = FxIndexMap::default();
4011 let mut is_never_pat = false;
4012
4013 pat.walk(&mut |pat| {
4014 match pat.kind {
4015 PatKind::Ident(annotation, ident, ref sub_pat)
4016 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
4017 {
4018 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
4019 }
4020 PatKind::Or(ref ps) => {
4021 match self.compute_and_check_or_pat_binding_map(ps) {
4024 Ok(bm) => binding_map.extend(bm),
4025 Err(IsNeverPattern) => is_never_pat = true,
4026 }
4027 return false;
4028 }
4029 PatKind::Never => is_never_pat = true,
4030 _ => {}
4031 }
4032
4033 true
4034 });
4035
4036 if is_never_pat {
4037 for (_, binding) in binding_map {
4038 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4039 }
4040 Err(IsNeverPattern)
4041 } else {
4042 Ok(binding_map)
4043 }
4044 }
4045
4046 fn is_base_res_local(&self, nid: NodeId) -> bool {
4047 #[allow(non_exhaustive_omitted_patterns)] match self.r.partial_res_map.get(&nid).map(|res|
res.expect_full_res()) {
Some(Res::Local(..)) => true,
_ => false,
}matches!(
4048 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4049 Some(Res::Local(..))
4050 )
4051 }
4052
4053 fn compute_and_check_or_pat_binding_map(
4073 &mut self,
4074 pats: &[Pat],
4075 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4076 let mut missing_vars = FxIndexMap::default();
4077 let mut inconsistent_vars = FxIndexMap::default();
4078
4079 let not_never_pats = pats
4081 .iter()
4082 .filter_map(|pat| {
4083 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4084 Some((binding_map, pat))
4085 })
4086 .collect::<Vec<_>>();
4087
4088 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4090 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4092
4093 for &(ref map, pat) in inners {
4094 for (&name, binding_inner) in map {
4095 match map_outer.get(&name) {
4096 None => {
4097 let binding_error =
4099 missing_vars.entry(name).or_insert_with(|| BindingError {
4100 name,
4101 origin: Default::default(),
4102 target: Default::default(),
4103 could_be_path: name.as_str().starts_with(char::is_uppercase),
4104 });
4105 binding_error.origin.push((binding_inner.span, pat.clone()));
4106 binding_error.target.push(pat_outer.clone());
4107 }
4108 Some(binding_outer) => {
4109 if binding_outer.annotation != binding_inner.annotation {
4110 inconsistent_vars
4112 .entry(name)
4113 .or_insert((binding_inner.span, binding_outer.span));
4114 }
4115 }
4116 }
4117 }
4118 }
4119 }
4120
4121 for (name, mut v) in missing_vars {
4123 if inconsistent_vars.contains_key(&name) {
4124 v.could_be_path = false;
4125 }
4126 self.report_error(
4127 v.origin.iter().next().unwrap().0,
4128 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4129 );
4130 }
4131
4132 for (name, v) in inconsistent_vars {
4134 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4135 }
4136
4137 if not_never_pats.is_empty() {
4139 Err(IsNeverPattern)
4141 } else {
4142 let mut binding_map = FxIndexMap::default();
4143 for (bm, _) in not_never_pats {
4144 binding_map.extend(bm);
4145 }
4146 Ok(binding_map)
4147 }
4148 }
4149
4150 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4152 let mut is_or_or_never = false;
4153 pat.walk(&mut |pat| match pat.kind {
4154 PatKind::Or(..) | PatKind::Never => {
4155 is_or_or_never = true;
4156 false
4157 }
4158 _ => true,
4159 });
4160 if is_or_or_never {
4161 let _ = self.compute_and_check_binding_map(pat);
4162 }
4163 }
4164
4165 fn resolve_arm(&mut self, arm: &'ast Arm) {
4166 self.with_rib(ValueNS, RibKind::Normal, |this| {
4167 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4168 if let Some(x) = arm.guard.as_ref().map(|g| &g.cond) {
match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};visit_opt!(this, visit_expr, arm.guard.as_ref().map(|g| &g.cond));
4169 if let Some(x) = &arm.body {
match ::rustc_ast_ir::visit::VisitorResult::branch(this.visit_expr(x)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};visit_opt!(this, visit_expr, &arm.body);
4170 });
4171 }
4172
4173 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4175 let mut bindings = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push((PatBoundCtx::Product, Default::default()));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(PatBoundCtx::Product, Default::default())])))
}
}smallvec![(PatBoundCtx::Product, Default::default())];
4176 self.resolve_pattern(pat, pat_src, &mut bindings);
4177 self.apply_pattern_bindings(bindings);
4178 }
4179
4180 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4182 let rib_bindings = self.innermost_rib_bindings(ValueNS);
4183 let Some((_, pat_bindings)) = pat_bindings.pop() else {
4184 ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4185 };
4186
4187 if rib_bindings.is_empty() {
4188 *rib_bindings = pat_bindings;
4191 } else {
4192 rib_bindings.extend(pat_bindings);
4193 }
4194 }
4195
4196 fn resolve_pattern(
4199 &mut self,
4200 pat: &'ast Pat,
4201 pat_src: PatternSource,
4202 bindings: &mut PatternBindings,
4203 ) {
4204 self.visit_pat(pat);
4210 self.resolve_pattern_inner(pat, pat_src, bindings);
4211 self.check_consistent_bindings(pat);
4213 }
4214
4215 #[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("resolve_pattern_inner",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(4234u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat_src")
}> =
::tracing::__macro_support::FieldName::new("pat_src");
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(&pat)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat_src)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
pat.walk(&mut |pat|
{
match pat.kind {
PatKind::Ident(bmode, ident, ref sub) => {
let has_sub = sub.is_some();
let res =
self.try_resolve_as_non_binding(pat_src, bmode, ident,
has_sub).unwrap_or_else(||
self.fresh_binding(ident, pat.id, pat_src, bindings));
self.r.record_partial_res(pat.id, PartialRes::new(res));
self.r.record_pat_span(pat.id, pat.span);
}
PatKind::TupleStruct(ref qself, ref path, ref sub_patterns)
=> {
self.smart_resolve_path(pat.id, qself, path,
PathSource::TupleStruct(pat.span,
self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p|
p.span))));
}
PatKind::Path(ref qself, ref path) => {
self.smart_resolve_path(pat.id, qself, path,
PathSource::Pat);
}
PatKind::Struct(ref qself, ref path, ref _fields, ref rest)
=> {
self.smart_resolve_path(pat.id, qself, path,
PathSource::Struct(None));
self.record_patterns_with_skipped_bindings(pat, rest);
}
PatKind::Or(ref ps) => {
bindings.push((PatBoundCtx::Or, Default::default()));
for p in ps {
bindings.push((PatBoundCtx::Product, Default::default()));
self.resolve_pattern_inner(p, pat_src, bindings);
let collected = bindings.pop().unwrap().1;
bindings.last_mut().unwrap().1.extend(collected);
}
let collected = bindings.pop().unwrap().1;
bindings.last_mut().unwrap().1.extend(collected);
return false;
}
PatKind::Guard(ref subpat, ref guard) => {
bindings.push((PatBoundCtx::Product, Default::default()));
let binding_ctx_stack_len = bindings.len();
self.resolve_pattern_inner(subpat, pat_src, bindings);
{
match (&bindings.len(), &binding_ctx_stack_len) {
(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);
}
}
}
};
let subpat_bindings = bindings.pop().unwrap().1;
self.with_rib(ValueNS, RibKind::Normal,
|this|
{
*this.innermost_rib_bindings(ValueNS) =
subpat_bindings.clone();
this.resolve_expr(&guard.cond, None);
});
bindings.last_mut().unwrap().1.extend(subpat_bindings);
return false;
}
_ => {}
}
true
});
}
}
}#[tracing::instrument(skip(self, bindings), level = "debug")]
4235 fn resolve_pattern_inner(
4236 &mut self,
4237 pat: &'ast Pat,
4238 pat_src: PatternSource,
4239 bindings: &mut PatternBindings,
4240 ) {
4241 pat.walk(&mut |pat| {
4243 match pat.kind {
4244 PatKind::Ident(bmode, ident, ref sub) => {
4245 let has_sub = sub.is_some();
4248 let res = self
4249 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4250 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4251 self.r.record_partial_res(pat.id, PartialRes::new(res));
4252 self.r.record_pat_span(pat.id, pat.span);
4253 }
4254 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4255 self.smart_resolve_path(
4256 pat.id,
4257 qself,
4258 path,
4259 PathSource::TupleStruct(
4260 pat.span,
4261 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4262 ),
4263 );
4264 }
4265 PatKind::Path(ref qself, ref path) => {
4266 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4267 }
4268 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4269 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4270 self.record_patterns_with_skipped_bindings(pat, rest);
4271 }
4272 PatKind::Or(ref ps) => {
4273 bindings.push((PatBoundCtx::Or, Default::default()));
4277 for p in ps {
4278 bindings.push((PatBoundCtx::Product, Default::default()));
4282 self.resolve_pattern_inner(p, pat_src, bindings);
4283 let collected = bindings.pop().unwrap().1;
4286 bindings.last_mut().unwrap().1.extend(collected);
4287 }
4288 let collected = bindings.pop().unwrap().1;
4292 bindings.last_mut().unwrap().1.extend(collected);
4293
4294 return false;
4296 }
4297 PatKind::Guard(ref subpat, ref guard) => {
4298 bindings.push((PatBoundCtx::Product, Default::default()));
4300 let binding_ctx_stack_len = bindings.len();
4303 self.resolve_pattern_inner(subpat, pat_src, bindings);
4304 assert_eq!(bindings.len(), binding_ctx_stack_len);
4305 let subpat_bindings = bindings.pop().unwrap().1;
4308 self.with_rib(ValueNS, RibKind::Normal, |this| {
4309 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4310 this.resolve_expr(&guard.cond, None);
4311 });
4312 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4319 return false;
4321 }
4322 _ => {}
4323 }
4324 true
4325 });
4326 }
4327
4328 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4329 match rest {
4330 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4331 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4333 && let Some(res) = partial_res.full_res()
4334 && let Some(def_id) = res.opt_def_id()
4335 {
4336 self.ribs[ValueNS]
4337 .last_mut()
4338 .unwrap()
4339 .patterns_with_skipped_bindings
4340 .entry(def_id)
4341 .or_default()
4342 .push((
4343 pat.span,
4344 match rest {
4345 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4346 _ => Ok(()),
4347 },
4348 ));
4349 }
4350 }
4351 ast::PatFieldsRest::None => {}
4352 }
4353 }
4354
4355 fn fresh_binding(
4356 &mut self,
4357 ident: Ident,
4358 pat_id: NodeId,
4359 pat_src: PatternSource,
4360 bindings: &mut PatternBindings,
4361 ) -> Res {
4362 let ident = ident.normalize_to_macro_rules();
4366
4367 let already_bound_and = bindings
4369 .iter()
4370 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4371 if already_bound_and {
4372 use ResolutionError::*;
4374 let error = match pat_src {
4375 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4377 _ => IdentifierBoundMoreThanOnceInSamePattern,
4379 };
4380 self.report_error(ident.span, error(ident));
4381 }
4382
4383 let already_bound_or = bindings
4386 .iter()
4387 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4388 let res = if let Some(&res) = already_bound_or {
4389 res
4392 } else {
4393 Res::Local(pat_id)
4395 };
4396
4397 bindings.last_mut().unwrap().1.insert(ident, res);
4399 res
4400 }
4401
4402 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4403 &mut self.ribs[ns].last_mut().unwrap().bindings
4404 }
4405
4406 fn try_resolve_as_non_binding(
4407 &mut self,
4408 pat_src: PatternSource,
4409 ann: BindingMode,
4410 ident: Ident,
4411 has_sub: bool,
4412 ) -> Option<Res> {
4413 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4417
4418 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4419 let (res, binding) = match ls_binding {
4420 LateDecl::Decl(binding)
4421 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4422 {
4423 self.r.record_use(ident, binding, Used::Other);
4428 return None;
4429 }
4430 LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4431 LateDecl::RibDef(res) => (res, None),
4432 };
4433
4434 match res {
4435 Res::SelfCtor(_) | Res::Def(
4437 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4438 _,
4439 ) if is_syntactic_ambiguity => {
4440 if let Some(binding) = binding {
4442 self.r.record_use(ident, binding, Used::Other);
4443 }
4444 Some(res)
4445 }
4446 Res::Def(
4447 DefKind::Ctor(..)
4448 | DefKind::Const { .. }
4449 | DefKind::AssocConst { .. }
4450 | DefKind::Static { .. },
4451 _,
4452 ) => {
4453 let binding = binding.expect("no binding for a ctor or static");
4459 self.report_error(
4460 ident.span,
4461 ResolutionError::BindingShadowsSomethingUnacceptable {
4462 shadowing_binding: pat_src,
4463 name: ident.name,
4464 participle: if binding.is_import() { "imported" } else { "defined" },
4465 article: binding.res().article(),
4466 shadowed_binding: binding.res(),
4467 shadowed_binding_span: binding.span,
4468 },
4469 );
4470 None
4471 }
4472 Res::Def(DefKind::ConstParam, def_id) => {
4473 self.report_error(
4476 ident.span,
4477 ResolutionError::BindingShadowsSomethingUnacceptable {
4478 shadowing_binding: pat_src,
4479 name: ident.name,
4480 participle: "defined",
4481 article: res.article(),
4482 shadowed_binding: res,
4483 shadowed_binding_span: self.r.def_span(def_id),
4484 },
4485 );
4486 None
4487 }
4488 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4489 None
4491 }
4492 Res::SelfCtor(_) => {
4493 self.r.dcx().span_delayed_bug(
4496 ident.span,
4497 "unexpected `SelfCtor` in pattern, expected identifier",
4498 );
4499 None
4500 }
4501 _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
format_args!("unexpected resolution for an identifier in pattern: {0:?}",
res))span_bug!(
4502 ident.span,
4503 "unexpected resolution for an identifier in pattern: {:?}",
4504 res,
4505 ),
4506 }
4507 }
4508
4509 fn resolve_restriction_path(
4510 &mut self,
4511 restriction: &'ast ast::RestrictionKind,
4512 kind: ResolvingRestrictionKind,
4513 ) {
4514 match &restriction {
4515 ast::RestrictionKind::Unrestricted => (),
4516 ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4517 self.smart_resolve_path(*id, &None, path, PathSource::Module);
4518 if let Some(res) = self.r.partial_res_map[&id].full_res()
4519 && let Some(def_id) = res.opt_def_id()
4520 {
4521 if !self.r.is_accessible_from(
4522 Visibility::Restricted(def_id),
4523 self.parent_scope.module,
4524 ) {
4525 self.r
4526 .dcx()
4527 .create_err(crate::diagnostics::RestrictionAncestorOnly {
4528 span: path.span,
4529 kind,
4530 })
4531 .emit();
4532 }
4533 }
4534 }
4535 }
4536 }
4537
4538 fn smart_resolve_path(
4544 &mut self,
4545 id: NodeId,
4546 qself: &Option<Box<QSelf>>,
4547 path: &Path,
4548 source: PathSource<'_, 'ast, 'ra>,
4549 ) {
4550 self.smart_resolve_path_fragment(
4551 qself,
4552 &Segment::from_path(path),
4553 source,
4554 Finalize::new(id, path.span),
4555 RecordPartialRes::Yes,
4556 None,
4557 );
4558 }
4559
4560 fn smart_resolve_path_fragment(
4561 &mut self,
4562 qself: &Option<Box<QSelf>>,
4563 path: &[Segment],
4564 source: PathSource<'_, 'ast, 'ra>,
4565 finalize: Finalize,
4566 record_partial_res: RecordPartialRes,
4567 parent_qself: Option<&QSelf>,
4568 ) -> PartialRes {
4569 let ns = source.namespace();
4570
4571 let Finalize { node_id, path_span, .. } = finalize;
4572 let report_errors = |this: &mut Self, res: Option<Res>| {
4573 if this.should_report_errs() {
4574 let (mut err, candidates) = this.smart_resolve_report_errors(
4575 path,
4576 None,
4577 path_span,
4578 source,
4579 res,
4580 parent_qself,
4581 );
4582
4583 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4584 let instead = res.is_some();
4585 let (suggestion, const_err) = if let Some((start, end)) =
4586 this.diag_metadata.in_range
4587 && path[0].ident.span.lo() == end.span.lo()
4588 && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(start.kind, ExprKind::Lit(_))
4589 {
4590 let mut sugg = ".";
4591 let mut span = start.span.between(end.span);
4592 if span.lo() + BytePos(2) == span.hi() {
4593 span = span.with_lo(span.lo() + BytePos(1));
4596 sugg = "";
4597 }
4598 (
4599 Some((
4600 span,
4601 "you might have meant to write `.` instead of `..`",
4602 sugg.to_string(),
4603 Applicability::MaybeIncorrect,
4604 )),
4605 None,
4606 )
4607 } else if res.is_none()
4608 && let PathSource::Type
4609 | PathSource::Expr(_)
4610 | PathSource::PreciseCapturingArg(..) = source
4611 {
4612 this.suggest_adding_generic_parameter(path, source)
4613 } else {
4614 (None, None)
4615 };
4616
4617 if let Some(const_err) = const_err {
4618 err.cancel();
4619 err = const_err;
4620 }
4621
4622 let ue = UseError {
4623 err,
4624 candidates,
4625 node_id,
4626 instead,
4627 suggestion,
4628 path: path.into(),
4629 is_call: source.is_call(),
4630 };
4631
4632 this.use_injections.push(ue);
4633 }
4634
4635 PartialRes::new(Res::Err)
4636 };
4637
4638 let report_errors_for_call =
4644 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4645 let (following_seg, prefix_path) = match path.split_last() {
4649 Some((last, path)) if !path.is_empty() => (Some(last), path),
4650 _ => return Some(parent_err),
4651 };
4652
4653 let (mut err, candidates) = this.smart_resolve_report_errors(
4654 prefix_path,
4655 following_seg,
4656 path_span,
4657 PathSource::Type,
4658 None,
4659 parent_qself,
4660 );
4661
4662 let failed_to_resolve = match parent_err.node {
4677 ResolutionError::FailedToResolve { .. } => true,
4678 _ => false,
4679 };
4680 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4681
4682 err.messages = take(&mut parent_err.messages);
4684 err.code = take(&mut parent_err.code);
4685 swap(&mut err.span, &mut parent_err.span);
4686 if failed_to_resolve {
4687 err.children = take(&mut parent_err.children);
4688 } else {
4689 err.children.append(&mut parent_err.children);
4690 }
4691 err.sort_span = parent_err.sort_span;
4692 err.is_lint = parent_err.is_lint.clone();
4693
4694 match &mut err.suggestions {
4696 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4697 Suggestions::Enabled(parent_suggestions) => {
4698 typo_suggestions.append(parent_suggestions)
4700 }
4701 Suggestions::Sealed(_) | Suggestions::Disabled => {
4702 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4707 }
4708 },
4709 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4710 }
4711
4712 parent_err.cancel();
4713
4714 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4715
4716 if this.should_report_errs() {
4717 if candidates.is_empty() {
4718 if path.len() == 2
4719 && let [segment] = prefix_path
4720 {
4721 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4727 } else {
4728 err.emit();
4733 }
4734 } else {
4735 this.use_injections.push(UseError {
4737 err,
4738 candidates,
4739 node_id,
4740 instead: false,
4741 suggestion: None,
4742 path: prefix_path.into(),
4743 is_call: source.is_call(),
4744 });
4745 }
4746 } else {
4747 err.cancel();
4748 }
4749
4750 None
4753 };
4754
4755 let partial_res = match self.resolve_qpath_anywhere(
4756 qself,
4757 path,
4758 ns,
4759 source.defer_to_typeck(),
4760 finalize,
4761 source,
4762 ) {
4763 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4764 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4766 && let [Segment { ident, .. }] = path
4767 && items.iter().any(|item| {
4768 if let AssocItemKind::Type(alias) = &item.kind
4769 && alias.ident == *ident
4770 {
4771 true
4772 } else {
4773 false
4774 }
4775 })
4776 {
4777 let mut diag = self.r.tcx.dcx().struct_allow("");
4778 diag.span_suggestion_verbose(
4779 path_span.shrink_to_lo(),
4780 "there is an associated type with the same name",
4781 "Self::",
4782 Applicability::MaybeIncorrect,
4783 );
4784 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4785 }
4786
4787 if source.is_expected(res) || res == Res::Err {
4788 partial_res
4789 } else {
4790 report_errors(self, Some(res))
4791 }
4792 }
4793
4794 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4795 if ns == ValueNS {
4799 let item_name = path.last().unwrap().ident;
4800 self.record_traits_in_scope(node_id, item_name);
4801 }
4802
4803 if PrimTy::from_name(path[0].ident.name).is_some() {
4804 let mut std_path = Vec::with_capacity(1 + path.len());
4805
4806 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4807 std_path.extend(path);
4808 if let PathResult::Module(_) | PathResult::NonModule(_) =
4809 self.resolve_path(&std_path, Some(ns), None, source)
4810 {
4811 let item_span =
4813 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4814
4815 self.r.confused_type_with_std_module.insert(item_span, path_span);
4816 self.r.confused_type_with_std_module.insert(path_span, path_span);
4817 }
4818 }
4819
4820 partial_res
4821 }
4822
4823 Err(err) => {
4824 if let Some(err) = report_errors_for_call(self, err) {
4825 self.report_error(err.span, err.node);
4826 }
4827
4828 PartialRes::new(Res::Err)
4829 }
4830
4831 _ => report_errors(self, None),
4832 };
4833
4834 if record_partial_res == RecordPartialRes::Yes {
4835 self.r.record_partial_res(node_id, partial_res);
4837 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4838 self.lint_unused_qualifications(path, ns, finalize);
4839 }
4840
4841 partial_res
4842 }
4843
4844 fn self_type_is_available(&mut self) -> bool {
4845 let binding = self
4846 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4847 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4848 }
4849
4850 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4851 let ident = Ident::new(kw::SelfLower, self_span);
4852 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4853 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4854 }
4855
4856 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4860 if self.should_report_errs() {
4861 self.r.report_error(span, resolution_error);
4862 }
4863 }
4864
4865 #[inline]
4866 fn should_report_errs(&self) -> bool {
4870 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4871 && !self.r.glob_error.is_some()
4872 }
4873
4874 fn resolve_qpath_anywhere(
4876 &mut self,
4877 qself: &Option<Box<QSelf>>,
4878 path: &[Segment],
4879 primary_ns: Namespace,
4880 defer_to_typeck: bool,
4881 finalize: Finalize,
4882 source: PathSource<'_, 'ast, 'ra>,
4883 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4884 let mut fin_res = None;
4885
4886 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4887 if i == 0 || ns != primary_ns {
4888 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4889 Some(partial_res)
4890 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4891 {
4892 return Ok(Some(partial_res));
4893 }
4894 partial_res => {
4895 if fin_res.is_none() {
4896 fin_res = partial_res;
4897 }
4898 }
4899 }
4900 }
4901 }
4902
4903 if !(primary_ns != MacroNS) {
::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4904 if qself.is_none()
4905 && let PathResult::NonModule(res) =
4906 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4907 {
4908 return Ok(Some(res));
4909 }
4910
4911 Ok(fin_res)
4912 }
4913
4914 fn resolve_qpath(
4916 &mut self,
4917 qself: &Option<Box<QSelf>>,
4918 path: &[Segment],
4919 ns: Namespace,
4920 finalize: Finalize,
4921 source: PathSource<'_, 'ast, 'ra>,
4922 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4923 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:4923",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(4923u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_qpath(qself={0:?}, path={1:?}, ns={2:?}, finalize={3:?})",
qself, path, ns, finalize) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
4924 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4925 qself, path, ns, finalize,
4926 );
4927
4928 if let Some(qself) = qself {
4929 if qself.position == 0 {
4930 return Ok(Some(PartialRes::with_unresolved_segments(
4934 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4935 path.len(),
4936 )));
4937 }
4938
4939 let num_privacy_errors = self.r.privacy_errors.len();
4940 let trait_res = self.smart_resolve_path_fragment(
4942 &None,
4943 &path[..qself.position],
4944 PathSource::Trait(AliasPossibility::No),
4945 Finalize::new(finalize.node_id, qself.path_span),
4946 RecordPartialRes::No,
4947 Some(&qself),
4948 );
4949
4950 if trait_res.expect_full_res() == Res::Err {
4951 return Ok(Some(trait_res));
4952 }
4953
4954 self.r.privacy_errors.truncate(num_privacy_errors);
4957
4958 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4966 let partial_res = self.smart_resolve_path_fragment(
4967 &None,
4968 &path[..=qself.position],
4969 PathSource::TraitItem(ns, &source),
4970 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4971 RecordPartialRes::No,
4972 Some(&qself),
4973 );
4974
4975 return Ok(Some(PartialRes::with_unresolved_segments(
4979 partial_res.base_res(),
4980 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4981 )));
4982 }
4983
4984 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4985 PathResult::NonModule(path_res) => path_res,
4986 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4987 PartialRes::new(module.res().unwrap())
4988 }
4989 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4993 PartialRes::new(Res::Err)
4994 }
4995 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
5008 if (ns == TypeNS || path.len() > 1)
5009 && PrimTy::from_name(path[0].ident.name).is_some() =>
5010 {
5011 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
5012 let tcx = self.r.tcx();
5013
5014 let gate_err_sym_msg = match prim {
5015 PrimTy::Float(FloatTy::F16) if !self.r.features.f16() => {
5016 Some((sym::f16, "the type `f16` is unstable"))
5017 }
5018 PrimTy::Float(FloatTy::F128) if !self.r.features.f128() => {
5019 Some((sym::f128, "the type `f128` is unstable"))
5020 }
5021 _ => None,
5022 };
5023
5024 if let Some((sym, msg)) = gate_err_sym_msg {
5025 let span = path[0].ident.span;
5026 if !span.allows_unstable(sym) {
5027 feature_err(tcx.sess, sym, span, msg).emit();
5028 }
5029 };
5030
5031 if let Some(id) = path[0].id {
5033 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
5034 }
5035
5036 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
5037 }
5038 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
5039 PartialRes::new(module.res().unwrap())
5040 }
5041 PathResult::Failed {
5042 is_error_from_last_segment: false,
5043 span,
5044 label,
5045 suggestion,
5046 module,
5047 segment,
5048 error_implied_by_parse_error: _,
5049 message,
5050 note: _,
5051 } => {
5052 return Err(respan(
5053 span,
5054 ResolutionError::FailedToResolve {
5055 segment: segment.name,
5056 label,
5057 suggestion,
5058 module,
5059 message,
5060 },
5061 ));
5062 }
5063 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5064 PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5065 };
5066
5067 Ok(Some(result))
5068 }
5069
5070 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5071 if let Some(label) = label {
5072 if label.ident.as_str().as_bytes()[1] != b'_' {
5073 self.diag_metadata.unused_labels.insert(id, label.ident.span);
5074 }
5075
5076 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5077 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5078 }
5079
5080 self.with_label_rib(RibKind::Normal, |this| {
5081 let ident = label.ident.normalize_to_macro_rules();
5082 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5083 f(this);
5084 });
5085 } else {
5086 f(self);
5087 }
5088 }
5089
5090 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5091 self.with_resolved_label(label, id, |this| this.visit_block(block));
5092 }
5093
5094 fn resolve_block(&mut self, block: &'ast Block) {
5095 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:5095",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5095u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving block) entering block")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving block) entering block");
5096 let orig_module = self.parent_scope.module;
5098 let anonymous_module = self.r.block_map.get(&block.id).copied();
5099
5100 let mut num_macro_definition_ribs = 0;
5101 if let Some(anonymous_module) = anonymous_module {
5102 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:5102",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5102u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving block) found anonymous module, moving down")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving block) found anonymous module, moving down");
5103 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5104 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5105 self.parent_scope.module = anonymous_module.to_module();
5106 } else {
5107 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5108 }
5109
5110 for stmt in &block.stmts {
5112 if let StmtKind::Item(ref item) = stmt.kind
5113 && let ItemKind::MacroDef(..) = item.kind
5114 {
5115 num_macro_definition_ribs += 1;
5116 let res = self.r.owner_def_id(item.id).to_def_id();
5117 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5118 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5119 }
5120
5121 self.visit_stmt(stmt);
5122 }
5123
5124 self.parent_scope.module = orig_module;
5126 for _ in 0..num_macro_definition_ribs {
5127 self.ribs[ValueNS].pop();
5128 self.label_ribs.pop();
5129 }
5130 self.last_block_rib = self.ribs[ValueNS].pop();
5131 if anonymous_module.is_some() {
5132 self.ribs[TypeNS].pop();
5133 }
5134 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:5134",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5134u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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!("(resolving block) leaving block")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(resolving block) leaving block");
5135 }
5136
5137 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5138 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:5138",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5138u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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_anon_const(constant: {0:?}, anon_const_kind: {1:?})",
constant, anon_const_kind) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
5139 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5140 constant, anon_const_kind
5141 );
5142
5143 let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5144 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5145 this.resolve_expr(&constant.value, None)
5146 })
5147 }
5148
5149 fn resolve_anon_const_manual(
5156 &mut self,
5157 is_trivial_const_arg: bool,
5158 anon_const_kind: AnonConstKind,
5159 resolve_expr: impl FnOnce(&mut Self),
5160 ) {
5161 let is_repeat_expr = match anon_const_kind {
5162 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5163 _ => IsRepeatExpr::No,
5164 };
5165
5166 let may_use_generics = match anon_const_kind {
5167 AnonConstKind::EnumDiscriminant => {
5168 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5169 }
5170 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5171 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5172 AnonConstKind::ConstArg(_) => {
5173 if self.r.features.generic_const_exprs()
5174 || self.r.features.min_generic_const_args()
5175 || is_trivial_const_arg
5176 {
5177 ConstantHasGenerics::Yes
5178 } else {
5179 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5180 }
5181 }
5182 };
5183
5184 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5185 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
5186 resolve_expr(this);
5187 });
5188 });
5189 }
5190
5191 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5192 self.resolve_expr(&f.expr, Some(e));
5193 self.visit_ident(&f.ident);
5194 for elem in f.attrs.iter() {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_attribute(elem))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(self, visit_attribute, f.attrs.iter());
5195 }
5196
5197 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5198 self.record_candidate_traits_for_expr_if_necessary(expr);
5202
5203 match expr.kind {
5205 ExprKind::Path(ref qself, ref path) => {
5206 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5207 visit::walk_expr(self, expr);
5208 }
5209
5210 ExprKind::Struct(ref se) => {
5211 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5212 if let Some(qself) = &se.qself {
5216 self.visit_ty(&qself.ty);
5217 }
5218 self.visit_path(&se.path);
5219 for elem in &se.fields {
match ::rustc_ast_ir::visit::VisitorResult::branch(self.resolve_expr_field(elem,
expr)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};
};walk_list!(self, resolve_expr_field, &se.fields, expr);
5220 match &se.rest {
5221 StructRest::Base(expr) => self.visit_expr(expr),
5222 StructRest::Rest(_span) => {}
5223 StructRest::None | StructRest::NoneWithError(_) => {}
5224 }
5225 }
5226
5227 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5228 match self.resolve_label(label.ident) {
5229 Ok((node_id, _)) => {
5230 self.r.current_owner.label_res_map.insert(expr.id, node_id);
5232 self.diag_metadata.unused_labels.swap_remove(&node_id);
5233 }
5234 Err(error) => {
5235 self.report_error(label.ident.span, error);
5236 }
5237 }
5238
5239 visit::walk_expr(self, expr);
5241 }
5242
5243 ExprKind::Break(None, Some(ref e)) => {
5244 self.resolve_expr(e, Some(expr));
5247 }
5248
5249 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5250 self.visit_expr(scrutinee);
5251 self.resolve_pattern_top(pat, PatternSource::Let);
5252 }
5253
5254 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5255 self.visit_expr(scrutinee);
5256 let mut bindings = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push((PatBoundCtx::Product, Default::default()));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(PatBoundCtx::Product, Default::default())])))
}
}smallvec![(PatBoundCtx::Product, Default::default())];
5258 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5259 for (_, bindings) in &mut bindings {
5264 for (_, binding) in bindings {
5265 *binding = Res::Err;
5266 }
5267 }
5268 self.apply_pattern_bindings(bindings);
5269 }
5270
5271 ExprKind::If(ref cond, ref then, ref opt_else) => {
5272 self.with_rib(ValueNS, RibKind::Normal, |this| {
5273 let old = this.diag_metadata.in_if_condition.replace(cond);
5274 this.visit_expr(cond);
5275 this.diag_metadata.in_if_condition = old;
5276 this.visit_block(then);
5277 });
5278 if let Some(expr) = opt_else {
5279 self.visit_expr(expr);
5280 }
5281 }
5282
5283 ExprKind::Loop(ref block, label, _) => {
5284 self.resolve_labeled_block(label, expr.id, block)
5285 }
5286
5287 ExprKind::While(ref cond, ref block, label) => {
5288 self.with_resolved_label(label, expr.id, |this| {
5289 this.with_rib(ValueNS, RibKind::Normal, |this| {
5290 let old = this.diag_metadata.in_if_condition.replace(cond);
5291 this.visit_expr(cond);
5292 this.diag_metadata.in_if_condition = old;
5293 this.visit_block(block);
5294 })
5295 });
5296 }
5297
5298 ExprKind::ForLoop(ForLoop { ref pat, ref iter, ref body, label, kind: _ }) => {
5299 self.visit_expr(iter);
5300 self.with_rib(ValueNS, RibKind::Normal, |this| {
5301 this.resolve_pattern_top(pat, PatternSource::For);
5302 this.resolve_labeled_block(label, expr.id, body);
5303 });
5304 }
5305
5306 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5307
5308 ExprKind::Field(ref subexpression, _) => {
5310 self.resolve_expr(subexpression, Some(expr));
5311 }
5312 ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5313 self.resolve_expr(receiver, Some(expr));
5314 for arg in args {
5315 self.resolve_expr(arg, None);
5316 }
5317 self.visit_path_segment(seg);
5318 }
5319
5320 ExprKind::Call(ref callee, ref arguments) => {
5321 self.resolve_expr(callee, Some(expr));
5322 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5323 for (idx, argument) in arguments.iter().enumerate() {
5324 if const_args.contains(&idx) {
5327 let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5330 self.resolve_anon_const_manual(
5331 is_trivial_const_arg,
5332 AnonConstKind::ConstArg(IsRepeatExpr::No),
5333 |this| this.resolve_expr(argument, None),
5334 );
5335 } else {
5336 self.resolve_expr(argument, None);
5337 }
5338 }
5339 }
5340 ExprKind::Type(ref _type_expr, ref _ty) => {
5341 visit::walk_expr(self, expr);
5342 }
5343 ExprKind::Closure(ast::Closure {
5345 binder: ClosureBinder::For { ref generic_params, span },
5346 ..
5347 }) => {
5348 self.with_generic_param_rib(
5349 generic_params,
5350 RibKind::Normal,
5351 expr.id,
5352 LifetimeBinderKind::Closure,
5353 span,
5354 |this| visit::walk_expr(this, expr),
5355 );
5356 }
5357 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5358 ExprKind::Gen(..) => {
5359 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5360 }
5361 ExprKind::Repeat(ref elem, ref ct) => {
5362 self.visit_expr(elem);
5363 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5364 }
5365 ExprKind::ConstBlock(ref ct) => {
5366 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5367 }
5368 ExprKind::Index(ref elem, ref idx, _) => {
5369 self.resolve_expr(elem, Some(expr));
5370 self.visit_expr(idx);
5371 }
5372 ExprKind::Assign(ref lhs, ref rhs, _) => {
5373 if !self.diag_metadata.is_assign_rhs {
5374 self.diag_metadata.in_assignment = Some(expr);
5375 }
5376 self.visit_expr(lhs);
5377 self.diag_metadata.is_assign_rhs = true;
5378 self.diag_metadata.in_assignment = None;
5379 self.visit_expr(rhs);
5380 self.diag_metadata.is_assign_rhs = false;
5381 }
5382 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5383 self.diag_metadata.in_range = Some((start, end));
5384 self.resolve_expr(start, Some(expr));
5385 self.resolve_expr(end, Some(expr));
5386 self.diag_metadata.in_range = None;
5387 }
5388 _ => {
5389 visit::walk_expr(self, expr);
5390 }
5391 }
5392 }
5393
5394 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5395 match expr.kind {
5396 ExprKind::Field(_, ident) => {
5397 self.record_traits_in_scope(expr.id, ident);
5402 }
5403 ExprKind::MethodCall(ref call) => {
5404 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:5404",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5404u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::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 candidate traits for expr) recording traits for {0}",
expr.id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
5405 self.record_traits_in_scope(expr.id, call.seg.ident);
5406 }
5407 _ => {
5408 }
5410 }
5411 }
5412
5413 fn record_traits_in_scope(&mut self, node_id: NodeId, ident: Ident) {
5414 let traits = self.r.traits_in_scope(
5415 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5416 &self.parent_scope,
5417 ident.span,
5418 Some((ident.name, ValueNS)),
5419 );
5420 self.r.current_owner.trait_map.insert(node_id, traits);
5421 }
5422
5423 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5424 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5428 let res = *doc_link_resolutions
5429 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5430 .or_default()
5431 .entry((Symbol::intern(path_str), ns))
5432 .or_insert_with_key(|(path, ns)| {
5433 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5434 if let Some(res) = res
5435 && let Some(def_id) = res.opt_def_id()
5436 && self.is_invalid_proc_macro_item_for_doc(def_id)
5437 {
5438 return None;
5441 }
5442 res
5443 });
5444 self.r.doc_link_resolutions = doc_link_resolutions;
5445 res
5446 }
5447
5448 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5449 if !#[allow(non_exhaustive_omitted_patterns)] match self.r.tcx.sess.opts.resolve_doc_links
{
ResolveDocLinks::ExportedMetadata => true,
_ => false,
}matches!(self.r.tcx.sess.opts.resolve_doc_links, ResolveDocLinks::ExportedMetadata)
5450 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5451 {
5452 return false;
5453 }
5454 let Some(local_did) = did.as_local() else { return true };
5455 !self.r.proc_macros.contains(&local_did)
5456 }
5457
5458 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5459 match self.r.tcx.sess.opts.resolve_doc_links {
5460 ResolveDocLinks::None => return,
5461 ResolveDocLinks::ExportedMetadata
5462 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5463 || !maybe_exported.eval(self.r) =>
5464 {
5465 return;
5466 }
5467 ResolveDocLinks::Exported
5468 if !maybe_exported.eval(self.r)
5469 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5470 {
5471 return;
5472 }
5473 ResolveDocLinks::ExportedMetadata
5474 | ResolveDocLinks::Exported
5475 | ResolveDocLinks::All => {}
5476 }
5477
5478 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5479 return;
5480 }
5481
5482 let mut need_traits_in_scope = false;
5483 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5484 let mut any_resolved = false;
5486 let mut need_assoc = false;
5487 for ns in [TypeNS, ValueNS, MacroNS] {
5488 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5489 any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
_ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5492 } else if ns != MacroNS {
5493 need_assoc = true;
5494 }
5495 }
5496
5497 if need_assoc || !any_resolved {
5499 let mut path = &path_str[..];
5500 while let Some(idx) = path.rfind("::") {
5501 path = &path[..idx];
5502 need_traits_in_scope = true;
5503 for ns in [TypeNS, ValueNS, MacroNS] {
5504 self.resolve_and_cache_rustdoc_path(path, ns);
5505 }
5506 }
5507 }
5508 }
5509
5510 if need_traits_in_scope {
5511 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5513 doc_link_traits_in_scope
5514 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5515 .or_insert_with(|| {
5516 self.r
5517 .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5518 .into_iter()
5519 .filter_map(|tr| {
5520 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5521 return None;
5524 }
5525 Some(tr.def_id)
5526 })
5527 .collect()
5528 });
5529 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5530 }
5531 }
5532
5533 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5534 if let Some(seg) = path.first()
5536 && seg.ident.name == kw::PathRoot
5537 {
5538 return;
5539 }
5540
5541 if finalize.path_span.from_expansion()
5542 || path.iter().any(|seg| seg.ident.span.from_expansion())
5543 {
5544 return;
5545 }
5546
5547 let end_pos =
5548 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5549 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5550 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5559 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5560 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5561 (res == binding.res()).then_some((seg, binding))
5562 });
5563
5564 if let Some((seg, decl)) = unqualified {
5565 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5566 decl,
5567 node_id: finalize.node_id,
5568 path_span: finalize.path_span,
5569 removal_span: path[0].ident.span.until(seg.ident.span),
5570 });
5571 }
5572 }
5573
5574 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5575 if let Some(define_opaque) = define_opaque {
5576 for (id, path) in define_opaque {
5577 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5578 }
5579 }
5580 }
5581
5582 fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) {
5583 for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls {
5584 if let Some(target) = known_eii_macro_resolution {
5587 self.smart_resolve_path(*node_id, &None, target, PathSource::ExternItemImpl);
5588 } else {
5589 self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5590 }
5591 }
5592 }
5593}
5594
5595struct ItemInfoCollector<'a, 'ast, 'ra, 'tcx> {
5599 r: &'a mut Resolver<'ra, 'tcx>,
5600 use_items: Vec<&'ast Item>,
5602}
5603
5604impl ItemInfoCollector<'_, '_, '_, '_> {
5605 fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5606 self.r
5607 .delegation_fn_sigs
5608 .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5609 }
5610}
5611
5612fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5613 let required = generics
5614 .params
5615 .iter()
5616 .filter_map(|param| match ¶m.kind {
5617 ast::GenericParamKind::Lifetime => Some("'_"),
5618 ast::GenericParamKind::Type { default } => {
5619 if default.is_none() {
5620 Some("_")
5621 } else {
5622 None
5623 }
5624 }
5625 ast::GenericParamKind::Const { default, .. } => {
5626 if default.is_none() {
5627 Some("_")
5628 } else {
5629 None
5630 }
5631 }
5632 })
5633 .collect::<Vec<_>>();
5634
5635 if required.is_empty() { None } else { Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", "))) }
5636}
5637
5638impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, 'ast, '_, '_> {
5639 fn visit_item(&mut self, item: &'ast Item) {
5640 match &item.kind {
5641 ItemKind::TyAlias(TyAlias { generics, .. })
5642 | ItemKind::Const(ConstItem { generics, .. })
5643 | ItemKind::Fn(Fn { generics, .. })
5644 | ItemKind::Enum(_, generics, _)
5645 | ItemKind::Struct(_, generics, _)
5646 | ItemKind::Union(_, generics, _)
5647 | ItemKind::Impl(Impl { generics, .. })
5648 | ItemKind::Trait(Trait { generics, .. })
5649 | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5650 if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5651 self.collect_fn_info(&sig.decl, item.id);
5652 }
5653
5654 let def_id = self.r.owner_def_id(item.id);
5655 let count = generics
5656 .params
5657 .iter()
5658 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5659 .count();
5660 self.r.item_generics_num_lifetimes.insert(def_id, count);
5661 }
5662
5663 ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5664 for foreign_item in items {
5665 if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5666 self.collect_fn_info(&sig.decl, foreign_item.id);
5667 }
5668 }
5669 }
5670
5671 ItemKind::Use(..) | ItemKind::ExternCrate(..) => {
5672 self.use_items.push(item);
5673 }
5674
5675 ItemKind::Mod(..)
5676 | ItemKind::Static(..)
5677 | ItemKind::ConstBlock(..)
5678 | ItemKind::MacroDef(..)
5679 | ItemKind::GlobalAsm(..)
5680 | ItemKind::MacCall(..)
5681 | ItemKind::DelegationMac(..) => {}
5682 ItemKind::Delegation(..) => {
5683 }
5688 }
5689 visit::walk_item(self, item)
5690 }
5691
5692 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5693 if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5694 self.collect_fn_info(&sig.decl, item.id);
5695 }
5696
5697 if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5698 let def_id = self.r.owner_def_id(item.id);
5699 if let Some(suggestion) = required_generic_args_suggestion(generics) {
5700 self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5701 }
5702 }
5703 visit::walk_assoc_item(self, item, ctxt);
5704 }
5705}
5706
5707impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5708 pub(crate) fn late_resolve_crate<'ast>(
5710 &mut self,
5711 krate: &'ast Crate,
5712 ) -> (Vec<&'ast Item>, Vec<UseError<'tcx>>) {
5713 with_owner(self, CRATE_NODE_ID, |this| {
5714 let mut info_collector = ItemInfoCollector { r: this, use_items: Vec::new() };
5715 visit::walk_crate(&mut info_collector, krate);
5716 let use_items = info_collector.use_items;
5717 let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5718 late_resolution_visitor
5719 .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5720 visit::walk_crate(&mut late_resolution_visitor, krate);
5721 let LateResolutionVisitor { use_injections, diag_metadata, .. } =
5722 late_resolution_visitor;
5723 for (id, span) in diag_metadata.unused_labels.iter() {
5724 this.lint_buffer.buffer_lint(
5725 lint::builtin::UNUSED_LABELS,
5726 *id,
5727 *span,
5728 crate::diagnostics::UnusedLabel,
5729 );
5730 }
5731 (use_items, use_injections)
5732 })
5733 }
5734}
5735
5736fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5738 let mut path = expected_path.iter().rev();
5739 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5740 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5741 return false;
5742 }
5743 def_id = parent;
5744 }
5745 true
5746}