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<'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)]
430pub(crate) enum PathSource<'a, 'ast, 'ra> {
431 Type,
433 Trait(AliasPossibility),
435 Expr(Option<&'ast Expr>),
437 Pat,
439 Struct(Option<&'a Expr>),
441 TupleStruct(Span, &'ra [Span]),
443 TraitItem(Namespace, &'a PathSource<'a, 'ast, 'ra>),
448 Delegation,
450 ExternItemImpl,
452 PreciseCapturingArg(Namespace),
454 ReturnTypeNotation,
456 DefineOpaques,
458 Macro,
460 Module,
462}
463
464impl PathSource<'_, '_, '_> {
465 fn namespace(self) -> Namespace {
466 match self {
467 PathSource::Type
468 | PathSource::Trait(_)
469 | PathSource::Struct(_)
470 | PathSource::DefineOpaques
471 | PathSource::Module => TypeNS,
472 PathSource::Expr(..)
473 | PathSource::Pat
474 | PathSource::TupleStruct(..)
475 | PathSource::Delegation
476 | PathSource::ExternItemImpl
477 | PathSource::ReturnTypeNotation => ValueNS,
478 PathSource::TraitItem(ns, _) => ns,
479 PathSource::PreciseCapturingArg(ns) => ns,
480 PathSource::Macro => MacroNS,
481 }
482 }
483
484 fn defer_to_typeck(self) -> bool {
485 match self {
486 PathSource::Type
487 | PathSource::Expr(..)
488 | PathSource::Pat
489 | PathSource::Struct(_)
490 | PathSource::TupleStruct(..)
491 | PathSource::ReturnTypeNotation => true,
492 PathSource::Trait(_)
493 | PathSource::TraitItem(..)
494 | PathSource::DefineOpaques
495 | PathSource::Delegation
496 | PathSource::ExternItemImpl
497 | PathSource::PreciseCapturingArg(..)
498 | PathSource::Macro
499 | PathSource::Module => false,
500 }
501 }
502
503 fn descr_expected(self) -> &'static str {
504 match &self {
505 PathSource::DefineOpaques => "type alias or associated type with opaqaue types",
506 PathSource::Type => "type",
507 PathSource::Trait(_) => "trait",
508 PathSource::Pat => "unit struct, unit variant or constant",
509 PathSource::Struct(_) => "struct, variant or union type",
510 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(..))
511 | PathSource::TupleStruct(..) => "tuple struct or tuple variant",
512 PathSource::TraitItem(ns, _) => match ns {
513 TypeNS => "associated type",
514 ValueNS => "method or associated constant",
515 MacroNS => ::rustc_middle::util::bug::bug_fmt(format_args!("associated macro"))bug!("associated macro"),
516 },
517 PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
518 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
521 ExprKind::Path(_, path)
523 if let [segment, _] = path.segments.as_slice()
524 && segment.ident.name == kw::PathRoot =>
525 {
526 "external crate"
527 }
528 ExprKind::Path(_, path)
529 if let Some(segment) = path.segments.last()
530 && let Some(c) = segment.ident.to_string().chars().next()
531 && c.is_uppercase() =>
532 {
533 "function, tuple struct or tuple variant"
534 }
535 _ => "function",
536 },
537 _ => "value",
538 },
539 PathSource::ReturnTypeNotation | PathSource::Delegation => "function",
540 PathSource::ExternItemImpl => "function or static",
541 PathSource::PreciseCapturingArg(..) => "type or const parameter",
542 PathSource::Macro => "macro",
543 PathSource::Module => "module",
544 }
545 }
546
547 fn is_call(self) -> bool {
548 #[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(..), .. })))
549 }
550
551 pub(crate) fn is_expected(self, res: Res) -> bool {
552 match self {
553 PathSource::DefineOpaques => {
554 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum |
DefKind::TyAlias | DefKind::AssocTy, _) | Res::SelfTyAlias { .. } =>
true,
_ => false,
}matches!(
555 res,
556 Res::Def(
557 DefKind::Struct
558 | DefKind::Union
559 | DefKind::Enum
560 | DefKind::TyAlias
561 | DefKind::AssocTy,
562 _
563 ) | Res::SelfTyAlias { .. }
564 )
565 }
566 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!(
567 res,
568 Res::Def(
569 DefKind::Struct
570 | DefKind::Union
571 | DefKind::Enum
572 | DefKind::Trait
573 | DefKind::TraitAlias
574 | DefKind::TyAlias
575 | DefKind::AssocTy
576 | DefKind::TyParam
577 | DefKind::OpaqueTy
578 | DefKind::ForeignTy,
579 _,
580 ) | Res::PrimTy(..)
581 | Res::SelfTyParam { .. }
582 | Res::SelfTyAlias { .. }
583 ),
584 PathSource::Trait(AliasPossibility::No) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
585 PathSource::Trait(AliasPossibility::Maybe) => {
586 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
587 }
588 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!(
589 res,
590 Res::Def(
591 DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
592 | DefKind::Const { .. }
593 | DefKind::Static { .. }
594 | DefKind::Fn
595 | DefKind::AssocFn
596 | DefKind::AssocConst { .. }
597 | DefKind::ConstParam,
598 _,
599 ) | Res::Local(..)
600 | Res::SelfCtor(..)
601 ),
602 PathSource::Pat => {
603 res.expected_in_unit_struct_pat()
604 || #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _) => true,
_ => false,
}matches!(
605 res,
606 Res::Def(DefKind::Const { .. } | DefKind::AssocConst { .. }, _)
607 )
608 }
609 PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
610 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!(
611 res,
612 Res::Def(
613 DefKind::Struct
614 | DefKind::Union
615 | DefKind::Variant
616 | DefKind::TyAlias
617 | DefKind::AssocTy,
618 _,
619 ) | Res::SelfTyParam { .. }
620 | Res::SelfTyAlias { .. }
621 ),
622 PathSource::TraitItem(ns, _) => match res {
623 Res::Def(DefKind::AssocConst { .. } | DefKind::AssocFn, _) if ns == ValueNS => true,
624 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
625 _ => false,
626 },
627 PathSource::ReturnTypeNotation => match res {
628 Res::Def(DefKind::AssocFn, _) => true,
629 _ => false,
630 },
631 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, _)),
632 PathSource::ExternItemImpl => {
633 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) |
DefKind::Static { .. }, _) => true,
_ => false,
}matches!(
634 res,
635 Res::Def(
636 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Static { .. },
637 _
638 )
639 )
640 }
641 PathSource::PreciseCapturingArg(ValueNS) => {
642 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::ConstParam, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::ConstParam, _))
643 }
644 PathSource::PreciseCapturingArg(TypeNS) => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } |
Res::SelfTyAlias { .. } => true,
_ => false,
}matches!(
646 res,
647 Res::Def(DefKind::TyParam, _) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }
648 ),
649 PathSource::PreciseCapturingArg(MacroNS) => false,
650 PathSource::Macro => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Macro(_), _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Macro(_), _)),
651 PathSource::Module => #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
652 }
653 }
654
655 fn error_code(self, has_unexpected_resolution: bool) -> ErrCode {
656 match (self, has_unexpected_resolution) {
657 (PathSource::Trait(_), true) => E0404,
658 (PathSource::Trait(_), false) => E0405,
659 (PathSource::Type | PathSource::DefineOpaques, true) => E0573,
660 (PathSource::Type | PathSource::DefineOpaques, false) => E0425,
661 (PathSource::Struct(_), true) => E0574,
662 (PathSource::Struct(_), false) => E0422,
663 (PathSource::Expr(..), true)
664 | (PathSource::Delegation, true)
665 | (PathSource::ExternItemImpl, true) => E0423,
666 (PathSource::Expr(..), false)
667 | (PathSource::Delegation, false)
668 | (PathSource::ExternItemImpl, false) => E0425,
669 (PathSource::Pat | PathSource::TupleStruct(..), true) => E0532,
670 (PathSource::Pat | PathSource::TupleStruct(..), false) => E0531,
671 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, true) => E0575,
672 (PathSource::TraitItem(..) | PathSource::ReturnTypeNotation, false) => E0576,
673 (PathSource::PreciseCapturingArg(..), true) => E0799,
674 (PathSource::PreciseCapturingArg(..), false) => E0800,
675 (PathSource::Macro, _) => E0425,
676 (PathSource::Module, true) => E0577,
681 (PathSource::Module, false) => E0433,
682 }
683 }
684}
685
686#[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)]
690enum MaybeExported<'a> {
691 Ok(NodeId),
692 Impl(Option<DefId>),
693 ImplItem(Result<DefId, &'a ast::Visibility>),
694 NestedUse(&'a ast::Visibility),
695}
696
697impl MaybeExported<'_> {
698 fn eval(self, r: &Resolver<'_, '_>) -> bool {
699 let def_id = match self {
700 MaybeExported::Ok(node_id) => Some(if r.current_owner.id == node_id {
701 r.current_owner.def_id
702 } else {
703 r.current_owner.node_id_to_def_id[&node_id]
704 }),
705 MaybeExported::Impl(Some(trait_def_id)) | MaybeExported::ImplItem(Ok(trait_def_id)) => {
706 trait_def_id.as_local()
707 }
708 MaybeExported::Impl(None) => return true,
709 MaybeExported::ImplItem(Err(vis)) | MaybeExported::NestedUse(vis) => {
710 return vis.kind.is_pub();
711 }
712 };
713 def_id.is_none_or(|def_id| r.effective_visibilities.is_exported(def_id))
714 }
715}
716
717#[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)]
719pub(crate) struct UnnecessaryQualification<'ra> {
720 pub decl: LateDecl<'ra>,
721 pub node_id: NodeId,
722 pub path_span: Span,
723 pub removal_span: Span,
724}
725
726#[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)]
727pub(crate) struct DiagMetadata<'ast> {
728 current_trait_assoc_items: Option<&'ast [Box<AssocItem>]>,
730
731 pub(crate) current_self_type: Option<&'ast Ty>,
733
734 current_self_item: Option<NodeId>,
736
737 pub(crate) current_item: Option<&'ast Item>,
739
740 currently_processing_generic_args: bool,
743
744 current_function: Option<(FnKind<'ast>, Span)>,
746
747 unused_labels: FxIndexMap<NodeId, Span>,
750
751 current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
753
754 current_pat: Option<&'ast Pat>,
755
756 in_if_condition: Option<&'ast Expr>,
758
759 in_assignment: Option<&'ast Expr>,
761 is_assign_rhs: bool,
762
763 in_non_gat_assoc_type: Option<bool>,
765
766 in_range: Option<(&'ast Expr, &'ast Expr)>,
768
769 current_trait_object: Option<&'ast [ast::GenericBound]>,
772
773 current_where_predicate: Option<&'ast WherePredicate>,
775
776 in_assoc_ty_binding: bool,
778
779 current_type_path: Option<&'ast Ty>,
780
781 current_impl_items: Option<&'ast [Box<AssocItem>]>,
783
784 current_impl_item: Option<&'ast AssocItem>,
786
787 currently_processing_impl_trait: Option<(TraitRef, Ty)>,
789
790 current_elision_failures: Vec<(MissingLifetime, Either<NodeId, Range<NodeId>>)>,
793}
794
795struct LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
796 r: &'a mut Resolver<'ra, 'tcx>,
797
798 parent_scope: ParentScope<'ra>,
800
801 ribs: PerNS<Vec<Rib<'ra>>>,
803
804 last_block_rib: Option<Rib<'ra>>,
806
807 label_ribs: Vec<Rib<'ra, NodeId>>,
809
810 lifetime_ribs: Vec<LifetimeRib>,
812
813 lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>,
819
820 current_trait_ref: Option<(Module<'ra>, TraitRef)>,
822
823 diag_metadata: Box<DiagMetadata<'ast>>,
825
826 in_func_body: bool,
832
833 lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
835
836 use_injections: Vec<UseError<'tcx>>,
838}
839
840impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
841 fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
842 &self.r
843 }
844}
845impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for LateResolutionVisitor<'_, '_, 'ra, 'tcx> {
846 fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
847 &mut self.r
848 }
849}
850
851impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
853 fn visit_attribute(&mut self, _: &'ast Attribute) {
854 }
857 fn visit_item(&mut self, item: &'ast Item) {
858 let prev = replace(&mut self.diag_metadata.current_item, Some(item));
859 let old_ignore = replace(&mut self.in_func_body, false);
861 with_owner(self, item.id, |this| {
862 this.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item))
863 });
864 self.in_func_body = old_ignore;
865 self.diag_metadata.current_item = prev;
866 }
867 fn visit_arm(&mut self, arm: &'ast Arm) {
868 self.resolve_arm(arm);
869 }
870 fn visit_block(&mut self, block: &'ast Block) {
871 let old_macro_rules = self.parent_scope.macro_rules;
872 self.resolve_block(block);
873 self.parent_scope.macro_rules = old_macro_rules;
874 }
875 fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
876 ::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:#?}");
877 }
878 fn visit_expr(&mut self, expr: &'ast Expr) {
879 self.resolve_expr(expr, None);
880 }
881 fn visit_pat(&mut self, p: &'ast Pat) {
882 let prev = self.diag_metadata.current_pat;
883 self.diag_metadata.current_pat = Some(p);
884
885 if let PatKind::Guard(subpat, _) = &p.kind {
886 self.visit_pat(subpat);
888 } else {
889 visit::walk_pat(self, p);
890 }
891
892 self.diag_metadata.current_pat = prev;
893 }
894 fn visit_local(&mut self, local: &'ast Local) {
895 let local_spans = match local.pat.kind {
896 PatKind::Wild => None,
898 _ => Some((
899 local.pat.span,
900 local.ty.as_ref().map(|ty| ty.span),
901 local.kind.init().map(|init| init.span),
902 )),
903 };
904 let original = replace(&mut self.diag_metadata.current_let_binding, local_spans);
905 self.resolve_local(local);
906 self.diag_metadata.current_let_binding = original;
907 }
908 fn visit_ty(&mut self, ty: &'ast Ty) {
909 let prev = self.diag_metadata.current_trait_object;
910 let prev_ty = self.diag_metadata.current_type_path;
911 match &ty.kind {
912 TyKind::Ref(None, _) | TyKind::PinnedRef(None, _) => {
913 let span = self.r.tcx.sess.source_map().start_point(ty.span);
917 self.resolve_elided_lifetime(ty.id, span);
918 visit::walk_ty(self, ty);
919 }
920 TyKind::Path(qself, path) => {
921 self.diag_metadata.current_type_path = Some(ty);
922
923 let source = if let Some(seg) = path.segments.last()
927 && let Some(args) = &seg.args
928 && #[allow(non_exhaustive_omitted_patterns)] match **args {
GenericArgs::ParenthesizedElided(..) => true,
_ => false,
}matches!(**args, GenericArgs::ParenthesizedElided(..))
929 {
930 PathSource::ReturnTypeNotation
931 } else {
932 PathSource::Type
933 };
934
935 self.smart_resolve_path(ty.id, qself, path, source);
936
937 if qself.is_none()
939 && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
940 && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) =
941 partial_res.full_res()
942 {
943 let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
947 self.with_generic_param_rib(
948 &[],
949 RibKind::Normal,
950 ty.id,
951 LifetimeBinderKind::PolyTrait,
952 span,
953 |this| this.visit_path(path),
954 );
955 } else {
956 visit::walk_ty(self, ty)
957 }
958 }
959 TyKind::ImplicitSelf => {
960 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
961 let res = self
962 .resolve_ident_in_lexical_scope(
963 self_ty,
964 TypeNS,
965 Some(Finalize::new(ty.id, ty.span)),
966 None,
967 )
968 .map_or(Res::Err, |d| d.res());
969 self.r.record_partial_res(ty.id, PartialRes::new(res));
970 visit::walk_ty(self, ty)
971 }
972 TyKind::ImplTrait(..) => {
973 let candidates = self.lifetime_elision_candidates.take();
974 self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
975 self.lifetime_elision_candidates = candidates;
976 }
977 TyKind::TraitObject(bounds, ..) => {
978 self.diag_metadata.current_trait_object = Some(&bounds[..]);
979 visit::walk_ty(self, ty)
980 }
981 TyKind::FnPtr(fn_ptr) => {
982 let span = ty.span.shrink_to_lo().to(fn_ptr.decl_span.shrink_to_lo());
983 self.with_generic_param_rib(
984 &fn_ptr.generic_params,
985 RibKind::Normal,
986 ty.id,
987 LifetimeBinderKind::FnPtrType,
988 span,
989 |this| {
990 this.visit_generic_params(&fn_ptr.generic_params, false);
991 this.resolve_fn_signature(
992 ty.id,
993 false,
994 fn_ptr.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
997 &fn_ptr.decl.output,
998 false,
999 )
1000 },
1001 )
1002 }
1003 TyKind::UnsafeBinder(unsafe_binder) => {
1004 let span = ty.span.shrink_to_lo().to(unsafe_binder.inner_ty.span.shrink_to_lo());
1005 self.with_generic_param_rib(
1006 &unsafe_binder.generic_params,
1007 RibKind::Normal,
1008 ty.id,
1009 LifetimeBinderKind::FnPtrType,
1010 span,
1011 |this| {
1012 this.visit_generic_params(&unsafe_binder.generic_params, false);
1013 this.with_lifetime_rib(
1014 LifetimeRibKind::AnonymousReportError,
1017 |this| this.visit_ty(&unsafe_binder.inner_ty),
1018 );
1019 },
1020 )
1021 }
1022 TyKind::Array(element_ty, length) => {
1023 self.visit_ty(element_ty);
1024 self.resolve_anon_const(length, AnonConstKind::ConstArg(IsRepeatExpr::No));
1025 }
1026 TyKind::DirectConstArg(expr) => self.resolve_anon_const_manual(
1027 true,
1028 AnonConstKind::ConstArg(IsRepeatExpr::No),
1029 |this| this.resolve_expr(expr, None),
1030 ),
1031 _ => visit::walk_ty(self, ty),
1032 }
1033 self.diag_metadata.current_trait_object = prev;
1034 self.diag_metadata.current_type_path = prev_ty;
1035 }
1036
1037 fn visit_ty_pat(&mut self, t: &'ast TyPat) -> Self::Result {
1038 match &t.kind {
1039 TyPatKind::Range(start, end, _) => {
1040 if let Some(start) = start {
1041 self.resolve_anon_const(start, AnonConstKind::ConstArg(IsRepeatExpr::No));
1042 }
1043 if let Some(end) = end {
1044 self.resolve_anon_const(end, AnonConstKind::ConstArg(IsRepeatExpr::No));
1045 }
1046 }
1047 TyPatKind::Or(patterns) => {
1048 for pat in patterns {
1049 self.visit_ty_pat(pat)
1050 }
1051 }
1052 TyPatKind::NotNull | TyPatKind::Err(_) => {}
1053 }
1054 }
1055
1056 fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
1057 let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
1058 self.with_generic_param_rib(
1059 &tref.bound_generic_params,
1060 RibKind::Normal,
1061 tref.trait_ref.ref_id,
1062 LifetimeBinderKind::PolyTrait,
1063 span,
1064 |this| {
1065 this.visit_generic_params(&tref.bound_generic_params, false);
1066 this.smart_resolve_path(
1067 tref.trait_ref.ref_id,
1068 &None,
1069 &tref.trait_ref.path,
1070 PathSource::Trait(AliasPossibility::Maybe),
1071 );
1072 this.visit_trait_ref(&tref.trait_ref);
1073 },
1074 );
1075 }
1076 fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
1077 with_owner(self, foreign_item.id, |this| {
1078 this.resolve_doc_links(&foreign_item.attrs, MaybeExported::Ok(foreign_item.id));
1079 let def_kind = this.r.tcx.def_kind(this.r.current_owner.def_id);
1080 match foreign_item.kind {
1081 ForeignItemKind::TyAlias(TyAlias { ref generics, .. }) => {
1082 this.with_generic_param_rib(
1083 &generics.params,
1084 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1085 foreign_item.id,
1086 LifetimeBinderKind::Item,
1087 generics.span,
1088 |this| visit::walk_item(this, foreign_item),
1089 );
1090 }
1091 ForeignItemKind::Fn(Fn { ref generics, .. }) => {
1092 this.with_generic_param_rib(
1093 &generics.params,
1094 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
1095 foreign_item.id,
1096 LifetimeBinderKind::Function,
1097 generics.span,
1098 |this| visit::walk_item(this, foreign_item),
1099 );
1100 }
1101 ForeignItemKind::Static(..) => {
1102 this.with_static_rib(def_kind, |this| visit::walk_item(this, foreign_item))
1103 }
1104 ForeignItemKind::MacCall(..) => {
1105 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
1106 }
1107 }
1108 })
1109 }
1110 fn visit_fn(&mut self, fn_kind: FnKind<'ast>, _: &AttrVec, sp: Span, fn_id: NodeId) {
1111 let previous_value = self.diag_metadata.current_function;
1112 match fn_kind {
1113 FnKind::Fn(FnCtxt::Foreign, _, Fn { sig, ident, generics, .. })
1116 | FnKind::Fn(_, _, Fn { sig, ident, generics, body: None, .. }) => {
1117 self.visit_fn_header(&sig.header);
1118 self.visit_ident(ident);
1119 self.visit_generics(generics);
1120 self.resolve_fn_signature(
1121 fn_id,
1122 sig.decl.has_self(),
1123 sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
1124 &sig.decl.output,
1125 false,
1126 );
1127 return;
1128 }
1129 FnKind::Fn(..) => {
1130 self.diag_metadata.current_function = Some((fn_kind, sp));
1131 }
1132 FnKind::Closure(..) => {}
1134 };
1135 {
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:1135",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1135u32),
::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");
1136
1137 if let FnKind::Fn(_, _, f) = fn_kind {
1138 self.resolve_eii(f.eii_impl.as_deref());
1139 }
1140
1141 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
1143 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
1145 match fn_kind {
1146 FnKind::Fn(_, _, Fn { sig, generics, contract, body, .. }) => {
1147 this.visit_generics(generics);
1148
1149 let declaration = &sig.decl;
1150 this.resolve_fn_signature(
1151 fn_id,
1152 declaration.has_self(),
1153 declaration
1154 .inputs
1155 .iter()
1156 .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
1157 &declaration.output,
1158 sig.header.coroutine_marker.is_some(),
1159 );
1160
1161 if let Some(contract) = contract {
1162 this.visit_contract(contract);
1163 }
1164
1165 if let Some(body) = body {
1166 let previous_state = replace(&mut this.in_func_body, true);
1169 this.last_block_rib = None;
1171 this.with_lifetime_rib(
1174 LifetimeRibKind::elided(LifetimeRes::Infer),
1175 |this| this.visit_block(body),
1176 );
1177
1178 {
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:1178",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1178u32),
::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");
1179 this.in_func_body = previous_state;
1180 }
1181 }
1182 FnKind::Closure(binder, _, declaration, body) => {
1183 this.visit_closure_binder(binder);
1184
1185 this.with_lifetime_rib(
1186 match binder {
1187 ClosureBinder::NotPresent => {
1189 LifetimeRibKind::AnonymousCreateParameter {
1190 binder: fn_id,
1191 report_in_path: false,
1192 }
1193 }
1194 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1195 },
1196 |this| this.resolve_params(&declaration.inputs),
1198 );
1199 this.with_lifetime_rib(
1200 match binder {
1201 ClosureBinder::NotPresent => {
1202 LifetimeRibKind::elided(LifetimeRes::Infer)
1203 }
1204 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
1205 },
1206 |this| visit::walk_fn_ret_ty(this, &declaration.output),
1207 );
1208
1209 let previous_state = replace(&mut this.in_func_body, true);
1212 this.with_lifetime_rib(
1214 LifetimeRibKind::elided(LifetimeRes::Infer),
1215 |this| this.visit_expr(body),
1216 );
1217
1218 {
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:1218",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1218u32),
::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");
1219 this.in_func_body = previous_state;
1220 }
1221 }
1222 })
1223 });
1224 self.diag_metadata.current_function = previous_value;
1225 }
1226
1227 fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1228 self.resolve_lifetime(lifetime, use_ctxt)
1229 }
1230
1231 fn visit_precise_capturing_arg(&mut self, arg: &'ast PreciseCapturingArg) {
1232 match arg {
1233 PreciseCapturingArg::Lifetime(_) => {}
1236
1237 PreciseCapturingArg::Arg(path, id) => {
1238 let mut check_ns = |ns| {
1245 self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns).is_some()
1246 };
1247 if !check_ns(TypeNS) && check_ns(ValueNS) {
1249 self.smart_resolve_path(
1250 *id,
1251 &None,
1252 path,
1253 PathSource::PreciseCapturingArg(ValueNS),
1254 );
1255 } else {
1256 self.smart_resolve_path(
1257 *id,
1258 &None,
1259 path,
1260 PathSource::PreciseCapturingArg(TypeNS),
1261 );
1262 }
1263 }
1264 }
1265
1266 visit::walk_precise_capturing_arg(self, arg)
1267 }
1268
1269 fn visit_generics(&mut self, generics: &'ast Generics) {
1270 self.visit_generic_params(&generics.params, self.diag_metadata.current_self_item.is_some());
1271 for p in &generics.where_clause.predicates {
1272 self.visit_where_predicate(p);
1273 }
1274 }
1275
1276 fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
1277 match b {
1278 ClosureBinder::NotPresent => {}
1279 ClosureBinder::For { generic_params, .. } => {
1280 self.visit_generic_params(
1281 generic_params,
1282 self.diag_metadata.current_self_item.is_some(),
1283 );
1284 }
1285 }
1286 }
1287
1288 #[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("visit_generic_arg",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1288u32),
::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("arg")
}> =
::tracing::__macro_support::FieldName::new("arg");
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(&arg)
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 prev =
replace(&mut self.diag_metadata.currently_processing_generic_args,
true);
match arg {
GenericArg::Type(ty) => {
if let TyKind::Path(None, ref path) = ty.kind &&
let Some(ident) = path.as_single_argless_ident() &&
self.maybe_resolve_ident_in_lexical_scope(ident,
TypeNS).is_none() &&
self.maybe_resolve_ident_in_lexical_scope(ident,
ValueNS).is_some() {
self.resolve_anon_const_manual(true,
AnonConstKind::ConstArg(IsRepeatExpr::No),
|this|
{
this.smart_resolve_path(ty.id, &None, path,
PathSource::Expr(None));
this.visit_path(path);
})
} else { self.visit_ty(ty) }
}
GenericArg::Lifetime(lt) =>
self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
GenericArg::Const(ct) => {
self.resolve_anon_const(ct,
AnonConstKind::ConstArg(IsRepeatExpr::No))
}
}
self.diag_metadata.currently_processing_generic_args = prev;
}
}
}#[instrument(level = "debug", skip(self))]
1289 fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
1290 let prev = replace(&mut self.diag_metadata.currently_processing_generic_args, true);
1291 match arg {
1292 GenericArg::Type(ty) => {
1293 if let TyKind::Path(None, ref path) = ty.kind
1302 && let Some(ident) = path.as_single_argless_ident()
1303 && self.maybe_resolve_ident_in_lexical_scope(ident, TypeNS).is_none()
1304 && self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS).is_some()
1305 {
1306 self.resolve_anon_const_manual(
1307 true,
1308 AnonConstKind::ConstArg(IsRepeatExpr::No),
1309 |this| {
1310 this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
1311 this.visit_path(path);
1312 },
1313 )
1314 } else {
1315 self.visit_ty(ty)
1316 }
1317 }
1318 GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
1319 GenericArg::Const(ct) => {
1320 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::No))
1321 }
1322 }
1323 self.diag_metadata.currently_processing_generic_args = prev;
1324 }
1325
1326 fn visit_assoc_item_constraint(&mut self, constraint: &'ast AssocItemConstraint) {
1327 self.visit_ident(&constraint.ident);
1328 if let Some(ref gen_args) = constraint.gen_args {
1329 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1331 this.visit_generic_args(gen_args)
1332 });
1333 }
1334 match constraint.kind {
1335 AssocItemConstraintKind::Equality { ref term } => match term {
1336 Term::Ty(ty) => {
1337 let prev = replace(&mut self.diag_metadata.in_assoc_ty_binding, true);
1338 self.visit_ty(ty);
1339 self.diag_metadata.in_assoc_ty_binding = prev;
1340 }
1341 Term::Const(c) => {
1342 self.resolve_anon_const(c, AnonConstKind::ConstArg(IsRepeatExpr::No))
1343 }
1344 },
1345 AssocItemConstraintKind::Bound { ref bounds } => {
1346 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);
1347 }
1348 }
1349 }
1350
1351 fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1352 let Some(ref args) = path_segment.args else {
1353 return;
1354 };
1355
1356 match &**args {
1357 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1358 GenericArgs::Parenthesized(p_args) => {
1359 for rib in self.lifetime_ribs.iter().rev() {
1361 match rib.kind {
1362 LifetimeRibKind::Generics {
1365 binder,
1366 kind: LifetimeBinderKind::PolyTrait,
1367 ..
1368 } => {
1369 self.resolve_fn_signature(
1370 binder,
1371 false,
1372 p_args.inputs.iter().map(|param| (None, &*param.ty)),
1373 &p_args.output,
1374 false,
1375 );
1376 break;
1377 }
1378 LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1381 visit::walk_generic_args(self, args);
1382 break;
1383 }
1384 LifetimeRibKind::AnonymousCreateParameter { .. }
1385 | LifetimeRibKind::AnonymousReportError
1386 | LifetimeRibKind::ImplTrait
1387 | LifetimeRibKind::Elided { .. }
1388 | LifetimeRibKind::ElisionFailure
1389 | LifetimeRibKind::ConcreteAnonConst(_)
1390 | LifetimeRibKind::ConstParamTy => {}
1391 }
1392 }
1393 }
1394 GenericArgs::ParenthesizedElided(_) => {}
1395 }
1396 }
1397
1398 fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1399 {
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:1399",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1399u32),
::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);
1400 let previous_value = replace(&mut self.diag_metadata.current_where_predicate, Some(p));
1401 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1402 if let WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1403 bounded_ty,
1404 bounds,
1405 bound_generic_params,
1406 ..
1407 }) = &p.kind
1408 {
1409 let span = p.span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1410 this.with_generic_param_rib(
1411 bound_generic_params,
1412 RibKind::Normal,
1413 bounded_ty.id,
1414 LifetimeBinderKind::WhereBound,
1415 span,
1416 |this| {
1417 this.visit_generic_params(bound_generic_params, false);
1418 this.visit_ty(bounded_ty);
1419 for bound in bounds {
1420 this.visit_param_bound(bound, BoundKind::Bound)
1421 }
1422 },
1423 );
1424 } else {
1425 visit::walk_where_predicate(this, p);
1426 }
1427 });
1428 self.diag_metadata.current_where_predicate = previous_value;
1429 }
1430
1431 fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1432 for (op, _) in &asm.operands {
1433 match op {
1434 InlineAsmOperand::In { expr, .. }
1435 | InlineAsmOperand::Out { expr: Some(expr), .. }
1436 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1437 InlineAsmOperand::Out { expr: None, .. } => {}
1438 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1439 self.visit_expr(in_expr);
1440 if let Some(out_expr) = out_expr {
1441 self.visit_expr(out_expr);
1442 }
1443 }
1444 InlineAsmOperand::Const { anon_const, .. } => {
1445 self.resolve_anon_const(anon_const, AnonConstKind::InlineConst);
1448 }
1449 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1450 InlineAsmOperand::Label { block } => self.visit_block(block),
1451 }
1452 }
1453 }
1454
1455 fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1456 self.with_rib(ValueNS, RibKind::InlineAsmSym, |this| {
1458 this.with_rib(TypeNS, RibKind::InlineAsmSym, |this| {
1459 this.with_label_rib(RibKind::InlineAsmSym, |this| {
1460 this.smart_resolve_path(sym.id, &sym.qself, &sym.path, PathSource::Expr(None));
1461 visit::walk_inline_asm_sym(this, sym);
1462 });
1463 })
1464 });
1465 }
1466
1467 fn visit_variant(&mut self, v: &'ast Variant) {
1468 self.resolve_doc_links(&v.attrs, MaybeExported::Ok(v.id));
1469 self.visit_id(v.id);
1470 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);
1471 self.visit_vis(&v.vis);
1472 self.visit_ident(&v.ident);
1473 self.visit_variant_data(&v.data);
1474 if let Some(discr) = &v.disr_expr {
1475 self.resolve_anon_const(discr, AnonConstKind::EnumDiscriminant);
1476 }
1477 }
1478
1479 fn visit_field_def(&mut self, f: &'ast FieldDef) {
1480 self.resolve_doc_links(&f.attrs, MaybeExported::Ok(f.id));
1481 let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, extras: _ } = f;
1482 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);
1483 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));
1484 self.resolve_restriction_path(&f.mut_restriction().kind);
1485 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);
1486 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));
1487 if let Some(v) = f.default_value() {
1488 self.resolve_anon_const(v, AnonConstKind::FieldDefaultValue);
1489 }
1490 }
1491}
1492
1493impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1494 fn new(resolver: &'a mut Resolver<'ra, 'tcx>) -> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
1495 let graph_root = resolver.graph_root;
1498 let parent_scope = ParentScope::module(graph_root, resolver.arenas);
1499 let start_rib_kind = RibKind::Module(graph_root);
1500 LateResolutionVisitor {
1501 r: resolver,
1502 parent_scope,
1503 ribs: PerNS {
1504 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)],
1505 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)],
1506 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)],
1507 },
1508 last_block_rib: None,
1509 label_ribs: Vec::new(),
1510 lifetime_ribs: Vec::new(),
1511 lifetime_elision_candidates: None,
1512 current_trait_ref: None,
1513 diag_metadata: Default::default(),
1514 in_func_body: false,
1516 lifetime_uses: Default::default(),
1517 use_injections: Vec::new(),
1518 }
1519 }
1520
1521 fn maybe_resolve_ident_in_lexical_scope(
1522 &mut self,
1523 ident: Ident,
1524 ns: Namespace,
1525 ) -> Option<LateDecl<'ra>> {
1526 self.r.resolve_ident_in_lexical_scope(
1527 ident,
1528 ns,
1529 &self.parent_scope,
1530 None,
1531 &self.ribs[ns],
1532 None,
1533 Some(&self.diag_metadata),
1534 )
1535 }
1536
1537 fn resolve_ident_in_lexical_scope(
1538 &mut self,
1539 ident: Ident,
1540 ns: Namespace,
1541 finalize: Option<Finalize>,
1542 ignore_decl: Option<Decl<'ra>>,
1543 ) -> Option<LateDecl<'ra>> {
1544 self.r.resolve_ident_in_lexical_scope(
1545 ident,
1546 ns,
1547 &self.parent_scope,
1548 finalize,
1549 &self.ribs[ns],
1550 ignore_decl,
1551 Some(&self.diag_metadata),
1552 )
1553 }
1554
1555 fn resolve_path(
1556 &mut self,
1557 path: &[Segment],
1558 opt_ns: Option<Namespace>, finalize: Option<Finalize>,
1560 source: PathSource<'_, 'ast, 'ra>,
1561 ) -> PathResult<'ra> {
1562 self.r.cm_mut().resolve_path_with_ribs(
1563 path,
1564 opt_ns,
1565 &self.parent_scope,
1566 Some(source),
1567 finalize.map(|finalize| Finalize { stage: Stage::Late, ..finalize }),
1568 Some(&self.ribs),
1569 None,
1570 None,
1571 Some(&self.diag_metadata),
1572 )
1573 }
1574
1575 fn with_rib<T>(
1595 &mut self,
1596 ns: Namespace,
1597 kind: RibKind<'ra>,
1598 work: impl FnOnce(&mut Self) -> T,
1599 ) -> T {
1600 self.ribs[ns].push(Rib::new(kind));
1601 let ret = work(self);
1602 self.ribs[ns].pop();
1603 ret
1604 }
1605
1606 fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1607 let mut forward_ty_ban_rib =
1613 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1614 let mut forward_const_ban_rib =
1615 Rib::new(RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::Default));
1616 for param in params.iter() {
1617 match param.kind {
1618 GenericParamKind::Type { .. } => {
1619 forward_ty_ban_rib
1620 .bindings
1621 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1622 }
1623 GenericParamKind::Const { .. } => {
1624 forward_const_ban_rib
1625 .bindings
1626 .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1627 }
1628 GenericParamKind::Lifetime => {}
1629 }
1630 }
1631
1632 if add_self_upper {
1642 forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1644 }
1645
1646 let mut forward_ty_ban_rib_const_param_ty = Rib {
1649 bindings: forward_ty_ban_rib.bindings.clone(),
1650 patterns_with_skipped_bindings: Default::default(),
1651 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1652 };
1653 let mut forward_const_ban_rib_const_param_ty = Rib {
1654 bindings: forward_const_ban_rib.bindings.clone(),
1655 patterns_with_skipped_bindings: Default::default(),
1656 kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy),
1657 };
1658 if !self.r.features.generic_const_parameter_types() {
1661 forward_ty_ban_rib_const_param_ty.bindings.clear();
1662 forward_const_ban_rib_const_param_ty.bindings.clear();
1663 }
1664
1665 self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1666 for param in params {
1667 match param.kind {
1668 GenericParamKind::Lifetime => {
1669 for bound in ¶m.bounds {
1670 this.visit_param_bound(bound, BoundKind::Bound);
1671 }
1672 }
1673 GenericParamKind::Type { ref default } => {
1674 for bound in ¶m.bounds {
1675 this.visit_param_bound(bound, BoundKind::Bound);
1676 }
1677
1678 if let Some(ty) = default {
1679 this.ribs[TypeNS].push(forward_ty_ban_rib);
1680 this.ribs[ValueNS].push(forward_const_ban_rib);
1681 this.visit_ty(ty);
1682 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1683 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1684 }
1685
1686 let i = &Ident::with_dummy_span(param.ident.name);
1688 forward_ty_ban_rib.bindings.swap_remove(i);
1689 forward_ty_ban_rib_const_param_ty.bindings.swap_remove(i);
1690 }
1691 GenericParamKind::Const { ref ty, span: _, ref default } => {
1692 if !param.bounds.is_empty() {
::core::panicking::panic("assertion failed: param.bounds.is_empty()")
};assert!(param.bounds.is_empty());
1694
1695 this.ribs[TypeNS].push(forward_ty_ban_rib_const_param_ty);
1696 this.ribs[ValueNS].push(forward_const_ban_rib_const_param_ty);
1697 if this.r.features.generic_const_parameter_types() {
1698 this.visit_ty(ty)
1699 } else {
1700 this.ribs[TypeNS].push(Rib::new(RibKind::ConstParamTy));
1701 this.ribs[ValueNS].push(Rib::new(RibKind::ConstParamTy));
1702 this.with_lifetime_rib(LifetimeRibKind::ConstParamTy, |this| {
1703 this.visit_ty(ty)
1704 });
1705 this.ribs[TypeNS].pop().unwrap();
1706 this.ribs[ValueNS].pop().unwrap();
1707 }
1708 forward_const_ban_rib_const_param_ty = this.ribs[ValueNS].pop().unwrap();
1709 forward_ty_ban_rib_const_param_ty = this.ribs[TypeNS].pop().unwrap();
1710
1711 if let Some(expr) = default {
1712 this.ribs[TypeNS].push(forward_ty_ban_rib);
1713 this.ribs[ValueNS].push(forward_const_ban_rib);
1714 this.resolve_anon_const(
1715 expr,
1716 AnonConstKind::ConstArg(IsRepeatExpr::No),
1717 );
1718 forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1719 forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1720 }
1721
1722 let i = &Ident::with_dummy_span(param.ident.name);
1724 forward_const_ban_rib.bindings.swap_remove(i);
1725 forward_const_ban_rib_const_param_ty.bindings.swap_remove(i);
1726 }
1727 }
1728 }
1729 })
1730 }
1731
1732 #[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(1732u32),
::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))]
1733 fn with_lifetime_rib<T>(
1734 &mut self,
1735 kind: LifetimeRibKind,
1736 work: impl FnOnce(&mut Self) -> T,
1737 ) -> T {
1738 self.lifetime_ribs.push(LifetimeRib::new(kind));
1739 let outer_elision_candidates = self.lifetime_elision_candidates.take();
1740 let ret = work(self);
1741 self.lifetime_elision_candidates = outer_elision_candidates;
1742 self.lifetime_ribs.pop();
1743 ret
1744 }
1745
1746 #[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(1746u32),
::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:1772",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1772u32),
::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:1817",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1817u32),
::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:1821",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1821u32),
::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))]
1747 fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1748 let ident = lifetime.ident;
1749
1750 if ident.name == kw::StaticLifetime {
1751 self.record_lifetime_use(
1752 lifetime.id,
1753 LifetimeRes::Static,
1754 LifetimeElisionCandidate::Ignore,
1755 );
1756 return;
1757 }
1758
1759 if ident.name == kw::UnderscoreLifetime {
1760 return self.resolve_anonymous_lifetime(lifetime, lifetime.id, false);
1761 }
1762
1763 let mut lifetime_rib_iter = self.lifetime_ribs.iter().rev();
1764 while let Some(rib) = lifetime_rib_iter.next() {
1765 let normalized_ident = ident.normalize_to_macros_2_0();
1766 if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1767 self.record_lifetime_use(lifetime.id, res, LifetimeElisionCandidate::Ignore);
1768
1769 if let LifetimeRes::Param { param, binder } = res {
1770 match self.lifetime_uses.entry(param) {
1771 Entry::Vacant(v) => {
1772 debug!("First use of {:?} at {:?}", res, ident.span);
1773 let use_set = self
1774 .lifetime_ribs
1775 .iter()
1776 .rev()
1777 .find_map(|rib| match rib.kind {
1778 LifetimeRibKind::Item
1781 | LifetimeRibKind::AnonymousReportError
1782 | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1783 LifetimeRibKind::AnonymousCreateParameter {
1786 binder: anon_binder,
1787 ..
1788 } => Some(if binder == anon_binder {
1789 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1790 } else {
1791 LifetimeUseSet::Many
1792 }),
1793 LifetimeRibKind::Elided { res: r, error_in_path } => {
1796 Some(if res == r && !error_in_path {
1797 LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1798 } else {
1799 LifetimeUseSet::Many
1800 })
1801 }
1802 LifetimeRibKind::Generics { .. }
1803 | LifetimeRibKind::ConstParamTy => None,
1804 LifetimeRibKind::ConcreteAnonConst(_) => {
1805 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
1806 }
1807
1808 LifetimeRibKind::ImplTrait => {
1809 if self.r.features.anonymous_lifetime_in_impl_trait() {
1810 None
1811 } else {
1812 Some(LifetimeUseSet::Many)
1813 }
1814 }
1815 })
1816 .unwrap_or(LifetimeUseSet::Many);
1817 debug!(?use_ctxt, ?use_set);
1818 v.insert(use_set);
1819 }
1820 Entry::Occupied(mut o) => {
1821 debug!("Many uses of {:?} at {:?}", res, ident.span);
1822 *o.get_mut() = LifetimeUseSet::Many;
1823 }
1824 }
1825 }
1826 return;
1827 }
1828
1829 match rib.kind {
1830 LifetimeRibKind::Item => break,
1831 LifetimeRibKind::ConstParamTy => {
1832 let guar = self.emit_non_static_lt_in_const_param_ty_error(lifetime);
1833 self.record_lifetime_err(lifetime.id, guar);
1834 return;
1835 }
1836 LifetimeRibKind::ConcreteAnonConst(cause) => {
1837 let guar = self.emit_forbidden_non_static_lifetime_error(cause, lifetime);
1838 self.record_lifetime_err(lifetime.id, guar);
1839 return;
1840 }
1841 LifetimeRibKind::AnonymousCreateParameter { .. }
1842 | LifetimeRibKind::Elided { .. }
1843 | LifetimeRibKind::Generics { .. }
1844 | LifetimeRibKind::ElisionFailure
1845 | LifetimeRibKind::AnonymousReportError
1846 | LifetimeRibKind::ImplTrait => {}
1847 }
1848 }
1849
1850 let normalized_ident = ident.normalize_to_macros_2_0();
1851 let outer_res = lifetime_rib_iter
1852 .find_map(|rib| rib.bindings.get_key_value(&normalized_ident).map(|(&outer, _)| outer));
1853
1854 let guar = self.emit_undeclared_lifetime_error(lifetime, outer_res);
1855 self.record_lifetime_err(lifetime.id, guar);
1856 }
1857
1858 #[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(1858u32),
::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:1878",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(1878u32),
::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))]
1859 fn resolve_anonymous_lifetime(
1860 &mut self,
1861 lifetime: &Lifetime,
1862 id_for_lint: NodeId,
1863 elided: bool,
1864 ) {
1865 debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1866
1867 let kind =
1868 if elided { MissingLifetimeKind::Ampersand } else { MissingLifetimeKind::Underscore };
1869 let missing_lifetime = MissingLifetime {
1870 id: lifetime.id,
1871 span: lifetime.ident.span,
1872 kind,
1873 count: 1,
1874 id_for_lint,
1875 };
1876 let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1877 for (i, rib) in self.lifetime_ribs.iter().enumerate().rev() {
1878 debug!(?rib.kind);
1879 match rib.kind {
1880 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1881 let res = self.create_fresh_lifetime(lifetime.ident, binder, kind);
1882 self.record_lifetime_use(lifetime.id, res, elision_candidate);
1883 return;
1884 }
1885 LifetimeRibKind::AnonymousReportError => {
1886 let guar = if elided {
1887 let suggestion = if self.diag_metadata.in_assoc_ty_binding {
1888 None
1894 } else {
1895 self.lifetime_ribs[i..].iter().rev().find_map(|rib| {
1896 if let LifetimeRibKind::Generics {
1900 span,
1901 kind:
1902 LifetimeBinderKind::PolyTrait
1903 | LifetimeBinderKind::WhereBound,
1904 ..
1905 } = rib.kind
1906 {
1907 Some(crate::diagnostics::ElidedAnonymousLifetimeReportErrorSuggestion {
1908 lo: span.shrink_to_lo(),
1909 hi: lifetime.ident.span.shrink_to_hi(),
1910 })
1911 } else {
1912 None
1913 }
1914 })
1915 };
1916 if !self.in_func_body
1919 && let Some((module, _)) = &self.current_trait_ref
1920 && let Some(ty) = &self.diag_metadata.current_self_type
1921 && Some(true) == self.diag_metadata.in_non_gat_assoc_type
1922 && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _, _) =
1923 module.kind
1924 {
1925 if def_id_matches_path(
1926 self.r.tcx,
1927 trait_id,
1928 &["core", "iter", "traits", "iterator", "Iterator"],
1929 ) {
1930 self.r.dcx().emit_err(
1931 crate::diagnostics::LendingIteratorReportError {
1932 lifetime: lifetime.ident.span,
1933 ty: ty.span,
1934 },
1935 )
1936 } else {
1937 let decl = if !trait_id.is_local()
1938 && let Some(assoc) = self.diag_metadata.current_impl_item
1939 && let AssocItemKind::Type(_) = assoc.kind
1940 && let assocs = self.r.tcx.associated_items(trait_id)
1941 && let Some(ident) = assoc.kind.ident()
1942 && let Some(assoc) = assocs.find_by_ident_and_kind(
1943 self.r.tcx,
1944 ident,
1945 AssocTag::Type,
1946 trait_id,
1947 ) {
1948 let mut decl: MultiSpan =
1949 self.r.tcx.def_span(assoc.def_id).into();
1950 decl.push_span_label(
1951 self.r.tcx.def_span(trait_id),
1952 String::new(),
1953 );
1954 decl
1955 } else {
1956 DUMMY_SP.into()
1957 };
1958 let mut err = self.r.dcx().create_err(
1959 crate::diagnostics::AnonymousLifetimeNonGatReportError {
1960 lifetime: lifetime.ident.span,
1961 decl,
1962 },
1963 );
1964 self.point_at_impl_lifetimes(&mut err, i, lifetime.ident.span);
1965 err.emit()
1966 }
1967 } else if self.diag_metadata.in_assoc_ty_binding {
1968 let mut err = self.r.dcx().create_err(
1973 crate::diagnostics::ElidedAnonymousLifetimeReportError {
1974 span: lifetime.ident.span,
1975 suggestion,
1976 },
1977 );
1978 self.suggest_introducing_lifetime_for_assoc_ty_binding(
1979 &mut err,
1980 lifetime.ident.span,
1981 );
1982 err.emit()
1983 } else {
1984 self.r.dcx().emit_err(
1985 crate::diagnostics::ElidedAnonymousLifetimeReportError {
1986 span: lifetime.ident.span,
1987 suggestion,
1988 },
1989 )
1990 }
1991 } else {
1992 self.r.dcx().emit_err(
1993 crate::diagnostics::ExplicitAnonymousLifetimeReportError {
1994 span: lifetime.ident.span,
1995 },
1996 )
1997 };
1998 self.record_lifetime_err(lifetime.id, guar);
1999 return;
2000 }
2001 LifetimeRibKind::Elided { res, .. } => {
2002 self.record_lifetime_use(lifetime.id, res, elision_candidate);
2003 return;
2004 }
2005 LifetimeRibKind::ElisionFailure => {
2006 self.diag_metadata
2007 .current_elision_failures
2008 .push((missing_lifetime, Either::Left(lifetime.id)));
2009 return;
2010 }
2011 LifetimeRibKind::Item => break,
2012 LifetimeRibKind::Generics { .. }
2013 | LifetimeRibKind::ConstParamTy
2014 | LifetimeRibKind::ImplTrait => {}
2015 LifetimeRibKind::ConcreteAnonConst(_) => {
2016 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
2018 }
2019 }
2020 }
2021 let guar = self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2022 self.record_lifetime_err(lifetime.id, guar);
2023 }
2024
2025 fn point_at_impl_lifetimes(&mut self, err: &mut Diag<'_>, i: usize, lifetime: Span) {
2026 let Some((rib, span)) =
2027 self.lifetime_ribs[..i].iter().rev().find_map(|rib| match rib.kind {
2028 LifetimeRibKind::Generics { span, kind: LifetimeBinderKind::ImplBlock, .. } => {
2029 Some((rib, span))
2030 }
2031 _ => None,
2032 })
2033 else {
2034 return;
2035 };
2036 if !rib.bindings.is_empty() {
2037 err.span_label(
2038 span,
2039 ::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!(
2040 "there {} named lifetime{} specified on the impl block you could use",
2041 if rib.bindings.len() == 1 { "is a" } else { "are" },
2042 pluralize!(rib.bindings.len()),
2043 ),
2044 );
2045 if rib.bindings.len() == 1 {
2046 err.span_suggestion_verbose(
2047 lifetime.shrink_to_hi(),
2048 "consider using the lifetime from the impl block",
2049 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ",
rib.bindings.keys().next().unwrap()))
})format!("{} ", rib.bindings.keys().next().unwrap()),
2050 Applicability::MaybeIncorrect,
2051 );
2052 }
2053 } else {
2054 struct AnonRefFinder;
2055 impl<'ast> Visitor<'ast> for AnonRefFinder {
2056 type Result = ControlFlow<Span>;
2057
2058 fn visit_ty(&mut self, ty: &'ast ast::Ty) -> Self::Result {
2059 if let ast::TyKind::Ref(None, mut_ty) = &ty.kind {
2060 return ControlFlow::Break(mut_ty.ty.span.shrink_to_lo());
2061 }
2062 visit::walk_ty(self, ty)
2063 }
2064
2065 fn visit_lifetime(
2066 &mut self,
2067 lt: &'ast ast::Lifetime,
2068 _cx: visit::LifetimeCtxt,
2069 ) -> Self::Result {
2070 if lt.ident.name == kw::UnderscoreLifetime {
2071 return ControlFlow::Break(lt.ident.span);
2072 }
2073 visit::walk_lifetime(self, lt)
2074 }
2075 }
2076
2077 if let Some(ty) = &self.diag_metadata.current_self_type
2078 && let ControlFlow::Break(sp) = AnonRefFinder.visit_ty(ty)
2079 {
2080 err.multipart_suggestion(
2081 "add a lifetime to the impl block and use it in the self type and associated \
2082 type",
2083 ::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![
2084 (span, "<'a>".to_string()),
2085 (sp, "'a ".to_string()),
2086 (lifetime.shrink_to_hi(), "'a ".to_string()),
2087 ],
2088 Applicability::MaybeIncorrect,
2089 );
2090 } else if let Some(item) = &self.diag_metadata.current_item
2091 && let ItemKind::Impl(impl_) = &item.kind
2092 && let Some(of_trait) = &impl_.of_trait
2093 && let ControlFlow::Break(sp) = AnonRefFinder.visit_trait_ref(&of_trait.trait_ref)
2094 {
2095 err.multipart_suggestion(
2096 "add a lifetime to the impl block and use it in the trait and associated type",
2097 ::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![
2098 (span, "<'a>".to_string()),
2099 (sp, "'a".to_string()),
2100 (lifetime.shrink_to_hi(), "'a ".to_string()),
2101 ],
2102 Applicability::MaybeIncorrect,
2103 );
2104 } else {
2105 err.span_label(
2106 span,
2107 "you could add a lifetime on the impl block, if the trait or the self type \
2108 could have one",
2109 );
2110 }
2111 }
2112 }
2113
2114 #[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(2114u32),
::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))]
2115 fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
2116 let id = self.r.next_node_id();
2117 let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
2118
2119 self.record_lifetime_use(
2120 anchor_id,
2121 LifetimeRes::ElidedAnchor { start: id, end: id + 1 },
2122 LifetimeElisionCandidate::Ignore,
2123 );
2124 self.resolve_anonymous_lifetime(<, anchor_id, true);
2125 }
2126
2127 #[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(2127u32),
::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:2135",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2135u32),
::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))]
2128 fn create_fresh_lifetime(
2129 &mut self,
2130 ident: Ident,
2131 binder: NodeId,
2132 kind: MissingLifetimeKind,
2133 ) -> LifetimeRes {
2134 debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
2135 debug!(?ident.span);
2136
2137 let param = self.r.next_node_id();
2139 let res = LifetimeRes::Fresh { param, kind };
2140 self.record_lifetime_def(param, res);
2141
2142 self.r
2144 .current_owner
2145 .extra_lifetime_params_map
2146 .entry(binder)
2147 .or_insert_with(Vec::new)
2148 .push((ident, param, kind));
2149 res
2150 }
2151
2152 #[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(2152u32),
::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))]
2153 fn resolve_elided_lifetimes_in_path(
2154 &mut self,
2155 partial_res: PartialRes,
2156 path: &[Segment],
2157 source: PathSource<'_, 'ast, 'ra>,
2158 path_span: Span,
2159 ) {
2160 let proj_start = path.len() - partial_res.unresolved_segments();
2161 for (i, segment) in path.iter().enumerate() {
2162 if segment.has_lifetime_args {
2163 continue;
2164 }
2165 let Some(segment_id) = segment.id else {
2166 continue;
2167 };
2168
2169 let type_def_id = match partial_res.base_res() {
2172 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => {
2173 self.r.tcx.parent(def_id)
2174 }
2175 Res::Def(DefKind::Variant, def_id)
2176 if i + 2 == proj_start && segment.has_generic_args =>
2177 {
2178 self.r.tcx.parent(def_id)
2179 }
2180 Res::Def(DefKind::Variant, def_id)
2181 if i + 1 == proj_start
2182 && !i.checked_sub(1).is_some_and(|i| path[i].has_generic_args) =>
2183 {
2184 self.r.tcx.parent(def_id)
2185 }
2186 Res::Def(DefKind::Struct, def_id)
2187 | Res::Def(DefKind::Union, def_id)
2188 | Res::Def(DefKind::Enum, def_id)
2189 | Res::Def(DefKind::TyAlias, def_id)
2190 | Res::Def(DefKind::Trait, def_id)
2191 if i + 1 == proj_start =>
2192 {
2193 def_id
2194 }
2195 _ => continue,
2196 };
2197
2198 let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
2199 if expected_lifetimes == 0 {
2200 continue;
2201 }
2202
2203 let node_ids = self.r.next_node_ids(expected_lifetimes);
2204 self.record_lifetime_use(
2205 segment_id,
2206 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
2207 LifetimeElisionCandidate::Ignore,
2208 );
2209
2210 let inferred = match source {
2211 PathSource::Trait(..)
2212 | PathSource::TraitItem(..)
2213 | PathSource::Type
2214 | PathSource::PreciseCapturingArg(..)
2215 | PathSource::ReturnTypeNotation
2216 | PathSource::Macro
2217 | PathSource::Module => false,
2218 PathSource::Expr(..)
2219 | PathSource::Pat
2220 | PathSource::Struct(_)
2221 | PathSource::TupleStruct(..)
2222 | PathSource::DefineOpaques
2223 | PathSource::Delegation
2224 | PathSource::ExternItemImpl => true,
2225 };
2226 if inferred {
2227 for id in node_ids {
2230 self.record_lifetime_use(
2231 id,
2232 LifetimeRes::Infer,
2233 LifetimeElisionCandidate::Ignore,
2234 );
2235 }
2236 continue;
2237 }
2238
2239 let elided_lifetime_span = if segment.has_generic_args {
2240 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
2242 } else {
2243 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
2247 };
2248 let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
2249
2250 let kind = if segment.has_generic_args {
2251 MissingLifetimeKind::Comma
2252 } else {
2253 MissingLifetimeKind::Brackets
2254 };
2255 let missing_lifetime = MissingLifetime {
2256 id: node_ids.start,
2257 id_for_lint: segment_id,
2258 span: elided_lifetime_span,
2259 kind,
2260 count: expected_lifetimes,
2261 };
2262 let mut should_lint = true;
2263 for rib in self.lifetime_ribs.iter().rev() {
2264 match rib.kind {
2265 LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. }
2272 | LifetimeRibKind::Elided { error_in_path: true, .. } => {
2273 let sess = self.r.tcx.sess;
2274 let subdiag = elided_lifetime_in_path_suggestion(
2275 sess.source_map(),
2276 expected_lifetimes,
2277 path_span,
2278 !segment.has_generic_args,
2279 elided_lifetime_span,
2280 );
2281 let guar = self.r.dcx().emit_err(
2282 crate::diagnostics::ImplicitElidedLifetimeNotAllowedHere {
2283 span: path_span,
2284 subdiag,
2285 },
2286 );
2287 should_lint = false;
2288
2289 for id in node_ids {
2290 self.record_lifetime_err(id, guar);
2291 }
2292 break;
2293 }
2294 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
2296 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2298 for id in node_ids {
2299 let res = self.create_fresh_lifetime(ident, binder, kind);
2300 self.record_lifetime_use(
2301 id,
2302 res,
2303 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2304 );
2305 }
2306 break;
2307 }
2308 LifetimeRibKind::Elided { res, error_in_path: false } => {
2309 let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
2310 for id in node_ids {
2311 self.record_lifetime_use(
2312 id,
2313 res,
2314 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
2315 );
2316 }
2317 break;
2318 }
2319 LifetimeRibKind::ElisionFailure => {
2320 self.diag_metadata
2321 .current_elision_failures
2322 .push((missing_lifetime, Either::Right(node_ids)));
2323 break;
2324 }
2325 LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
2330 let guar =
2331 self.report_missing_lifetime_specifiers([&missing_lifetime], None);
2332 for id in node_ids {
2333 self.record_lifetime_err(id, guar);
2334 }
2335 break;
2336 }
2337 LifetimeRibKind::Generics { .. }
2338 | LifetimeRibKind::ConstParamTy
2339 | LifetimeRibKind::ImplTrait => {}
2340 LifetimeRibKind::ConcreteAnonConst(_) => {
2341 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
2343 }
2344 }
2345 }
2346
2347 if should_lint {
2348 let include_angle_bracket = !segment.has_generic_args;
2349 self.r.lint_buffer.dyn_buffer_lint_any(
2350 lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
2351 segment_id,
2352 elided_lifetime_span,
2353 move |dcx, level, sess| {
2354 let source_map = sess
2355 .downcast_ref::<rustc_session::Session>()
2356 .expect("expected a `Session`")
2357 .source_map();
2358 crate::diagnostics::ElidedLifetimesInPaths {
2359 subdiag: elided_lifetime_in_path_suggestion(
2360 source_map,
2361 expected_lifetimes,
2362 path_span,
2363 include_angle_bracket,
2364 elided_lifetime_span,
2365 ),
2366 }
2367 .into_diag(dcx, level)
2368 },
2369 );
2370 }
2371 }
2372 }
2373
2374 #[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(2375u32),
::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))]
2376 fn record_lifetime_use(
2377 &mut self,
2378 id: NodeId,
2379 res: LifetimeRes,
2380 candidate: LifetimeElisionCandidate,
2381 ) {
2382 self.record_lifetime_def(id, res);
2383
2384 match res {
2385 LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static { .. } => {
2386 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2387 candidates.push((res, candidate));
2388 }
2389 }
2390 LifetimeRes::Infer | LifetimeRes::Error(..) | LifetimeRes::ElidedAnchor { .. } => {}
2391 }
2392 }
2393
2394 #[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(2396u32),
::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))]
2397 fn record_lifetime_err(&mut self, id: NodeId, guar: ErrorGuaranteed) {
2398 self.record_lifetime_def(id, LifetimeRes::Error(guar));
2399 }
2400
2401 #[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(2402u32),
::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))]
2403 fn record_lifetime_def(&mut self, id: NodeId, res: LifetimeRes) {
2404 if let Some(prev_res) = self.r.current_owner.lifetimes_res_map.insert(id, res) {
2405 panic!(
2406 "lifetime parameter {id:?} resolved multiple times ({prev_res:?} before, {res:?} now)"
2407 )
2408 }
2409 }
2410
2411 #[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(2412u32),
::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:2428",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2428u32),
::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))]
2413 fn resolve_fn_signature(
2414 &mut self,
2415 fn_id: NodeId,
2416 has_self: bool,
2417 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2418 output_ty: &'ast FnRetTy,
2419 report_elided_lifetimes_in_path: bool,
2420 ) {
2421 let rib = LifetimeRibKind::AnonymousCreateParameter {
2422 binder: fn_id,
2423 report_in_path: report_elided_lifetimes_in_path,
2424 };
2425 self.with_lifetime_rib(rib, |this| {
2426 let elision_lifetime = this.resolve_fn_params(has_self, inputs);
2428 debug!(?elision_lifetime);
2429
2430 let outer_failures = take(&mut this.diag_metadata.current_elision_failures);
2431 let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
2432 if fn_id == this.r.current_owner.id {
2433 this.r.current_owner.lifetime_elision_allowed = true;
2434 }
2435 LifetimeRibKind::elided(*res)
2436 } else {
2437 LifetimeRibKind::ElisionFailure
2438 };
2439 this.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, output_ty));
2440 let elision_failures =
2441 replace(&mut this.diag_metadata.current_elision_failures, outer_failures);
2442 if !elision_failures.is_empty() {
2443 let Err(failure_info) = elision_lifetime else { bug!() };
2444 let guar = this.report_missing_lifetime_specifiers(
2445 elision_failures.iter().map(|(missing_lifetime, ..)| missing_lifetime),
2446 Some(failure_info),
2447 );
2448 let mut record_res = |lifetime| this.record_lifetime_err(lifetime, guar);
2449 for (_, nodes) in elision_failures {
2450 match nodes {
2451 Either::Left(node_id) => record_res(node_id),
2452 Either::Right(node_ids) => {
2453 for lifetime in node_ids {
2454 record_res(lifetime)
2455 }
2456 }
2457 }
2458 }
2459 }
2460 });
2461 }
2462
2463 fn resolve_fn_params(
2467 &mut self,
2468 has_self: bool,
2469 inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
2470 ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
2471 enum Elision {
2472 None,
2474 Self_(LifetimeRes),
2476 Param(LifetimeRes),
2478 Err,
2480 }
2481
2482 let outer_candidates = self.lifetime_elision_candidates.take();
2484
2485 let mut elision_lifetime = Elision::None;
2487 let mut parameter_info = Vec::new();
2489 let mut all_candidates = Vec::new();
2490
2491 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())];
2493 for (pat, _) in inputs.clone() {
2494 {
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:2494",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2494u32),
::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:?}");
2495 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
2496 if let Some(pat) = pat {
2497 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2498 }
2499 });
2500 }
2501 self.apply_pattern_bindings(bindings);
2502
2503 for (index, (pat, ty)) in inputs.enumerate() {
2504 {
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:2504",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2504u32),
::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:?}");
2505 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);
2507 self.lifetime_elision_candidates = Some(Default::default());
2508 self.visit_ty(ty);
2509 let local_candidates = self.lifetime_elision_candidates.take();
2510
2511 if let Some(candidates) = local_candidates {
2512 let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect();
2513 let lifetime_count = distinct.len();
2514 if lifetime_count != 0 {
2515 parameter_info.push(ElisionFnParameter {
2516 index,
2517 ident: if let Some(pat) = pat
2518 && let PatKind::Ident(_, ident, _) = pat.kind
2519 {
2520 Some(ident)
2521 } else {
2522 None
2523 },
2524 lifetime_count,
2525 span: ty.span,
2526 });
2527 all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| {
2528 match candidate {
2529 LifetimeElisionCandidate::Ignore => None,
2530 LifetimeElisionCandidate::Missing(missing) => Some(missing),
2531 }
2532 }));
2533 }
2534 if !distinct.is_empty() {
2535 match elision_lifetime {
2536 Elision::None => {
2538 if let Some(res) = distinct.get_only() {
2539 elision_lifetime = Elision::Param(*res)
2541 } else {
2542 elision_lifetime = Elision::Err;
2544 }
2545 }
2546 Elision::Param(_) => elision_lifetime = Elision::Err,
2548 Elision::Self_(_) | Elision::Err => {}
2550 }
2551 }
2552 }
2553
2554 if index == 0 && has_self {
2556 let self_lifetime = self.find_lifetime_for_self(ty);
2557 elision_lifetime = match self_lifetime {
2558 Set1::One(lifetime) => Elision::Self_(lifetime),
2560 Set1::Many => Elision::Err,
2565 Set1::Empty => Elision::None,
2568 }
2569 }
2570 {
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:2570",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2570u32),
::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");
2571 }
2572
2573 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);
2575 self.lifetime_elision_candidates = outer_candidates;
2576
2577 if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime {
2578 return Ok(res);
2579 }
2580
2581 Err((all_candidates, parameter_info))
2583 }
2584
2585 fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
2587 struct FindReferenceVisitor<'a, 'ra, 'tcx> {
2591 r: &'a Resolver<'ra, 'tcx>,
2592 impl_self: Option<Res>,
2593 lifetime: Set1<LifetimeRes>,
2594 }
2595
2596 impl<'ra> Visitor<'ra> for FindReferenceVisitor<'_, '_, '_> {
2597 fn visit_ty(&mut self, ty: &'ra Ty) {
2598 {
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:2598",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2598u32),
::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);
2599 if let TyKind::Ref(lt, _) | TyKind::PinnedRef(lt, _) = ty.kind {
2600 let mut visitor =
2602 SelfVisitor { r: self.r, impl_self: self.impl_self, self_found: false };
2603 visitor.visit_ty(ty);
2604 {
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:2604",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2604u32),
::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);
2605 if visitor.self_found {
2606 let lt_id = if let Some(lt) = lt {
2607 lt.id
2608 } else {
2609 let res = self.r.current_owner.lifetimes_res_map[&ty.id];
2610 let LifetimeRes::ElidedAnchor { start, .. } = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2611 start
2612 };
2613 let lt_res = self.r.current_owner.lifetimes_res_map[<_id];
2614 {
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:2614",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2614u32),
::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);
2615 self.lifetime.insert(lt_res);
2616 }
2617 }
2618 visit::walk_ty(self, ty)
2619 }
2620
2621 fn visit_expr(&mut self, _: &'ra Expr) {}
2624 }
2625
2626 struct SelfVisitor<'a, 'ra, 'tcx> {
2629 r: &'a Resolver<'ra, 'tcx>,
2630 impl_self: Option<Res>,
2631 self_found: bool,
2632 }
2633
2634 impl SelfVisitor<'_, '_, '_> {
2635 fn is_self_ty(&self, ty: &Ty) -> bool {
2637 match ty.kind {
2638 TyKind::ImplicitSelf => true,
2639 TyKind::Path(None, _) => {
2640 let path_res = self.r.partial_res_map[&ty.id].full_res();
2641 if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
2642 return true;
2643 }
2644 self.impl_self.is_some() && path_res == self.impl_self
2645 }
2646 _ => false,
2647 }
2648 }
2649 }
2650
2651 impl<'ra> Visitor<'ra> for SelfVisitor<'_, '_, '_> {
2652 fn visit_ty(&mut self, ty: &'ra Ty) {
2653 {
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:2653",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2653u32),
::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);
2654 if self.is_self_ty(ty) {
2655 {
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:2655",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2655u32),
::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");
2656 self.self_found = true;
2657 }
2658 visit::walk_ty(self, ty)
2659 }
2660
2661 fn visit_expr(&mut self, _: &'ra Expr) {}
2664 }
2665
2666 let impl_self = self
2667 .diag_metadata
2668 .current_self_type
2669 .and_then(|ty| {
2670 if let TyKind::Path(None, _) = ty.kind {
2671 self.r.partial_res_map.get(&ty.id)
2672 } else {
2673 None
2674 }
2675 })
2676 .and_then(|res| res.full_res())
2677 .filter(|res| {
2678 #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _) |
Res::PrimTy(_) => true,
_ => false,
}matches!(
2682 res,
2683 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
2684 )
2685 });
2686 let mut visitor = FindReferenceVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
2687 visitor.visit_ty(ty);
2688 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:2688",
"rustc_resolve::late", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2688u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindReferenceVisitor found={0:?}",
visitor.lifetime) as &dyn ::tracing::field::Value))])
});
} else { ; }
};trace!("FindReferenceVisitor found={:?}", visitor.lifetime);
2689 visitor.lifetime
2690 }
2691
2692 fn resolve_label(&self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'ra>> {
2695 let mut suggestion = None;
2696
2697 for i in (0..self.label_ribs.len()).rev() {
2698 let rib = &self.label_ribs[i];
2699
2700 if let RibKind::MacroDefinition(def) = rib.kind
2701 && def == self.r.macro_def(label.span.ctxt())
2704 {
2705 label.span.remove_mark();
2706 }
2707
2708 let ident = label.normalize_to_macro_rules();
2709 if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2710 let definition_span = ident.span;
2711 return if self.is_label_valid_from_rib(i) {
2712 Ok((*id, definition_span))
2713 } else {
2714 Err(ResolutionError::UnreachableLabel {
2715 name: label.name,
2716 definition_span,
2717 suggestion,
2718 })
2719 };
2720 }
2721
2722 suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2725 }
2726
2727 Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2728 }
2729
2730 fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2732 let ribs = &self.label_ribs[rib_index + 1..];
2733 ribs.iter().all(|rib| !rib.kind.is_label_barrier())
2734 }
2735
2736 fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2737 {
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:2737",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2737u32),
::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");
2738 let kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2739 self.with_current_self_item(item, |this| {
2740 this.with_generic_param_rib(
2741 &generics.params,
2742 RibKind::Item(HasGenericParams::Yes(generics.span), kind),
2743 item.id,
2744 LifetimeBinderKind::Item,
2745 generics.span,
2746 |this| {
2747 let item_def_id = this.r.current_owner.def_id.to_def_id();
2748 this.with_self_rib(
2749 Res::SelfTyAlias { alias_to: item_def_id, is_trait_impl: false },
2750 |this| {
2751 visit::walk_item(this, item);
2752 },
2753 );
2754 },
2755 );
2756 });
2757 }
2758
2759 fn future_proof_import(&mut self, use_tree: &UseTree) {
2760 if let [segment, rest @ ..] = use_tree.prefix.segments.as_slice() {
2761 let ident = segment.ident;
2762 if ident.is_path_segment_keyword() || ident.span.is_rust_2015() {
2763 return;
2764 }
2765
2766 let nss = match use_tree.kind {
2767 UseTreeKind::Simple(..) if rest.is_empty() => &[TypeNS, ValueNS][..],
2768 _ => &[TypeNS],
2769 };
2770 let report_error = |this: &Self, ns| {
2771 if this.should_report_errs() {
2772 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2773 this.r.dcx().emit_err(crate::diagnostics::ImportsCannotReferTo {
2774 span: ident.span,
2775 what,
2776 });
2777 }
2778 };
2779
2780 for &ns in nss {
2781 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2782 Some(LateDecl::RibDef(..)) => {
2783 report_error(self, ns);
2784 }
2785 Some(LateDecl::Decl(binding)) => {
2786 if let Some(LateDecl::RibDef(..)) =
2787 self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2788 {
2789 report_error(self, ns);
2790 }
2791 }
2792 None => {}
2793 }
2794 }
2795 } else if let UseTreeKind::Nested { items, .. } = &use_tree.kind {
2796 for (use_tree, _) in items {
2797 self.future_proof_import(use_tree);
2798 }
2799 }
2800 }
2801
2802 fn resolve_item(&mut self, item: &'ast Item) {
2803 let mod_inner_docs =
2804 #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Mod(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
2805 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(..)) {
2806 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2807 }
2808
2809 {
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:2809",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(2809u32),
::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);
2810
2811 let def_kind = self.r.tcx.def_kind(self.r.current_owner.def_id);
2812 match &item.kind {
2813 ItemKind::TyAlias(TyAlias { generics, .. }) => {
2814 self.with_generic_param_rib(
2815 &generics.params,
2816 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2817 item.id,
2818 LifetimeBinderKind::Item,
2819 generics.span,
2820 |this| visit::walk_item(this, item),
2821 );
2822 }
2823
2824 ItemKind::Fn(Fn { generics, define_opaque, .. }) => {
2825 self.with_generic_param_rib(
2826 &generics.params,
2827 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2828 item.id,
2829 LifetimeBinderKind::Function,
2830 generics.span,
2831 |this| visit::walk_item(this, item),
2832 );
2833 self.resolve_define_opaques(define_opaque);
2834 }
2835
2836 ItemKind::Enum(_, generics, _)
2837 | ItemKind::Struct(_, generics, _)
2838 | ItemKind::Union(_, generics, _) => {
2839 self.resolve_adt(item, generics);
2840 }
2841
2842 ItemKind::Impl(Impl { generics, of_trait, self_ty, items: impl_items, .. }) => {
2843 self.diag_metadata.current_impl_items = Some(impl_items);
2844 self.resolve_implementation(
2845 &item.attrs,
2846 generics,
2847 of_trait.as_deref(),
2848 self_ty,
2849 item.id,
2850 impl_items,
2851 );
2852 self.diag_metadata.current_impl_items = None;
2853 }
2854
2855 ItemKind::Trait(Trait { generics, bounds, items, impl_restriction, .. }) => {
2856 self.resolve_restriction_path(&impl_restriction.kind);
2858
2859 self.with_generic_param_rib(
2861 &generics.params,
2862 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2863 item.id,
2864 LifetimeBinderKind::Item,
2865 generics.span,
2866 |this| {
2867 let local_def_id = this.r.current_owner.def_id.to_def_id();
2868 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2869 this.visit_generics(generics);
2870 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);
2871 this.resolve_trait_items(items);
2872 });
2873 },
2874 );
2875 }
2876
2877 ItemKind::TraitAlias(TraitAlias { generics, bounds, .. }) => {
2878 self.with_generic_param_rib(
2880 &generics.params,
2881 RibKind::Item(HasGenericParams::Yes(generics.span), def_kind),
2882 item.id,
2883 LifetimeBinderKind::Item,
2884 generics.span,
2885 |this| {
2886 let local_def_id = this.r.current_owner.def_id.to_def_id();
2887 this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2888 this.visit_generics(generics);
2889 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);
2890 });
2891 },
2892 );
2893 }
2894
2895 ItemKind::Mod(..) => {
2896 let module = self.r.expect_module(self.r.current_owner.def_id.to_def_id());
2897 let orig_module = replace(&mut self.parent_scope.module, module);
2898 self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
2899 this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
2900 if mod_inner_docs {
2901 this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
2902 }
2903 let old_macro_rules = this.parent_scope.macro_rules;
2904 visit::walk_item(this, item);
2905 if item.attrs.iter().all(|attr| {
2908 !attr.has_name(sym::macro_use) && !attr.has_name(sym::macro_escape)
2909 }) {
2910 this.parent_scope.macro_rules = old_macro_rules;
2911 }
2912 })
2913 });
2914 self.parent_scope.module = orig_module;
2915 }
2916
2917 ItemKind::Static(ast::StaticItem {
2918 ident, ty, expr, define_opaque, eii_impl, ..
2919 }) => {
2920 self.with_static_rib(def_kind, |this| {
2921 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Static), |this| {
2922 this.visit_ty(ty);
2923 });
2924 if let Some(expr) = expr {
2925 this.resolve_static_body(expr, Some((*ident, ConstantItemKind::Static)));
2928 }
2929 });
2930 self.resolve_define_opaques(define_opaque);
2931 self.resolve_eii(eii_impl.as_deref());
2932 }
2933
2934 ItemKind::Const(ast::ConstItem {
2935 ident,
2936 generics,
2937 ty,
2938 body,
2939 kind,
2940 define_opaque,
2941 defaultness: _,
2942 }) => {
2943 self.with_generic_param_rib(
2944 &generics.params,
2945 RibKind::Item(
2946 if self.r.features.generic_const_items() {
2947 HasGenericParams::Yes(generics.span)
2948 } else {
2949 HasGenericParams::No
2950 },
2951 def_kind,
2952 ),
2953 item.id,
2954 LifetimeBinderKind::ConstItem,
2955 generics.span,
2956 |this| {
2957 this.visit_generics(generics);
2958
2959 this.with_lifetime_rib(
2960 LifetimeRibKind::elided(LifetimeRes::Static),
2961 |this: &mut LateResolutionVisitor<'a, 'ast, 'ra, 'tcx>| {
2962 if *kind == ast::ConstItemKind::TypeConst
2963 && !this.r.features.generic_const_parameter_types()
2964 {
2965 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
2966 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
2967 this.with_lifetime_rib(
2968 LifetimeRibKind::ConstParamTy,
2969 |this| this.visit_ty(ty),
2970 )
2971 })
2972 });
2973 } else {
2974 this.visit_ty(ty);
2975 }
2976 },
2977 );
2978
2979 this.resolve_const_item_rhs(body, Some((*ident, ConstantItemKind::Const)));
2980 },
2981 );
2982 self.resolve_define_opaques(define_opaque);
2983 }
2984 ItemKind::ConstBlock(ConstBlockItem { id: _, span: _, block }) => self
2985 .with_generic_param_rib(
2986 &[],
2987 RibKind::Item(HasGenericParams::No, def_kind),
2988 item.id,
2989 LifetimeBinderKind::ConstItem,
2990 DUMMY_SP,
2991 |this| {
2992 this.with_lifetime_rib(
2993 LifetimeRibKind::elided(LifetimeRes::Infer),
2994 |this| {
2995 this.with_constant_rib(
2996 IsRepeatExpr::No,
2997 ConstantHasGenerics::Yes,
2998 Some((ConstBlockItem::IDENT, ConstantItemKind::Const)),
2999 |this| this.resolve_labeled_block(None, block.id, block),
3000 )
3001 },
3002 );
3003 },
3004 ),
3005
3006 ItemKind::Use(use_tree) => {
3007 let maybe_exported = match use_tree.kind {
3008 UseTreeKind::Simple(_) | UseTreeKind::Glob(_) => MaybeExported::Ok(item.id),
3009 UseTreeKind::Nested { .. } => MaybeExported::NestedUse(&item.vis),
3010 };
3011 self.resolve_doc_links(&item.attrs, maybe_exported);
3012
3013 self.future_proof_import(use_tree);
3014 }
3015
3016 ItemKind::MacroDef(_, macro_def) => {
3017 if macro_def.macro_rules {
3020 let def_id = self.r.current_owner.def_id;
3021 self.parent_scope.macro_rules = self.r.macro_rules_scopes[&def_id];
3022 }
3023
3024 if let Some(EiiDecl { foreign_item: extern_item_path, impl_unsafe: _ }) =
3025 ¯o_def.eii_declaration
3026 {
3027 self.smart_resolve_path(
3028 item.id,
3029 &None,
3030 extern_item_path,
3031 PathSource::ExternItemImpl,
3032 );
3033 }
3034 }
3035
3036 ItemKind::ForeignMod(_) | ItemKind::GlobalAsm(_) => {
3037 visit::walk_item(self, item);
3038 }
3039
3040 ItemKind::Delegation(delegation) => {
3041 let span = delegation.path.segments.last().unwrap().ident.span;
3042 self.with_generic_param_rib(
3043 &[],
3044 RibKind::Item(HasGenericParams::Yes(span), def_kind),
3045 item.id,
3046 LifetimeBinderKind::Function,
3047 span,
3048 |this| this.resolve_delegation(delegation, item.id, false),
3049 );
3050 }
3051
3052 ItemKind::ExternCrate(..) => {}
3053
3054 ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
3055 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3056 }
3057 }
3058 }
3059
3060 fn with_generic_param_rib<F>(
3061 &mut self,
3062 params: &[GenericParam],
3063 kind: RibKind<'ra>,
3064 binder: NodeId,
3065 generics_kind: LifetimeBinderKind,
3066 generics_span: Span,
3067 f: F,
3068 ) where
3069 F: FnOnce(&mut Self),
3070 {
3071 {
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:3071",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3071u32),
::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");
3072 let lifetime_kind =
3073 LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind };
3074
3075 let mut function_type_rib = Rib::new(kind);
3076 let mut function_value_rib = Rib::new(kind);
3077 let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
3078
3079 if !params.is_empty() {
3081 let mut seen_bindings = FxHashMap::default();
3082 let mut seen_lifetimes = FxHashSet::default();
3084
3085 for ns in [ValueNS, TypeNS] {
3087 for parent_rib in self.ribs[ns].iter().rev() {
3088 if #[allow(non_exhaustive_omitted_patterns)] match parent_rib.kind {
RibKind::Module(..) | RibKind::Block(..) => true,
_ => false,
}matches!(parent_rib.kind, RibKind::Module(..) | RibKind::Block(..)) {
3091 break;
3092 }
3093
3094 seen_bindings
3095 .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span)));
3096 }
3097 }
3098
3099 for rib in self.lifetime_ribs.iter().rev() {
3101 seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
3102 if let LifetimeRibKind::Item = rib.kind {
3103 break;
3104 }
3105 }
3106
3107 for param in params {
3108 let ident = param.ident.normalize_to_macros_2_0();
3109 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/late.rs:3109",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3109u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("with_generic_param_rib: {0}",
param.id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("with_generic_param_rib: {}", param.id);
3110
3111 if let GenericParamKind::Lifetime = param.kind
3112 && let Some(&original) = seen_lifetimes.get(&ident)
3113 {
3114 let guar = diagnostics::signal_lifetime_shadowing(
3115 self.r.tcx.sess,
3116 original,
3117 param.ident,
3118 );
3119 self.record_lifetime_err(param.id, guar);
3121 continue;
3122 }
3123
3124 match seen_bindings.entry(ident) {
3125 Entry::Occupied(entry) => {
3126 let span = *entry.get();
3127 let err = ResolutionError::NameAlreadyUsedInParameterList(ident, span);
3128 let guar = self.r.report_error(param.ident.span, err);
3129 let rib = match param.kind {
3130 GenericParamKind::Lifetime => {
3131 self.record_lifetime_err(param.id, guar);
3133 continue;
3134 }
3135 GenericParamKind::Type { .. } => &mut function_type_rib,
3136 GenericParamKind::Const { .. } => &mut function_value_rib,
3137 };
3138
3139 self.r.record_partial_res(param.id, PartialRes::new(Res::Err));
3141 rib.bindings.insert(ident, Res::Err);
3142 continue;
3143 }
3144 Entry::Vacant(entry) => {
3145 entry.insert(param.ident.span);
3146 }
3147 }
3148
3149 if param.ident.name == kw::UnderscoreLifetime {
3150 let is_raw_underscore_lifetime = self
3153 .r
3154 .tcx
3155 .sess
3156 .psess
3157 .raw_identifier_spans
3158 .iter()
3159 .any(|span| span == param.span());
3160
3161 let guar = self
3162 .r
3163 .dcx()
3164 .create_err(crate::diagnostics::UnderscoreLifetimeIsReserved {
3165 span: param.ident.span,
3166 })
3167 .emit_unless_delay(is_raw_underscore_lifetime);
3168 self.record_lifetime_err(param.id, guar);
3170 continue;
3171 }
3172
3173 if param.ident.name == kw::StaticLifetime {
3174 let guar =
3175 self.r.dcx().emit_err(crate::diagnostics::StaticLifetimeIsReserved {
3176 span: param.ident.span,
3177 lifetime: param.ident,
3178 });
3179 self.record_lifetime_err(param.id, guar);
3181 continue;
3182 }
3183
3184 let def_id = self.r.local_def_id(param.id);
3185
3186 let (rib, def_kind) = match param.kind {
3188 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
3189 GenericParamKind::Const { .. } => {
3190 (&mut function_value_rib, DefKind::ConstParam)
3191 }
3192 GenericParamKind::Lifetime => {
3193 let res = LifetimeRes::Param { param: def_id, binder };
3194 self.record_lifetime_def(param.id, res);
3195 function_lifetime_rib.bindings.insert(ident, (param.id, res));
3196 continue;
3197 }
3198 };
3199
3200 let res = match kind {
3201 RibKind::Item(..) | RibKind::AssocItem => {
3202 Res::Def(def_kind, def_id.to_def_id())
3203 }
3204 RibKind::Normal => {
3205 if self.r.features.non_lifetime_binders()
3208 && #[allow(non_exhaustive_omitted_patterns)] match param.kind {
GenericParamKind::Type { .. } => true,
_ => false,
}matches!(param.kind, GenericParamKind::Type { .. })
3209 {
3210 Res::Def(def_kind, def_id.to_def_id())
3211 } else {
3212 Res::Err
3213 }
3214 }
3215 _ => ::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),
3216 };
3217 self.r.record_partial_res(param.id, PartialRes::new(res));
3218 rib.bindings.insert(ident, res);
3219 }
3220 }
3221
3222 self.lifetime_ribs.push(function_lifetime_rib);
3223 self.ribs[ValueNS].push(function_value_rib);
3224 self.ribs[TypeNS].push(function_type_rib);
3225
3226 f(self);
3227
3228 self.ribs[TypeNS].pop();
3229 self.ribs[ValueNS].pop();
3230 let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
3231
3232 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
3234 for (_, res) in function_lifetime_rib.bindings.values() {
3235 candidates.retain(|(r, _)| r != res);
3236 }
3237 }
3238
3239 if let LifetimeBinderKind::FnPtrType
3240 | LifetimeBinderKind::WhereBound
3241 | LifetimeBinderKind::Function
3242 | LifetimeBinderKind::ImplBlock = generics_kind
3243 {
3244 self.maybe_report_lifetime_uses(generics_span, params)
3245 }
3246 }
3247
3248 fn with_label_rib(&mut self, kind: RibKind<'ra>, f: impl FnOnce(&mut Self)) {
3249 self.label_ribs.push(Rib::new(kind));
3250 f(self);
3251 self.label_ribs.pop();
3252 }
3253
3254 fn with_static_rib(&mut self, def_kind: DefKind, f: impl FnOnce(&mut Self)) {
3255 let kind = RibKind::Item(HasGenericParams::No, def_kind);
3256 self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
3257 }
3258
3259 #[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(3267u32),
::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))]
3268 fn with_constant_rib(
3269 &mut self,
3270 is_repeat: IsRepeatExpr,
3271 may_use_generics: ConstantHasGenerics,
3272 item: Option<(Ident, ConstantItemKind)>,
3273 f: impl FnOnce(&mut Self),
3274 ) {
3275 let f = |this: &mut Self| {
3276 this.with_rib(ValueNS, RibKind::ConstantItem(may_use_generics, item), |this| {
3277 this.with_rib(
3278 TypeNS,
3279 RibKind::ConstantItem(
3280 may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
3281 item,
3282 ),
3283 |this| {
3284 this.with_label_rib(RibKind::ConstantItem(may_use_generics, item), f);
3285 },
3286 )
3287 })
3288 };
3289
3290 if let ConstantHasGenerics::No(cause) = may_use_generics {
3291 self.with_lifetime_rib(LifetimeRibKind::ConcreteAnonConst(cause), f)
3292 } else {
3293 f(self)
3294 }
3295 }
3296
3297 fn with_current_self_type<T>(
3298 &mut self,
3299 self_type: &'ast Ty,
3300 f: impl FnOnce(&mut Self) -> T,
3301 ) -> T {
3302 let previous_value = replace(&mut self.diag_metadata.current_self_type, Some(self_type));
3304 let result = f(self);
3305 self.diag_metadata.current_self_type = previous_value;
3306 result
3307 }
3308
3309 fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
3310 let previous_value = replace(&mut self.diag_metadata.current_self_item, Some(self_item.id));
3311 let result = f(self);
3312 self.diag_metadata.current_self_item = previous_value;
3313 result
3314 }
3315
3316 fn resolve_trait_items(&mut self, trait_items: &'ast [Box<AssocItem>]) {
3318 let trait_assoc_items =
3319 replace(&mut self.diag_metadata.current_trait_assoc_items, Some(trait_items));
3320
3321 for item in trait_items {
3322 with_owner(self, item.id, |this| this.resolve_trait_item(item));
3323 }
3324
3325 self.diag_metadata.current_trait_assoc_items = trait_assoc_items;
3326 }
3327
3328 fn resolve_trait_item(&mut self, item: &'ast Item<AssocItemKind>) {
3329 let walk_assoc_item =
3330 |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
3331 this.with_generic_param_rib(
3332 &generics.params,
3333 RibKind::AssocItem,
3334 item.id,
3335 kind,
3336 generics.span,
3337 |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
3338 );
3339 };
3340
3341 self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
3342 match &item.kind {
3343 AssocItemKind::Const(ast::ConstItem {
3344 generics,
3345 ty,
3346 body,
3347 kind,
3348 define_opaque,
3349 ..
3350 }) => {
3351 self.with_generic_param_rib(
3352 &generics.params,
3353 RibKind::AssocItem,
3354 item.id,
3355 LifetimeBinderKind::ConstItem,
3356 generics.span,
3357 |this| {
3358 this.with_lifetime_rib(
3359 LifetimeRibKind::Elided {
3360 res: LifetimeRes::Static,
3361 error_in_path: true,
3362 },
3363 |this| {
3364 this.visit_generics(generics);
3365 if *kind == ConstItemKind::TypeConst
3366 && !this.r.features.generic_const_parameter_types()
3367 {
3368 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3369 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3370 this.with_lifetime_rib(
3371 LifetimeRibKind::ConstParamTy,
3372 |this| this.visit_ty(ty),
3373 )
3374 })
3375 });
3376 } else {
3377 this.visit_ty(ty);
3378 }
3379
3380 this.resolve_const_item_rhs(body, None);
3389 },
3390 )
3391 },
3392 );
3393
3394 self.resolve_define_opaques(define_opaque);
3395 }
3396 AssocItemKind::Fn(Fn { generics, define_opaque, .. }) => {
3397 walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
3398
3399 self.resolve_define_opaques(define_opaque);
3400 }
3401 AssocItemKind::Delegation(delegation) => {
3402 self.with_generic_param_rib(
3403 &[],
3404 RibKind::AssocItem,
3405 item.id,
3406 LifetimeBinderKind::Function,
3407 delegation.path.segments.last().unwrap().ident.span,
3408 |this| this.resolve_delegation(delegation, item.id, false),
3409 );
3410 }
3411 AssocItemKind::Type(TyAlias { generics, .. }) => self
3412 .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3413 walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
3414 }),
3415 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3416 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3417 }
3418 };
3419 }
3420
3421 fn with_optional_trait_ref<T>(
3423 &mut self,
3424 opt_trait_ref: Option<&TraitRef>,
3425 self_type: &'ast Ty,
3426 f: impl FnOnce(&mut Self, Option<DefId>) -> T,
3427 ) -> T {
3428 let mut new_val = None;
3429 let mut new_id = None;
3430 if let Some(trait_ref) = opt_trait_ref {
3431 let path: Vec<_> = Segment::from_path(&trait_ref.path);
3432 self.diag_metadata.currently_processing_impl_trait =
3433 Some((trait_ref.clone(), self_type.clone()));
3434 let res = self.smart_resolve_path_fragment(
3435 &None,
3436 &path,
3437 PathSource::Trait(AliasPossibility::No),
3438 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
3439 RecordPartialRes::Yes,
3440 None,
3441 );
3442 self.diag_metadata.currently_processing_impl_trait = None;
3443 if let Some(def_id) = res.expect_full_res().opt_def_id() {
3444 new_id = Some(def_id);
3445 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
3446 }
3447 }
3448 let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
3449 let result = f(self, new_id);
3450 self.current_trait_ref = original_trait_ref;
3451 result
3452 }
3453
3454 fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
3455 let mut self_type_rib = Rib::new(RibKind::Normal);
3456
3457 self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
3459 self.ribs[ns].push(self_type_rib);
3460 f(self);
3461 self.ribs[ns].pop();
3462 }
3463
3464 fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
3465 self.with_self_rib_ns(TypeNS, self_res, f)
3466 }
3467
3468 fn resolve_implementation(
3469 &mut self,
3470 attrs: &[ast::Attribute],
3471 generics: &'ast Generics,
3472 of_trait: Option<&'ast ast::TraitImplHeader>,
3473 self_type: &'ast Ty,
3474 item_id: NodeId,
3475 impl_items: &'ast [Box<AssocItem>],
3476 ) {
3477 {
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:3477",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3477u32),
::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");
3478 self.with_generic_param_rib(
3480 &generics.params,
3481 RibKind::Item(HasGenericParams::Yes(generics.span), self.r.tcx.def_kind(self.r.current_owner.def_id)),
3482 item_id,
3483 LifetimeBinderKind::ImplBlock,
3484 generics.span,
3485 |this| {
3486 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
3488 this.with_lifetime_rib(
3489 LifetimeRibKind::AnonymousCreateParameter {
3490 binder: item_id,
3491 report_in_path: true
3492 },
3493 |this| {
3494 this.with_optional_trait_ref(
3496 of_trait.map(|t| &t.trait_ref),
3497 self_type,
3498 |this, trait_id| {
3499 this.resolve_doc_links(attrs, MaybeExported::Impl(trait_id));
3500
3501 let item_def_id = this.r.current_owner.def_id;
3502
3503 if let Some(trait_id) = trait_id {
3505 this.r
3506 .trait_impls
3507 .entry(trait_id)
3508 .or_default()
3509 .push(item_def_id);
3510 }
3511
3512 let item_def_id = item_def_id.to_def_id();
3513 let res = Res::SelfTyAlias {
3514 alias_to: item_def_id,
3515 is_trait_impl: trait_id.is_some(),
3516 };
3517 this.with_self_rib(res, |this| {
3518 if let Some(of_trait) = of_trait {
3519 visit::walk_trait_ref(this, &of_trait.trait_ref);
3521 }
3522 this.visit_ty(self_type);
3524 this.visit_generics(generics);
3526
3527 this.with_current_self_type(self_type, |this| {
3529 this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
3530 {
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:3530",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3530u32),
::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, ...)");
3531 let mut seen_trait_items = Default::default();
3532 for item in impl_items {
3533 with_owner(this, item.id, |this| {
3534 this.resolve_impl_item(&**item, &mut seen_trait_items, trait_id, of_trait.is_some());
3535 })
3536 }
3537 });
3538 });
3539 });
3540 },
3541 )
3542 },
3543 );
3544 });
3545 },
3546 );
3547 }
3548
3549 fn resolve_impl_item(
3550 &mut self,
3551 item: &'ast AssocItem,
3552 seen_trait_items: &mut FxHashMap<DefId, Span>,
3553 trait_id: Option<DefId>,
3554 is_in_trait_impl: bool,
3555 ) {
3556 use crate::ResolutionError::*;
3557 self.resolve_doc_links(&item.attrs, MaybeExported::ImplItem(trait_id.ok_or(&item.vis)));
3558 let prev = self.diag_metadata.current_impl_item.take();
3559 self.diag_metadata.current_impl_item = Some(&item);
3560 match &item.kind {
3561 AssocItemKind::Const(ast::ConstItem {
3562 ident,
3563 generics,
3564 ty,
3565 body,
3566 kind,
3567 define_opaque,
3568 ..
3569 }) => {
3570 {
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:3570",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3570u32),
::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");
3571 self.with_generic_param_rib(
3572 &generics.params,
3573 RibKind::AssocItem,
3574 item.id,
3575 LifetimeBinderKind::ConstItem,
3576 generics.span,
3577 |this| {
3578 this.with_lifetime_rib(
3579 LifetimeRibKind::Elided {
3580 res: LifetimeRes::Static,
3581 error_in_path: true,
3582 },
3583 |this| {
3584 this.check_trait_item(
3587 item.id,
3588 *ident,
3589 *ident,
3590 &item.kind,
3591 ValueNS,
3592 item.span,
3593 seen_trait_items,
3594 |i, s, c| ConstNotMemberOfTrait(i, s, c),
3595 );
3596
3597 this.visit_generics(generics);
3598 if *kind == ConstItemKind::TypeConst
3599 && !this.r.tcx.features().generic_const_parameter_types()
3600 {
3601 this.with_rib(TypeNS, RibKind::ConstParamTy, |this| {
3602 this.with_rib(ValueNS, RibKind::ConstParamTy, |this| {
3603 this.with_lifetime_rib(
3604 LifetimeRibKind::ConstParamTy,
3605 |this| this.visit_ty(ty),
3606 )
3607 })
3608 });
3609 } else {
3610 this.visit_ty(ty);
3611 }
3612 this.resolve_const_item_rhs(body, None);
3618 },
3619 )
3620 },
3621 );
3622 self.resolve_define_opaques(define_opaque);
3623 }
3624 AssocItemKind::Fn(fn_kind @ Fn { ident, generics, define_opaque, .. }) => {
3625 {
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:3625",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3625u32),
::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");
3626 self.with_generic_param_rib(
3628 &generics.params,
3629 RibKind::AssocItem,
3630 item.id,
3631 LifetimeBinderKind::Function,
3632 generics.span,
3633 |this| {
3634 let effective_ident = if is_in_trait_impl && fn_kind.is_pin_drop_sugar() {
3635 Ident::new(sym::pin_drop, ident.span)
3636 } else {
3637 *ident
3638 };
3639 this.check_trait_item(
3642 item.id,
3643 effective_ident,
3644 *ident,
3645 &item.kind,
3646 ValueNS,
3647 item.span,
3648 seen_trait_items,
3649 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3650 );
3651
3652 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3653 },
3654 );
3655
3656 self.resolve_define_opaques(define_opaque);
3657 }
3658 AssocItemKind::Type(TyAlias { ident, generics, .. }) => {
3659 self.diag_metadata.in_non_gat_assoc_type = Some(generics.params.is_empty());
3660 {
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:3660",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3660u32),
::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");
3661 self.with_generic_param_rib(
3663 &generics.params,
3664 RibKind::AssocItem,
3665 item.id,
3666 LifetimeBinderKind::ImplAssocType,
3667 generics.span,
3668 |this| {
3669 this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
3670 this.check_trait_item(
3673 item.id,
3674 *ident,
3675 *ident,
3676 &item.kind,
3677 TypeNS,
3678 item.span,
3679 seen_trait_items,
3680 |i, s, c| TypeNotMemberOfTrait(i, s, c),
3681 );
3682
3683 visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
3684 });
3685 },
3686 );
3687 self.diag_metadata.in_non_gat_assoc_type = None;
3688 }
3689 AssocItemKind::Delegation(delegation) => {
3690 {
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:3690",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3690u32),
::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");
3691 self.with_generic_param_rib(
3692 &[],
3693 RibKind::AssocItem,
3694 item.id,
3695 LifetimeBinderKind::Function,
3696 delegation.path.segments.last().unwrap().ident.span,
3697 |this| {
3698 this.check_trait_item(
3699 item.id,
3700 delegation.ident,
3701 delegation.ident,
3702 &item.kind,
3703 ValueNS,
3704 item.span,
3705 seen_trait_items,
3706 |i, s, c| MethodNotMemberOfTrait(i, s, c),
3707 );
3708
3709 this.resolve_delegation(delegation, item.id, is_in_trait_impl);
3712 },
3713 );
3714 }
3715 AssocItemKind::MacCall(_) | AssocItemKind::DelegationMac(..) => {
3716 {
::core::panicking::panic_fmt(format_args!("unexpanded macro in resolve!"));
}panic!("unexpanded macro in resolve!")
3717 }
3718 }
3719 self.diag_metadata.current_impl_item = prev;
3720 }
3721
3722 fn check_trait_item<F>(
3723 &mut self,
3724 id: NodeId,
3725 mut ident: Ident,
3726 mut reported_ident: Ident,
3727 kind: &AssocItemKind,
3728 ns: Namespace,
3729 span: Span,
3730 seen_trait_items: &mut FxHashMap<DefId, Span>,
3731 err: F,
3732 ) where
3733 F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'ra>,
3734 {
3735 let Some((module, _)) = self.current_trait_ref else {
3737 return;
3738 };
3739 ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3740 reported_ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
3741 let key = BindingKey::new(IdentKey::new(ident), ns);
3742 let mut decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3743 {
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:3743",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3743u32),
::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);
3744 if decl.is_none() {
3745 let ns = match ns {
3748 ValueNS => TypeNS,
3749 TypeNS => ValueNS,
3750 _ => ns,
3751 };
3752 let key = BindingKey::new(IdentKey::new(ident), ns);
3753 decl = self.r.resolution(module, key).and_then(|r| r.best_decl());
3754 {
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:3754",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3754u32),
::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);
3755 }
3756
3757 let feed_visibility = |this: &mut Self, def_id| {
3758 let vis = this.r.tcx.visibility(def_id);
3759 let vis = if vis.is_visible_locally() {
3760 vis.expect_local()
3761 } else {
3762 this.r.dcx().span_delayed_bug(
3763 span,
3764 "error should be emitted when an unexpected trait item is used",
3765 );
3766 Visibility::Public
3767 };
3768 this.r.tcx.feed_visibility_for_trait_impl_item(this.r.current_owner.def_id, vis);
3772 };
3773
3774 let Some(decl) = decl else {
3775 let candidate = self.find_similarly_named_assoc_item(reported_ident.name, kind);
3777 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3778 let path_names = path_names_to_string(path);
3779 self.report_error(span, err(reported_ident, path_names, candidate));
3780 feed_visibility(self, module.def_id());
3781 return;
3782 };
3783
3784 let res = decl.res();
3785 let Res::Def(def_kind, id_in_trait) = res else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
3786 feed_visibility(self, id_in_trait);
3787
3788 match seen_trait_items.entry(id_in_trait) {
3789 Entry::Occupied(entry) => {
3790 self.report_error(
3791 span,
3792 ResolutionError::TraitImplDuplicate {
3793 name: ident,
3794 old_span: *entry.get(),
3795 trait_item_span: decl.span,
3796 },
3797 );
3798 return;
3799 }
3800 Entry::Vacant(entry) => {
3801 entry.insert(span);
3802 }
3803 };
3804
3805 match (def_kind, kind) {
3806 (DefKind::AssocTy, AssocItemKind::Type(..))
3807 | (DefKind::AssocFn, AssocItemKind::Fn(..))
3808 | (DefKind::AssocConst { .. }, AssocItemKind::Const(..))
3809 | (DefKind::AssocFn, AssocItemKind::Delegation(..)) => {
3810 self.r.record_partial_res(id, PartialRes::new(res));
3811 return;
3812 }
3813 _ => {}
3814 }
3815
3816 let path = &self.current_trait_ref.as_ref().unwrap().1.path;
3818 let (code, kind) = match kind {
3819 AssocItemKind::Const(..) => (E0323, "const"),
3820 AssocItemKind::Fn(..) => (E0324, "method"),
3821 AssocItemKind::Type(..) => (E0325, "type"),
3822 AssocItemKind::Delegation(..) => (E0324, "method"),
3823 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
3824 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpanded macro"))span_bug!(span, "unexpanded macro")
3825 }
3826 };
3827 let trait_path = path_names_to_string(path);
3828 self.report_error(
3829 span,
3830 ResolutionError::TraitImplMismatch {
3831 name: ident,
3832 kind,
3833 code,
3834 trait_path,
3835 trait_item_span: decl.span,
3836 },
3837 );
3838 }
3839
3840 fn resolve_static_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) {
3841 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3842 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3843 this.visit_expr(expr)
3844 });
3845 })
3846 }
3847
3848 fn resolve_const_item_rhs(
3849 &mut self,
3850 body: &'ast Option<Box<Expr>>,
3851 item: Option<(Ident, ConstantItemKind)>,
3852 ) {
3853 if let Some(body) = body {
3854 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3855 this.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, item, |this| {
3856 this.visit_expr(body)
3857 })
3858 })
3859 }
3860 }
3861
3862 fn resolve_delegation(
3863 &mut self,
3864 delegation: &'ast Delegation,
3865 item_id: NodeId,
3866 is_in_trait_impl: bool,
3867 ) {
3868 self.smart_resolve_path(
3869 delegation.id,
3870 &delegation.qself,
3871 &delegation.path,
3872 PathSource::Delegation,
3873 );
3874
3875 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3878 if let Some(qself) = &delegation.qself {
3879 this.visit_ty(&qself.ty);
3880 }
3881
3882 this.visit_path(&delegation.path);
3883 });
3884
3885 let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
3886 let def_id = self
3887 .r
3888 .partial_res_map
3889 .get(&resolution_node_id)
3890 .and_then(|r| r.expect_full_res().opt_def_id());
3891
3892 let resolution_id = def_id.ok_or_else(|| {
3893 self.r.tcx.dcx().span_delayed_bug(
3894 delegation.path.span,
3895 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LateResolutionVisitor: couldn\'t resolve node {0:?} in delegation item",
resolution_node_id))
})format!(
3896 "LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
3897 ),
3898 )
3899 });
3900
3901 let info = DelegationInfo { resolution_id };
3902 self.r.delegation_infos.insert(self.r.current_owner.def_id, info);
3903
3904 let Some(body) = &delegation.body else { return };
3905 self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
3906 let ident = Ident::new(kw::SelfLower, body.span.normalize_to_macro_rules());
3907 let res = Res::Local(delegation.id);
3908 this.innermost_rib_bindings(ValueNS).insert(ident, res);
3909
3910 this.with_label_rib(RibKind::FnOrCoroutine, |this| {
3912 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3913 this.visit_block(body);
3914 });
3915 });
3916 });
3917 }
3918
3919 fn resolve_params(&mut self, params: &'ast [Param]) {
3920 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())];
3921 self.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
3922 for Param { pat, .. } in params {
3923 this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
3924 }
3925 this.apply_pattern_bindings(bindings);
3926 });
3927 for Param { ty, .. } in params {
3928 self.visit_ty(ty);
3929 }
3930 }
3931
3932 fn resolve_local(&mut self, local: &'ast Local) {
3933 {
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:3933",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(3933u32),
::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);
3934 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);
3936
3937 if let Some((init, els)) = local.kind.init_else_opt() {
3939 self.visit_expr(init);
3940
3941 if let Some(els) = els {
3943 self.visit_block(els);
3944 }
3945 }
3946
3947 self.resolve_pattern_top(&local.pat, PatternSource::Let);
3949 }
3950
3951 fn compute_and_check_binding_map(
3971 &mut self,
3972 pat: &Pat,
3973 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
3974 let mut binding_map = FxIndexMap::default();
3975 let mut is_never_pat = false;
3976
3977 pat.walk(&mut |pat| {
3978 match pat.kind {
3979 PatKind::Ident(annotation, ident, ref sub_pat)
3980 if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
3981 {
3982 binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
3983 }
3984 PatKind::Or(ref ps) => {
3985 match self.compute_and_check_or_pat_binding_map(ps) {
3988 Ok(bm) => binding_map.extend(bm),
3989 Err(IsNeverPattern) => is_never_pat = true,
3990 }
3991 return false;
3992 }
3993 PatKind::Never => is_never_pat = true,
3994 _ => {}
3995 }
3996
3997 true
3998 });
3999
4000 if is_never_pat {
4001 for (_, binding) in binding_map {
4002 self.report_error(binding.span, ResolutionError::BindingInNeverPattern);
4003 }
4004 Err(IsNeverPattern)
4005 } else {
4006 Ok(binding_map)
4007 }
4008 }
4009
4010 fn is_base_res_local(&self, nid: NodeId) -> bool {
4011 #[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!(
4012 self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
4013 Some(Res::Local(..))
4014 )
4015 }
4016
4017 fn compute_and_check_or_pat_binding_map(
4037 &mut self,
4038 pats: &[Pat],
4039 ) -> Result<FxIndexMap<Ident, BindingInfo>, IsNeverPattern> {
4040 let mut missing_vars = FxIndexMap::default();
4041 let mut inconsistent_vars = FxIndexMap::default();
4042
4043 let not_never_pats = pats
4045 .iter()
4046 .filter_map(|pat| {
4047 let binding_map = self.compute_and_check_binding_map(pat).ok()?;
4048 Some((binding_map, pat))
4049 })
4050 .collect::<Vec<_>>();
4051
4052 for &(ref map_outer, pat_outer) in not_never_pats.iter() {
4054 let inners = not_never_pats.iter().filter(|(_, pat)| pat.id != pat_outer.id);
4056
4057 for &(ref map, pat) in inners {
4058 for (&name, binding_inner) in map {
4059 match map_outer.get(&name) {
4060 None => {
4061 let binding_error =
4063 missing_vars.entry(name).or_insert_with(|| BindingError {
4064 name,
4065 origin: Default::default(),
4066 target: Default::default(),
4067 could_be_path: name.as_str().starts_with(char::is_uppercase),
4068 });
4069 binding_error.origin.push((binding_inner.span, pat.clone()));
4070 binding_error.target.push(pat_outer.clone());
4071 }
4072 Some(binding_outer) => {
4073 if binding_outer.annotation != binding_inner.annotation {
4074 inconsistent_vars
4076 .entry(name)
4077 .or_insert((binding_inner.span, binding_outer.span));
4078 }
4079 }
4080 }
4081 }
4082 }
4083 }
4084
4085 for (name, mut v) in missing_vars {
4087 if inconsistent_vars.contains_key(&name) {
4088 v.could_be_path = false;
4089 }
4090 self.report_error(
4091 v.origin.first().unwrap().0,
4092 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
4093 );
4094 }
4095
4096 for (name, v) in inconsistent_vars {
4098 self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(name, v.1));
4099 }
4100
4101 if not_never_pats.is_empty() {
4103 Err(IsNeverPattern)
4105 } else {
4106 let mut binding_map = FxIndexMap::default();
4107 for (bm, _) in not_never_pats {
4108 binding_map.extend(bm);
4109 }
4110 Ok(binding_map)
4111 }
4112 }
4113
4114 fn check_consistent_bindings(&mut self, pat: &'ast Pat) {
4116 let mut is_or_or_never = false;
4117 pat.walk(&mut |pat| match pat.kind {
4118 PatKind::Or(..) | PatKind::Never => {
4119 is_or_or_never = true;
4120 false
4121 }
4122 _ => true,
4123 });
4124 if is_or_or_never {
4125 let _ = self.compute_and_check_binding_map(pat);
4126 }
4127 }
4128
4129 fn resolve_arm(&mut self, arm: &'ast Arm) {
4130 self.with_rib(ValueNS, RibKind::Normal, |this| {
4131 this.resolve_pattern_top(&arm.pat, PatternSource::Match);
4132 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));
4133 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);
4134 });
4135 }
4136
4137 fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
4139 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())];
4140 self.resolve_pattern(pat, pat_src, &mut bindings);
4141 self.apply_pattern_bindings(bindings);
4142 }
4143
4144 fn apply_pattern_bindings(&mut self, mut pat_bindings: PatternBindings) {
4146 let rib_bindings = self.innermost_rib_bindings(ValueNS);
4147 let Some((_, pat_bindings)) = pat_bindings.pop() else {
4148 ::rustc_middle::util::bug::bug_fmt(format_args!("tried applying nonexistent bindings from pattern"));bug!("tried applying nonexistent bindings from pattern");
4149 };
4150
4151 if rib_bindings.is_empty() {
4152 *rib_bindings = pat_bindings;
4155 } else {
4156 rib_bindings.extend(pat_bindings);
4157 }
4158 }
4159
4160 fn resolve_pattern(
4163 &mut self,
4164 pat: &'ast Pat,
4165 pat_src: PatternSource,
4166 bindings: &mut PatternBindings,
4167 ) {
4168 self.visit_pat(pat);
4174 self.resolve_pattern_inner(pat, pat_src, bindings);
4175 self.check_consistent_bindings(pat);
4177 }
4178
4179 #[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(4198u32),
::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")]
4199 fn resolve_pattern_inner(
4200 &mut self,
4201 pat: &'ast Pat,
4202 pat_src: PatternSource,
4203 bindings: &mut PatternBindings,
4204 ) {
4205 pat.walk(&mut |pat| {
4207 match pat.kind {
4208 PatKind::Ident(bmode, ident, ref sub) => {
4209 let has_sub = sub.is_some();
4212 let res = self
4213 .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
4214 .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
4215 self.r.record_partial_res(pat.id, PartialRes::new(res));
4216 self.r.record_pat_span(pat.id, pat.span);
4217 }
4218 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
4219 self.smart_resolve_path(
4220 pat.id,
4221 qself,
4222 path,
4223 PathSource::TupleStruct(
4224 pat.span,
4225 self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
4226 ),
4227 );
4228 }
4229 PatKind::Path(ref qself, ref path) => {
4230 self.smart_resolve_path(pat.id, qself, path, PathSource::Pat);
4231 }
4232 PatKind::Struct(ref qself, ref path, ref _fields, ref rest) => {
4233 self.smart_resolve_path(pat.id, qself, path, PathSource::Struct(None));
4234 self.record_patterns_with_skipped_bindings(pat, rest);
4235 }
4236 PatKind::Or(ref ps) => {
4237 bindings.push((PatBoundCtx::Or, Default::default()));
4241 for p in ps {
4242 bindings.push((PatBoundCtx::Product, Default::default()));
4246 self.resolve_pattern_inner(p, pat_src, bindings);
4247 let collected = bindings.pop().unwrap().1;
4250 bindings.last_mut().unwrap().1.extend(collected);
4251 }
4252 let collected = bindings.pop().unwrap().1;
4256 bindings.last_mut().unwrap().1.extend(collected);
4257
4258 return false;
4260 }
4261 PatKind::Guard(ref subpat, ref guard) => {
4262 bindings.push((PatBoundCtx::Product, Default::default()));
4264 let binding_ctx_stack_len = bindings.len();
4267 self.resolve_pattern_inner(subpat, pat_src, bindings);
4268 assert_eq!(bindings.len(), binding_ctx_stack_len);
4269 let subpat_bindings = bindings.pop().unwrap().1;
4272 self.with_rib(ValueNS, RibKind::Normal, |this| {
4273 *this.innermost_rib_bindings(ValueNS) = subpat_bindings.clone();
4274 this.resolve_expr(&guard.cond, None);
4275 });
4276 bindings.last_mut().unwrap().1.extend(subpat_bindings);
4283 return false;
4285 }
4286 _ => {}
4287 }
4288 true
4289 });
4290 }
4291
4292 fn record_patterns_with_skipped_bindings(&mut self, pat: &Pat, rest: &ast::PatFieldsRest) {
4293 match rest {
4294 ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) => {
4295 if let Some(partial_res) = self.r.partial_res_map.get(&pat.id)
4297 && let Some(res) = partial_res.full_res()
4298 && let Some(def_id) = res.opt_def_id()
4299 {
4300 self.ribs[ValueNS]
4301 .last_mut()
4302 .unwrap()
4303 .patterns_with_skipped_bindings
4304 .entry(def_id)
4305 .or_default()
4306 .push((
4307 pat.span,
4308 match rest {
4309 ast::PatFieldsRest::Recovered(guar) => Err(*guar),
4310 _ => Ok(()),
4311 },
4312 ));
4313 }
4314 }
4315 ast::PatFieldsRest::None => {}
4316 }
4317 }
4318
4319 fn fresh_binding(
4320 &mut self,
4321 ident: Ident,
4322 pat_id: NodeId,
4323 pat_src: PatternSource,
4324 bindings: &mut PatternBindings,
4325 ) -> Res {
4326 let ident = ident.normalize_to_macro_rules();
4330
4331 let already_bound_and = bindings
4333 .iter()
4334 .any(|(ctx, map)| *ctx == PatBoundCtx::Product && map.contains_key(&ident));
4335 if already_bound_and {
4336 use ResolutionError::*;
4338 let error = match pat_src {
4339 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
4341 _ => IdentifierBoundMoreThanOnceInSamePattern,
4343 };
4344 self.report_error(ident.span, error(ident));
4345 }
4346
4347 let already_bound_or = bindings
4350 .iter()
4351 .find_map(|(ctx, map)| if *ctx == PatBoundCtx::Or { map.get(&ident) } else { None });
4352 let res = if let Some(&res) = already_bound_or {
4353 res
4356 } else {
4357 Res::Local(pat_id)
4359 };
4360
4361 bindings.last_mut().unwrap().1.insert(ident, res);
4363 res
4364 }
4365
4366 fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxIndexMap<Ident, Res> {
4367 &mut self.ribs[ns].last_mut().unwrap().bindings
4368 }
4369
4370 fn try_resolve_as_non_binding(
4371 &mut self,
4372 pat_src: PatternSource,
4373 ann: BindingMode,
4374 ident: Ident,
4375 has_sub: bool,
4376 ) -> Option<Res> {
4377 let is_syntactic_ambiguity = !has_sub && ann == BindingMode::NONE;
4381
4382 let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
4383 let (res, binding) = match ls_binding {
4384 LateDecl::Decl(binding)
4385 if is_syntactic_ambiguity && binding.is_ambiguity_recursive() =>
4386 {
4387 self.r.record_use(ident, binding, Used::Other);
4392 return None;
4393 }
4394 LateDecl::Decl(binding) => (binding.res(), Some(binding)),
4395 LateDecl::RibDef(res) => (res, None),
4396 };
4397
4398 match res {
4399 Res::SelfCtor(_) | Res::Def(
4401 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::ConstParam,
4402 _,
4403 ) if is_syntactic_ambiguity => {
4404 if let Some(binding) = binding {
4406 self.r.record_use(ident, binding, Used::Other);
4407 }
4408 Some(res)
4409 }
4410 Res::Def(
4411 DefKind::Ctor(..)
4412 | DefKind::Const { .. }
4413 | DefKind::AssocConst { .. }
4414 | DefKind::Static { .. },
4415 _,
4416 ) => {
4417 let binding = binding.expect("no binding for a ctor or static");
4423 self.report_error(
4424 ident.span,
4425 ResolutionError::BindingShadowsSomethingUnacceptable {
4426 shadowing_binding: pat_src,
4427 name: ident.name,
4428 participle: if binding.is_import() { "imported" } else { "defined" },
4429 article: binding.res().article(),
4430 shadowed_binding: binding.res(),
4431 shadowed_binding_span: binding.span,
4432 },
4433 );
4434 None
4435 }
4436 Res::Def(DefKind::ConstParam, def_id) => {
4437 self.report_error(
4440 ident.span,
4441 ResolutionError::BindingShadowsSomethingUnacceptable {
4442 shadowing_binding: pat_src,
4443 name: ident.name,
4444 participle: "defined",
4445 article: res.article(),
4446 shadowed_binding: res,
4447 shadowed_binding_span: self.r.def_span(def_id),
4448 },
4449 );
4450 None
4451 }
4452 Res::Def(DefKind::Fn | DefKind::AssocFn, _) | Res::Local(..) | Res::Err => {
4453 None
4455 }
4456 Res::SelfCtor(_) => {
4457 self.r.dcx().span_delayed_bug(
4460 ident.span,
4461 "unexpected `SelfCtor` in pattern, expected identifier",
4462 );
4463 None
4464 }
4465 _ => ::rustc_middle::util::bug::span_bug_fmt(ident.span,
format_args!("unexpected resolution for an identifier in pattern: {0:?}",
res))span_bug!(
4466 ident.span,
4467 "unexpected resolution for an identifier in pattern: {:?}",
4468 res,
4469 ),
4470 }
4471 }
4472
4473 fn resolve_restriction_path(&mut self, restriction: &'ast ast::RestrictionKind) {
4474 match &restriction {
4475 ast::RestrictionKind::Unrestricted => (),
4476 ast::RestrictionKind::Restricted { path, id, shorthand: _ } => {
4477 self.smart_resolve_path(*id, &None, path, PathSource::Module);
4478 }
4479 }
4480 }
4481
4482 fn smart_resolve_path(
4488 &mut self,
4489 id: NodeId,
4490 qself: &Option<Box<QSelf>>,
4491 path: &Path,
4492 source: PathSource<'_, 'ast, 'ra>,
4493 ) {
4494 self.smart_resolve_path_fragment(
4495 qself,
4496 &Segment::from_path(path),
4497 source,
4498 Finalize::new(id, path.span),
4499 RecordPartialRes::Yes,
4500 None,
4501 );
4502 }
4503
4504 fn smart_resolve_path_fragment(
4505 &mut self,
4506 qself: &Option<Box<QSelf>>,
4507 path: &[Segment],
4508 source: PathSource<'_, 'ast, 'ra>,
4509 finalize: Finalize,
4510 record_partial_res: RecordPartialRes,
4511 parent_qself: Option<&QSelf>,
4512 ) -> PartialRes {
4513 let ns = source.namespace();
4514
4515 let Finalize { node_id, path_span, .. } = finalize;
4516 let report_errors = |this: &mut Self, res: Option<Res>| {
4517 if this.should_report_errs() {
4518 let (mut err, candidates) = this.smart_resolve_report_errors(
4519 path,
4520 None,
4521 path_span,
4522 source,
4523 res,
4524 parent_qself,
4525 );
4526
4527 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4528 let instead = res.is_some();
4529 let (suggestion, const_err) = if let Some((start, end)) =
4530 this.diag_metadata.in_range
4531 && path[0].ident.span.lo() == end.span.lo()
4532 && !#[allow(non_exhaustive_omitted_patterns)] match start.kind {
ExprKind::Lit(_) => true,
_ => false,
}matches!(start.kind, ExprKind::Lit(_))
4533 {
4534 let mut sugg = ".";
4535 let mut span = start.span.between(end.span);
4536 if span.lo() + BytePos(2) == span.hi() {
4537 span = span.with_lo(span.lo() + BytePos(1));
4540 sugg = "";
4541 }
4542 (
4543 Some((
4544 span,
4545 "you might have meant to write `.` instead of `..`",
4546 sugg.to_string(),
4547 Applicability::MaybeIncorrect,
4548 )),
4549 None,
4550 )
4551 } else if res.is_none()
4552 && let PathSource::Type
4553 | PathSource::Expr(_)
4554 | PathSource::PreciseCapturingArg(..) = source
4555 {
4556 this.suggest_adding_generic_parameter(path, source)
4557 } else {
4558 (None, None)
4559 };
4560
4561 if let Some(const_err) = const_err {
4562 err.cancel();
4563 err = const_err;
4564 }
4565
4566 let ue = UseError {
4567 err,
4568 candidates,
4569 node_id,
4570 instead,
4571 suggestion,
4572 path: path.into(),
4573 is_call: source.is_call(),
4574 };
4575
4576 this.use_injections.push(ue);
4577 }
4578
4579 PartialRes::new(Res::Err)
4580 };
4581
4582 let report_errors_for_call =
4588 |this: &mut Self, parent_err: Spanned<ResolutionError<'ra>>| {
4589 let (following_seg, prefix_path) = match path.split_last() {
4593 Some((last, path)) if !path.is_empty() => (Some(last), path),
4594 _ => return Some(parent_err),
4595 };
4596
4597 let (mut err, candidates) = this.smart_resolve_report_errors(
4598 prefix_path,
4599 following_seg,
4600 path_span,
4601 PathSource::Type,
4602 None,
4603 parent_qself,
4604 );
4605
4606 let failed_to_resolve = match parent_err.node {
4621 ResolutionError::FailedToResolve { .. } => true,
4622 _ => false,
4623 };
4624 let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
4625
4626 err.messages = take(&mut parent_err.messages);
4628 err.code = take(&mut parent_err.code);
4629 swap(&mut err.span, &mut parent_err.span);
4630 if failed_to_resolve {
4631 err.children = take(&mut parent_err.children);
4632 } else {
4633 err.children.append(&mut parent_err.children);
4634 }
4635 err.sort_span = parent_err.sort_span;
4636 err.is_lint = parent_err.is_lint.clone();
4637
4638 match &mut err.suggestions {
4640 Suggestions::Enabled(typo_suggestions) => match &mut parent_err.suggestions {
4641 Suggestions::Enabled(parent_suggestions) => {
4642 typo_suggestions.append(parent_suggestions)
4644 }
4645 Suggestions::Sealed(_) | Suggestions::Disabled => {
4646 err.suggestions = std::mem::take(&mut parent_err.suggestions);
4651 }
4652 },
4653 Suggestions::Sealed(_) | Suggestions::Disabled => (),
4654 }
4655
4656 parent_err.cancel();
4657
4658 let node_id = this.parent_scope.module.nearest_parent_mod_node_id();
4659
4660 if this.should_report_errs() {
4661 if candidates.is_empty() {
4662 if path.len() == 2
4663 && let [segment] = prefix_path
4664 {
4665 err.stash(segment.ident.span, rustc_errors::StashKey::CallAssocMethod);
4671 } else {
4672 err.emit();
4677 }
4678 } else {
4679 this.use_injections.push(UseError {
4681 err,
4682 candidates,
4683 node_id,
4684 instead: false,
4685 suggestion: None,
4686 path: prefix_path.into(),
4687 is_call: source.is_call(),
4688 });
4689 }
4690 } else {
4691 err.cancel();
4692 }
4693
4694 None
4697 };
4698
4699 let partial_res = match self.resolve_qpath_anywhere(
4700 qself,
4701 path,
4702 ns,
4703 source.defer_to_typeck(),
4704 finalize,
4705 source,
4706 ) {
4707 Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
4708 if let Some(items) = self.diag_metadata.current_trait_assoc_items
4710 && let [Segment { ident, .. }] = path
4711 && items.iter().any(|item| {
4712 if let AssocItemKind::Type(alias) = &item.kind
4713 && alias.ident == *ident
4714 {
4715 true
4716 } else {
4717 false
4718 }
4719 })
4720 {
4721 let mut diag = self.r.tcx.dcx().struct_allow("");
4722 diag.span_suggestion_verbose(
4723 path_span.shrink_to_lo(),
4724 "there is an associated type with the same name",
4725 "Self::",
4726 Applicability::MaybeIncorrect,
4727 );
4728 diag.stash(path_span, StashKey::AssociatedTypeSuggestion);
4729 }
4730
4731 if source.is_expected(res) || res == Res::Err {
4732 partial_res
4733 } else {
4734 report_errors(self, Some(res))
4735 }
4736 }
4737
4738 Ok(Some(partial_res)) if source.defer_to_typeck() => {
4739 if ns == ValueNS {
4743 let item_name = path.last().unwrap().ident;
4744 self.record_traits_in_scope(node_id, item_name);
4745 }
4746
4747 if PrimTy::from_name(path[0].ident.name).is_some() {
4748 let mut std_path = Vec::with_capacity(1 + path.len());
4749
4750 std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
4751 std_path.extend(path);
4752 if let PathResult::Module(_) | PathResult::NonModule(_) =
4753 self.resolve_path(&std_path, Some(ns), None, source)
4754 {
4755 let item_span = path.last().map_or(path_span, |segment| segment.ident.span);
4757
4758 self.r.confused_type_with_std_module.insert(item_span, path_span);
4759 self.r.confused_type_with_std_module.insert(path_span, path_span);
4760 }
4761 }
4762
4763 partial_res
4764 }
4765
4766 Err(err) => {
4767 if let Some(err) = report_errors_for_call(self, err) {
4768 self.report_error(err.span, err.node);
4769 }
4770
4771 PartialRes::new(Res::Err)
4772 }
4773
4774 _ => report_errors(self, None),
4775 };
4776
4777 if record_partial_res == RecordPartialRes::Yes {
4778 self.r.record_partial_res(node_id, partial_res);
4780 self.resolve_elided_lifetimes_in_path(partial_res, path, source, path_span);
4781 self.lint_unused_qualifications(path, ns, finalize);
4782 }
4783
4784 partial_res
4785 }
4786
4787 fn self_type_is_available(&mut self) -> bool {
4788 let binding = self
4789 .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
4790 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4791 }
4792
4793 fn self_value_is_available(&mut self, self_span: Span) -> bool {
4794 let ident = Ident::new(kw::SelfLower, self_span);
4795 let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
4796 if let Some(LateDecl::RibDef(res)) = binding { res != Res::Err } else { false }
4797 }
4798
4799 fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'ra>) {
4803 if self.should_report_errs() {
4804 self.r.report_error(span, resolution_error);
4805 }
4806 }
4807
4808 #[inline]
4809 fn should_report_errs(&self) -> bool {
4813 !(self.r.tcx.sess.opts.actually_rustdoc && self.in_func_body)
4814 && !self.r.glob_error.is_some()
4815 }
4816
4817 fn resolve_qpath_anywhere(
4819 &mut self,
4820 qself: &Option<Box<QSelf>>,
4821 path: &[Segment],
4822 primary_ns: Namespace,
4823 defer_to_typeck: bool,
4824 finalize: Finalize,
4825 source: PathSource<'_, 'ast, 'ra>,
4826 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4827 let mut fin_res = None;
4828
4829 for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
4830 if i == 0 || ns != primary_ns {
4831 match self.resolve_qpath(qself, path, ns, finalize, source)? {
4832 Some(partial_res)
4833 if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
4834 {
4835 return Ok(Some(partial_res));
4836 }
4837 partial_res => {
4838 if fin_res.is_none() {
4839 fin_res = partial_res;
4840 }
4841 }
4842 }
4843 }
4844 }
4845
4846 if !(primary_ns != MacroNS) {
::core::panicking::panic("assertion failed: primary_ns != MacroNS")
};assert!(primary_ns != MacroNS);
4847 if qself.is_none()
4848 && let PathResult::NonModule(res) =
4849 self.r.cm().maybe_resolve_path(path, Some(MacroNS), &self.parent_scope, None)
4850 {
4851 return Ok(Some(res));
4852 }
4853
4854 Ok(fin_res)
4855 }
4856
4857 fn resolve_qpath(
4859 &mut self,
4860 qself: &Option<Box<QSelf>>,
4861 path: &[Segment],
4862 ns: Namespace,
4863 finalize: Finalize,
4864 source: PathSource<'_, 'ast, 'ra>,
4865 ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
4866 {
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:4866",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(4866u32),
::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!(
4867 "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
4868 qself, path, ns, finalize,
4869 );
4870
4871 if let Some(qself) = qself {
4872 if qself.position == 0 {
4873 return Ok(Some(PartialRes::with_unresolved_segments(
4877 Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
4878 path.len(),
4879 )));
4880 }
4881
4882 let num_privacy_errors = self.r.privacy_errors.len();
4883 let trait_res = self.smart_resolve_path_fragment(
4885 &None,
4886 &path[..qself.position],
4887 PathSource::Trait(AliasPossibility::No),
4888 Finalize::new(finalize.node_id, qself.path_span),
4889 RecordPartialRes::No,
4890 Some(&qself),
4891 );
4892
4893 if trait_res.expect_full_res() == Res::Err {
4894 return Ok(Some(trait_res));
4895 }
4896
4897 self.r.privacy_errors.truncate(num_privacy_errors);
4900
4901 let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
4909 let partial_res = self.smart_resolve_path_fragment(
4910 &None,
4911 &path[..=qself.position],
4912 PathSource::TraitItem(ns, &source),
4913 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
4914 RecordPartialRes::No,
4915 Some(&qself),
4916 );
4917
4918 return Ok(Some(PartialRes::with_unresolved_segments(
4922 partial_res.base_res(),
4923 partial_res.unresolved_segments() + path.len() - qself.position - 1,
4924 )));
4925 }
4926
4927 let result = match self.resolve_path(path, Some(ns), Some(finalize), source) {
4928 PathResult::NonModule(path_res) => path_res,
4929 PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
4930 PartialRes::new(module.res().unwrap())
4931 }
4932 PathResult::Failed { error_implied_by_parse_error: true, .. } => {
4936 PartialRes::new(Res::Err)
4937 }
4938 PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
4951 if (ns == TypeNS || path.len() > 1)
4952 && PrimTy::from_name(path[0].ident.name).is_some() =>
4953 {
4954 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
4955 let tcx = self.r.tcx();
4956
4957 let gate_err_sym_msg = match prim {
4958 PrimTy::Float(FloatTy::F16) if !self.r.features.f16() => {
4959 Some((sym::f16, "the type `f16` is unstable"))
4960 }
4961 PrimTy::Float(FloatTy::F128) if !self.r.features.f128() => {
4962 Some((sym::f128, "the type `f128` is unstable"))
4963 }
4964 _ => None,
4965 };
4966
4967 if let Some((sym, msg)) = gate_err_sym_msg {
4968 let span = path[0].ident.span;
4969 if !span.allows_unstable(sym) {
4970 feature_err(tcx.sess, sym, span, msg).emit();
4971 }
4972 };
4973
4974 if let Some(id) = path[0].id {
4976 self.r.partial_res_map.insert(id, PartialRes::new(Res::PrimTy(prim)));
4977 }
4978
4979 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
4980 }
4981 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4982 PartialRes::new(module.res().unwrap())
4983 }
4984 PathResult::Failed {
4985 is_error_from_last_segment: false,
4986 span,
4987 label,
4988 suggestion,
4989 module,
4990 segment,
4991 error_implied_by_parse_error: _,
4992 message,
4993 note: _,
4994 } => {
4995 return Err(respan(
4996 span,
4997 ResolutionError::FailedToResolve {
4998 segment: segment.name,
4999 label,
5000 suggestion,
5001 module,
5002 message,
5003 },
5004 ));
5005 }
5006 PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
5007 PathResult::Indeterminate => ::rustc_middle::util::bug::bug_fmt(format_args!("indeterminate path result in resolve_qpath"))bug!("indeterminate path result in resolve_qpath"),
5008 };
5009
5010 Ok(Some(result))
5011 }
5012
5013 fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
5014 if let Some(label) = label {
5015 if label.ident.as_str().as_bytes()[1] != b'_' {
5016 self.diag_metadata.unused_labels.insert(id, label.ident.span);
5017 }
5018
5019 if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
5020 diagnostics::signal_label_shadowing(self.r.tcx.sess, orig_span, label.ident)
5021 }
5022
5023 self.with_label_rib(RibKind::Normal, |this| {
5024 let ident = label.ident.normalize_to_macro_rules();
5025 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
5026 f(this);
5027 });
5028 } else {
5029 f(self);
5030 }
5031 }
5032
5033 fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
5034 self.with_resolved_label(label, id, |this| this.visit_block(block));
5035 }
5036
5037 fn resolve_block(&mut self, block: &'ast Block) {
5038 {
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:5038",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5038u32),
::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");
5039 let orig_module = self.parent_scope.module;
5041 let anonymous_module = self.r.block_map.get(&block.id).copied();
5042
5043 let mut num_macro_definition_ribs = 0;
5044 if let Some(anonymous_module) = anonymous_module {
5045 {
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:5045",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5045u32),
::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");
5046 self.ribs[ValueNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5047 self.ribs[TypeNS].push(Rib::new(RibKind::Block(Some(anonymous_module))));
5048 self.parent_scope.module = anonymous_module.to_module();
5049 } else {
5050 self.ribs[ValueNS].push(Rib::new(RibKind::Block(None)));
5051 }
5052
5053 for stmt in &block.stmts {
5055 if let StmtKind::Item(ref item) = stmt.kind
5056 && let ItemKind::MacroDef(..) = item.kind
5057 {
5058 num_macro_definition_ribs += 1;
5059 let res = self.r.owner_def_id(item.id).to_def_id();
5060 self.ribs[ValueNS].push(Rib::new(RibKind::MacroDefinition(res)));
5061 self.label_ribs.push(Rib::new(RibKind::MacroDefinition(res)));
5062 }
5063
5064 self.visit_stmt(stmt);
5065 }
5066
5067 self.parent_scope.module = orig_module;
5069 for _ in 0..num_macro_definition_ribs {
5070 self.ribs[ValueNS].pop();
5071 self.label_ribs.pop();
5072 }
5073 self.last_block_rib = self.ribs[ValueNS].pop();
5074 if anonymous_module.is_some() {
5075 self.ribs[TypeNS].pop();
5076 }
5077 {
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:5077",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5077u32),
::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");
5078 }
5079
5080 fn resolve_anon_const(&mut self, constant: &'ast AnonConst, anon_const_kind: AnonConstKind) {
5081 {
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:5081",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5081u32),
::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!(
5082 "resolve_anon_const(constant: {:?}, anon_const_kind: {:?})",
5083 constant, anon_const_kind
5084 );
5085
5086 let is_trivial_const_arg = constant.value.is_potential_trivial_const_arg();
5087 self.resolve_anon_const_manual(is_trivial_const_arg, anon_const_kind, |this| {
5088 this.resolve_expr(&constant.value, None)
5089 })
5090 }
5091
5092 fn resolve_anon_const_manual(
5099 &mut self,
5100 is_trivial_const_arg: bool,
5101 anon_const_kind: AnonConstKind,
5102 resolve_expr: impl FnOnce(&mut Self),
5103 ) {
5104 let is_repeat_expr = match anon_const_kind {
5105 AnonConstKind::ConstArg(is_repeat_expr) => is_repeat_expr,
5106 _ => IsRepeatExpr::No,
5107 };
5108
5109 let may_use_generics = match anon_const_kind {
5110 AnonConstKind::EnumDiscriminant => {
5111 ConstantHasGenerics::No(NoConstantGenericsReason::IsEnumDiscriminant)
5112 }
5113 AnonConstKind::FieldDefaultValue => ConstantHasGenerics::Yes,
5114 AnonConstKind::InlineConst => ConstantHasGenerics::Yes,
5115 AnonConstKind::ConstArg(_) => {
5116 if self.r.features.generic_const_exprs()
5117 || self.r.features.min_generic_const_args()
5118 || is_trivial_const_arg
5119 {
5120 ConstantHasGenerics::Yes
5121 } else {
5122 ConstantHasGenerics::No(NoConstantGenericsReason::NonTrivialConstArg)
5123 }
5124 }
5125 };
5126
5127 self.with_constant_rib(is_repeat_expr, may_use_generics, None, |this| {
5128 this.with_lifetime_rib(LifetimeRibKind::elided(LifetimeRes::Infer), |this| {
5129 resolve_expr(this);
5130 });
5131 });
5132 }
5133
5134 fn resolve_expr_field(&mut self, f: &'ast ExprField, e: &'ast Expr) {
5135 self.resolve_expr(&f.expr, Some(e));
5136 self.visit_ident(&f.ident);
5137 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());
5138 }
5139
5140 fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
5141 self.record_candidate_traits_for_expr_if_necessary(expr);
5145
5146 match expr.kind {
5148 ExprKind::Path(ref qself, ref path) => {
5149 self.smart_resolve_path(expr.id, qself, path, PathSource::Expr(parent));
5150 visit::walk_expr(self, expr);
5151 }
5152
5153 ExprKind::Struct(ref se) => {
5154 self.smart_resolve_path(expr.id, &se.qself, &se.path, PathSource::Struct(parent));
5155 if let Some(qself) = &se.qself {
5159 self.visit_ty(&qself.ty);
5160 }
5161 self.visit_path(&se.path);
5162 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);
5163 match &se.rest {
5164 StructRest::Base(expr) => self.visit_expr(expr),
5165 StructRest::Rest(_span) => {}
5166 StructRest::None | StructRest::NoneWithError(_) => {}
5167 }
5168 }
5169
5170 ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
5171 match self.resolve_label(label.ident) {
5172 Ok((node_id, _)) => {
5173 self.r.current_owner.label_res_map.insert(expr.id, node_id);
5175 self.diag_metadata.unused_labels.swap_remove(&node_id);
5176 }
5177 Err(error) => {
5178 self.report_error(label.ident.span, error);
5179 }
5180 }
5181
5182 visit::walk_expr(self, expr);
5184 }
5185
5186 ExprKind::Break(None, Some(ref e)) => {
5187 self.resolve_expr(e, Some(expr));
5190 }
5191
5192 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::No) => {
5193 self.visit_expr(scrutinee);
5194 self.resolve_pattern_top(pat, PatternSource::Let);
5195 }
5196
5197 ExprKind::Let(ref pat, ref scrutinee, _, Recovered::Yes(_)) => {
5198 self.visit_expr(scrutinee);
5199 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())];
5201 self.resolve_pattern(pat, PatternSource::Let, &mut bindings);
5202 for (_, bindings) in &mut bindings {
5207 for (_, binding) in bindings {
5208 *binding = Res::Err;
5209 }
5210 }
5211 self.apply_pattern_bindings(bindings);
5212 }
5213
5214 ExprKind::If(ref cond, ref then, ref opt_else) => {
5215 self.with_rib(ValueNS, RibKind::Normal, |this| {
5216 let old = this.diag_metadata.in_if_condition.replace(cond);
5217 this.visit_expr(cond);
5218 this.diag_metadata.in_if_condition = old;
5219 this.visit_block(then);
5220 });
5221 if let Some(expr) = opt_else {
5222 self.visit_expr(expr);
5223 }
5224 }
5225
5226 ExprKind::Loop(ref block, label, _) => {
5227 self.resolve_labeled_block(label, expr.id, block)
5228 }
5229
5230 ExprKind::While(ref cond, ref block, label) => {
5231 self.with_resolved_label(label, expr.id, |this| {
5232 this.with_rib(ValueNS, RibKind::Normal, |this| {
5233 let old = this.diag_metadata.in_if_condition.replace(cond);
5234 this.visit_expr(cond);
5235 this.diag_metadata.in_if_condition = old;
5236 this.visit_block(block);
5237 })
5238 });
5239 }
5240
5241 ExprKind::ForLoop(ForLoop { ref pat, ref iter, ref body, label, kind: _ }) => {
5242 self.visit_expr(iter);
5243 self.with_rib(ValueNS, RibKind::Normal, |this| {
5244 this.resolve_pattern_top(pat, PatternSource::For);
5245 this.resolve_labeled_block(label, expr.id, body);
5246 });
5247 }
5248
5249 ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
5250
5251 ExprKind::Field(ref subexpression, _) => {
5253 self.resolve_expr(subexpression, Some(expr));
5254 }
5255 ExprKind::MethodCall(MethodCall { ref seg, ref receiver, ref args, .. }) => {
5256 self.resolve_expr(receiver, Some(expr));
5257 for arg in args {
5258 self.resolve_expr(arg, None);
5259 }
5260 self.visit_path_segment(seg);
5261 }
5262
5263 ExprKind::Call(ref callee, ref arguments) => {
5264 self.resolve_expr(callee, Some(expr));
5265 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
5266 for (idx, argument) in arguments.iter().enumerate() {
5267 if const_args.contains(&idx) {
5270 let is_trivial_const_arg = argument.is_potential_trivial_const_arg();
5273 self.resolve_anon_const_manual(
5274 is_trivial_const_arg,
5275 AnonConstKind::ConstArg(IsRepeatExpr::No),
5276 |this| this.resolve_expr(argument, None),
5277 );
5278 } else {
5279 self.resolve_expr(argument, None);
5280 }
5281 }
5282 }
5283 ExprKind::Type(ref _type_expr, ref _ty) => {
5284 visit::walk_expr(self, expr);
5285 }
5286 ExprKind::Closure(ast::Closure {
5288 binder: ClosureBinder::For { ref generic_params, span },
5289 ..
5290 }) => {
5291 self.with_generic_param_rib(
5292 generic_params,
5293 RibKind::Normal,
5294 expr.id,
5295 LifetimeBinderKind::Closure,
5296 span,
5297 |this| visit::walk_expr(this, expr),
5298 );
5299 }
5300 ExprKind::Closure(..) => visit::walk_expr(self, expr),
5301 ExprKind::Gen(..) => {
5302 self.with_label_rib(RibKind::FnOrCoroutine, |this| visit::walk_expr(this, expr));
5303 }
5304 ExprKind::Repeat(ref elem, ref ct) => {
5305 self.visit_expr(elem);
5306 self.resolve_anon_const(ct, AnonConstKind::ConstArg(IsRepeatExpr::Yes));
5307 }
5308 ExprKind::ConstBlock(ref ct) => {
5309 self.resolve_anon_const(ct, AnonConstKind::InlineConst);
5310 }
5311 ExprKind::Index(ref elem, ref idx, _) => {
5312 self.resolve_expr(elem, Some(expr));
5313 self.visit_expr(idx);
5314 }
5315 ExprKind::Assign(ref lhs, ref rhs, _) => {
5316 if !self.diag_metadata.is_assign_rhs {
5317 self.diag_metadata.in_assignment = Some(expr);
5318 }
5319 self.visit_expr(lhs);
5320 self.diag_metadata.is_assign_rhs = true;
5321 self.diag_metadata.in_assignment = None;
5322 self.visit_expr(rhs);
5323 self.diag_metadata.is_assign_rhs = false;
5324 }
5325 ExprKind::Range(Some(ref start), Some(ref end), RangeLimits::HalfOpen) => {
5326 self.diag_metadata.in_range = Some((start, end));
5327 self.resolve_expr(start, Some(expr));
5328 self.resolve_expr(end, Some(expr));
5329 self.diag_metadata.in_range = None;
5330 }
5331 _ => {
5332 visit::walk_expr(self, expr);
5333 }
5334 }
5335 }
5336
5337 fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
5338 match expr.kind {
5339 ExprKind::Field(_, ident) => {
5340 self.record_traits_in_scope(expr.id, ident);
5345 }
5346 ExprKind::MethodCall(ref call) => {
5347 {
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:5347",
"rustc_resolve::late", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late.rs"),
::tracing_core::__macro_support::Option::Some(5347u32),
::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);
5348 self.record_traits_in_scope(expr.id, call.seg.ident);
5349 }
5350 _ => {
5351 }
5353 }
5354 }
5355
5356 fn record_traits_in_scope(&mut self, node_id: NodeId, ident: Ident) {
5357 let traits = self.r.traits_in_scope(
5358 self.current_trait_ref.as_ref().map(|(module, _)| *module),
5359 &self.parent_scope,
5360 ident.span,
5361 Some((ident.name, ValueNS)),
5362 );
5363 self.r.current_owner.trait_map.insert(node_id, traits);
5364 }
5365
5366 fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option<Res> {
5367 let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions);
5371 let res = *doc_link_resolutions
5372 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5373 .or_default()
5374 .entry((Symbol::intern(path_str), ns))
5375 .or_insert_with_key(|(path, ns)| {
5376 let res = self.r.resolve_rustdoc_path(path.as_str(), *ns, self.parent_scope);
5377 if let Some(res) = res
5378 && let Some(def_id) = res.opt_def_id()
5379 && self.is_invalid_proc_macro_item_for_doc(def_id)
5380 {
5381 return None;
5384 }
5385 res
5386 });
5387 self.r.doc_link_resolutions = doc_link_resolutions;
5388 res
5389 }
5390
5391 fn is_invalid_proc_macro_item_for_doc(&self, did: DefId) -> bool {
5392 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)
5393 || !self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
5394 {
5395 return false;
5396 }
5397 let Some(local_did) = did.as_local() else { return true };
5398 !self.r.proc_macros.contains(&local_did)
5399 }
5400
5401 fn resolve_doc_links(&mut self, attrs: &[Attribute], maybe_exported: MaybeExported<'_>) {
5402 match self.r.tcx.sess.opts.resolve_doc_links {
5403 ResolveDocLinks::None => return,
5404 ResolveDocLinks::ExportedMetadata
5405 if !self.r.tcx.crate_types().iter().copied().any(CrateType::has_metadata)
5406 || !maybe_exported.eval(self.r) =>
5407 {
5408 return;
5409 }
5410 ResolveDocLinks::Exported
5411 if !maybe_exported.eval(self.r)
5412 && !rustdoc::has_primitive_or_keyword_or_attribute_docs(attrs) =>
5413 {
5414 return;
5415 }
5416 ResolveDocLinks::ExportedMetadata
5417 | ResolveDocLinks::Exported
5418 | ResolveDocLinks::All => {}
5419 }
5420
5421 if !attrs.iter().any(|attr| attr.may_have_doc_links()) {
5422 return;
5423 }
5424
5425 let mut need_traits_in_scope = false;
5426 for path_str in rustdoc::attrs_to_preprocessed_links(attrs) {
5427 let mut any_resolved = false;
5429 let mut need_assoc = false;
5430 for ns in [TypeNS, ValueNS, MacroNS] {
5431 if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) {
5432 any_resolved = !#[allow(non_exhaustive_omitted_patterns)] match res {
Res::NonMacroAttr(NonMacroAttrKind::Tool) => true,
_ => false,
}matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool));
5435 } else if ns != MacroNS {
5436 need_assoc = true;
5437 }
5438 }
5439
5440 if need_assoc || !any_resolved {
5442 let mut path = &path_str[..];
5443 while let Some(idx) = path.rfind("::") {
5444 path = &path[..idx];
5445 need_traits_in_scope = true;
5446 for ns in [TypeNS, ValueNS, MacroNS] {
5447 self.resolve_and_cache_rustdoc_path(path, ns);
5448 }
5449 }
5450 }
5451 }
5452
5453 if need_traits_in_scope {
5454 let mut doc_link_traits_in_scope = std::mem::take(&mut self.r.doc_link_traits_in_scope);
5456 doc_link_traits_in_scope
5457 .entry(self.parent_scope.module.nearest_parent_mod().expect_local())
5458 .or_insert_with(|| {
5459 self.r
5460 .traits_in_scope(None, &self.parent_scope, DUMMY_SP, None)
5461 .into_iter()
5462 .filter_map(|tr| {
5463 if self.is_invalid_proc_macro_item_for_doc(tr.def_id) {
5464 return None;
5467 }
5468 Some(tr.def_id)
5469 })
5470 .collect()
5471 });
5472 self.r.doc_link_traits_in_scope = doc_link_traits_in_scope;
5473 }
5474 }
5475
5476 fn lint_unused_qualifications(&mut self, path: &[Segment], ns: Namespace, finalize: Finalize) {
5477 if let Some(seg) = path.first()
5479 && seg.ident.name == kw::PathRoot
5480 {
5481 return;
5482 }
5483
5484 if finalize.path_span.from_expansion()
5485 || path.iter().any(|seg| seg.ident.span.from_expansion())
5486 {
5487 return;
5488 }
5489
5490 let end_pos =
5491 path.iter().position(|seg| seg.has_generic_args).map_or(path.len(), |pos| pos + 1);
5492 let unqualified = path[..end_pos].iter().enumerate().skip(1).rev().find_map(|(i, seg)| {
5493 let ns = if i + 1 == path.len() { ns } else { TypeNS };
5502 let res = self.r.partial_res_map.get(&seg.id?)?.full_res()?;
5503 let binding = self.resolve_ident_in_lexical_scope(seg.ident, ns, None, None)?;
5504 (res == binding.res()).then_some((seg, binding))
5505 });
5506
5507 if let Some((seg, decl)) = unqualified {
5508 self.r.potentially_unnecessary_qualifications.push(UnnecessaryQualification {
5509 decl,
5510 node_id: finalize.node_id,
5511 path_span: finalize.path_span,
5512 removal_span: path[0].ident.span.until(seg.ident.span),
5513 });
5514 }
5515 }
5516
5517 fn resolve_define_opaques(&mut self, define_opaque: &Option<ThinVec<(NodeId, Path)>>) {
5518 if let Some(define_opaque) = define_opaque {
5519 for (id, path) in define_opaque {
5520 self.smart_resolve_path(*id, &None, path, PathSource::DefineOpaques);
5521 }
5522 }
5523 }
5524
5525 fn resolve_eii(&mut self, eii_impl: Option<&EiiImpl>) {
5526 if let Some(EiiImpl { node_id, eii_macro_path, known_eii_macro_resolution, .. }) = eii_impl
5527 {
5528 if let Some(target) = known_eii_macro_resolution {
5531 self.smart_resolve_path(*node_id, &None, target, PathSource::ExternItemImpl);
5532 } else {
5533 self.smart_resolve_path(*node_id, &None, &eii_macro_path, PathSource::Macro);
5534 }
5535 }
5536 }
5537}
5538
5539struct ItemInfoCollector<'a, 'ast, 'ra, 'tcx> {
5543 r: &'a mut Resolver<'ra, 'tcx>,
5544 use_items: Vec<&'ast Item>,
5546}
5547
5548impl ItemInfoCollector<'_, '_, '_, '_> {
5549 fn collect_fn_info(&mut self, decl: &FnDecl, id: NodeId) {
5550 self.r
5551 .delegation_fn_sigs
5552 .insert(self.r.owner_def_id(id), DelegationFnSig { has_self: decl.has_self() });
5553 }
5554}
5555
5556fn required_generic_args_suggestion(generics: &ast::Generics) -> Option<String> {
5557 let required = generics
5558 .params
5559 .iter()
5560 .filter_map(|param| match ¶m.kind {
5561 ast::GenericParamKind::Lifetime => Some("'_"),
5562 ast::GenericParamKind::Type { default } => {
5563 if default.is_none() {
5564 Some("_")
5565 } else {
5566 None
5567 }
5568 }
5569 ast::GenericParamKind::Const { default, .. } => {
5570 if default.is_none() {
5571 Some("_")
5572 } else {
5573 None
5574 }
5575 }
5576 })
5577 .collect::<Vec<_>>();
5578
5579 if required.is_empty() { None } else { Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", required.join(", ")))
})format!("<{}>", required.join(", "))) }
5580}
5581
5582impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, 'ast, '_, '_> {
5583 fn visit_item(&mut self, item: &'ast Item) {
5584 match &item.kind {
5585 ItemKind::TyAlias(TyAlias { generics, .. })
5586 | ItemKind::Const(ConstItem { generics, .. })
5587 | ItemKind::Fn(Fn { generics, .. })
5588 | ItemKind::Enum(_, generics, _)
5589 | ItemKind::Struct(_, generics, _)
5590 | ItemKind::Union(_, generics, _)
5591 | ItemKind::Impl(Impl { generics, .. })
5592 | ItemKind::Trait(Trait { generics, .. })
5593 | ItemKind::TraitAlias(TraitAlias { generics, .. }) => {
5594 if let ItemKind::Fn(Fn { sig, .. }) = &item.kind {
5595 self.collect_fn_info(&sig.decl, item.id);
5596 }
5597
5598 let def_id = self.r.owner_def_id(item.id);
5599 let count = generics
5600 .params
5601 .iter()
5602 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ast::GenericParamKind::Lifetime { .. } => true,
_ => false,
}matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
5603 .count();
5604 self.r.item_generics_num_lifetimes.insert(def_id, count);
5605 }
5606
5607 ItemKind::ForeignMod(ForeignMod { items, .. }) => {
5608 for foreign_item in items {
5609 if let ForeignItemKind::Fn(Fn { sig, .. }) = &foreign_item.kind {
5610 self.collect_fn_info(&sig.decl, foreign_item.id);
5611 }
5612 }
5613 }
5614
5615 ItemKind::Use(..) | ItemKind::ExternCrate(..) => {
5616 self.use_items.push(item);
5617 }
5618
5619 ItemKind::Mod(..)
5620 | ItemKind::Static(..)
5621 | ItemKind::ConstBlock(..)
5622 | ItemKind::MacroDef(..)
5623 | ItemKind::GlobalAsm(..)
5624 | ItemKind::MacCall(..)
5625 | ItemKind::DelegationMac(..) => {}
5626 ItemKind::Delegation(..) => {
5627 }
5632 }
5633 visit::walk_item(self, item)
5634 }
5635
5636 fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
5637 if let AssocItemKind::Fn(Fn { sig, .. }) = &item.kind {
5638 self.collect_fn_info(&sig.decl, item.id);
5639 }
5640
5641 if let AssocItemKind::Type(ast::TyAlias { generics, .. }) = &item.kind {
5642 let def_id = self.r.owner_def_id(item.id);
5643 if let Some(suggestion) = required_generic_args_suggestion(generics) {
5644 self.r.item_required_generic_args_suggestions.insert(def_id, suggestion);
5645 }
5646 }
5647 visit::walk_assoc_item(self, item, ctxt);
5648 }
5649}
5650
5651impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
5652 pub(crate) fn late_resolve_crate<'ast>(
5654 &mut self,
5655 krate: &'ast Crate,
5656 ) -> (Vec<&'ast Item>, Vec<UseError<'tcx>>) {
5657 with_owner(self, CRATE_NODE_ID, |this| {
5658 let mut info_collector = ItemInfoCollector { r: this, use_items: Vec::new() };
5659 visit::walk_crate(&mut info_collector, krate);
5660 let use_items = info_collector.use_items;
5661 let mut late_resolution_visitor = LateResolutionVisitor::new(this);
5662 late_resolution_visitor
5663 .resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID));
5664 visit::walk_crate(&mut late_resolution_visitor, krate);
5665 let LateResolutionVisitor { use_injections, diag_metadata, .. } =
5666 late_resolution_visitor;
5667 for (id, span) in diag_metadata.unused_labels.iter() {
5668 this.lint_buffer.buffer_lint(
5669 lint::builtin::UNUSED_LABELS,
5670 *id,
5671 *span,
5672 crate::diagnostics::UnusedLabel,
5673 );
5674 }
5675 (use_items, use_injections)
5676 })
5677 }
5678}
5679
5680fn def_id_matches_path(tcx: TyCtxt<'_>, mut def_id: DefId, expected_path: &[&str]) -> bool {
5682 let mut path = expected_path.iter().rev();
5683 while let (Some(parent), Some(next_step)) = (tcx.opt_parent(def_id), path.next()) {
5684 if !tcx.opt_item_name(def_id).is_some_and(|n| n.as_str() == *next_step) {
5685 return false;
5686 }
5687 def_id = parent;
5688 }
5689 true
5690}