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 { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, extras: _ } = f;
1504 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);
1505 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));
1506 self.resolve_restriction_path(&f.mut_restriction().kind, ResolvingRestrictionKind::Mut);
1507 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);
1508 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));
1509 if let Some(v) = f.default_value() {
1510 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1511 }
1512 }
1513}
1514
1515impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1516 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1517 let graph_root = resolver.graph_root;
1520 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1521 let start_rib_kind = RibKind::Module(graph_root);
1522 LateResolutionVisitor {
1523 r: resolver,
1524 parent_scope,
1525 ribs: PerNS {
1526 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)],
1527 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)],
1528 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)],
1529 },
1530 last_block_rib: None,
1531 label_ribs: Vec::new(),
1532 lifetime_ribs: Vec::new(),
1533 lifetime_elision_candidates: None,
1534 current_trait_ref: None,
1535 diag_metadata: Default::default(),
1536 in_func_body: false,
1538 lifetime_uses: Default::default(),
1539 use_injections: Vec::new(),
1540 }
1541 }
1542
1543 fn maybe_resolve_ident_in_lexical_scope(
1544 &mut self,
1545 ident: Ident,
1546 ns: Namespace,
1547 ) -> Option<LateDecl<'ra>> {
1548 self.r.resolve_ident_in_lexical_scope(
1549 ident,
1550 ns,
1551 &self.parent_scope,
1552 None,
1553 &self.ribs[ns],
1554 None,
1555 Some(&self.diag_metadata),
1556 )
1557 }
1558
1559 fn resolve_ident_in_lexical_scope(
1560 &mut self,
1561 ident: Ident,
1562 ns: Namespace,
1563 finalize: Option<Finalize>,
1564 ignore_decl: Option<Decl<'ra>>,
1565 ) -> Option<LateDecl<'ra>> {
1566 self.r.resolve_ident_in_lexical_scope(
1567 ident,
1568 ns,
1569 &self.parent_scope,
1570 finalize,
1571 &self.ribs[ns],
1572 ignore_decl,
1573 Some(&self.diag_metadata),
1574 )
1575 }
1576
1577 fn resolve_path(
1578 &mut self,
1579 path: &[Segment],
1580 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1582 source: PathSource<'_, 'ast, 'ra>,
1583 ) -> PathResult<'ra> {
1584 self.r.cm_mut().resolve_path_with_ribs(
1585 path,
1586 opt_ns,
1587 &self.parent_scope,
1588 Some(source),
1589 finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1590 Some(&self.ribs),
1591 None,
1592 None,
1593 Some(&self.diag_metadata),
1594 )
1595 }
1596
1597 fn with_rib<T>(
1617 &mut self,
1618 ns: Namespace,
1619 kind: RibKind<'ra>,
1620 work: impl FnOnce(&mut Self) -> T,
1621 ) -> T {
1622 self.ribs[ns].push(Rib::new(kind));
1623 let ret = work(self);
1624 self.ribs[ns].pop();
1625 ret
1626 }
1627
1628 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1629 let mut forward_ty_ban_rib =
1635 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1636 let mut forward_const_ban_rib =
1637 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1638 for param in params.iter() {
1639 match param.kind {
1640 GenericParamKind::Type { .. } => {
1641 forward_ty_ban_rib
1642 .bindings
1643 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1644 }
1645 GenericParamKind::Const { .. } => {
1646 forward_const_ban_rib
1647 .bindings
1648 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1649 }
1650 GenericParamKind::Lifetime => {}
1651 }
1652 }
1653
1654 if add_self_upper {
1664 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1666 }
1667
1668 let mut forward_ty_ban_rib_const_param_ty = Rib {
1671 bindings: forward_ty_ban_rib.bindings.clone(),
1672 patterns_with_skipped_bindings: Default::default(),
1673 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1674 };
1675 let mut forward_const_ban_rib_const_param_ty = Rib {
1676 bindings: forward_const_ban_rib.bindings.clone(),
1677 patterns_with_skipped_bindings: Default::default(),
1678 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1679 };
1680 if !self.r.features.generic_const_parameter_types() {
1683 forward_ty_ban_rib_const_param_ty.bindings.clear();
1684 forward_const_ban_rib_const_param_ty.bindings.clear();
1685 }
1686
1687 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1688 for param in params {
1689 match param.kind {
1690 GenericParamKind::Lifetime => {
1691 for bound in ¶m.bounds {
1692 this.visit_param_bound(bound, BoundKind::Bound);
1693 }
1694 }
1695 GenericParamKind::Type { ref default } => {
1696 for bound in ¶m.bounds {
1697 this.visit_param_bound(bound, BoundKind::Bound);
1698 }
1699
1700 if let Some(ty) = default {
1701 this.ribs[TypeNS].push(forward_ty_ban_rib);
1702 this.ribs[ValueNS].push(forward_const_ban_rib);
1703 this.visit_ty(ty);
1704 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1705 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1706 }
1707
1708 let i = &Ident::with_dummy_span(param.ident.name);
1710 forward_ty_ban_rib.bindings.swap_remove(i);
1711 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1712 }
1713 GenericParamKind::Const { ref ty, span: _, ref default } => {
1714 if !param.bounds.is_empty() {
::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1716
1717 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1718 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1719 if this.r.features.generic_const_parameter_types() {
1720 this.visit_ty(ty)
1721 } else {
1722 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1723 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1724 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1725 this.visit_ty(ty)
1726 });
1727 this.ribs[TypeNS].pop().unwrap();
1728 this.ribs[ValueNS].pop().unwrap();
1729 }
1730 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1731 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1732
1733 if let Some(expr) = default {
1734 this.ribs[TypeNS].push(forward_ty_ban_rib);
1735 this.ribs[ValueNS].push(forward_const_ban_rib);
1736 this.resolve_anon_const(
1737 expr,
1738 AnonConstKind::ConstArg(IsRepeatExpr::No),
1739 );
1740 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1741 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1742 }
1743
1744 let i = &Ident::with_dummy_span(param.ident.name);
1746 forward_const_ban_rib.bindings.swap_remove(i);
1747 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1748 }
1749 }
1750 }
1751 })
1752 }
1753
1754 #[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(1754u32),
::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))]
1755 fn with_lifetime_rib<T>(
1756 &mut self,
1757 kind: LifetimeRibKind,
1758 work: impl FnOnce(&mut Self) -> T,
1759 ) -> T {
1760 self.lifetime_ribs.push(LifetimeRib::new(kind));
1761 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1762 let ret = work(self);
1763 self.lifetime_elision_candidates = outer_elision_candidates;
1764 self.lifetime_ribs.pop();
1765 ret
1766 }
1767
1768 #[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(1768u32),
::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:1794",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1794u32),
::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:1839",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1839u32),
::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:1843",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1843u32),
::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))]
1769 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1770 let ident = lifetime.ident;
1771
1772 if ident.name == kw::StaticLifetime {
1773 self.record_lifetime_use(
1774 lifetime.id,
1775 LifetimeRes::Static,
1776 LifetimeElisionCandidate::Ignore,
1777 );
1778 return;
1779 }
1780
1781 if ident.name == kw::UnderscoreLifetime {
1782 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1783 }
1784
1785 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1786 while let Some(rib) = lifetime_rib_iter.next() {
1787 let normalized_ident = ident.normalize_to_macros_2_0();
1788 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1789 self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1790
1791 if let LifetimeRes::Param { param, binder } = res {
1792 match self.lifetime_uses.entry(param) {
1793 Entry::Vacant(v) => {
1794 debug!("First use of {:?} at {:?}", res, ident.span);
1795 let use_set = self
1796 .lifetime_ribs
1797 .iter()
1798 .rev()
1799 .find_map(|rib| match rib.kind {
1800 LifetimeRibKind::Item
1803 | LifetimeRibKind::AnonymousReportError
1804 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1805 LifetimeRibKind::AnonymousCreateParameter {
1808 binder: anon_binder,
1809 ..
1810 } => Some(if binder == anon_binder {
1811 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1812 } else {
1813 LifetimeUseSet::Many
1814 }),
1815 LifetimeRibKind::Elided { res: r, error_in_path } => {
1818 Some(if res == r && !error_in_path {
1819 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1820 } else {
1821 LifetimeUseSet::Many
1822 })
1823 }
1824 LifetimeRibKind::Generics { .. }
1825 | LifetimeRibKind::ConstParamTy => None,
1826 LifetimeRibKind::ConcreteAnonConst(_) => {
1827 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1828 }
1829
1830 LifetimeRibKind::ImplTrait => {
1831 if self.r.features.anonymous_lifetime_in_impl_trait() {
1832 None
1833 } else {
1834 Some(LifetimeUseSet::Many)
1835 }
1836 }
1837 })
1838 .unwrap_or(LifetimeUseSet::Many);
1839 debug!(?use_ctxt, ?use_set);
1840 v.insert(use_set);
1841 }
1842 Entry::Occupied(mut o) => {
1843 debug!("Many uses of {:?} at {:?}", res, ident.span);
1844 *o.get_mut() = LifetimeUseSet::Many;
1845 }
1846 }
1847 }
1848 return;
1849 }
1850
1851 match rib.kind {
1852 LifetimeRibKind::Item => break,
1853 LifetimeRibKind::ConstParamTy => {
1854 let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1855 self.record_lifetime_err(lifetime.id, guar);
1856 return;
1857 }
1858 LifetimeRibKind::ConcreteAnonConst(cause) => {
1859 let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1860 self.record_lifetime_err(lifetime.id, guar);
1861 return;
1862 }
1863 LifetimeRibKind::AnonymousCreateParameter { .. }
1864 | LifetimeRibKind::Elided { .. }
1865 | LifetimeRibKind::Generics { .. }
1866 | LifetimeRibKind::ElisionFailure
1867 | LifetimeRibKind::AnonymousReportError
1868 | LifetimeRibKind::ImplTrait => {}
1869 }
1870 }
1871
1872 let normalized_ident = ident.normalize_to_macros_2_0();
1873 let outer_res = lifetime_rib_iter
1874 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1875
1876 let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1877 self.record_lifetime_err(lifetime.id, guar);
1878 }
1879
1880 #[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(1880u32),
::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:1900",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1900u32),
::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))]
1881 fn resolve_anonymous_lifetime(
1882 &mut self,
1883 lifetime: &Lifetime,
1884 id_for_lint: NodeId,
1885 elided: bool,
1886 ) {
1887 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1888
1889 let kind =
1890 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1891 let missing_lifetime = MissingLifetime {
1892 id: lifetime.id,
1893 span: lifetime.ident.span,
1894 kind,
1895 count: 1,
1896 id_for_lint,
1897 };
1898 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1899 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1900 debug!(?rib.kind);
1901 match rib.kind {
1902 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1903 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1904 self.record_lifetime_use(lifetime.id, res, elision_candidate);
1905 return;
1906 }
1907 LifetimeRibKind::AnonymousReportError => {
1908 let guar = if elided {
1909 let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1910 None
1916 } else {
1917 self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1918 if let LifetimeRibKind::Generics {
1922 span,
1923 kind:
1924 LifetimeBinderKind::PolyTrait
1925 | LifetimeBinderKind::WhereBound,
1926 ..
1927 } = rib.kind
1928 {
1929 Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1930 lo: span.shrink_to_lo(),
1931 hi: lifetime.ident.span.shrink_to_hi(),
1932 })
1933 } else {
1934 None
1935 }
1936 })
1937 };
1938 if !self.in_func_body
1941 && let Some((module, _)) = &self.current_trait_ref
1942 && let Some(ty) = &self.diag_metadata.current_self_type
1943 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1944 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1945 module.kind
1946 {
1947 if def_id_matches_path(
1948 self.r.tcx,
1949 trait_id,
1950 &["core", "iter", "traits", "iterator", "Iterator"],
1951 ) {
1952 self.r.dcx().emit_err(
1953 crate::diagnostics::LendingIteratorReportError {
1954 lifetime: lifetime.ident.span,
1955 ty: ty.span,
1956 },
1957 )
1958 } else {
1959 let decl = if !trait_id.is_local()
1960 && let Some(assoc) = self.diag_metadata.current_impl_item
1961 && let AssocItemKind::Type(_) = assoc.kind
1962 && let assocs = self.r.tcx.associated_items(trait_id)
1963 && let Some(ident) = assoc.kind.ident()
1964 && let Some(assoc) = assocs.find_by_ident_and_kind(
1965 self.r.tcx,
1966 ident,
1967 AssocTag::Type,
1968 trait_id,
1969 ) {
1970 let mut decl: MultiSpan =
1971 self.r.tcx.def_span(assoc.def_id).into();
1972 decl.push_span_label(
1973 self.r.tcx.def_span(trait_id),
1974 String::new(),
1975 );
1976 decl
1977 } else {
1978 DUMMY_SP.into()
1979 };
1980 let mut err = self.r.dcx().create_err(
1981 crate::diagnostics::AnonymousLifetimeNonGatReportError {
1982 lifetime: lifetime.ident.span,
1983 decl,
1984 },
1985 );
1986 self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1987 err.emit()
1988 }
1989 } else if self.diag_metadata.in_assoc_ty_binding {
1990 let mut err = self.r.dcx().create_err(
1995 crate::diagnostics::ElidedAnonymousLifetimeReportError {
1996 span: lifetime.ident.span,
1997 suggestion,
1998 },
1999 );
2000 self.suggest_introducing_lifetime_for_assoc_ty_binding(
2001 &mut err,
2002 lifetime.ident.span,
2003 );
2004 err.emit()
2005 } else {
2006 self.r.dcx().emit_err(
2007 crate::diagnostics::ElidedAnonymousLifetimeReportError {
2008 span: lifetime.ident.span,
2009 suggestion,
2010 },
2011 )
2012 }
2013 } else {
2014 self.r.dcx().emit_err(
2015 crate::diagnostics::ExplicitAnonymousLifetimeReportError {
2016 span: lifetime.ident.span,
2017 },
2018 )
2019 };
2020 self.record_lifetime_err(lifetime.id, guar);
2021 return;
2022 }
2023 LifetimeRibKind::Elided { res, .. } => {
2024 self.record_lifetime_use(lifetime.id, res, elision_candidate);
2025 return;
2026 }
2027 LifetimeRibKind::ElisionFailure => {
2028 self.diag_metadata
2029 .current_elision_failures
2030 .push((missing_lifetime, Either::Left(lifetime.id)));
2031 return;
2032 }
2033 LifetimeRibKind::Item => break,
2034 LifetimeRibKind::Generics { .. }
2035 | LifetimeRibKind::ConstParamTy
2036 | LifetimeRibKind::ImplTrait => {}
2037 LifetimeRibKind::ConcreteAnonConst(_) => {
2038 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2040 }
2041 }
2042 }
2043 let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2044 self.record_lifetime_err(lifetime.id, guar);
2045 }
2046
2047 fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2048 let Some((rib, span)) =
2049 self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2050 LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2051 Some((rib, span))
2052 }
2053 _ => None,
2054 })
2055 else {
2056 return;
2057 };
2058 if !rib.bindings.is_empty() {
2059 err.span_label(
2060 span,
2061 ::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!(
2062 "there {} named lifetime{} specified on the impl block you could use",
2063 if rib.bindings.len() == 1 { "is a" } else { "are" },
2064 pluralize!(rib.bindings.len()),
2065 ),
2066 );
2067 if rib.bindings.len() == 1 {
2068 err.span_suggestion_verbose(
2069 lifetime.shrink_to_hi(),
2070 "consider using the lifetime from the impl block",
2071 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ",
rib.bindings.keys().next().unwrap()))
})format!("{} ", rib.bindings.keys().next().unwrap()),
2072 Applicability::MaybeIncorrect,
2073 );
2074 }
2075 } else {
2076 struct AnonRefFinder;
2077 impl<'ast> Visitor<'ast> for AnonRefFinder {
2078 type Result = ControlFlow<Span>;
2079
2080 fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2081 if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2082 return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2083 }
2084 visit::walk_ty(self, ty)
2085 }
2086
2087 fn visit_lifetime(
2088 &mut self,
2089 lt: &'ast ast::Lifetime,
2090 _cx: visit::LifetimeCtxt,
2091 ) -> Self::Result {
2092 if lt.ident.name == kw::UnderscoreLifetime {
2093 return ControlFlow::Break(lt.ident.span);
2094 }
2095 visit::walk_lifetime(self, lt)
2096 }
2097 }
2098
2099 if let Some(ty) = &self.diag_metadata.current_self_type
2100 && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2101 {
2102 err.multipart_suggestion(
2103 "add a lifetime to the impl block and use it in the self type and associated \
2104 type",
2105 ::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![
2106 (span, "<'a>".to_string()),
2107 (sp, "'a ".to_string()),
2108 (lifetime.shrink_to_hi(), "'a ".to_string()),
2109 ],
2110 Applicability::MaybeIncorrect,
2111 );
2112 } else if let Some(item) = &self.diag_metadata.current_item
2113 && let ItemKind::Impl(impl_) = &item.kind
2114 && let Some(of_trait) = &impl_.of_trait
2115 && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2116 {
2117 err.multipart_suggestion(
2118 "add a lifetime to the impl block and use it in the trait and associated type",
2119 ::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![
2120 (span, "<'a>".to_string()),
2121 (sp, "'a".to_string()),
2122 (lifetime.shrink_to_hi(), "'a ".to_string()),
2123 ],
2124 Applicability::MaybeIncorrect,
2125 );
2126 } else {
2127 err.span_label(
2128 span,
2129 "you could add a lifetime on the impl block, if the trait or the self type \
2130 could have one",
2131 );
2132 }
2133 }
2134 }
2135
2136 #[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(2136u32),
::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))]
2137 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2138 let id = self.r.next_node_id();
2139 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2140
2141 self.record_lifetime_use(
2142 anchor_id,
2143 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2144 LifetimeElisionCandidate::Ignore,
2145 );
2146 self.resolve_anonymous_lifetime(<, anchor_id, true);
2147 }
2148
2149 #[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(2149u32),
::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:2157",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2157u32),
::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))]
2150 fn create_fresh_lifetime(
2151 &mut self,
2152 ident: Ident,
2153 binder: NodeId,
2154 kind: MissingLifetimeKind,
2155 ) -> LifetimeRes {
2156 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2157 debug!(?ident.span);
2158
2159 let param = self.r.next_node_id();
2161 let res = LifetimeRes::Fresh { param, kind };
2162 self.record_lifetime_def(param, res);
2163
2164 self.r
2166 .current_owner
2167 .extra_lifetime_params_map
2168 .entry(binder)
2169 .or_insert_with(Vec::new)
2170 .push((ident, param, kind));
2171 res
2172 }
2173
2174 #[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(2174u32),
::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))]
2175 fn resolve_elided_lifetimes_in_path(
2176 &mut self,
2177 partial_res: PartialRes,
2178 path: &[Segment],
2179 source: PathSource<'_, 'ast, 'ra>,
2180 path_span: Span,
2181 ) {
2182 let proj_start = path.len() - partial_res.unresolved_segments();
2183 for (i, segment) in path.iter().enumerate() {
2184 if segment.has_lifetime_args {
2185 continue;
2186 }
2187 let Some(segment_id) = segment.id else {
2188 continue;
2189 };
2190
2191 let type_def_id = match partial_res.base_res() {
2194 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2195 self.r.tcx.parent(def_id)
2196 }
2197 Res::Def(DefKind::Variant, def_id)
2198 if i + 2 == proj_start && segment.has_generic_args =>
2199 {
2200 self.r.tcx.parent(def_id)
2201 }
2202 Res::Def(DefKind::Variant, def_id)
2203 if i + 1 == proj_start
2204 && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2205 {
2206 self.r.tcx.parent(def_id)
2207 }
2208 Res::Def(DefKind::Struct, def_id)
2209 | Res::Def(DefKind::Union, def_id)
2210 | Res::Def(DefKind::Enum, def_id)
2211 | Res::Def(DefKind::TyAlias, def_id)
2212 | Res::Def(DefKind::Trait, def_id)
2213 if i + 1 == proj_start =>
2214 {
2215 def_id
2216 }
2217 _ => continue,
2218 };
2219
2220 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2221 if expected_lifetimes == 0 {
2222 continue;
2223 }
2224
2225 let node_ids = self.r.next_node_ids(expected_lifetimes);
2226 self.record_lifetime_use(
2227 segment_id,
2228 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2229 LifetimeElisionCandidate::Ignore,
2230 );
2231
2232 let inferred = match source {
2233 PathSource::Trait(..)
2234 | PathSource::TraitItem(..)
2235 | PathSource::Type
2236 | PathSource::PreciseCapturingArg(..)
2237 | PathSource::ReturnTypeNotation
2238 | PathSource::Macro
2239 | PathSource::Module => false,
2240 PathSource::Expr(..)
2241 | PathSource::Pat
2242 | PathSource::Struct(_)
2243 | PathSource::TupleStruct(..)
2244 | PathSource::DefineOpaques
2245 | PathSource::Delegation
2246 | PathSource::ExternItemImpl => true,
2247 };
2248 if inferred {
2249 for id in node_ids {
2252 self.record_lifetime_use(
2253 id,
2254 LifetimeRes::Infer,
2255 LifetimeElisionCandidate::Ignore,
2256 );
2257 }
2258 continue;
2259 }
2260
2261 let elided_lifetime_span = if segment.has_generic_args {
2262 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2264 } else {
2265 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2269 };
2270 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2271
2272 let kind = if segment.has_generic_args {
2273 MissingLifetimeKind::Comma
2274 } else {
2275 MissingLifetimeKind::Brackets
2276 };
2277 let missing_lifetime = MissingLifetime {
2278 id: node_ids.start,
2279 id_for_lint: segment_id,
2280 span: elided_lifetime_span,
2281 kind,
2282 count: expected_lifetimes,
2283 };
2284 let mut should_lint = true;
2285 for rib in self.lifetime_ribs.iter().rev() {
2286 match rib.kind {
2287 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2294 | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2295 let sess = self.r.tcx.sess;
2296 let subdiag = elided_lifetime_in_path_suggestion(
2297 sess.source_map(),
2298 expected_lifetimes,
2299 path_span,
2300 !segment.has_generic_args,
2301 elided_lifetime_span,
2302 );
2303 let guar = self.r.dcx().emit_err(
2304 crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2305 span: path_span,
2306 subdiag,
2307 },
2308 );
2309 should_lint = false;
2310
2311 for id in node_ids {
2312 self.record_lifetime_err(id, guar);
2313 }
2314 break;
2315 }
2316 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2318 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2320 for id in node_ids {
2321 let res = self.create_fresh_lifetime(ident, binder, kind);
2322 self.record_lifetime_use(
2323 id,
2324 res,
2325 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2326 );
2327 }
2328 break;
2329 }
2330 LifetimeRibKind::Elided { res, error_in_path: false } => {
2331 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2332 for id in node_ids {
2333 self.record_lifetime_use(
2334 id,
2335 res,
2336 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2337 );
2338 }
2339 break;
2340 }
2341 LifetimeRibKind::ElisionFailure => {
2342 self.diag_metadata
2343 .current_elision_failures
2344 .push((missing_lifetime, Either::Right(node_ids)));
2345 break;
2346 }
2347 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2352 let guar =
2353 self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2354 for id in node_ids {
2355 self.record_lifetime_err(id, guar);
2356 }
2357 break;
2358 }
2359 LifetimeRibKind::Generics { .. }
2360 | LifetimeRibKind::ConstParamTy
2361 | LifetimeRibKind::ImplTrait => {}
2362 LifetimeRibKind::ConcreteAnonConst(_) => {
2363 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2365 }
2366 }
2367 }
2368
2369 if should_lint {
2370 let include_angle_bracket = !segment.has_generic_args;
2371 self.r.lint_buffer.dyn_buffer_lint_any(
2372 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2373 segment_id,
2374 elided_lifetime_span,
2375 move |dcx, level, sess| {
2376 let source_map = sess
2377 .downcast_ref::<rustc_session::Session>()
2378 .expect("expected a `Session`")
2379 .source_map();
2380 crate::diagnostics::ElidedLifetimesInPaths {
2381 subdiag: elided_lifetime_in_path_suggestion(
2382 source_map,
2383 expected_lifetimes,
2384 path_span,
2385 include_angle_bracket,
2386 elided_lifetime_span,
2387 ),
2388 }
2389 .into_diag(dcx, level)
2390 },
2391 );
2392 }
2393 }
2394 }
2395
2396 #[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(2397u32),
::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))]
2398 fn record_lifetime_use(
2399 &mut self,
2400 id: NodeId,
2401 res: LifetimeRes,
2402 candidate: LifetimeElisionCandidate,
2403 ) {
2404 self.record_lifetime_def(id, res);
2405
2406 match res {
2407 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2408 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2409 candidates.push((res, candidate));
2410 }
2411 }
2412 LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2413 }
2414 }
2415
2416 #[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(2418u32),
::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))]
2419 fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2420 self.record_lifetime_def(id, LifetimeRes::Error(guar));
2421 }
2422
2423 #[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(2424u32),
::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))]
2425 fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2426 if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2427 panic!(
2428 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2429 )
2430 }
2431 }
2432
2433 #[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(2434u32),
::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:2450",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2450u32),
::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))]
2435 fn resolve_fn_signature(
2436 &mut self,
2437 fn_id: NodeId,
2438 has_self: bool,
2439 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2440 output_ty: &'ast FnRetTy,
2441 report_elided_lifetimes_in_path: bool,
2442 ) {
2443 let rib = LifetimeRibKind::AnonymousCreateParameter {
2444 binder: fn_id,
2445 report_in_path: report_elided_lifetimes_in_path,
2446 };
2447 self.with_lifetime_rib(rib, |this| {
2448 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2450 debug!(?elision_lifetime);
2451
2452 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2453 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2454 if fn_id == this.r.current_owner.id {
2455 this.r.current_owner.lifetime_elision_allowed = true;
2456 }
2457 LifetimeRibKind::elided(*res)
2458 } else {
2459 LifetimeRibKind::ElisionFailure
2460 };
2461 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2462 let elision_failures =
2463 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2464 if !elision_failures.is_empty() {
2465 let Err(failure_info) = elision_lifetime else { bug!() };
2466 let guar = this.report_missing_lifetime_specifiers(
2467 elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2468 Some(failure_info),
2469 );
2470 let mut record_res = |lifetime| this.record_lifetime_err(lifetime, guar);
2471 for (_, nodes) in elision_failures {
2472 match nodes {
2473 Either::Left(node_id) => record_res(node_id),
2474 Either::Right(node_ids) => {
2475 for lifetime in node_ids {
2476 record_res(lifetime)
2477 }
2478 }
2479 }
2480 }
2481 }
2482 });
2483 }
2484
2485 fn resolve_fn_params(
2489 &mut self,
2490 has_self: bool,
2491 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2492 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2493 enum Elision {
2494 None,
2496 Self_(LifetimeRes),
2498 Param(LifetimeRes),
2500 Err,
2502 }
2503
2504 let outer_candidates = self.lifetime_elision_candidates.take();
2506
2507 let mut elision_lifetime = Elision::None;
2509 let mut parameter_info = Vec::new();
2511 let mut all_candidates = Vec::new();
2512
2513 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())];
2515 for (pat, _) in inputs.clone() {
2516 {
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:2516",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2516u32),
::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:?}");
2517 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
2518 if let Some(pat) = pat {
2519 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2520 }
2521 });
2522 }
2523 self.apply_pattern_bindings(bindings);
2524
2525 for (index, (pat, ty)) in inputs.enumerate() {
2526 {
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:2526",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2526u32),
::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:?}");
2527 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);
2529 self.lifetime_elision_candidates = Some(Default::default());
2530 self.visit_ty(ty);
2531 let local_candidates = self.lifetime_elision_candidates.take();
2532
2533 if let Some(candidates) = local_candidates {
2534 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2535 let lifetime_count = distinct.len();
2536 if lifetime_count != 0 {
2537 parameter_info.push(ElisionFnParameter {
2538 index,
2539 ident: if let Some(pat) = pat
2540 && let PatKind::Ident(_, ident, _) = pat.kind
2541 {
2542 Some(ident)
2543 } else {
2544 None
2545 },
2546 lifetime_count,
2547 span: ty.span,
2548 });
2549 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2550 match candidate {
2551 LifetimeElisionCandidate::Ignore => None,
2552 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2553 }
2554 }));
2555 }
2556 if !distinct.is_empty() {
2557 match elision_lifetime {
2558 Elision::None => {
2560 if let Some(res) = distinct.get_only() {
2561 elision_lifetime = Elision::Param(*res)
2563 } else {
2564 elision_lifetime = Elision::Err;
2566 }
2567 }
2568 Elision::Param(_) => elision_lifetime = Elision::Err,
2570 Elision::Self_(_) | Elision::Err => {}
2572 }
2573 }
2574 }
2575
2576 if index == 0 && has_self {
2578 let self_lifetime = self.find_lifetime_for_self(ty);
2579 elision_lifetime = match self_lifetime {
2580 Set1::One(lifetime) => Elision::Self_(lifetime),
2582 Set1::Many => Elision::Err,
2587 Set1::Empty => Elision::None,
2590 }
2591 }
2592 {
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:2592",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2592u32),
::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");
2593 }
2594
2595 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);
2597 self.lifetime_elision_candidates = outer_candidates;
2598
2599 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2600 return Ok(res);
2601 }
2602
2603 Err((all_candidates, parameter_info))
2605 }
2606
2607 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2609 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2613 r: &'a Resolver<'ra, 'tcx>,
2614 impl_self: Option<Res>,
2615 lifetime: Set1<LifetimeRes>,
2616 }
2617
2618 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2619 fn visit_ty(&mut self, ty: &'ra Ty) {
2620 {
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:2620",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2620u32),
::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);
2621 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2622 let mut visitor =
2624 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2625 visitor.visit_ty(ty);
2626 {
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:2626",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2626u32),
::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);
2627 if visitor.self_found {
2628 let lt_id = if let Some(lt) = lt {
2629 lt.id
2630 } else {
2631 let res = self.r.current_owner.lifetimes_res_map[&ty.id];
2632 let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2633 start
2634 };
2635 let lt_res = self.r.current_owner.lifetimes_res_map[<_id];
2636 {
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:2636",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2636u32),
::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);
2637 self.lifetime.insert(lt_res);
2638 }
2639 }
2640 visit::walk_ty(self, ty)
2641 }
2642
2643 fn visit_expr(&mut self, _: &'ra Expr) {}
2646 }
2647
2648 struct SelfVisitor<'a, 'ra, 'tcx> {
2651 r: &'a Resolver<'ra, 'tcx>,
2652 impl_self: Option<Res>,
2653 self_found: bool,
2654 }
2655
2656 impl SelfVisitor<'_, '_, '_> {
2657 fn is_self_ty(&self, ty: &Ty) -> bool {
2659 match ty.kind {
2660 TyKind::ImplicitSelf => true,
2661 TyKind::Path(None, _) => {
2662 let path_res = self.r.partial_res_map[&ty.id].full_res();
2663 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2664 return true;
2665 }
2666 self.impl_self.is_some() && path_res == self.impl_self
2667 }
2668 _ => false,
2669 }
2670 }
2671 }
2672
2673 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2674 fn visit_ty(&mut self, ty: &'ra Ty) {
2675 {
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:2675",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2675u32),
::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);
2676 if self.is_self_ty(ty) {
2677 {
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:2677",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2677u32),
::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");
2678 self.self_found = true;
2679 }
2680 visit::walk_ty(self, ty)
2681 }
2682
2683 fn visit_expr(&mut self, _: &'ra Expr) {}
2686 }
2687
2688 let impl_self = self
2689 .diag_metadata
2690 .current_self_type
2691 .and_then(|ty| {
2692 if let TyKind::Path(None, _) = ty.kind {
2693 self.r.partial_res_map.get(&ty.id)
2694 } else {
2695 None
2696 }
2697 })
2698 .and_then(|res| res.full_res())
2699 .filter(|res| {
2700 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
Res::PrimTy(_) => true,
_ => false,
}matches!(
2704 res,
2705 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2706 )
2707 });
2708 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2709 visitor.visit_ty(ty);
2710 {
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:2710",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2710u32),
::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);
2711 visitor.lifetime
2712 }
2713
2714 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2717 let mut suggestion = None;
2718
2719 for i in (0..self.label_ribs.len()).rev() {
2720 let rib = &self.label_ribs[i];
2721
2722 if let RibKind::MacroDefinition(def) = rib.kind
2723 && def == self.r.macro_def(label.span.ctxt())
2726 {
2727 label.span.remove_mark();
2728 }
2729
2730 let ident = label.normalize_to_macro_rules();
2731 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2732 let definition_span = ident.span;
2733 return if self.is_label_valid_from_rib(i) {
2734 Ok((*id, definition_span))
2735 } else {
2736 Err(ResolutionError::UnreachableLabel {
2737 name: label.name,
2738 definition_span,
2739 suggestion,
2740 })
2741 };
2742 }
2743
2744 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2747 }
2748
2749 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2750 }
2751
2752 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2754 let ribs = &self.label_ribs[rib_index + 1..];
2755 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2756 }
2757
2758 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2759 {
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:2759",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2759u32),
::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");
2760 let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2761 self.with_current_self_item(item, |this| {
2762 this.with_generic_param_rib(
2763 &generics.params,
2764 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2765 item.id,
2766 LifetimeBinderKind::Item,
2767 generics.span,
2768 |this| {
2769 let item_def_id = this.r.current_owner.def_id.to_def_id();
2770 this.with_self_rib(
2771 Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2772 |this| {
2773 visit::walk_item(this, item);
2774 },
2775 );
2776 },
2777 );
2778 });
2779 }
2780
2781 fn future_proof_import(&mut self, use_tree: &UseTree) {
2782 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2783 let ident = segment.ident;
2784 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2785 return;
2786 }
2787
2788 let nss = match use_tree.kind {
2789 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2790 _ => &[TypeNS],
2791 };
2792 let report_error = |this: &Self, ns| {
2793 if this.should_report_errs() {
2794 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2795 this.r.dcx().emit_err(crate::diagnostics::ImportsCannotReferTo {
2796 span: ident.span,
2797 what,
2798 });
2799 }
2800 };
2801
2802 for &ns in nss {
2803 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2804 Some(LateDecl::RibDef(..)) => {
2805 report_error(self, ns);
2806 }
2807 Some(LateDecl::Decl(binding)) => {
2808 if let Some(LateDecl::RibDef(..)) =
2809 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2810 {
2811 report_error(self, ns);
2812 }
2813 }
2814 None => {}
2815 }
2816 }
2817 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2818 for (use_tree, _) in items {
2819 self.future_proof_import(use_tree);
2820 }
2821 }
2822 }
2823
2824 fn resolve_item(&mut self, item: &'ast Item) {
2825 let mod_inner_docs =
2826 #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Mod(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2827 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(..)) {
2828 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2829 }
2830
2831 {
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:2831",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2831u32),
::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);
2832
2833 let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2834 match &item.kind {
2835 ItemKind::TyAlias(TyAlias { generics, .. }) => {
2836 self.with_generic_param_rib(
2837 &generics.params,
2838 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2839 item.id,
2840 LifetimeBinderKind::Item,
2841 generics.span,
2842 |this| visit::walk_item(this, item),
2843 );
2844 }
2845
2846 ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2847 self.with_generic_param_rib(
2848 &generics.params,
2849 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2850 item.id,
2851 LifetimeBinderKind::Function,
2852 generics.span,
2853 |this| visit::walk_item(this, item),
2854 );
2855 self.resolve_define_opaques(define_opaque);
2856 }
2857
2858 ItemKind::Enum(_, generics, _)
2859 | ItemKind::Struct(_, generics, _)
2860 | ItemKind::Union(_, generics, _) => {
2861 self.resolve_adt(item, generics);
2862 }
2863
2864 ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2865 self.diag_metadata.current_impl_items = Some(impl_items);
2866 self.resolve_implementation(
2867 &item.attrs,
2868 generics,
2869 of_trait.as_deref(),
2870 self_ty,
2871 item.id,
2872 impl_items,
2873 );
2874 self.diag_metadata.current_impl_items = None;
2875 }
2876
2877 ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2878 self.resolve_restriction_path(
2880 &impl_restriction.kind,
2881 ResolvingRestrictionKind::Impl,
2882 );
2883
2884 self.with_generic_param_rib(
2886 &generics.params,
2887 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2888 item.id,
2889 LifetimeBinderKind::Item,
2890 generics.span,
2891 |this| {
2892 let local_def_id = this.r.current_owner.def_id.to_def_id();
2893 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2894 this.visit_generics(generics);
2895 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);
2896 this.resolve_trait_items(items);
2897 });
2898 },
2899 );
2900 }
2901
2902 ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2903 self.with_generic_param_rib(
2905 &generics.params,
2906 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2907 item.id,
2908 LifetimeBinderKind::Item,
2909 generics.span,
2910 |this| {
2911 let local_def_id = this.r.current_owner.def_id.to_def_id();
2912 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2913 this.visit_generics(generics);
2914 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);
2915 });
2916 },
2917 );
2918 }
2919
2920 ItemKind::Mod(..) => {
2921 let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2922 let orig_module = replace(&mut self.parent_scope.module, module);
2923 self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2924 this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2925 if mod_inner_docs {
2926 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2927 }
2928 let old_macro_rules = this.parent_scope.macro_rules;
2929 visit::walk_item(this, item);
2930 if item.attrs.iter().all(|attr| {
2933 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2934 }) {
2935 this.parent_scope.macro_rules = old_macro_rules;
2936 }
2937 })
2938 });
2939 self.parent_scope.module = orig_module;
2940 }
2941
2942 ItemKind::Static(ast::StaticItem {
2943 ident, ty, expr, define_opaque, eii_impls, ..
2944 }) => {
2945 self.with_static_rib(def_kind, |this| {
2946 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| {
2947 this.visit_ty(ty);
2948 });
2949 if let Some(expr) = expr {
2950 this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2953 }
2954 });
2955 self.resolve_define_opaques(define_opaque);
2956 self.resolve_eii(&eii_impls);
2957 }
2958
2959 ItemKind::Const(ast::ConstItem {
2960 ident,
2961 generics,
2962 ty,
2963 body,
2964 kind,
2965 define_opaque,
2966 defaultness: _,
2967 }) => {
2968 self.with_generic_param_rib(
2969 &generics.params,
2970 RibKind::Item(
2971 if self.r.features.generic_const_items() {
2972 HasGenericParams::Yes(generics.span)
2973 } else {
2974 HasGenericParams::No
2975 },
2976 def_kind,
2977 ),
2978 item.id,
2979 LifetimeBinderKind::ConstItem,
2980 generics.span,
2981 |this| {
2982 this.visit_generics(generics);
2983
2984 this.with_lifetime_rib(
2985 LifetimeRibKind::elided(LifetimeRes::Static),
2986 |this: &mut LateResolutionVisitor<'a, 'ast, 'ra, 'tcx>| {
2987 if *kind == ast::ConstItemKind::TypeConst
2988 && !this.r.features.generic_const_parameter_types()
2989 {
2990 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2991 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2992 this.with_lifetime_rib(
2993 LifetimeRibKind::ConstParamTy,
2994 |this| this.visit_ty(ty),
2995 )
2996 })
2997 });
2998 } else {
2999 this.visit_ty(ty);
3000 }
3001 },
3002 );
3003
3004 this.resolve_const_item_rhs(body, Some((*ident, ConstantItemKind::Const)));
3005 },
3006 );
3007 self.resolve_define_opaques(define_opaque);
3008 }
3009 ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
3010 .with_generic_param_rib(
3011 &[],
3012 RibKind::Item(HasGenericParams::No, def_kind),
3013 item.id,
3014 LifetimeBinderKind::ConstItem,
3015 DUMMY_SP,
3016 |this| {
3017 this.with_lifetime_rib(
3018 LifetimeRibKind::elided(LifetimeRes::Infer),
3019 |this| {
3020 this.with_constant_rib(
3021 IsRepeatExpr::No,
3022 ConstantHasGenerics::Yes,
3023 Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
3024 |this| this.resolve_labeled_block(None, block.id, block),
3025 )
3026 },
3027 );
3028 },
3029 ),
3030
3031 ItemKind::Use(use_tree) => {
3032 let maybe_exported = match use_tree.kind {
3033 UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3034 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3035 };
3036 self.resolve_doc_links(&item.attrs, maybe_exported);
3037
3038 self.future_proof_import(use_tree);
3039 }
3040
3041 ItemKind::MacroDef(_, macro_def) => {
3042 if macro_def.macro_rules {
3045 let def_id = self.r.current_owner.def_id;
3046 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3047 }
3048
3049 if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3050 ¯o_def.eii_declaration
3051 {
3052 self.smart_resolve_path(
3053 item.id,
3054 &None,
3055 extern_item_path,
3056 PathSource::ExternItemImpl,
3057 );
3058 }
3059 }
3060
3061 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3062 visit::walk_item(self, item);
3063 }
3064
3065 ItemKind::Delegation(delegation) => {
3066 let span = delegation.path.segments.last().unwrap().ident.span;
3067 self.with_generic_param_rib(
3068 &[],
3069 RibKind::Item(HasGenericParams::Yes(span), def_kind),
3070 item.id,
3071 LifetimeBinderKind::Function,
3072 span,
3073 |this| this.resolve_delegation(delegation, item.id, false),
3074 );
3075 }
3076
3077 ItemKind::ExternCrate(..) => {}
3078
3079 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3080 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3081 }
3082 }
3083 }
3084
3085 fn with_generic_param_rib<F>(
3086 &mut self,
3087 params: &[GenericParam],
3088 kind: RibKind<'ra>,
3089 binder: NodeId,
3090 generics_kind: LifetimeBinderKind,
3091 generics_span: Span,
3092 f: F,
3093 ) where
3094 F: FnOnce(&mut Self),
3095 {
3096 {
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:3096",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3096u32),
::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");
3097 let lifetime_kind =
3098 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3099
3100 let mut function_type_rib = Rib::new(kind);
3101 let mut function_value_rib = Rib::new(kind);
3102 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3103
3104 if !params.is_empty() {
3106 let mut seen_bindings = FxHashMap::default();
3107 let mut seen_lifetimes = FxHashSet::default();
3109
3110 for ns in [ValueNS, TypeNS] {
3112 for parent_rib in self.ribs[ns].iter().rev() {
3113 if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
RibKind::Module(..) | RibKind::Block(..) => true,
_ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3116 break;
3117 }
3118
3119 seen_bindings
3120 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3121 }
3122 }
3123
3124 for rib in self.lifetime_ribs.iter().rev() {
3126 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3127 if let LifetimeRibKind::Item = rib.kind {
3128 break;
3129 }
3130 }
3131
3132 for param in params {
3133 let ident = param.ident.normalize_to_macros_2_0();
3134 {
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:3134",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3134u32),
::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);
3135
3136 if let GenericParamKind::Lifetime = param.kind
3137 && let Some(&original) = seen_lifetimes.get(&ident)
3138 {
3139 let guar = diagnostics::signal_lifetime_shadowing(
3140 self.r.tcx.sess,
3141 original,
3142 param.ident,
3143 );
3144 self.record_lifetime_err(param.id, guar);
3146 continue;
3147 }
3148
3149 match seen_bindings.entry(ident) {
3150 Entry::Occupied(entry) => {
3151 let span = *entry.get();
3152 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3153 let guar = self.r.report_error(param.ident.span, err);
3154 let rib = match param.kind {
3155 GenericParamKind::Lifetime => {
3156 self.record_lifetime_err(param.id, guar);
3158 continue;
3159 }
3160 GenericParamKind::Type { .. } => &mut function_type_rib,
3161 GenericParamKind::Const { .. } => &mut function_value_rib,
3162 };
3163
3164 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3166 rib.bindings.insert(ident, Res::Err);
3167 continue;
3168 }
3169 Entry::Vacant(entry) => {
3170 entry.insert(param.ident.span);
3171 }
3172 }
3173
3174 if param.ident.name == kw::UnderscoreLifetime {
3175 let is_raw_underscore_lifetime = self
3178 .r
3179 .tcx
3180 .sess
3181 .psess
3182 .raw_identifier_spans
3183 .iter()
3184 .any(|span| span == param.span());
3185
3186 let guar = self
3187 .r
3188 .dcx()
3189 .create_err(crate::diagnostics::UnderscoreLifetimeIsReserved {
3190 span: param.ident.span,
3191 })
3192 .emit_unless_delay(is_raw_underscore_lifetime);
3193 self.record_lifetime_err(param.id, guar);
3195 continue;
3196 }
3197
3198 if param.ident.name == kw::StaticLifetime {
3199 let guar =
3200 self.r.dcx().emit_err(crate::diagnostics::StaticLifetimeIsReserved {
3201 span: param.ident.span,
3202 lifetime: param.ident,
3203 });
3204 self.record_lifetime_err(param.id, guar);
3206 continue;
3207 }
3208
3209 let def_id = self.r.local_def_id(param.id);
3210
3211 let (rib, def_kind) = match param.kind {
3213 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3214 GenericParamKind::Const { .. } => {
3215 (&mut function_value_rib, DefKind::ConstParam)
3216 }
3217 GenericParamKind::Lifetime => {
3218 let res = LifetimeRes::Param { param: def_id, binder };
3219 self.record_lifetime_def(param.id, res);
3220 function_lifetime_rib.bindings.insert(ident, (param.id, res));
3221 continue;
3222 }
3223 };
3224
3225 let res = match kind {
3226 RibKind::Item(..) | RibKind::AssocItem => {
3227 Res::Def(def_kind, def_id.to_def_id())
3228 }
3229 RibKind::Normal => {
3230 if self.r.features.non_lifetime_binders()
3233 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamKind::Type { .. } => true,
_ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3234 {
3235 Res::Def(def_kind, def_id.to_def_id())
3236 } else {
3237 Res::Err
3238 }
3239 }
3240 _ => ::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),
3241 };
3242 self.r.record_partial_res(param.id, PartialRes::new(res));
3243 rib.bindings.insert(ident, res);
3244 }
3245 }
3246
3247 self.lifetime_ribs.push(function_lifetime_rib);
3248 self.ribs[ValueNS].push(function_value_rib);
3249 self.ribs[TypeNS].push(function_type_rib);
3250
3251 f(self);
3252
3253 self.ribs[TypeNS].pop();
3254 self.ribs[ValueNS].pop();
3255 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3256
3257 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3259 for (_, res) in function_lifetime_rib.bindings.values() {
3260 candidates.retain(|(r, _)| r != res);
3261 }
3262 }
3263
3264 if let LifetimeBinderKind::FnPtrType
3265 | LifetimeBinderKind::WhereBound
3266 | LifetimeBinderKind::Function
3267 | LifetimeBinderKind::ImplBlock = generics_kind
3268 {
3269 self.maybe_report_lifetime_uses(generics_span, params)
3270 }
3271 }
3272
3273 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3274 self.label_ribs.push(Rib::new(kind));
3275 f(self);
3276 self.label_ribs.pop();
3277 }
3278
3279 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3280 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3281 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3282 }
3283
3284 #[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(3292u32),
::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))]
3293 fn with_constant_rib(
3294 &mut self,
3295 is_repeat: IsRepeatExpr,
3296 may_use_generics: ConstantHasGenerics,
3297 item: Option<(Ident, ConstantItemKind)>,
3298 f: impl FnOnce(&mut Self),
3299 ) {
3300 let f = |this: &mut Self| {
3301 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3302 this.with_rib(
3303 TypeNS,
3304 RibKind::ConstantItem(
3305 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3306 item,
3307 ),
3308 |this| {
3309 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3310 },
3311 )
3312 })
3313 };
3314
3315 if let ConstantHasGenerics::No(cause) = may_use_generics {
3316 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3317 } else {
3318 f(self)
3319 }
3320 }
3321
3322 fn with_current_self_type<T>(
3323 &mut self,
3324 self_type: &'ast Ty,
3325 f: impl FnOnce(&mut Self) -> T,
3326 ) -> T {
3327 let previous_value = replace(&mut self.diag_metadata.current_self_type, Some(self_type));
3329 let result = f(self);
3330 self.diag_metadata.current_self_type = previous_value;
3331 result
3332 }
3333
3334 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3335 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3336 let result = f(self);
3337 self.diag_metadata.current_self_item = previous_value;
3338 result
3339 }
3340
3341 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3343 let trait_assoc_items =
3344 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3345
3346 for item in trait_items {
3347 with_owner(self, item.id, |this| this.resolve_trait_item(item));
3348 }
3349
3350 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3351 }
3352
3353 fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3354 let walk_assoc_item =
3355 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3356 this.with_generic_param_rib(
3357 &generics.params,
3358 RibKind::AssocItem,
3359 item.id,
3360 kind,
3361 generics.span,
3362 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3363 );
3364 };
3365
3366 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3367 match &item.kind {
3368 AssocItemKind::Const(ast::ConstItem {
3369 generics,
3370 ty,
3371 body,
3372 kind,
3373 define_opaque,
3374 ..
3375 }) => {
3376 self.with_generic_param_rib(
3377 &generics.params,
3378 RibKind::AssocItem,
3379 item.id,
3380 LifetimeBinderKind::ConstItem,
3381 generics.span,
3382 |this| {
3383 this.with_lifetime_rib(
3384 LifetimeRibKind::Elided {
3385 res: LifetimeRes::Static,
3386 error_in_path: true,
3387 },
3388 |this| {
3389 this.visit_generics(generics);
3390 if *kind == ConstItemKind::TypeConst
3391 && !this.r.features.generic_const_parameter_types()
3392 {
3393 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3394 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3395 this.with_lifetime_rib(
3396 LifetimeRibKind::ConstParamTy,
3397 |this| this.visit_ty(ty),
3398 )
3399 })
3400 });
3401 } else {
3402 this.visit_ty(ty);
3403 }
3404
3405 this.resolve_const_item_rhs(body, None);
3414 },
3415 )
3416 },
3417 );
3418
3419 self.resolve_define_opaques(define_opaque);
3420 }
3421 AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3422 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3423
3424 self.resolve_define_opaques(define_opaque);
3425 }
3426 AssocItemKind::Delegation(delegation) => {
3427 self.with_generic_param_rib(
3428 &[],
3429 RibKind::AssocItem,
3430 item.id,
3431 LifetimeBinderKind::Function,
3432 delegation.path.segments.last().unwrap().ident.span,
3433 |this| this.resolve_delegation(delegation, item.id, false),
3434 );
3435 }
3436 AssocItemKind::Type(TyAlias { generics, .. }) => self
3437 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3438 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3439 }),
3440 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3441 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3442 }
3443 };
3444 }
3445
3446 fn with_optional_trait_ref<T>(
3448 &mut self,
3449 opt_trait_ref: Option<&TraitRef>,
3450 self_type: &'ast Ty,
3451 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3452 ) -> T {
3453 let mut new_val = None;
3454 let mut new_id = None;
3455 if let Some(trait_ref) = opt_trait_ref {
3456 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3457 self.diag_metadata.currently_processing_impl_trait =
3458 Some((trait_ref.clone(), self_type.clone()));
3459 let res = self.smart_resolve_path_fragment(
3460 &None,
3461 &path,
3462 PathSource::Trait(AliasPossibility::No),
3463 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3464 RecordPartialRes::Yes,
3465 None,
3466 );
3467 self.diag_metadata.currently_processing_impl_trait = None;
3468 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3469 new_id = Some(def_id);
3470 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3471 }
3472 }
3473 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3474 let result = f(self, new_id);
3475 self.current_trait_ref = original_trait_ref;
3476 result
3477 }
3478
3479 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3480 let mut self_type_rib = Rib::new(RibKind::Normal);
3481
3482 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3484 self.ribs[ns].push(self_type_rib);
3485 f(self);
3486 self.ribs[ns].pop();
3487 }
3488
3489 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3490 self.with_self_rib_ns(TypeNS, self_res, f)
3491 }
3492
3493 fn resolve_implementation(
3494 &mut self,
3495 attrs: &[ast::Attribute],
3496 generics: &'ast Generics,
3497 of_trait: Option<&'ast ast::TraitImplHeader>,
3498 self_type: &'ast Ty,
3499 item_id: NodeId,
3500 impl_items: &'ast [Box<AssocItem>],
3501 ) {
3502 {
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:3502",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3502u32),
::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");
3503 self.with_generic_param_rib(
3505 &generics.params,
3506 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3507 item_id,
3508 LifetimeBinderKind::ImplBlock,
3509 generics.span,
3510 |this| {
3511 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3513 this.with_lifetime_rib(
3514 LifetimeRibKind::AnonymousCreateParameter {
3515 binder: item_id,
3516 report_in_path: true
3517 },
3518 |this| {
3519 this.with_optional_trait_ref(
3521 of_trait.map(|t| &t.trait_ref),
3522 self_type,
3523 |this, trait_id| {
3524 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3525
3526 let item_def_id = this.r.current_owner.def_id;
3527
3528 if let Some(trait_id) = trait_id {
3530 this.r
3531 .trait_impls
3532 .entry(trait_id)
3533 .or_default()
3534 .push(item_def_id);
3535 }
3536
3537 let item_def_id = item_def_id.to_def_id();
3538 let res = Res::SelfTyAlias {
3539 alias_to: item_def_id,
3540 is_trait_impl: trait_id.is_some(),
3541 };
3542 this.with_self_rib(res, |this| {
3543 if let Some(of_trait) = of_trait {
3544 visit::walk_trait_ref(this, &of_trait.trait_ref);
3546 }
3547 this.visit_ty(self_type);
3549 this.visit_generics(generics);
3551
3552 this.with_current_self_type(self_type, |this| {
3554 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3555 {
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:3555",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3555u32),
::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, ...)");
3556 let mut seen_trait_items = Default::default();
3557 for item in impl_items {
3558 with_owner(this, item.id, |this| {
3559 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3560 })
3561 }
3562 });
3563 });
3564 });
3565 },
3566 )
3567 },
3568 );
3569 });
3570 },
3571 );
3572 }
3573
3574 fn resolve_impl_item(
3575 &mut self,
3576 item: &'ast AssocItem,
3577 seen_trait_items: &mut FxHashMap<DefId, Span>,
3578 trait_id: Option<DefId>,
3579 is_in_trait_impl: bool,
3580 ) {
3581 use crate::ResolutionError::*;
3582 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3583 let prev = self.diag_metadata.current_impl_item.take();
3584 self.diag_metadata.current_impl_item = Some(&item);
3585 match &item.kind {
3586 AssocItemKind::Const(ast::ConstItem {
3587 ident,
3588 generics,
3589 ty,
3590 body,
3591 kind,
3592 define_opaque,
3593 ..
3594 }) => {
3595 {
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:3595",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3595u32),
::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");
3596 self.with_generic_param_rib(
3597 &generics.params,
3598 RibKind::AssocItem,
3599 item.id,
3600 LifetimeBinderKind::ConstItem,
3601 generics.span,
3602 |this| {
3603 this.with_lifetime_rib(
3604 LifetimeRibKind::Elided {
3605 res: LifetimeRes::Static,
3606 error_in_path: true,
3607 },
3608 |this| {
3609 this.check_trait_item(
3612 item.id,
3613 *ident,
3614 *ident,
3615 &item.kind,
3616 ValueNS,
3617 item.span,
3618 seen_trait_items,
3619 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3620 );
3621
3622 this.visit_generics(generics);
3623 if *kind == ConstItemKind::TypeConst
3624 && !this.r.tcx.features().generic_const_parameter_types()
3625 {
3626 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3627 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3628 this.with_lifetime_rib(
3629 LifetimeRibKind::ConstParamTy,
3630 |this| this.visit_ty(ty),
3631 )
3632 })
3633 });
3634 } else {
3635 this.visit_ty(ty);
3636 }
3637 this.resolve_const_item_rhs(body, None);
3643 },
3644 )
3645 },
3646 );
3647 self.resolve_define_opaques(define_opaque);
3648 }
3649 AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3650 {
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:3650",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3650u32),
::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");
3651 self.with_generic_param_rib(
3653 &generics.params,
3654 RibKind::AssocItem,
3655 item.id,
3656 LifetimeBinderKind::Function,
3657 generics.span,
3658 |this| {
3659 let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3660 Ident::new(sym::pin_drop, ident.span)
3661 } else {
3662 *ident
3663 };
3664 this.check_trait_item(
3667 item.id,
3668 effective_ident,
3669 *ident,
3670 &item.kind,
3671 ValueNS,
3672 item.span,
3673 seen_trait_items,
3674 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3675 );
3676
3677 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3678 },
3679 );
3680
3681 self.resolve_define_opaques(define_opaque);
3682 }
3683 AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3684 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3685 {
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:3685",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3685u32),
::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");
3686 self.with_generic_param_rib(
3688 &generics.params,
3689 RibKind::AssocItem,
3690 item.id,
3691 LifetimeBinderKind::ImplAssocType,
3692 generics.span,
3693 |this| {
3694 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3695 this.check_trait_item(
3698 item.id,
3699 *ident,
3700 *ident,
3701 &item.kind,
3702 TypeNS,
3703 item.span,
3704 seen_trait_items,
3705 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3706 );
3707
3708 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3709 });
3710 },
3711 );
3712 self.diag_metadata.in_non_gat_assoc_type = None;
3713 }
3714 AssocItemKind::Delegation(delegation) => {
3715 {
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:3715",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3715u32),
::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");
3716 self.with_generic_param_rib(
3717 &[],
3718 RibKind::AssocItem,
3719 item.id,
3720 LifetimeBinderKind::Function,
3721 delegation.path.segments.last().unwrap().ident.span,
3722 |this| {
3723 this.check_trait_item(
3724 item.id,
3725 delegation.ident,
3726 delegation.ident,
3727 &item.kind,
3728 ValueNS,
3729 item.span,
3730 seen_trait_items,
3731 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3732 );
3733
3734 this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3737 },
3738 );
3739 }
3740 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3741 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3742 }
3743 }
3744 self.diag_metadata.current_impl_item = prev;
3745 }
3746
3747 fn check_trait_item<F>(
3748 &mut self,
3749 id: NodeId,
3750 mut ident: Ident,
3751 mut reported_ident: Ident,
3752 kind: &AssocItemKind,
3753 ns: Namespace,
3754 span: Span,
3755 seen_trait_items: &mut FxHashMap<DefId, Span>,
3756 err: F,
3757 ) where
3758 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3759 {
3760 let Some((module, _)) = self.current_trait_ref else {
3762 return;
3763 };
3764 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3765 reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3766 let key = BindingKey::new(IdentKey::new(ident), ns);
3767 let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3768 {
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:3768",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3768u32),
::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);
3769 if decl.is_none() {
3770 let ns = match ns {
3773 ValueNS => TypeNS,
3774 TypeNS => ValueNS,
3775 _ => ns,
3776 };
3777 let key = BindingKey::new(IdentKey::new(ident), ns);
3778 decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3779 {
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:3779",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3779u32),
::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);
3780 }
3781
3782 let feed_visibility = |this: &mut Self, def_id| {
3783 let vis = this.r.tcx.visibility(def_id);
3784 let vis = if vis.is_visible_locally() {
3785 vis.expect_local()
3786 } else {
3787 this.r.dcx().span_delayed_bug(
3788 span,
3789 "error should be emitted when an unexpected trait item is used",
3790 );
3791 Visibility::Public
3792 };
3793 this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3797 };
3798
3799 let Some(decl) = decl else {
3800 let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3802 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3803 let path_names = path_names_to_string(path);
3804 self.report_error(span, err(reported_ident, path_names, candidate));
3805 feed_visibility(self, module.def_id());
3806 return;
3807 };
3808
3809 let res = decl.res();
3810 let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3811 feed_visibility(self, id_in_trait);
3812
3813 match seen_trait_items.entry(id_in_trait) {
3814 Entry::Occupied(entry) => {
3815 self.report_error(
3816 span,
3817 ResolutionError::TraitImplDuplicate {
3818 name: ident,
3819 old_span: *entry.get(),
3820 trait_item_span: decl.span,
3821 },
3822 );
3823 return;
3824 }
3825 Entry::Vacant(entry) => {
3826 entry.insert(span);
3827 }
3828 };
3829
3830 match (def_kind, kind) {
3831 (DefKind::AssocTy, AssocItemKind::Type(..))
3832 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3833 | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3834 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3835 self.r.record_partial_res(id, PartialRes::new(res));
3836 return;
3837 }
3838 _ => {}
3839 }
3840
3841 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3843 let (code, kind) = match kind {
3844 AssocItemKind::Const(..) => (E0323, "const"),
3845 AssocItemKind::Fn(..) => (E0324, "method"),
3846 AssocItemKind::Type(..) => (E0325, "type"),
3847 AssocItemKind::Delegation(..) => (E0324, "method"),
3848 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3849 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3850 }
3851 };
3852 let trait_path = path_names_to_string(path);
3853 self.report_error(
3854 span,
3855 ResolutionError::TraitImplMismatch {
3856 name: ident,
3857 kind,
3858 code,
3859 trait_path,
3860 trait_item_span: decl.span,
3861 },
3862 );
3863 }
3864
3865 fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3866 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3867 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3868 this.visit_expr(expr)
3869 });
3870 })
3871 }
3872
3873 fn resolve_const_item_rhs(
3874 &mut self,
3875 body: &'ast Option<Box<Expr>>,
3876 item: Option<(Ident, ConstantItemKind)>,
3877 ) {
3878 if let Some(body) = body {
3879 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3880 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3881 this.visit_expr(body)
3882 })
3883 })
3884 }
3885 }
3886
3887 fn resolve_delegation(
3888 &mut self,
3889 delegation: &'ast Delegation,
3890 item_id: NodeId,
3891 is_in_trait_impl: bool,
3892 ) {
3893 self.smart_resolve_path(
3894 delegation.id,
3895 &delegation.qself,
3896 &delegation.path,
3897 PathSource::Delegation,
3898 );
3899
3900 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3903 if let Some(qself) = &delegation.qself {
3904 this.visit_ty(&qself.ty);
3905 }
3906
3907 this.visit_path(&delegation.path);
3908 });
3909
3910 let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
3911 let def_id = self
3912 .r
3913 .partial_res_map
3914 .get(&resolution_node_id)
3915 .and_then(|r| r.expect_full_res().opt_def_id());
3916
3917 let resolution_id = def_id.ok_or_else(|| {
3918 self.r.tcx.dcx().span_delayed_bug(
3919 delegation.path.span,
3920 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LateResolutionVisitor: couldn\'t resolve node {0:?} in delegation item",
resolution_node_id))
})format!(
3921 "LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
3922 ),
3923 )
3924 });
3925
3926 let info = DelegationInfo { resolution_id };
3927 self.r.delegation_infos.insert(self.r.current_owner.def_id, info);
3928
3929 let Some(body) = &delegation.body else { return };
3930 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3931 let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3932 let res = Res::Local(delegation.id);
3933 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3934
3935 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3937 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3938 this.visit_block(body);
3939 });
3940 });
3941 });
3942 }
3943
3944 fn resolve_params(&mut self, params: &'ast [Param]) {
3945 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())];
3946 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3947 for Param { pat, .. } in params {
3948 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3949 }
3950 this.apply_pattern_bindings(bindings);
3951 });
3952 for Param { ty, .. } in params {
3953 self.visit_ty(ty);
3954 }
3955 }
3956
3957 fn resolve_local(&mut self, local: &'ast Local) {
3958 {
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:3958",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3958u32),
::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);
3959 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);
3961
3962 if let Some((init, els)) = local.kind.init_else_opt() {
3964 self.visit_expr(init);
3965
3966 if let Some(els) = els {
3968 self.visit_block(els);
3969 }
3970 }
3971
3972 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3974 }
3975
3976 fn compute_and_check_binding_map(
3996 &mut self,
3997 pat: &Pat,
3998 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3999 let mut binding_map = FxIndexMap::default();
4000 let mut is_never_pat = false;
4001
4002 pat.walk(&mut |pat| {
4003 match pat.kind {
4004 PatKind::Ident(annotation, ident, ref sub_pat)
4005 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
4006 {
4007 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
4008 }
4009 PatKind::Or(ref ps) => {
4010 match self.compute_and_check_or_pat_binding_map(ps) {
4013 Ok(bm) => binding_map.extend(bm),
4014 Err(IsNeverPattern) => is_never_pat = true,
4015 }
4016 return false;
4017 }
4018 PatKind::Never => is_never_pat = true,
4019 _ => {}
4020 }
4021
4022 true
4023 });
4024
4025 if is_never_pat {
4026 for (_, binding) in binding_map {
4027 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4028 }
4029 Err(IsNeverPattern)
4030 } else {
4031 Ok(binding_map)
4032 }
4033 }
4034
4035 fn is_base_res_local(&self, nid: NodeId) -> bool {
4036 #[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!(
4037 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4038 Some(Res::Local(..))
4039 )
4040 }
4041
4042 fn compute_and_check_or_pat_binding_map(
4062 &mut self,
4063 pats: &[Pat],
4064 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4065 let mut missing_vars = FxIndexMap::default();
4066 let mut inconsistent_vars = FxIndexMap::default();
4067
4068 let not_never_pats = pats
4070 .iter()
4071 .filter_map(|pat| {
4072 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4073 Some((binding_map, pat))
4074 })
4075 .collect::<Vec<_>>();
4076
4077 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4079 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4081
4082 for &(ref map, pat) in inners {
4083 for (&name, binding_inner) in map {
4084 match map_outer.get(&name) {
4085 None => {
4086 let binding_error =
4088 missing_vars.entry(name).or_insert_with(|| BindingError {
4089 name,
4090 origin: Default::default(),
4091 target: Default::default(),
4092 could_be_path: name.as_str().starts_with(char::is_uppercase),
4093 });
4094 binding_error.origin.push((binding_inner.span, pat.clone()));
4095 binding_error.target.push(pat_outer.clone());
4096 }
4097 Some(binding_outer) => {
4098 if binding_outer.annotation != binding_inner.annotation {
4099 inconsistent_vars
4101 .entry(name)
4102 .or_insert((binding_inner.span, binding_outer.span));
4103 }
4104 }
4105 }
4106 }
4107 }
4108 }
4109
4110 for (name, mut v) in missing_vars {
4112 if inconsistent_vars.contains_key(&name) {
4113 v.could_be_path = false;
4114 }
4115 self.report_error(
4116 v.origin.iter().next().unwrap().0,
4117 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4118 );
4119 }
4120
4121 for (name, v) in inconsistent_vars {
4123 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4124 }
4125
4126 if not_never_pats.is_empty() {
4128 Err(IsNeverPattern)
4130 } else {
4131 let mut binding_map = FxIndexMap::default();
4132 for (bm, _) in not_never_pats {
4133 binding_map.extend(bm);
4134 }
4135 Ok(binding_map)
4136 }
4137 }
4138
4139 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4141 let mut is_or_or_never = false;
4142 pat.walk(&mut |pat| match pat.kind {
4143 PatKind::Or(..) | PatKind::Never => {
4144 is_or_or_never = true;
4145 false
4146 }
4147 _ => true,
4148 });
4149 if is_or_or_never {
4150 let _ = self.compute_and_check_binding_map(pat);
4151 }
4152 }
4153
4154 fn resolve_arm(&mut self, arm: &'ast Arm) {
4155 self.with_rib(ValueNS, RibKind::Normal, |this| {
4156 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4157 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));
4158 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);
4159 });
4160 }
4161
4162 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4164 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())];
4165 self.resolve_pattern(pat, pat_src, &mut bindings);
4166 self.apply_pattern_bindings(bindings);
4167 }
4168
4169 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4171 let rib_bindings = self.innermost_rib_bindings(ValueNS);
4172 let Some((_, pat_bindings)) = pat_bindings.pop() else {
4173 ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4174 };
4175
4176 if rib_bindings.is_empty() {
4177 *rib_bindings = pat_bindings;
4180 } else {
4181 rib_bindings.extend(pat_bindings);
4182 }
4183 }
4184
4185 fn resolve_pattern(
4188 &mut self,
4189 pat: &'ast Pat,
4190 pat_src: PatternSource,
4191 bindings: &mut PatternBindings,
4192 ) {
4193 self.visit_pat(pat);
4199 self.resolve_pattern_inner(pat, pat_src, bindings);
4200 self.check_consistent_bindings(pat);
4202 }
4203
4204 #[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(4223u32),
::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")]
4224 fn resolve_pattern_inner(
4225 &mut self,
4226 pat: &'ast Pat,
4227 pat_src: PatternSource,
4228 bindings: &mut PatternBindings,
4229 ) {
4230 pat.walk(&mut |pat| {
4232 match pat.kind {
4233 PatKind::Ident(bmode, ident, ref sub) => {
4234 let has_sub = sub.is_some();
4237 let res = self
4238 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4239 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4240 self.r.record_partial_res(pat.id, PartialRes::new(res));
4241 self.r.record_pat_span(pat.id, pat.span);
4242 }
4243 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4244 self.smart_resolve_path(
4245 pat.id,
4246 qself,
4247 path,
4248 PathSource::TupleStruct(
4249 pat.span,
4250 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4251 ),
4252 );
4253 }
4254 PatKind::Path(ref qself, ref path) => {
4255 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4256 }
4257 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4258 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4259 self.record_patterns_with_skipped_bindings(pat, rest);
4260 }
4261 PatKind::Or(ref ps) => {
4262 bindings.push((PatBoundCtx::Or, Default::default()));
4266 for p in ps {
4267 bindings.push((PatBoundCtx::Product, Default::default()));
4271 self.resolve_pattern_inner(p, pat_src, bindings);
4272 let collected = bindings.pop().unwrap().1;
4275 bindings.last_mut().unwrap().1.extend(collected);
4276 }
4277 let collected = bindings.pop().unwrap().1;
4281 bindings.last_mut().unwrap().1.extend(collected);
4282
4283 return false;
4285 }
4286 PatKind::Guard(ref subpat, ref guard) => {
4287 bindings.push((PatBoundCtx::Product, Default::default()));
4289 let binding_ctx_stack_len = bindings.len();
4292 self.resolve_pattern_inner(subpat, pat_src, bindings);
4293 assert_eq!(bindings.len(), binding_ctx_stack_len);
4294 let subpat_bindings = bindings.pop().unwrap().1;
4297 self.with_rib(ValueNS, RibKind::Normal, |this| {
4298 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4299 this.resolve_expr(&guard.cond, None);
4300 });
4301 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4308 return false;
4310 }
4311 _ => {}
4312 }
4313 true
4314 });
4315 }
4316
4317 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4318 match rest {
4319 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4320 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4322 && let Some(res) = partial_res.full_res()
4323 && let Some(def_id) = res.opt_def_id()
4324 {
4325 self.ribs[ValueNS]
4326 .last_mut()
4327 .unwrap()
4328 .patterns_with_skipped_bindings
4329 .entry(def_id)
4330 .or_default()
4331 .push((
4332 pat.span,
4333 match rest {
4334 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4335 _ => Ok(()),
4336 },
4337 ));
4338 }
4339 }
4340 ast::PatFieldsRest::None => {}
4341 }
4342 }
4343
4344 fn fresh_binding(
4345 &mut self,
4346 ident: Ident,
4347 pat_id: NodeId,
4348 pat_src: PatternSource,
4349 bindings: &mut PatternBindings,
4350 ) -> Res {
4351 let ident = ident.normalize_to_macro_rules();
4355
4356 let already_bound_and = bindings
4358 .iter()
4359 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4360 if already_bound_and {
4361 use ResolutionError::*;
4363 let error = match pat_src {
4364 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4366 _ => IdentifierBoundMoreThanOnceInSamePattern,
4368 };
4369 self.report_error(ident.span, error(ident));
4370 }
4371
4372 let already_bound_or = bindings
4375 .iter()
4376 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4377 let res = if let Some(&res) = already_bound_or {
4378 res
4381 } else {
4382 Res::Local(pat_id)
4384 };
4385
4386 bindings.last_mut().unwrap().1.insert(ident, res);
4388 res
4389 }
4390
4391 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4392 &mut self.ribs[ns].last_mut().unwrap().bindings
4393 }
4394
4395 fn try_resolve_as_non_binding(
4396 &mut self,
4397 pat_src: PatternSource,
4398 ann: BindingMode,
4399 ident: Ident,
4400 has_sub: bool,
4401 ) -> Option<Res> {
4402 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4406
4407 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4408 let (res, binding) = match ls_binding {
4409 LateDecl::Decl(binding)
4410 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4411 {
4412 self.r.record_use(ident, binding, Used::Other);
4417 return None;
4418 }
4419 LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4420 LateDecl::RibDef(res) => (res, None),
4421 };
4422
4423 match res {
4424 Res::SelfCtor(_) | Res::Def(
4426 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4427 _,
4428 ) if is_syntactic_ambiguity => {
4429 if let Some(binding) = binding {
4431 self.r.record_use(ident, binding, Used::Other);
4432 }
4433 Some(res)
4434 }
4435 Res::Def(
4436 DefKind::Ctor(..)
4437 | DefKind::Const { .. }
4438 | DefKind::AssocConst { .. }
4439 | DefKind::Static { .. },
4440 _,
4441 ) => {
4442 let binding = binding.expect("no binding for a ctor or static");
4448 self.report_error(
4449 ident.span,
4450 ResolutionError::BindingShadowsSomethingUnacceptable {
4451 shadowing_binding: pat_src,
4452 name: ident.name,
4453 participle: if binding.is_import() { "imported" } else { "defined" },
4454 article: binding.res().article(),
4455 shadowed_binding: binding.res(),
4456 shadowed_binding_span: binding.span,
4457 },
4458 );
4459 None
4460 }
4461 Res::Def(DefKind::ConstParam, def_id) => {
4462 self.report_error(
4465 ident.span,
4466 ResolutionError::BindingShadowsSomethingUnacceptable {
4467 shadowing_binding: pat_src,
4468 name: ident.name,
4469 participle: "defined",
4470 article: res.article(),
4471 shadowed_binding: res,
4472 shadowed_binding_span: self.r.def_span(def_id),
4473 },
4474 );
4475 None
4476 }
4477 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4478 None
4480 }
4481 Res::SelfCtor(_) => {
4482 self.r.dcx().span_delayed_bug(
4485 ident.span,
4486 "unexpected `SelfCtor` in pattern, expected identifier",
4487 );
4488 None
4489 }
4490 _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
format_args!("unexpected resolution for an identifier in pattern: {0:?}",
res))span_bug!(
4491 ident.span,
4492 "unexpected resolution for an identifier in pattern: {:?}",
4493 res,
4494 ),
4495 }
4496 }
4497
4498 fn resolve_restriction_path(
4499 &mut self,
4500 restriction: &'ast ast::RestrictionKind,
4501 kind: ResolvingRestrictionKind,
4502 ) {
4503 match &restriction {
4504 ast::RestrictionKind::Unrestricted => (),
4505 ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4506 self.smart_resolve_path(*id, &None, path, PathSource::Module);
4507 if let Some(res) = self.r.partial_res_map[&id].full_res()
4508 && let Some(def_id) = res.opt_def_id()
4509 {
4510 if !self.r.is_accessible_from(
4511 Visibility::Restricted(def_id),
4512 self.parent_scope.module,
4513 ) {
4514 self.r
4515 .dcx()
4516 .create_err(crate::diagnostics::RestrictionAncestorOnly {
4517 span: path.span,
4518 kind,
4519 })
4520 .emit();
4521 }
4522 }
4523 }
4524 }
4525 }
4526
4527 fn smart_resolve_path(
4533 &mut self,
4534 id: NodeId,
4535 qself: &Option<Box<QSelf>>,
4536 path: &Path,
4537 source: PathSource<'_, 'ast, 'ra>,
4538 ) {
4539 self.smart_resolve_path_fragment(
4540 qself,
4541 &Segment::from_path(path),
4542 source,
4543 Finalize::new(id, path.span),
4544 RecordPartialRes::Yes,
4545 None,
4546 );
4547 }
4548
4549 fn smart_resolve_path_fragment(
4550 &mut self,
4551 qself: &Option<Box<QSelf>>,
4552 path: &[Segment],
4553 source: PathSource<'_, 'ast, 'ra>,
4554 finalize: Finalize,
4555 record_partial_res: RecordPartialRes,
4556 parent_qself: Option<&QSelf>,
4557 ) -> PartialRes {
4558 let ns = source.namespace();
4559
4560 let Finalize { node_id, path_span, .. } = finalize;
4561 let report_errors = |this: &mut Self, res: Option<Res>| {
4562 if this.should_report_errs() {
4563 let (mut err, candidates) = this.smart_resolve_report_errors(
4564 path,
4565 None,
4566 path_span,
4567 source,
4568 res,
4569 parent_qself,
4570 );
4571
4572 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4573 let instead = res.is_some();
4574 let (suggestion, const_err) = if let Some((start, end)) =
4575 this.diag_metadata.in_range
4576 && path[0].ident.span.lo() == end.span.lo()
4577 && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(start.kind, ExprKind::Lit(_))
4578 {
4579 let mut sugg = ".";
4580 let mut span = start.span.between(end.span);
4581 if span.lo() + BytePos(2) == span.hi() {
4582 span = span.with_lo(span.lo() + BytePos(1));
4585 sugg = "";
4586 }
4587 (
4588 Some((
4589 span,
4590 "you might have meant to write `.` instead of `..`",
4591 sugg.to_string(),
4592 Applicability::MaybeIncorrect,
4593 )),
4594 None,
4595 )
4596 } else if res.is_none()
4597 && let PathSource::Type
4598 | PathSource::Expr(_)
4599 | PathSource::PreciseCapturingArg(..) = source
4600 {
4601 this.suggest_adding_generic_parameter(path, source)
4602 } else {
4603 (None, None)
4604 };
4605
4606 if let Some(const_err) = const_err {
4607 err.cancel();
4608 err = const_err;
4609 }
4610
4611 let ue = UseError {
4612 err,
4613 candidates,
4614 node_id,
4615 instead,
4616 suggestion,
4617 path: path.into(),
4618 is_call: source.is_call(),
4619 };
4620
4621 this.use_injections.push(ue);
4622 }
4623
4624 PartialRes::new(Res::Err)
4625 };
4626
4627 let report_errors_for_call =
4633 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4634 let (following_seg, prefix_path) = match path.split_last() {
4638 Some((last, path)) if !path.is_empty() => (Some(last), path),
4639 _ => return Some(parent_err),
4640 };
4641
4642 let (mut err, candidates) = this.smart_resolve_report_errors(
4643 prefix_path,
4644 following_seg,
4645 path_span,
4646 PathSource::Type,
4647 None,
4648 parent_qself,
4649 );
4650
4651 let failed_to_resolve = match parent_err.node {
4666 ResolutionError::FailedToResolve { .. } => true,
4667 _ => false,
4668 };
4669 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4670
4671 err.messages = take(&mut parent_err.messages);
4673 err.code = take(&mut parent_err.code);
4674 swap(&mut err.span, &mut parent_err.span);
4675 if failed_to_resolve {
4676 err.children = take(&mut parent_err.children);
4677 } else {
4678 err.children.append(&mut parent_err.children);
4679 }
4680 err.sort_span = parent_err.sort_span;
4681 err.is_lint = parent_err.is_lint.clone();
4682
4683 match &mut err.suggestions {
4685 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4686 Suggestions::Enabled(parent_suggestions) => {
4687 typo_suggestions.append(parent_suggestions)
4689 }
4690 Suggestions::Sealed(_) | Suggestions::Disabled => {
4691 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4696 }
4697 },
4698 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4699 }
4700
4701 parent_err.cancel();
4702
4703 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4704
4705 if this.should_report_errs() {
4706 if candidates.is_empty() {
4707 if path.len() == 2
4708 && let [segment] = prefix_path
4709 {
4710 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4716 } else {
4717 err.emit();
4722 }
4723 } else {
4724 this.use_injections.push(UseError {
4726 err,
4727 candidates,
4728 node_id,
4729 instead: false,
4730 suggestion: None,
4731 path: prefix_path.into(),
4732 is_call: source.is_call(),
4733 });
4734 }
4735 } else {
4736 err.cancel();
4737 }
4738
4739 None
4742 };
4743
4744 let partial_res = match self.resolve_qpath_anywhere(
4745 qself,
4746 path,
4747 ns,
4748 source.defer_to_typeck(),
4749 finalize,
4750 source,
4751 ) {
4752 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4753 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4755 && let [Segment { ident, .. }] = path
4756 && items.iter().any(|item| {
4757 if let AssocItemKind::Type(alias) = &item.kind
4758 && alias.ident == *ident
4759 {
4760 true
4761 } else {
4762 false
4763 }
4764 })
4765 {
4766 let mut diag = self.r.tcx.dcx().struct_allow("");
4767 diag.span_suggestion_verbose(
4768 path_span.shrink_to_lo(),
4769 "there is an associated type with the same name",
4770 "Self::",
4771 Applicability::MaybeIncorrect,
4772 );
4773 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4774 }
4775
4776 if source.is_expected(res) || res == Res::Err {
4777 partial_res
4778 } else {
4779 report_errors(self, Some(res))
4780 }
4781 }
4782
4783 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4784 if ns == ValueNS {
4788 let item_name = path.last().unwrap().ident;
4789 self.record_traits_in_scope(node_id, item_name);
4790 }
4791
4792 if PrimTy::from_name(path[0].ident.name).is_some() {
4793 let mut std_path = Vec::with_capacity(1 + path.len());
4794
4795 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4796 std_path.extend(path);
4797 if let PathResult::Module(_) | PathResult::NonModule(_) =
4798 self.resolve_path(&std_path, Some(ns), None, source)
4799 {
4800 let item_span =
4802 path.iter().last().map_or(path_span, |segment| segment.ident.span);
4803
4804 self.r.confused_type_with_std_module.insert(item_span, path_span);
4805 self.r.confused_type_with_std_module.insert(path_span, path_span);
4806 }
4807 }
4808
4809 partial_res
4810 }
4811
4812 Err(err) => {
4813 if let Some(err) = report_errors_for_call(self, err) {
4814 self.report_error(err.span, err.node);
4815 }
4816
4817 PartialRes::new(Res::Err)
4818 }
4819
4820 _ => report_errors(self, None),
4821 };
4822
4823 if record_partial_res == RecordPartialRes::Yes {
4824 self.r.record_partial_res(node_id, partial_res);
4826 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4827 self.lint_unused_qualifications(path, ns, finalize);
4828 }
4829
4830 partial_res
4831 }
4832
4833 fn self_type_is_available(&mut self) -> bool {
4834 let binding = self
4835 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4836 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4837 }
4838
4839 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4840 let ident = Ident::new(kw::SelfLower, self_span);
4841 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4842 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4843 }
4844
4845 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4849 if self.should_report_errs() {
4850 self.r.report_error(span, resolution_error);
4851 }
4852 }
4853
4854 #[inline]
4855 fn should_report_errs(&self) -> bool {
4859 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4860 && !self.r.glob_error.is_some()
4861 }
4862
4863 fn resolve_qpath_anywhere(
4865 &mut self,
4866 qself: &Option<Box<QSelf>>,
4867 path: &[Segment],
4868 primary_ns: Namespace,
4869 defer_to_typeck: bool,
4870 finalize: Finalize,
4871 source: PathSource<'_, 'ast, 'ra>,
4872 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4873 let mut fin_res = None;
4874
4875 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4876 if i == 0 || ns != primary_ns {
4877 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4878 Some(partial_res)
4879 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4880 {
4881 return Ok(Some(partial_res));
4882 }
4883 partial_res => {
4884 if fin_res.is_none() {
4885 fin_res = partial_res;
4886 }
4887 }
4888 }
4889 }
4890 }
4891
4892 if !(primary_ns != MacroNS) {
::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4893 if qself.is_none()
4894 && let PathResult::NonModule(res) =
4895 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4896 {
4897 return Ok(Some(res));
4898 }
4899
4900 Ok(fin_res)
4901 }
4902
4903 fn resolve_qpath(
4905 &mut self,
4906 qself: &Option<Box<QSelf>>,
4907 path: &[Segment],
4908 ns: Namespace,
4909 finalize: Finalize,
4910 source: PathSource<'_, 'ast, 'ra>,
4911 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4912 {
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:4912",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(4912u32),
::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!(
4913 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4914 qself, path, ns, finalize,
4915 );
4916
4917 if let Some(qself) = qself {
4918 if qself.position == 0 {
4919 return Ok(Some(PartialRes::with_unresolved_segments(
4923 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4924 path.len(),
4925 )));
4926 }
4927
4928 let num_privacy_errors = self.r.privacy_errors.len();
4929 let trait_res = self.smart_resolve_path_fragment(
4931 &None,
4932 &path[..qself.position],
4933 PathSource::Trait(AliasPossibility::No),
4934 Finalize::new(finalize.node_id, qself.path_span),
4935 RecordPartialRes::No,
4936 Some(&qself),
4937 );
4938
4939 if trait_res.expect_full_res() == Res::Err {
4940 return Ok(Some(trait_res));
4941 }
4942
4943 self.r.privacy_errors.truncate(num_privacy_errors);
4946
4947 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4955 let partial_res = self.smart_resolve_path_fragment(
4956 &None,
4957 &path[..=qself.position],
4958 PathSource::TraitItem(ns, &source),
4959 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4960 RecordPartialRes::No,
4961 Some(&qself),
4962 );
4963
4964 return Ok(Some(PartialRes::with_unresolved_segments(
4968 partial_res.base_res(),
4969 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4970 )));
4971 }
4972
4973 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4974 PathResult::NonModule(path_res) => path_res,
4975 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4976 PartialRes::new(module.res().unwrap())
4977 }
4978 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4982 PartialRes::new(Res::Err)
4983 }
4984 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4997 if (ns == TypeNS || path.len() > 1)
4998 && PrimTy::from_name(path[0].ident.name).is_some() =>
4999 {
5000 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
5001 let tcx = self.r.tcx();
5002
5003 let gate_err_sym_msg = match prim {
5004 PrimTy::Float(FloatTy::F16) if !self.r.features.f16() => {
5005 Some((sym::f16, "the type `f16` is unstable"))
5006 }
5007 PrimTy::Float(FloatTy::F128) if !self.r.features.f128() => {
5008 Some((sym::f128, "the type `f128` is unstable"))
5009 }
5010 _ => None,
5011 };
5012
5013 if let Some((sym, msg)) = gate_err_sym_msg {
5014 let span = path[0].ident.span;
5015 if !span.allows_unstable(sym) {
5016 feature_err(tcx.sess, sym, span, msg).emit();
5017 }
5018 };
5019
5020 if let Some(id) = path[0].id {
5022 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
5023 }
5024
5025 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
5026 }
5027 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
5028 PartialRes::new(module.res().unwrap())
5029 }
5030 PathResult::Failed {
5031 is_error_from_last_segment: false,
5032 span,
5033 label,
5034 suggestion,
5035 module,
5036 segment,
5037 error_implied_by_parse_error: _,
5038 message,
5039 note: _,
5040 } => {
5041 return Err(respan(
5042 span,
5043 ResolutionError::FailedToResolve {
5044 segment: segment.name,
5045 label,
5046 suggestion,
5047 module,
5048 message,
5049 },
5050 ));
5051 }
5052 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5053 PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5054 };
5055
5056 Ok(Some(result))
5057 }
5058
5059 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5060 if let Some(label) = label {
5061 if label.ident.as_str().as_bytes()[1] != b'_' {
5062 self.diag_metadata.unused_labels.insert(id, label.ident.span);
5063 }
5064
5065 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5066 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5067 }
5068
5069 self.with_label_rib(RibKind::Normal, |this| {
5070 let ident = label.ident.normalize_to_macro_rules();
5071 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5072 f(this);
5073 });
5074 } else {
5075 f(self);
5076 }
5077 }
5078
5079 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5080 self.with_resolved_label(label, id, |this| this.visit_block(block));
5081 }
5082
5083 fn resolve_block(&mut self, block: &'ast Block) {
5084 {
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:5084",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5084u32),
::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");
5085 let orig_module = self.parent_scope.module;
5087 let anonymous_module = self.r.block_map.get(&block.id).copied();
5088
5089 let mut num_macro_definition_ribs = 0;
5090 if let Some(anonymous_module) = anonymous_module {
5091 {
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:5091",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5091u32),
::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");
5092 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5093 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5094 self.parent_scope.module = anonymous_module.to_module();
5095 } else {
5096 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5097 }
5098
5099 for stmt in &block.stmts {
5101 if let StmtKind::Item(ref item) = stmt.kind
5102 && let ItemKind::MacroDef(..) = item.kind
5103 {
5104 num_macro_definition_ribs += 1;
5105 let res = self.r.owner_def_id(item.id).to_def_id();
5106 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5107 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5108 }
5109
5110 self.visit_stmt(stmt);
5111 }
5112
5113 self.parent_scope.module = orig_module;
5115 for _ in 0..num_macro_definition_ribs {
5116 self.ribs[ValueNS].pop();
5117 self.label_ribs.pop();
5118 }
5119 self.last_block_rib = self.ribs[ValueNS].pop();
5120 if anonymous_module.is_some() {
5121 self.ribs[TypeNS].pop();
5122 }
5123 {
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:5123",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5123u32),
::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");
5124 }
5125
5126 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5127 {
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:5127",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5127u32),
::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!(
5128 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5129 constant, anon_const_kind
5130 );
5131
5132 let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5133 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5134 this.resolve_expr(&constant.value, None)
5135 })
5136 }
5137
5138 fn resolve_anon_const_manual(
5145 &mut self,
5146 is_trivial_const_arg: bool,
5147 anon_const_kind: AnonConstKind,
5148 resolve_expr: impl FnOnce(&mut Self),
5149 ) {
5150 let is_repeat_expr = match anon_const_kind {
5151 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5152 _ => IsRepeatExpr::No,
5153 };
5154
5155 let may_use_generics = match anon_const_kind {
5156 AnonConstKind::EnumDiscriminant => {
5157 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5158 }
5159 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5160 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5161 AnonConstKind::ConstArg(_) => {
5162 if self.r.features.generic_const_exprs()
5163 || self.r.features.min_generic_const_args()
5164 || is_trivial_const_arg
5165 {
5166 ConstantHasGenerics::Yes
5167 } else {
5168 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5169 }
5170 }
5171 };
5172
5173 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5174 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
5175 resolve_expr(this);
5176 });
5177 });
5178 }
5179
5180 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5181 self.resolve_expr(&f.expr, Some(e));
5182 self.visit_ident(&f.ident);
5183 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());
5184 }
5185
5186 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5187 self.record_candidate_traits_for_expr_if_necessary(expr);
5191
5192 match expr.kind {
5194 ExprKind::Path(ref qself, ref path) => {
5195 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5196 visit::walk_expr(self, expr);
5197 }
5198
5199 ExprKind::Struct(ref se) => {
5200 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5201 if let Some(qself) = &se.qself {
5205 self.visit_ty(&qself.ty);
5206 }
5207 self.visit_path(&se.path);
5208 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);
5209 match &se.rest {
5210 StructRest::Base(expr) => self.visit_expr(expr),
5211 StructRest::Rest(_span) => {}
5212 StructRest::None | StructRest::NoneWithError(_) => {}
5213 }
5214 }
5215
5216 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5217 match self.resolve_label(label.ident) {
5218 Ok((node_id, _)) => {
5219 self.r.current_owner.label_res_map.insert(expr.id, node_id);
5221 self.diag_metadata.unused_labels.swap_remove(&node_id);
5222 }
5223 Err(error) => {
5224 self.report_error(label.ident.span, error);
5225 }
5226 }
5227
5228 visit::walk_expr(self, expr);
5230 }
5231
5232 ExprKind::Break(None, Some(ref e)) => {
5233 self.resolve_expr(e, Some(expr));
5236 }
5237
5238 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5239 self.visit_expr(scrutinee);
5240 self.resolve_pattern_top(pat, PatternSource::Let);
5241 }
5242
5243 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5244 self.visit_expr(scrutinee);
5245 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())];
5247 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5248 for (_, bindings) in &mut bindings {
5253 for (_, binding) in bindings {
5254 *binding = Res::Err;
5255 }
5256 }
5257 self.apply_pattern_bindings(bindings);
5258 }
5259
5260 ExprKind::If(ref cond, ref then, ref opt_else) => {
5261 self.with_rib(ValueNS, RibKind::Normal, |this| {
5262 let old = this.diag_metadata.in_if_condition.replace(cond);
5263 this.visit_expr(cond);
5264 this.diag_metadata.in_if_condition = old;
5265 this.visit_block(then);
5266 });
5267 if let Some(expr) = opt_else {
5268 self.visit_expr(expr);
5269 }
5270 }
5271
5272 ExprKind::Loop(ref block, label, _) => {
5273 self.resolve_labeled_block(label, expr.id, block)
5274 }
5275
5276 ExprKind::While(ref cond, ref block, label) => {
5277 self.with_resolved_label(label, expr.id, |this| {
5278 this.with_rib(ValueNS, RibKind::Normal, |this| {
5279 let old = this.diag_metadata.in_if_condition.replace(cond);
5280 this.visit_expr(cond);
5281 this.diag_metadata.in_if_condition = old;
5282 this.visit_block(block);
5283 })
5284 });
5285 }
5286
5287 ExprKind::ForLoop(ForLoop { ref pat, ref iter, ref body, label, kind: _ }) => {
5288 self.visit_expr(iter);
5289 self.with_rib(ValueNS, RibKind::Normal, |this| {
5290 this.resolve_pattern_top(pat, PatternSource::For);
5291 this.resolve_labeled_block(label, expr.id, body);
5292 });
5293 }
5294
5295 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5296
5297 ExprKind::Field(ref subexpression, _) => {
5299 self.resolve_expr(subexpression, Some(expr));
5300 }
5301 ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5302 self.resolve_expr(receiver, Some(expr));
5303 for arg in args {
5304 self.resolve_expr(arg, None);
5305 }
5306 self.visit_path_segment(seg);
5307 }
5308
5309 ExprKind::Call(ref callee, ref arguments) => {
5310 self.resolve_expr(callee, Some(expr));
5311 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5312 for (idx, argument) in arguments.iter().enumerate() {
5313 if const_args.contains(&idx) {
5316 let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5319 self.resolve_anon_const_manual(
5320 is_trivial_const_arg,
5321 AnonConstKind::ConstArg(IsRepeatExpr::No),
5322 |this| this.resolve_expr(argument, None),
5323 );
5324 } else {
5325 self.resolve_expr(argument, None);
5326 }
5327 }
5328 }
5329 ExprKind::Type(ref _type_expr, ref _ty) => {
5330 visit::walk_expr(self, expr);
5331 }
5332 ExprKind::Closure(ast::Closure {
5334 binder: ClosureBinder::For { ref generic_params, span },
5335 ..
5336 }) => {
5337 self.with_generic_param_rib(
5338 generic_params,
5339 RibKind::Normal,
5340 expr.id,
5341 LifetimeBinderKind::Closure,
5342 span,
5343 |this| visit::walk_expr(this, expr),
5344 );
5345 }
5346 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5347 ExprKind::Gen(..) => {
5348 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5349 }
5350 ExprKind::Repeat(ref elem, ref ct) => {
5351 self.visit_expr(elem);
5352 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5353 }
5354 ExprKind::ConstBlock(ref ct) => {
5355 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5356 }
5357 ExprKind::Index(ref elem, ref idx, _) => {
5358 self.resolve_expr(elem, Some(expr));
5359 self.visit_expr(idx);
5360 }
5361 ExprKind::Assign(ref lhs, ref rhs, _) => {
5362 if !self.diag_metadata.is_assign_rhs {
5363 self.diag_metadata.in_assignment = Some(expr);
5364 }
5365 self.visit_expr(lhs);
5366 self.diag_metadata.is_assign_rhs = true;
5367 self.diag_metadata.in_assignment = None;
5368 self.visit_expr(rhs);
5369 self.diag_metadata.is_assign_rhs = false;
5370 }
5371 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5372 self.diag_metadata.in_range = Some((start, end));
5373 self.resolve_expr(start, Some(expr));
5374 self.resolve_expr(end, Some(expr));
5375 self.diag_metadata.in_range = None;
5376 }
5377 _ => {
5378 visit::walk_expr(self, expr);
5379 }
5380 }
5381 }
5382
5383 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5384 match expr.kind {
5385 ExprKind::Field(_, ident) => {
5386 self.record_traits_in_scope(expr.id, ident);
5391 }
5392 ExprKind::MethodCall(ref call) => {
5393 {
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:5393",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5393u32),
::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);
5394 self.record_traits_in_scope(expr.id, call.seg.ident);
5395 }
5396 _ => {
5397 }
5399 }
5400 }
5401
5402 fn record_traits_in_scope(&mut self, node_id: NodeId, ident: Ident) {
5403 let traits = self.r.traits_in_scope(
5404 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5405 &self.parent_scope,
5406 ident.span,
5407 Some((ident.name, ValueNS)),
5408 );
5409 self.r.current_owner.trait_map.insert(node_id, traits);
5410 }
5411
5412 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5413 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5417 let res = *doc_link_resolutions
5418 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5419 .or_default()
5420 .entry((Symbol::intern(path_str), ns))
5421 .or_insert_with_key(|(path, ns)| {
5422 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5423 if let Some(res) = res
5424 && let Some(def_id) = res.opt_def_id()
5425 && self.is_invalid_proc_macro_item_for_doc(def_id)
5426 {
5427 return None;
5430 }
5431 res
5432 });
5433 self.r.doc_link_resolutions = doc_link_resolutions;
5434 res
5435 }
5436
5437 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5438 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)
5439 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5440 {
5441 return false;
5442 }
5443 let Some(local_did) = did.as_local() else { return true };
5444 !self.r.proc_macros.contains(&local_did)
5445 }
5446
5447 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5448 match self.r.tcx.sess.opts.resolve_doc_links {
5449 ResolveDocLinks::None => return,
5450 ResolveDocLinks::ExportedMetadata
5451 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5452 || !maybe_exported.eval(self.r) =>
5453 {
5454 return;
5455 }
5456 ResolveDocLinks::Exported
5457 if !maybe_exported.eval(self.r)
5458 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5459 {
5460 return;
5461 }
5462 ResolveDocLinks::ExportedMetadata
5463 | ResolveDocLinks::Exported
5464 | ResolveDocLinks::All => {}
5465 }
5466
5467 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5468 return;
5469 }
5470
5471 let mut need_traits_in_scope = false;
5472 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5473 let mut any_resolved = false;
5475 let mut need_assoc = false;
5476 for ns in [TypeNS, ValueNS, MacroNS] {
5477 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5478 any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
_ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5481 } else if ns != MacroNS {
5482 need_assoc = true;
5483 }
5484 }
5485
5486 if need_assoc || !any_resolved {
5488 let mut path = &path_str[..];
5489 while let Some(idx) = path.rfind("::") {
5490 path = &path[..idx];
5491 need_traits_in_scope = true;
5492 for ns in [TypeNS, ValueNS, MacroNS] {
5493 self.resolve_and_cache_rustdoc_path(path, ns);
5494 }
5495 }
5496 }
5497 }
5498
5499 if need_traits_in_scope {
5500 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5502 doc_link_traits_in_scope
5503 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5504 .or_insert_with(|| {
5505 self.r
5506 .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5507 .into_iter()
5508 .filter_map(|tr| {
5509 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5510 return None;
5513 }
5514 Some(tr.def_id)
5515 })
5516 .collect()
5517 });
5518 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5519 }
5520 }
5521
5522 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5523 if let Some(seg) = path.first()
5525 && seg.ident.name == kw::PathRoot
5526 {
5527 return;
5528 }
5529
5530 if finalize.path_span.from_expansion()
5531 || path.iter().any(|seg| seg.ident.span.from_expansion())
5532 {
5533 return;
5534 }
5535
5536 let end_pos =
5537 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5538 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5539 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5548 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5549 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5550 (res == binding.res()).then_some((seg, binding))
5551 });
5552
5553 if let Some((seg, decl)) = unqualified {
5554 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5555 decl,
5556 node_id: finalize.node_id,
5557 path_span: finalize.path_span,
5558 removal_span: path[0].ident.span.until(seg.ident.span),
5559 });
5560 }
5561 }
5562
5563 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5564 if let Some(define_opaque) = define_opaque {
5565 for (id, path) in define_opaque {
5566 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5567 }
5568 }
5569 }
5570
5571 fn resolve_eii(&mut self, eii_impls: &[EiiImpl]) {
5572 for EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. } in eii_impls {
5573 if let Some(target) = known_eii_macro_resolution {
5576 self.smart_resolve_path(*node_id, &None, target, PathSource::ExternItemImpl);
5577 } else {
5578 self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5579 }
5580 }
5581 }
5582}
5583
5584struct ItemInfoCollector<'a, 'ast, 'ra, 'tcx> {
5588 r: &'a mut Resolver<'ra, 'tcx>,
5589 use_items: Vec<&'ast Item>,
5591}
5592
5593impl ItemInfoCollector<'_, '_, '_, '_> {
5594 fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5595 self.r
5596 .delegation_fn_sigs
5597 .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5598 }
5599}
5600
5601fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5602 let required = generics
5603 .params
5604 .iter()
5605 .filter_map(|param| match ¶m.kind {
5606 ast::GenericParamKind::Lifetime => Some("'_"),
5607 ast::GenericParamKind::Type { default } => {
5608 if default.is_none() {
5609 Some("_")
5610 } else {
5611 None
5612 }
5613 }
5614 ast::GenericParamKind::Const { default, .. } => {
5615 if default.is_none() {
5616 Some("_")
5617 } else {
5618 None
5619 }
5620 }
5621 })
5622 .collect::<Vec<_>>();
5623
5624 if required.is_empty() { None } else { Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", "))) }
5625}
5626
5627impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, 'ast, '_, '_> {
5628 fn visit_item(&mut self, item: &'ast Item) {
5629 match &item.kind {
5630 ItemKind::TyAlias(TyAlias { generics, .. })
5631 | ItemKind::Const(ConstItem { generics, .. })
5632 | ItemKind::Fn(Fn { generics, .. })
5633 | ItemKind::Enum(_, generics, _)
5634 | ItemKind::Struct(_, generics, _)
5635 | ItemKind::Union(_, generics, _)
5636 | ItemKind::Impl(Impl { generics, .. })
5637 | ItemKind::Trait(Trait { generics, .. })
5638 | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5639 if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5640 self.collect_fn_info(&sig.decl, item.id);
5641 }
5642
5643 let def_id = self.r.owner_def_id(item.id);
5644 let count = generics
5645 .params
5646 .iter()
5647 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5648 .count();
5649 self.r.item_generics_num_lifetimes.insert(def_id, count);
5650 }
5651
5652 ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5653 for foreign_item in items {
5654 if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5655 self.collect_fn_info(&sig.decl, foreign_item.id);
5656 }
5657 }
5658 }
5659
5660 ItemKind::Use(..) | ItemKind::ExternCrate(..) => {
5661 self.use_items.push(item);
5662 }
5663
5664 ItemKind::Mod(..)
5665 | ItemKind::Static(..)
5666 | ItemKind::ConstBlock(..)
5667 | ItemKind::MacroDef(..)
5668 | ItemKind::GlobalAsm(..)
5669 | ItemKind::MacCall(..)
5670 | ItemKind::DelegationMac(..) => {}
5671 ItemKind::Delegation(..) => {
5672 }
5677 }
5678 visit::walk_item(self, item)
5679 }
5680
5681 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5682 if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5683 self.collect_fn_info(&sig.decl, item.id);
5684 }
5685
5686 if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5687 let def_id = self.r.owner_def_id(item.id);
5688 if let Some(suggestion) = required_generic_args_suggestion(generics) {
5689 self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5690 }
5691 }
5692 visit::walk_assoc_item(self, item, ctxt);
5693 }
5694}
5695
5696impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5697 pub(crate) fn late_resolve_crate<'ast>(
5699 &mut self,
5700 krate: &'ast Crate,
5701 ) -> (Vec<&'ast Item>, Vec<UseError<'tcx>>) {
5702 with_owner(self, CRATE_NODE_ID, |this| {
5703 let mut info_collector = ItemInfoCollector { r: this, use_items: Vec::new() };
5704 visit::walk_crate(&mut info_collector, krate);
5705 let use_items = info_collector.use_items;
5706 let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5707 late_resolution_visitor
5708 .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5709 visit::walk_crate(&mut late_resolution_visitor, krate);
5710 let LateResolutionVisitor { use_injections, diag_metadata, .. } =
5711 late_resolution_visitor;
5712 for (id, span) in diag_metadata.unused_labels.iter() {
5713 this.lint_buffer.buffer_lint(
5714 lint::builtin::UNUSED_LABELS,
5715 *id,
5716 *span,
5717 crate::diagnostics::UnusedLabel,
5718 );
5719 }
5720 (use_items, use_injections)
5721 })
5722 }
5723}
5724
5725fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5727 let mut path = expected_path.iter().rev();
5728 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5729 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5730 return false;
5731 }
5732 def_id = parent;
5733 }
5734 true
5735}