1use std::borrow::Cow;
4use std::iter;
5use std::ops::Deref;
6
7use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty};
8use rustc_ast::{
9 self as ast, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericParam, GenericParamKind,
10 Item, ItemKind, MethodCall, NodeId, Path, PathSegment, Ty, TyKind,
11};
12use rustc_ast_pretty::pprust::where_bound_predicate_to_string;
13use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
14use rustc_errors::codes::*;
15use rustc_errors::{
16 Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
17 struct_span_code_err,
18};
19use rustc_hir as hir;
20use rustc_hir::attrs::AttributeKind;
21use rustc_hir::def::Namespace::{self, *};
22use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, MacroKinds};
23use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
24use rustc_hir::{MissingLifetimeKind, PrimTy};
25use rustc_middle::ty;
26use rustc_session::{Session, lint};
27use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
28use rustc_span::edition::Edition;
29use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
30use thin_vec::ThinVec;
31use tracing::debug;
32
33use super::NoConstantGenericsReason;
34use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
35use crate::late::{
36 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
37 LifetimeUseSet, QSelf, RibKind,
38};
39use crate::ty::fast_reject::SimplifiedType;
40use crate::{
41 Module, ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Resolver,
42 ScopeSet, Segment, errors, path_names_to_string,
43};
44
45type Res = def::Res<ast::NodeId>;
46
47enum AssocSuggestion {
49 Field(Span),
50 MethodWithSelf { called: bool },
51 AssocFn { called: bool },
52 AssocType,
53 AssocConst,
54}
55
56impl AssocSuggestion {
57 fn action(&self) -> &'static str {
58 match self {
59 AssocSuggestion::Field(_) => "use the available field",
60 AssocSuggestion::MethodWithSelf { called: true } => {
61 "call the method with the fully-qualified path"
62 }
63 AssocSuggestion::MethodWithSelf { called: false } => {
64 "refer to the method with the fully-qualified path"
65 }
66 AssocSuggestion::AssocFn { called: true } => "call the associated function",
67 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
68 AssocSuggestion::AssocConst => "use the associated `const`",
69 AssocSuggestion::AssocType => "use the associated type",
70 }
71 }
72}
73
74fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
75 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
76}
77
78fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
79 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
80}
81
82fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
84 let variant_path = &suggestion.path;
85 let variant_path_string = path_names_to_string(variant_path);
86
87 let path_len = suggestion.path.segments.len();
88 let enum_path = ast::Path {
89 span: suggestion.path.span,
90 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
91 tokens: None,
92 };
93 let enum_path_string = path_names_to_string(&enum_path);
94
95 (variant_path_string, enum_path_string)
96}
97
98#[derive(#[automatically_derived]
impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MissingLifetime {
#[inline]
fn clone(&self) -> MissingLifetime {
let _: ::core::clone::AssertParamIsClone<NodeId>;
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<MissingLifetimeKind>;
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MissingLifetime {
#[inline]
fn eq(&self, other: &MissingLifetime) -> bool {
self.id == other.id && self.id_for_lint == other.id_for_lint &&
self.span == other.span && self.kind == other.kind &&
self.count == other.count
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MissingLifetime {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {
let _: ::core::cmp::AssertParamIsEq<NodeId>;
let _: ::core::cmp::AssertParamIsEq<Span>;
let _: ::core::cmp::AssertParamIsEq<MissingLifetimeKind>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MissingLifetime {
#[inline]
fn partial_cmp(&self, other: &MissingLifetime)
-> ::core::option::Option<::core::cmp::Ordering> {
match ::core::cmp::PartialOrd::partial_cmp(&self.id, &other.id) {
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
match ::core::cmp::PartialOrd::partial_cmp(&self.id_for_lint,
&other.id_for_lint) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
match ::core::cmp::PartialOrd::partial_cmp(&self.span,
&other.span) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
match ::core::cmp::PartialOrd::partial_cmp(&self.kind,
&other.kind) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
::core::cmp::PartialOrd::partial_cmp(&self.count,
&other.count),
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
}
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MissingLifetime {
#[inline]
fn cmp(&self, other: &MissingLifetime) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.id, &other.id) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.id_for_lint,
&other.id_for_lint) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.span, &other.span) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.kind, &other.kind) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.count, &other.count),
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::fmt::Debug for MissingLifetime {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field5_finish(f,
"MissingLifetime", "id", &self.id, "id_for_lint",
&self.id_for_lint, "span", &self.span, "kind", &self.kind,
"count", &&self.count)
}
}Debug)]
100pub(super) struct MissingLifetime {
101 pub id: NodeId,
103 pub id_for_lint: NodeId,
110 pub span: Span,
112 pub kind: MissingLifetimeKind,
114 pub count: usize,
116}
117
118#[derive(#[automatically_derived]
impl ::core::clone::Clone for ElisionFnParameter {
#[inline]
fn clone(&self) -> ElisionFnParameter {
ElisionFnParameter {
index: ::core::clone::Clone::clone(&self.index),
ident: ::core::clone::Clone::clone(&self.ident),
lifetime_count: ::core::clone::Clone::clone(&self.lifetime_count),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ElisionFnParameter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ElisionFnParameter", "index", &self.index, "ident", &self.ident,
"lifetime_count", &self.lifetime_count, "span", &&self.span)
}
}Debug)]
121pub(super) struct ElisionFnParameter {
122 pub index: usize,
124 pub ident: Option<Ident>,
126 pub lifetime_count: usize,
128 pub span: Span,
130}
131
132#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LifetimeElisionCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LifetimeElisionCandidate::Ignore =>
::core::fmt::Formatter::write_str(f, "Ignore"),
LifetimeElisionCandidate::Named =>
::core::fmt::Formatter::write_str(f, "Named"),
LifetimeElisionCandidate::Missing(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Missing", &__self_0),
}
}
}Debug)]
135pub(super) enum LifetimeElisionCandidate {
136 Ignore,
138 Named,
140 Missing(MissingLifetime),
141}
142
143#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BaseError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["msg", "fallback_label", "span", "span_label", "could_be_expr",
"suggestion", "module"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.msg, &self.fallback_label, &self.span, &self.span_label,
&self.could_be_expr, &self.suggestion, &&self.module];
::core::fmt::Formatter::debug_struct_fields_finish(f, "BaseError",
names, values)
}
}Debug)]
145struct BaseError {
146 msg: String,
147 fallback_label: String,
148 span: Span,
149 span_label: Option<(Span, &'static str)>,
150 could_be_expr: bool,
151 suggestion: Option<(Span, &'static str, String)>,
152 module: Option<DefId>,
153}
154
155#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TypoCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TypoCandidate::Typo(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Typo",
&__self_0),
TypoCandidate::Shadowed(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Shadowed", __self_0, &__self_1),
TypoCandidate::None =>
::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug)]
156enum TypoCandidate {
157 Typo(TypoSuggestion),
158 Shadowed(Res, Option<Span>),
159 None,
160}
161
162impl TypoCandidate {
163 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
164 match self {
165 TypoCandidate::Typo(sugg) => Some(sugg),
166 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
167 }
168 }
169}
170
171impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
172 fn make_base_error(
173 &mut self,
174 path: &[Segment],
175 span: Span,
176 source: PathSource<'_, 'ast, 'ra>,
177 res: Option<Res>,
178 ) -> BaseError {
179 let mut expected = source.descr_expected();
181 let path_str = Segment::names_to_string(path);
182 let item_str = path.last().unwrap().ident;
183
184 if let Some(res) = res {
185 BaseError {
186 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
expected, res.descr(), path_str))
})format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
187 fallback_label: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"),
188 span,
189 span_label: match res {
190 Res::Def(DefKind::TyParam, def_id) => {
191 Some((self.r.def_span(def_id), "found this type parameter"))
192 }
193 _ => None,
194 },
195 could_be_expr: match res {
196 Res::Def(DefKind::Fn, _) => {
197 self.r
199 .tcx
200 .sess
201 .source_map()
202 .span_to_snippet(span)
203 .is_ok_and(|snippet| snippet.ends_with(')'))
204 }
205 Res::Def(
206 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
207 _,
208 )
209 | Res::SelfCtor(_)
210 | Res::PrimTy(_)
211 | Res::Local(_) => true,
212 _ => false,
213 },
214 suggestion: None,
215 module: None,
216 }
217 } else {
218 let mut span_label = None;
219 let item_ident = path.last().unwrap().ident;
220 let item_span = item_ident.span;
221 let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
222 {
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/diagnostics.rs:222",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(222u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_impl_items"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.diag_metadata.current_impl_items)
as &dyn Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_impl_items);
223 {
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/diagnostics.rs:223",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(223u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["self.diag_metadata.current_function"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.diag_metadata.current_function)
as &dyn Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_function);
224 let suggestion = if self.current_trait_ref.is_none()
225 && let Some((fn_kind, _)) = self.diag_metadata.current_function
226 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
227 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
228 && let Some(items) = self.diag_metadata.current_impl_items
229 && let Some(item) = items.iter().find(|i| {
230 i.kind.ident().is_some_and(|ident| {
231 ident.name == item_str.name && !sig.span.contains(item_span)
233 })
234 }) {
235 let sp = item_span.shrink_to_lo();
236
237 let field = match source {
240 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
241 expr.fields.iter().find(|f| f.ident == item_ident)
242 }
243 _ => None,
244 };
245 let pre = if let Some(field) = field
246 && field.is_shorthand
247 {
248 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", item_ident))
})format!("{item_ident}: ")
249 } else {
250 String::new()
251 };
252 let is_call = match field {
255 Some(ast::ExprField { expr, .. }) => {
256 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Call(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Call(..))
257 }
258 _ => #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(
259 source,
260 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
261 ),
262 };
263
264 match &item.kind {
265 AssocItemKind::Fn(fn_)
266 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
267 {
268 span_label = Some((
272 fn_.ident.span,
273 "a method by that name is available on `Self` here",
274 ));
275 None
276 }
277 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
278 span_label = Some((
279 fn_.ident.span,
280 "an associated function by that name is available on `Self` here",
281 ));
282 None
283 }
284 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
285 Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self.")))
286 }
287 AssocItemKind::Fn(_) => Some((
288 sp,
289 "consider using the associated function on `Self`",
290 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
291 )),
292 AssocItemKind::Const(..) => Some((
293 sp,
294 "consider using the associated constant on `Self`",
295 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
296 )),
297 _ => None,
298 }
299 } else {
300 None
301 };
302 (String::new(), "this scope".to_string(), None, suggestion)
303 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
304 if self.r.tcx.sess.edition() > Edition::Edition2015 {
305 expected = "crate";
308 (String::new(), "the list of imported crates".to_string(), None, None)
309 } else {
310 (
311 String::new(),
312 "the crate root".to_string(),
313 Some(CRATE_DEF_ID.to_def_id()),
314 None,
315 )
316 }
317 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
318 (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
319 } else {
320 let mod_path = &path[..path.len() - 1];
321 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
322 let mod_prefix = match mod_res {
323 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
324 _ => None,
325 };
326
327 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
328
329 let mod_prefix =
330 mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", res.descr()))
})format!("{} ", res.descr()));
331 (mod_prefix, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
Segment::names_to_string(mod_path)))
})format!("`{}`", Segment::names_to_string(mod_path)), module_did, None)
332 };
333
334 let (fallback_label, suggestion) = if path_str == "async"
335 && expected.starts_with("struct")
336 {
337 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
338 } else {
339 let override_suggestion =
341 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
342 let item_typo = item_str.to_string().to_lowercase();
343 Some((item_span, "you may want to use a bool value instead", item_typo))
344 } else if item_str.as_str() == "printf" {
347 Some((
348 item_span,
349 "you may have meant to use the `print` macro",
350 "print!".to_owned(),
351 ))
352 } else {
353 suggestion
354 };
355 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not found in {0}", mod_str))
})format!("not found in {mod_str}"), override_suggestion)
356 };
357
358 BaseError {
359 msg: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}",
expected, item_str, mod_prefix, mod_str))
})format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
360 fallback_label,
361 span: item_span,
362 span_label,
363 could_be_expr: false,
364 suggestion,
365 module,
366 }
367 }
368 }
369
370 pub(crate) fn smart_resolve_partial_mod_path_errors(
378 &mut self,
379 prefix_path: &[Segment],
380 following_seg: Option<&Segment>,
381 ) -> Vec<ImportSuggestion> {
382 if let Some(segment) = prefix_path.last()
383 && let Some(following_seg) = following_seg
384 {
385 let candidates = self.r.lookup_import_candidates(
386 segment.ident,
387 Namespace::TypeNS,
388 &self.parent_scope,
389 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
390 );
391 candidates
393 .into_iter()
394 .filter(|candidate| {
395 if let Some(def_id) = candidate.did
396 && let Some(module) = self.r.get_module(def_id)
397 {
398 Some(def_id) != self.parent_scope.module.opt_def_id()
399 && self
400 .r
401 .resolutions(module)
402 .borrow()
403 .iter()
404 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
405 } else {
406 false
407 }
408 })
409 .collect::<Vec<_>>()
410 } else {
411 Vec::new()
412 }
413 }
414
415 #[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("smart_resolve_report_errors",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(417u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["path",
"following_seg", "span", "source", "res", "qself"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
as &dyn 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:
(Diag<'tcx>, Vec<ImportSuggestion>) = loop {};
return __tracing_attr_fake_return;
}
{
{
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/diagnostics.rs:427",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(427u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["res", "source"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&res) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&source) as
&dyn Value))])
});
} else { ; }
};
let base_error = self.make_base_error(path, span, source, res);
let code = source.error_code(res.is_some());
let mut err =
self.r.dcx().struct_span_err(base_error.span,
base_error.msg.clone());
err.code(code);
if let Some(within_macro_span) =
base_error.span.within_macro(span,
self.r.tcx.sess.source_map()) {
err.span_label(within_macro_span,
"due to this macro variable");
}
self.detect_missing_binding_available_from_pattern(&mut err, path,
following_seg);
self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
self.suggest_range_struct_destructuring(&mut err, path, source);
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err,
source, res, base_error.span);
if let Some((span, label)) = base_error.span_label {
err.span_label(span, label);
}
if let Some(ref sugg) = base_error.suggestion {
err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2,
Applicability::MaybeIncorrect);
}
self.suggest_changing_type_to_const_param(&mut err, res, source,
path, following_seg, span);
self.explain_functions_in_pattern(&mut err, res, source);
if self.suggest_pattern_match_with_let(&mut err, source, span) {
err.span_label(base_error.span, base_error.fallback_label);
return (err, Vec::new());
}
self.suggest_self_or_self_ref(&mut err, path, span);
self.detect_assoc_type_constraint_meant_as_path(&mut err,
&base_error);
self.detect_rtn_with_fully_qualified_path(&mut err, path,
following_seg, span, source, res, qself);
if self.suggest_self_ty(&mut err, source, path, span) ||
self.suggest_self_value(&mut err, source, path, span) {
return (err, Vec::new());
}
if let Some((did, item)) =
self.lookup_doc_alias_name(path, source.namespace()) {
let item_name = item.name;
let suggestion_name = self.r.tcx.item_name(did);
err.span_suggestion(item.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has a name defined in the doc alias attribute as `{1}`",
suggestion_name, item_name))
}), suggestion_name, Applicability::MaybeIncorrect);
return (err, Vec::new());
};
let (found, suggested_candidates, mut candidates) =
self.try_lookup_name_relaxed(&mut err, source, path,
following_seg, span, res, &base_error);
if found { return (err, candidates); }
if self.suggest_shadowed(&mut err, source, path, following_seg,
span) {
candidates.clear();
}
let mut fallback =
self.suggest_trait_and_bounds(&mut err, source, res, span,
&base_error);
fallback |=
self.suggest_typo(&mut err, source, path, following_seg, span,
&base_error, suggested_candidates);
if fallback {
err.span_label(base_error.span, base_error.fallback_label);
}
self.err_code_special_cases(&mut err, source, path, span);
let module =
base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
self.r.find_cfg_stripped(&mut err,
&path.last().unwrap().ident.name, module);
(err, candidates)
}
}
}#[tracing::instrument(skip(self), level = "debug")]
418 pub(crate) fn smart_resolve_report_errors(
419 &mut self,
420 path: &[Segment],
421 following_seg: Option<&Segment>,
422 span: Span,
423 source: PathSource<'_, 'ast, 'ra>,
424 res: Option<Res>,
425 qself: Option<&QSelf>,
426 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
427 debug!(?res, ?source);
428 let base_error = self.make_base_error(path, span, source, res);
429
430 let code = source.error_code(res.is_some());
431 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
432 err.code(code);
433
434 if let Some(within_macro_span) =
437 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
438 {
439 err.span_label(within_macro_span, "due to this macro variable");
440 }
441
442 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
443 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
444 self.suggest_range_struct_destructuring(&mut err, path, source);
445 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
446
447 if let Some((span, label)) = base_error.span_label {
448 err.span_label(span, label);
449 }
450
451 if let Some(ref sugg) = base_error.suggestion {
452 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
453 }
454
455 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
456 self.explain_functions_in_pattern(&mut err, res, source);
457
458 if self.suggest_pattern_match_with_let(&mut err, source, span) {
459 err.span_label(base_error.span, base_error.fallback_label);
461 return (err, Vec::new());
462 }
463
464 self.suggest_self_or_self_ref(&mut err, path, span);
465 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
466 self.detect_rtn_with_fully_qualified_path(
467 &mut err,
468 path,
469 following_seg,
470 span,
471 source,
472 res,
473 qself,
474 );
475 if self.suggest_self_ty(&mut err, source, path, span)
476 || self.suggest_self_value(&mut err, source, path, span)
477 {
478 return (err, Vec::new());
479 }
480
481 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
482 let item_name = item.name;
483 let suggestion_name = self.r.tcx.item_name(did);
484 err.span_suggestion(
485 item.span,
486 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
487 suggestion_name,
488 Applicability::MaybeIncorrect
489 );
490
491 return (err, Vec::new());
492 };
493
494 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
495 &mut err,
496 source,
497 path,
498 following_seg,
499 span,
500 res,
501 &base_error,
502 );
503 if found {
504 return (err, candidates);
505 }
506
507 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
508 candidates.clear();
510 }
511
512 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
513 fallback |= self.suggest_typo(
514 &mut err,
515 source,
516 path,
517 following_seg,
518 span,
519 &base_error,
520 suggested_candidates,
521 );
522
523 if fallback {
524 err.span_label(base_error.span, base_error.fallback_label);
526 }
527 self.err_code_special_cases(&mut err, source, path, span);
528
529 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
530 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
531
532 (err, candidates)
533 }
534
535 fn detect_rtn_with_fully_qualified_path(
536 &self,
537 err: &mut Diag<'_>,
538 path: &[Segment],
539 following_seg: Option<&Segment>,
540 span: Span,
541 source: PathSource<'_, '_, '_>,
542 res: Option<Res>,
543 qself: Option<&QSelf>,
544 ) {
545 if let Some(Res::Def(DefKind::AssocFn, _)) = res
546 && let PathSource::TraitItem(TypeNS, _) = source
547 && let None = following_seg
548 && let Some(qself) = qself
549 && let TyKind::Path(None, ty_path) = &qself.ty.kind
550 && ty_path.segments.len() == 1
551 && self.diag_metadata.current_where_predicate.is_some()
552 {
553 err.span_suggestion_verbose(
554 span,
555 "you might have meant to use the return type notation syntax",
556 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}(..)",
ty_path.segments[0].ident, path[path.len() - 1].ident))
})format!("{}::{}(..)", ty_path.segments[0].ident, path[path.len() - 1].ident),
557 Applicability::MaybeIncorrect,
558 );
559 }
560 }
561
562 fn detect_assoc_type_constraint_meant_as_path(
563 &self,
564 err: &mut Diag<'_>,
565 base_error: &BaseError,
566 ) {
567 let Some(ty) = self.diag_metadata.current_type_path else {
568 return;
569 };
570 let TyKind::Path(_, path) = &ty.kind else {
571 return;
572 };
573 for segment in &path.segments {
574 let Some(params) = &segment.args else {
575 continue;
576 };
577 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
578 continue;
579 };
580 for param in ¶ms.args {
581 let ast::AngleBracketedArg::Constraint(constraint) = param else {
582 continue;
583 };
584 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
585 continue;
586 };
587 for bound in bounds {
588 let ast::GenericBound::Trait(trait_ref) = bound else {
589 continue;
590 };
591 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
592 && base_error.span == trait_ref.span
593 {
594 err.span_suggestion_verbose(
595 constraint.ident.span.between(trait_ref.span),
596 "you might have meant to write a path instead of an associated type bound",
597 "::",
598 Applicability::MachineApplicable,
599 );
600 }
601 }
602 }
603 }
604 }
605
606 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
607 if !self.self_type_is_available() {
608 return;
609 }
610 let Some(path_last_segment) = path.last() else { return };
611 let item_str = path_last_segment.ident;
612 if ["this", "my"].contains(&item_str.as_str()) {
614 err.span_suggestion_short(
615 span,
616 "you might have meant to use `self` here instead",
617 "self",
618 Applicability::MaybeIncorrect,
619 );
620 if !self.self_value_is_available(path[0].ident.span) {
621 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
622 &self.diag_metadata.current_function
623 {
624 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
625 (param.span.shrink_to_lo(), "&self, ")
626 } else {
627 (
628 self.r
629 .tcx
630 .sess
631 .source_map()
632 .span_through_char(*fn_span, '(')
633 .shrink_to_hi(),
634 "&self",
635 )
636 };
637 err.span_suggestion_verbose(
638 span,
639 "if you meant to use `self`, you are also missing a `self` receiver \
640 argument",
641 sugg,
642 Applicability::MaybeIncorrect,
643 );
644 }
645 }
646 }
647 }
648
649 fn try_lookup_name_relaxed(
650 &mut self,
651 err: &mut Diag<'_>,
652 source: PathSource<'_, '_, '_>,
653 path: &[Segment],
654 following_seg: Option<&Segment>,
655 span: Span,
656 res: Option<Res>,
657 base_error: &BaseError,
658 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
659 let span = match following_seg {
660 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
661 path[0].ident.span.to(path[path.len() - 1].ident.span)
664 }
665 _ => span,
666 };
667 let mut suggested_candidates = FxHashSet::default();
668 let ident = path.last().unwrap().ident;
670 let is_expected = &|res| source.is_expected(res);
671 let ns = source.namespace();
672 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
673 let path_str = Segment::names_to_string(path);
674 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
675 let mut candidates = self
676 .r
677 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
678 .into_iter()
679 .filter(|ImportSuggestion { did, .. }| {
680 match (did, res.and_then(|res| res.opt_def_id())) {
681 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
682 _ => true,
683 }
684 })
685 .collect::<Vec<_>>();
686 let intrinsic_candidates: Vec<_> = candidates
689 .extract_if(.., |sugg| {
690 let path = path_names_to_string(&sugg.path);
691 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
692 })
693 .collect();
694 if candidates.is_empty() {
695 candidates = intrinsic_candidates;
697 }
698 let crate_def_id = CRATE_DEF_ID.to_def_id();
699 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
700 let mut enum_candidates: Vec<_> = self
701 .r
702 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
703 .into_iter()
704 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
705 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
706 .collect();
707 if !enum_candidates.is_empty() {
708 enum_candidates.sort();
709
710 let preamble = if res.is_none() {
713 let others = match enum_candidates.len() {
714 1 => String::new(),
715 2 => " and 1 other".to_owned(),
716 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
717 };
718 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there is an enum variant `{0}`{1}; ",
enum_candidates[0].0, others))
})format!("there is an enum variant `{}`{}; ", enum_candidates[0].0, others)
719 } else {
720 String::new()
721 };
722 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}try using the variant\'s enum",
preamble))
})format!("{preamble}try using the variant's enum");
723
724 suggested_candidates.extend(
725 enum_candidates
726 .iter()
727 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
728 );
729 err.span_suggestions(
730 span,
731 msg,
732 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
733 Applicability::MachineApplicable,
734 );
735 }
736 }
737
738 let typo_sugg = self
740 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
741 .to_opt_suggestion()
742 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
743 if let [segment] = path
744 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
745 && self.self_type_is_available()
746 {
747 if let Some(candidate) =
748 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
749 {
750 let self_is_available = self.self_value_is_available(segment.ident.span);
751 let pre = match source {
754 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
755 if expr
756 .fields
757 .iter()
758 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
759 {
760 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
761 }
762 _ => String::new(),
763 };
764 match candidate {
765 AssocSuggestion::Field(field_span) => {
766 if self_is_available {
767 let source_map = self.r.tcx.sess.source_map();
768 let field_is_format_named_arg = source_map
770 .span_to_source(span, |s, start, _| {
771 Ok(s.get(start - 1..start) == Some("{"))
772 });
773 if let Ok(true) = field_is_format_named_arg {
774 err.help(
775 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the available field in a format string: `\"{{}}\", self.{0}`",
segment.ident.name))
})format!("you might have meant to use the available field in a format string: `\"{{}}\", self.{}`", segment.ident.name),
776 );
777 } else {
778 err.span_suggestion_verbose(
779 span.shrink_to_lo(),
780 "you might have meant to use the available field",
781 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
782 Applicability::MaybeIncorrect,
783 );
784 }
785 } else {
786 err.span_label(field_span, "a field by that name exists in `Self`");
787 }
788 }
789 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
790 let msg = if called {
791 "you might have meant to call the method"
792 } else {
793 "you might have meant to refer to the method"
794 };
795 err.span_suggestion_verbose(
796 span.shrink_to_lo(),
797 msg,
798 "self.",
799 Applicability::MachineApplicable,
800 );
801 }
802 AssocSuggestion::MethodWithSelf { .. }
803 | AssocSuggestion::AssocFn { .. }
804 | AssocSuggestion::AssocConst
805 | AssocSuggestion::AssocType => {
806 err.span_suggestion_verbose(
807 span.shrink_to_lo(),
808 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to {0}",
candidate.action()))
})format!("you might have meant to {}", candidate.action()),
809 "Self::",
810 Applicability::MachineApplicable,
811 );
812 }
813 }
814 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
815 return (true, suggested_candidates, candidates);
816 }
817
818 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
820 let mut args_snippet = String::new();
821 if let Some(args_span) = args_span
822 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
823 {
824 args_snippet = snippet;
825 }
826
827 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
828 let private_fields = self.has_private_fields(def_id);
829 let adjust_error_message =
830 private_fields && self.is_struct_with_fn_ctor(def_id);
831 if adjust_error_message {
832 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
833 }
834
835 if private_fields {
836 err.note("constructor is not visible here due to private fields");
837 }
838 } else {
839 err.span_suggestion(
840 call_span,
841 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
842 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
843 Applicability::MachineApplicable,
844 );
845 }
846
847 return (true, suggested_candidates, candidates);
848 }
849 }
850
851 if let Some(res) = res {
853 if self.smart_resolve_context_dependent_help(
854 err,
855 span,
856 source,
857 path,
858 res,
859 &path_str,
860 &base_error.fallback_label,
861 ) {
862 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
864 return (true, suggested_candidates, candidates);
865 }
866 }
867
868 if let Some(rib) = &self.last_block_rib {
870 for (ident, &res) in &rib.bindings {
871 if let Res::Local(_) = res
872 && path.len() == 1
873 && ident.span.eq_ctxt(path[0].ident.span)
874 && ident.name == path[0].ident.name
875 {
876 err.span_help(
877 ident.span,
878 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the binding `{0}` is available in a different scope in the same function",
path_str))
})format!("the binding `{path_str}` is available in a different scope in the same function"),
879 );
880 return (true, suggested_candidates, candidates);
881 }
882 }
883 }
884
885 if candidates.is_empty() {
886 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
887 }
888
889 (false, suggested_candidates, candidates)
890 }
891
892 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
893 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
894 for resolution in r.resolutions(m).borrow().values() {
895 let Some(did) =
896 resolution.borrow().best_decl().and_then(|binding| binding.res().opt_def_id())
897 else {
898 continue;
899 };
900 if did.is_local() {
901 continue;
905 }
906 if let Some(d) =
907 {
'done:
{
for i in r.tcx.get_all_attrs(did) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::Doc(d)) => {
break 'done Some(d);
}
_ => {}
}
}
None
}
}hir::find_attr!(r.tcx.get_all_attrs(did), AttributeKind::Doc(d) => d)
908 && d.aliases.contains_key(&item_name)
909 {
910 return Some(did);
911 }
912 }
913 None
914 };
915
916 if path.len() == 1 {
917 for rib in self.ribs[ns].iter().rev() {
918 let item = path[0].ident;
919 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
920 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
921 {
922 return Some((did, item));
923 }
924 }
925 } else {
926 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
935 let Some(id) = seg.id else {
936 continue;
937 };
938 let Some(res) = self.r.partial_res_map.get(&id) else {
939 continue;
940 };
941 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
942 && let module = self.r.expect_module(module)
943 && let item = path[idx + 1].ident
944 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
945 {
946 return Some((did, item));
947 }
948 break;
949 }
950 }
951 None
952 }
953
954 fn suggest_trait_and_bounds(
955 &self,
956 err: &mut Diag<'_>,
957 source: PathSource<'_, '_, '_>,
958 res: Option<Res>,
959 span: Span,
960 base_error: &BaseError,
961 ) -> bool {
962 let is_macro =
963 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
964 let mut fallback = false;
965
966 if let (
967 PathSource::Trait(AliasPossibility::Maybe),
968 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
969 false,
970 ) = (source, res, is_macro)
971 && let Some(bounds @ [first_bound, .., last_bound]) =
972 self.diag_metadata.current_trait_object
973 {
974 fallback = true;
975 let spans: Vec<Span> = bounds
976 .iter()
977 .map(|bound| bound.span())
978 .filter(|&sp| sp != base_error.span)
979 .collect();
980
981 let start_span = first_bound.span();
982 let end_span = last_bound.span();
984 let last_bound_span = spans.last().cloned().unwrap();
986 let mut multi_span: MultiSpan = spans.clone().into();
987 for sp in spans {
988 let msg = if sp == last_bound_span {
989 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...because of {0} bound{1}",
if bounds.len() - 1 == 1 { "this" } else { "these" },
if bounds.len() - 1 == 1 { "" } else { "s" }))
})format!(
990 "...because of {these} bound{s}",
991 these = pluralize!("this", bounds.len() - 1),
992 s = pluralize!(bounds.len() - 1),
993 )
994 } else {
995 String::new()
996 };
997 multi_span.push_span_label(sp, msg);
998 }
999 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1000 err.span_help(
1001 multi_span,
1002 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1003 auto-traits; structs and enums can't be bound in that way",
1004 );
1005 if bounds.iter().all(|bound| match bound {
1006 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1007 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1008 }) {
1009 let mut sugg = ::alloc::vec::Vec::new()vec![];
1010 if base_error.span != start_span {
1011 sugg.push((start_span.until(base_error.span), String::new()));
1012 }
1013 if base_error.span != end_span {
1014 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1015 }
1016
1017 err.multipart_suggestion(
1018 "if you meant to use a type and not a trait here, remove the bounds",
1019 sugg,
1020 Applicability::MaybeIncorrect,
1021 );
1022 }
1023 }
1024
1025 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1026 fallback
1027 }
1028
1029 fn suggest_typo(
1030 &mut self,
1031 err: &mut Diag<'_>,
1032 source: PathSource<'_, 'ast, 'ra>,
1033 path: &[Segment],
1034 following_seg: Option<&Segment>,
1035 span: Span,
1036 base_error: &BaseError,
1037 suggested_candidates: FxHashSet<String>,
1038 ) -> bool {
1039 let is_expected = &|res| source.is_expected(res);
1040 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1041 let typo_sugg =
1042 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1043 let mut fallback = false;
1044 let typo_sugg = typo_sugg
1045 .to_opt_suggestion()
1046 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1047 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1048 fallback = true;
1049 match self.diag_metadata.current_let_binding {
1050 Some((pat_sp, Some(ty_sp), None))
1051 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1052 {
1053 err.span_suggestion_short(
1054 pat_sp.between(ty_sp),
1055 "use `=` if you meant to assign",
1056 " = ",
1057 Applicability::MaybeIncorrect,
1058 );
1059 }
1060 _ => {}
1061 }
1062
1063 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1065 self.r.add_typo_suggestion(err, suggestion, ident_span);
1066 }
1067
1068 if self.let_binding_suggestion(err, ident_span) {
1069 fallback = false;
1070 }
1071
1072 fallback
1073 }
1074
1075 fn suggest_shadowed(
1076 &mut self,
1077 err: &mut Diag<'_>,
1078 source: PathSource<'_, '_, '_>,
1079 path: &[Segment],
1080 following_seg: Option<&Segment>,
1081 span: Span,
1082 ) -> bool {
1083 let is_expected = &|res| source.is_expected(res);
1084 let typo_sugg =
1085 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1086 let is_in_same_file = &|sp1, sp2| {
1087 let source_map = self.r.tcx.sess.source_map();
1088 let file1 = source_map.span_to_filename(sp1);
1089 let file2 = source_map.span_to_filename(sp2);
1090 file1 == file2
1091 };
1092 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1097 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1098 {
1099 err.span_label(
1100 sugg_span,
1101 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to refer to this {0}",
res.descr()))
})format!("you might have meant to refer to this {}", res.descr()),
1102 );
1103 return true;
1104 }
1105 false
1106 }
1107
1108 fn err_code_special_cases(
1109 &mut self,
1110 err: &mut Diag<'_>,
1111 source: PathSource<'_, '_, '_>,
1112 path: &[Segment],
1113 span: Span,
1114 ) {
1115 if let Some(err_code) = err.code {
1116 if err_code == E0425 {
1117 for label_rib in &self.label_ribs {
1118 for (label_ident, node_id) in &label_rib.bindings {
1119 let ident = path.last().unwrap().ident;
1120 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1121 err.span_label(label_ident.span, "a label with a similar name exists");
1122 if let PathSource::Expr(Some(Expr {
1123 kind: ExprKind::Break(None, Some(_)),
1124 ..
1125 })) = source
1126 {
1127 err.span_suggestion(
1128 span,
1129 "use the similarly named label",
1130 label_ident.name,
1131 Applicability::MaybeIncorrect,
1132 );
1133 self.diag_metadata.unused_labels.swap_remove(node_id);
1135 }
1136 }
1137 }
1138 }
1139
1140 self.suggest_ident_hidden_by_hygiene(err, path, span);
1141 if let Some(correct) = Self::likely_rust_type(path) {
1143 err.span_suggestion(
1144 span,
1145 "perhaps you intended to use this type",
1146 correct,
1147 Applicability::MaybeIncorrect,
1148 );
1149 }
1150 }
1151 }
1152 }
1153
1154 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1155 let [segment] = path else { return };
1156
1157 let ident = segment.ident;
1158 let callsite_span = span.source_callsite();
1159 for rib in self.ribs[ValueNS].iter().rev() {
1160 for (binding_ident, _) in &rib.bindings {
1161 if binding_ident.name == ident.name
1163 && !binding_ident.span.eq_ctxt(span)
1164 && !binding_ident.span.from_expansion()
1165 && binding_ident.span.lo() < callsite_span.lo()
1166 {
1167 err.span_help(
1168 binding_ident.span,
1169 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1170 );
1171 return;
1172 }
1173
1174 if binding_ident.name == ident.name
1176 && binding_ident.span.from_expansion()
1177 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1178 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1179 {
1180 err.span_help(
1181 binding_ident.span,
1182 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1183 );
1184 return;
1185 }
1186 }
1187 }
1188 }
1189
1190 fn suggest_self_ty(
1192 &self,
1193 err: &mut Diag<'_>,
1194 source: PathSource<'_, '_, '_>,
1195 path: &[Segment],
1196 span: Span,
1197 ) -> bool {
1198 if !is_self_type(path, source.namespace()) {
1199 return false;
1200 }
1201 err.code(E0411);
1202 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1203 if let Some(item) = self.diag_metadata.current_item
1204 && let Some(ident) = item.kind.ident()
1205 {
1206 err.span_label(
1207 ident.span,
1208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`Self` not allowed in {0} {1}",
item.kind.article(), item.kind.descr()))
})format!("`Self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1209 );
1210 }
1211 true
1212 }
1213
1214 fn suggest_self_value(
1215 &mut self,
1216 err: &mut Diag<'_>,
1217 source: PathSource<'_, '_, '_>,
1218 path: &[Segment],
1219 span: Span,
1220 ) -> bool {
1221 if !is_self_value(path, source.namespace()) {
1222 return false;
1223 }
1224
1225 {
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/diagnostics.rs:1225",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1225u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("smart_resolve_path_fragment: E0424, source={0:?}",
source) as &dyn Value))])
});
} else { ; }
};debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1226 err.code(E0424);
1227 err.span_label(
1228 span,
1229 match source {
1230 PathSource::Pat => {
1231 "`self` value is a keyword and may not be bound to variables or shadowed"
1232 }
1233 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1234 },
1235 );
1236
1237 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1240 return true;
1241 }
1242
1243 let is_assoc_fn = self.self_type_is_available();
1244 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1245 access identifiers it receives from parameters";
1246 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1247 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1252 err.span_label(*fn_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function has {0}",
self_from_macro))
})format!("this function has {self_from_macro}"));
1253 } else {
1254 let doesnt = if is_assoc_fn {
1255 let (span, sugg) = fn_kind
1256 .decl()
1257 .inputs
1258 .get(0)
1259 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1260 .unwrap_or_else(|| {
1261 let span = fn_kind
1264 .ident()
1265 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1266 (
1267 self.r
1268 .tcx
1269 .sess
1270 .source_map()
1271 .span_through_char(span, '(')
1272 .shrink_to_hi(),
1273 "&self",
1274 )
1275 });
1276 err.span_suggestion_verbose(
1277 span,
1278 "add a `self` receiver parameter to make the associated `fn` a method",
1279 sugg,
1280 Applicability::MaybeIncorrect,
1281 );
1282 "doesn't"
1283 } else {
1284 "can't"
1285 };
1286 if let Some(ident) = fn_kind.ident() {
1287 err.span_label(
1288 ident.span,
1289 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function {0} have a `self` parameter",
doesnt))
})format!("this function {doesnt} have a `self` parameter"),
1290 );
1291 }
1292 }
1293 } else if let Some(item) = self.diag_metadata.current_item {
1294 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1295 err.span_label(item.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("delegation supports {0}",
self_from_macro))
})format!("delegation supports {self_from_macro}"));
1296 } else {
1297 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1298 err.span_label(
1299 span,
1300 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`self` not allowed in {0} {1}",
item.kind.article(), item.kind.descr()))
})format!("`self` not allowed in {} {}", item.kind.article(), item.kind.descr()),
1301 );
1302 }
1303 }
1304 true
1305 }
1306
1307 fn detect_missing_binding_available_from_pattern(
1308 &self,
1309 err: &mut Diag<'_>,
1310 path: &[Segment],
1311 following_seg: Option<&Segment>,
1312 ) {
1313 let [segment] = path else { return };
1314 let None = following_seg else { return };
1315 for rib in self.ribs[ValueNS].iter().rev() {
1316 let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| {
1317 rib.patterns_with_skipped_bindings.to_sorted(&hcx, true)
1318 });
1319 for (def_id, spans) in patterns_with_skipped_bindings {
1320 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1321 && let Some(fields) = self.r.field_idents(*def_id)
1322 {
1323 for field in fields {
1324 if field.name == segment.ident.name {
1325 if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1326 let multispan: MultiSpan =
1329 spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1330 err.span_note(
1331 multispan,
1332 "this pattern had a recovered parse error which likely lost \
1333 the expected fields",
1334 );
1335 err.downgrade_to_delayed_bug();
1336 }
1337 let ty = self.r.tcx.item_name(*def_id);
1338 for (span, _) in spans {
1339 err.span_label(
1340 *span,
1341 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1342 "this pattern doesn't include `{field}`, which is \
1343 available in `{ty}`",
1344 ),
1345 );
1346 }
1347 }
1348 }
1349 }
1350 }
1351 }
1352 }
1353
1354 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1355 let Some(pat) = self.diag_metadata.current_pat else { return };
1356 let (bound, side, range) = match &pat.kind {
1357 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1358 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1359 _ => return,
1360 };
1361 if let ExprKind::Path(None, range_path) = &bound.kind
1362 && let [segment] = &range_path.segments[..]
1363 && let [s] = path
1364 && segment.ident == s.ident
1365 && segment.ident.span.eq_ctxt(range.span)
1366 {
1367 let (span, snippet) = match side {
1370 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1371 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
1372 };
1373 err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1374 span,
1375 ident: segment.ident,
1376 snippet,
1377 });
1378 }
1379
1380 enum Side {
1381 Start,
1382 End,
1383 }
1384 }
1385
1386 fn suggest_range_struct_destructuring(
1387 &mut self,
1388 err: &mut Diag<'_>,
1389 path: &[Segment],
1390 source: PathSource<'_, '_, '_>,
1391 ) {
1392 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1393 return;
1394 }
1395
1396 let Some(pat) = self.diag_metadata.current_pat else { return };
1397 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1398
1399 let [segment] = path else { return };
1400 let failing_span = segment.ident.span;
1401
1402 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1403 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1404
1405 if !in_start && !in_end {
1406 return;
1407 }
1408
1409 let start_snippet =
1410 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1411 let end_snippet =
1412 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1413
1414 let field = |name: &str, val: String| {
1415 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
1416 };
1417
1418 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1419 let ident = Ident::with_dummy_span(short);
1420 let path = Segment::from_path(&Path::from_ident(ident));
1421
1422 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1423 PathResult::NonModule(..) => short.to_string(),
1424 _ => full.to_string(),
1425 }
1426 };
1427 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1429 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1430 resolve_short_name(sym::Range, "std::ops::Range"),
1431 <[_]>::into_vec(::alloc::boxed::box_new([field("start", start),
field("end", end)]))vec![field("start", start), field("end", end)],
1432 ),
1433 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1434 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1435 <[_]>::into_vec(::alloc::boxed::box_new([field("start", start),
field("end", end)]))vec![field("start", start), field("end", end)],
1436 ),
1437 (Some(start), None, _) => (
1438 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1439 <[_]>::into_vec(::alloc::boxed::box_new([field("start", start)]))vec![field("start", start)],
1440 ),
1441 (None, Some(end), ast::RangeEnd::Excluded) => {
1442 (resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), <[_]>::into_vec(::alloc::boxed::box_new([field("end", end)]))vec![field("end", end)])
1443 }
1444 (None, Some(end), ast::RangeEnd::Included(_)) => (
1445 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1446 <[_]>::into_vec(::alloc::boxed::box_new([field("end", end)]))vec![field("end", end)],
1447 ),
1448 _ => return,
1449 };
1450
1451 err.span_suggestion_verbose(
1452 pat.span,
1453 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you meant to destructure a range use a struct pattern"))
})format!("if you meant to destructure a range use a struct pattern"),
1454 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
1455 Applicability::MaybeIncorrect,
1456 );
1457
1458 err.note(
1459 "range patterns match against the start and end of a range; \
1460 to bind the components, use a struct pattern",
1461 );
1462 }
1463
1464 fn suggest_swapping_misplaced_self_ty_and_trait(
1465 &mut self,
1466 err: &mut Diag<'_>,
1467 source: PathSource<'_, 'ast, 'ra>,
1468 res: Option<Res>,
1469 span: Span,
1470 ) {
1471 if let Some((trait_ref, self_ty)) =
1472 self.diag_metadata.currently_processing_impl_trait.clone()
1473 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1474 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1475 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1476 && let ModuleKind::Def(DefKind::Trait, ..) = module.kind
1477 && trait_ref.path.span == span
1478 && let PathSource::Trait(_) = source
1479 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1480 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1481 && let Ok(trait_ref_str) =
1482 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1483 {
1484 err.multipart_suggestion(
1485 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1486 <[_]>::into_vec(::alloc::boxed::box_new([(trait_ref.path.span, self_ty_str),
(self_ty.span, trait_ref_str)]))vec![(trait_ref.path.span, self_ty_str), (self_ty.span, trait_ref_str)],
1487 Applicability::MaybeIncorrect,
1488 );
1489 }
1490 }
1491
1492 fn explain_functions_in_pattern(
1493 &self,
1494 err: &mut Diag<'_>,
1495 res: Option<Res>,
1496 source: PathSource<'_, '_, '_>,
1497 ) {
1498 let PathSource::TupleStruct(_, _) = source else { return };
1499 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1500 err.primary_message("expected a pattern, found a function call");
1501 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1502 }
1503
1504 fn suggest_changing_type_to_const_param(
1505 &self,
1506 err: &mut Diag<'_>,
1507 res: Option<Res>,
1508 source: PathSource<'_, '_, '_>,
1509 path: &[Segment],
1510 following_seg: Option<&Segment>,
1511 span: Span,
1512 ) {
1513 if let PathSource::Expr(None) = source
1514 && let Some(Res::Def(DefKind::TyParam, _)) = res
1515 && following_seg.is_none()
1516 && let [segment] = path
1517 {
1518 let Some(item) = self.diag_metadata.current_item else { return };
1526 let Some(generics) = item.kind.generics() else { return };
1527 let Some(span) = generics.params.iter().find_map(|param| {
1528 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1530 Some(param.ident.span)
1531 } else {
1532 None
1533 }
1534 }) else {
1535 return;
1536 };
1537 err.subdiagnostic(errors::UnexpectedResChangeTyParamToConstParamSugg {
1538 before: span.shrink_to_lo(),
1539 after: span.shrink_to_hi(),
1540 });
1541 return;
1542 }
1543 let PathSource::Trait(_) = source else { return };
1544
1545 let applicability = match res {
1547 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1548 Applicability::MachineApplicable
1549 }
1550 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1554 if self.r.tcx.features().adt_const_params() =>
1555 {
1556 Applicability::MaybeIncorrect
1557 }
1558 _ => return,
1559 };
1560
1561 let Some(item) = self.diag_metadata.current_item else { return };
1562 let Some(generics) = item.kind.generics() else { return };
1563
1564 let param = generics.params.iter().find_map(|param| {
1565 if let [bound] = &*param.bounds
1567 && let ast::GenericBound::Trait(tref) = bound
1568 && tref.modifiers == ast::TraitBoundModifiers::NONE
1569 && tref.span == span
1570 && param.ident.span.eq_ctxt(span)
1571 {
1572 Some(param.ident.span)
1573 } else {
1574 None
1575 }
1576 });
1577
1578 if let Some(param) = param {
1579 err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1580 span: param.shrink_to_lo(),
1581 applicability,
1582 });
1583 }
1584 }
1585
1586 fn suggest_pattern_match_with_let(
1587 &self,
1588 err: &mut Diag<'_>,
1589 source: PathSource<'_, '_, '_>,
1590 span: Span,
1591 ) -> bool {
1592 if let PathSource::Expr(_) = source
1593 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1594 self.diag_metadata.in_if_condition
1595 {
1596 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1600 err.span_suggestion_verbose(
1601 expr_span.shrink_to_lo(),
1602 "you might have meant to use pattern matching",
1603 "let ",
1604 Applicability::MaybeIncorrect,
1605 );
1606 return true;
1607 }
1608 }
1609 false
1610 }
1611
1612 fn get_single_associated_item(
1613 &mut self,
1614 path: &[Segment],
1615 source: &PathSource<'_, 'ast, 'ra>,
1616 filter_fn: &impl Fn(Res) -> bool,
1617 ) -> Option<TypoSuggestion> {
1618 if let crate::PathSource::TraitItem(_, _) = source {
1619 let mod_path = &path[..path.len() - 1];
1620 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1621 self.resolve_path(mod_path, None, None, *source)
1622 {
1623 let targets: Vec<_> =
1624 self.r
1625 .resolutions(module)
1626 .borrow()
1627 .iter()
1628 .filter_map(|(key, resolution)| {
1629 resolution.borrow().best_decl().map(|binding| binding.res()).and_then(
1630 |res| if filter_fn(res) { Some((*key, res)) } else { None },
1631 )
1632 })
1633 .collect();
1634 if let [target] = targets.as_slice() {
1635 return Some(TypoSuggestion::single_item_from_ident(
1636 target.0.ident.0,
1637 target.1,
1638 ));
1639 }
1640 }
1641 }
1642 None
1643 }
1644
1645 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1647 let Some(ast::WherePredicate {
1649 kind:
1650 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1651 bounded_ty,
1652 bound_generic_params,
1653 bounds,
1654 }),
1655 span: where_span,
1656 ..
1657 }) = self.diag_metadata.current_where_predicate
1658 else {
1659 return false;
1660 };
1661 if !bound_generic_params.is_empty() {
1662 return false;
1663 }
1664
1665 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1667 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1669 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _)) => true,
_ => false,
}matches!(
1670 partial_res.full_res(),
1671 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1672 ) {
1673 return false;
1674 }
1675
1676 let peeled_ty = qself.ty.peel_refs();
1677 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1678 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1680 return false;
1681 };
1682 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _)) => true,
_ => false,
}matches!(
1683 partial_res.full_res(),
1684 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1685 ) {
1686 return false;
1687 }
1688 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1689 (&type_param_path.segments[..], &bounds[..])
1690 else {
1691 return false;
1692 };
1693 let [ast::PathSegment { ident, args: None, id }] =
1694 &poly_trait_ref.trait_ref.path.segments[..]
1695 else {
1696 return false;
1697 };
1698 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1699 return false;
1700 }
1701 if ident.span == span {
1702 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1703 return false;
1704 };
1705 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(hir::def::Res::Def(..))) {
1706 return false;
1707 }
1708
1709 let Some(new_where_bound_predicate) =
1710 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1711 else {
1712 return false;
1713 };
1714 err.span_suggestion_verbose(
1715 *where_span,
1716 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
1717 where_bound_predicate_to_string(&new_where_bound_predicate),
1718 Applicability::MaybeIncorrect,
1719 );
1720 }
1721 true
1722 }
1723
1724 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1727 let mut has_self_arg = None;
1728 if let PathSource::Expr(Some(parent)) = source
1729 && let ExprKind::Call(_, args) = &parent.kind
1730 && !args.is_empty()
1731 {
1732 let mut expr_kind = &args[0].kind;
1733 loop {
1734 match expr_kind {
1735 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1736 if arg_name.segments[0].ident.name == kw::SelfLower {
1737 let call_span = parent.span;
1738 let tail_args_span = if args.len() > 1 {
1739 Some(Span::new(
1740 args[1].span.lo(),
1741 args.last().unwrap().span.hi(),
1742 call_span.ctxt(),
1743 None,
1744 ))
1745 } else {
1746 None
1747 };
1748 has_self_arg = Some((call_span, tail_args_span));
1749 }
1750 break;
1751 }
1752 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1753 _ => break,
1754 }
1755 }
1756 }
1757 has_self_arg
1758 }
1759
1760 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1761 let sm = self.r.tcx.sess.source_map();
1766 if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1767 let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1770 let closing_brace = close_brace_span.map(|sp| span.to(sp));
1771 (true, closing_brace)
1772 } else {
1773 (false, None)
1774 }
1775 }
1776
1777 fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
1778 def_id
1779 .as_local()
1780 .and_then(|local_id| self.r.struct_constructors.get(&local_id))
1781 .map(|struct_ctor| {
1782 #[allow(non_exhaustive_omitted_patterns)] match struct_ctor.0 {
def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1783 struct_ctor.0,
1784 def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1785 )
1786 })
1787 .unwrap_or(false)
1788 }
1789
1790 fn update_err_for_private_tuple_struct_fields(
1791 &mut self,
1792 err: &mut Diag<'_>,
1793 source: &PathSource<'_, '_, '_>,
1794 def_id: DefId,
1795 ) -> Option<Vec<Span>> {
1796 match source {
1797 PathSource::TupleStruct(_, pattern_spans) => {
1799 err.primary_message(
1800 "cannot match against a tuple struct which contains private fields",
1801 );
1802
1803 Some(Vec::from(*pattern_spans))
1805 }
1806 PathSource::Expr(Some(Expr {
1808 kind: ExprKind::Call(path, args),
1809 span: call_span,
1810 ..
1811 })) => {
1812 err.primary_message(
1813 "cannot initialize a tuple struct which contains private fields",
1814 );
1815 self.suggest_alternative_construction_methods(
1816 def_id,
1817 err,
1818 path.span,
1819 *call_span,
1820 &args[..],
1821 );
1822
1823 self.r
1824 .field_idents(def_id)
1825 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1826 }
1827 _ => None,
1828 }
1829 }
1830
1831 fn smart_resolve_context_dependent_help(
1835 &mut self,
1836 err: &mut Diag<'_>,
1837 span: Span,
1838 source: PathSource<'_, '_, '_>,
1839 path: &[Segment],
1840 res: Res,
1841 path_str: &str,
1842 fallback_label: &str,
1843 ) -> bool {
1844 let ns = source.namespace();
1845 let is_expected = &|res| source.is_expected(res);
1846
1847 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
1848 const MESSAGE: &str = "use the path separator to refer to an item";
1849
1850 let (lhs_span, rhs_span) = match &expr.kind {
1851 ExprKind::Field(base, ident) => (base.span, ident.span),
1852 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1853 (receiver.span, *span)
1854 }
1855 _ => return false,
1856 };
1857
1858 if lhs_span.eq_ctxt(rhs_span) {
1859 err.span_suggestion_verbose(
1860 lhs_span.between(rhs_span),
1861 MESSAGE,
1862 "::",
1863 Applicability::MaybeIncorrect,
1864 );
1865 true
1866 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
1867 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1868 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
1869 {
1870 err.span_suggestion_verbose(
1874 lhs_source_span.until(rhs_span),
1875 MESSAGE,
1876 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
1877 Applicability::MaybeIncorrect,
1878 );
1879 true
1880 } else {
1881 false
1887 }
1888 };
1889
1890 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
1891 match source {
1892 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1893 | PathSource::TupleStruct(span, _) => {
1894 err.span(*span);
1897 *span
1898 }
1899 _ => span,
1900 }
1901 };
1902
1903 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
1904 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
1905
1906 match source {
1907 PathSource::Expr(Some(
1908 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1909 )) if path_sep(this, err, parent, DefKind::Struct) => {}
1910 PathSource::Expr(
1911 None
1912 | Some(Expr {
1913 kind:
1914 ExprKind::Path(..)
1915 | ExprKind::Binary(..)
1916 | ExprKind::Unary(..)
1917 | ExprKind::If(..)
1918 | ExprKind::While(..)
1919 | ExprKind::ForLoop { .. }
1920 | ExprKind::Match(..),
1921 ..
1922 }),
1923 ) if followed_by_brace => {
1924 if let Some(sp) = closing_brace {
1925 err.span_label(span, fallback_label.to_string());
1926 err.multipart_suggestion(
1927 "surround the struct literal with parentheses",
1928 <[_]>::into_vec(::alloc::boxed::box_new([(sp.shrink_to_lo(), "(".to_string()),
(sp.shrink_to_hi(), ")".to_string())]))vec![
1929 (sp.shrink_to_lo(), "(".to_string()),
1930 (sp.shrink_to_hi(), ")".to_string()),
1931 ],
1932 Applicability::MaybeIncorrect,
1933 );
1934 } else {
1935 err.span_label(
1936 span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might want to surround a struct literal with parentheses: `({0} {{ /* fields */ }})`?",
path_str))
})format!(
1938 "you might want to surround a struct literal with parentheses: \
1939 `({path_str} {{ /* fields */ }})`?"
1940 ),
1941 );
1942 }
1943 }
1944 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1945 let span = find_span(&source, err);
1946 err.span_label(this.r.def_span(def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"));
1947
1948 let (tail, descr, applicability, old_fields) = match source {
1949 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
1950 PathSource::TupleStruct(_, args) => (
1951 "",
1952 "pattern",
1953 Applicability::MachineApplicable,
1954 Some(
1955 args.iter()
1956 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
1957 .collect::<Vec<Option<String>>>(),
1958 ),
1959 ),
1960 _ => (": val", "literal", Applicability::HasPlaceholders, None),
1961 };
1962
1963 if !this.has_private_fields(def_id) {
1964 let fields = this.r.field_idents(def_id);
1967 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
1968
1969 if let PathSource::Expr(Some(Expr {
1970 kind: ExprKind::Call(path, args),
1971 span,
1972 ..
1973 })) = source
1974 && !args.is_empty()
1975 && let Some(fields) = &fields
1976 && args.len() == fields.len()
1977 {
1979 let path_span = path.span;
1980 let mut parts = Vec::new();
1981
1982 parts.push((
1984 path_span.shrink_to_hi().until(args[0].span),
1985 "{".to_owned(),
1986 ));
1987
1988 for (field, arg) in fields.iter().zip(args.iter()) {
1989 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
1991 }
1992
1993 parts.push((
1995 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
1996 "}".to_owned(),
1997 ));
1998
1999 err.multipart_suggestion_verbose(
2000 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead of calling",
descr))
})format!("use struct {descr} syntax instead of calling"),
2001 parts,
2002 applicability,
2003 );
2004 } else {
2005 let (fields, applicability) = match fields {
2006 Some(fields) => {
2007 let fields = if let Some(old_fields) = old_fields {
2008 fields
2009 .iter()
2010 .enumerate()
2011 .map(|(idx, new)| (new, old_fields.get(idx)))
2012 .map(|(new, old)| {
2013 if let Some(Some(old)) = old
2014 && new.as_str() != old
2015 {
2016 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2017 } else {
2018 new.to_string()
2019 }
2020 })
2021 .collect::<Vec<String>>()
2022 } else {
2023 fields
2024 .iter()
2025 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2026 .collect::<Vec<String>>()
2027 };
2028
2029 (fields.join(", "), applicability)
2030 }
2031 None => {
2032 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2033 }
2034 };
2035 let pad = if has_fields { " " } else { "" };
2036 err.span_suggestion(
2037 span,
2038 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2039 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}"),
2040 applicability,
2041 );
2042 }
2043 }
2044 if let PathSource::Expr(Some(Expr {
2045 kind: ExprKind::Call(path, args),
2046 span: call_span,
2047 ..
2048 })) = source
2049 {
2050 this.suggest_alternative_construction_methods(
2051 def_id,
2052 err,
2053 path.span,
2054 *call_span,
2055 &args[..],
2056 );
2057 }
2058 }
2059 _ => {
2060 err.span_label(span, fallback_label.to_string());
2061 }
2062 }
2063 };
2064
2065 match (res, source) {
2066 (
2067 Res::Def(DefKind::Macro(kinds), def_id),
2068 PathSource::Expr(Some(Expr {
2069 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2070 }))
2071 | PathSource::Struct(_),
2072 ) if kinds.contains(MacroKinds::BANG) => {
2073 let suggestable = def_id.is_local()
2075 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2076
2077 err.span_label(span, fallback_label.to_string());
2078
2079 if path
2081 .last()
2082 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2083 && suggestable
2084 {
2085 err.span_suggestion_verbose(
2086 span.shrink_to_hi(),
2087 "use `!` to invoke the macro",
2088 "!",
2089 Applicability::MaybeIncorrect,
2090 );
2091 }
2092
2093 if path_str == "try" && span.is_rust_2015() {
2094 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2095 }
2096 }
2097 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2098 err.span_label(span, fallback_label.to_string());
2099 }
2100 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2101 err.span_label(span, "type aliases cannot be used as traits");
2102 if self.r.tcx.sess.is_nightly_build() {
2103 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2104 `type` alias";
2105 let span = self.r.def_span(def_id);
2106 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2107 let snip = snip.replacen("type", "trait", 1);
2110 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2111 } else {
2112 err.span_help(span, msg);
2113 }
2114 }
2115 }
2116 (
2117 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2118 PathSource::Expr(Some(parent)),
2119 ) if path_sep(self, err, parent, kind) => {
2120 return true;
2121 }
2122 (
2123 Res::Def(DefKind::Enum, def_id),
2124 PathSource::TupleStruct(..) | PathSource::Expr(..),
2125 ) => {
2126 self.suggest_using_enum_variant(err, source, def_id, span);
2127 }
2128 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2129 let struct_ctor = match def_id.as_local() {
2130 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
2131 None => {
2132 let ctor = self.r.cstore().ctor_untracked(self.r.tcx(), def_id);
2133 ctor.map(|(ctor_kind, ctor_def_id)| {
2134 let ctor_res =
2135 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
2136 let ctor_vis = self.r.tcx.visibility(ctor_def_id);
2137 let field_visibilities = self
2138 .r
2139 .tcx
2140 .associated_item_def_ids(def_id)
2141 .iter()
2142 .map(|field_id| self.r.tcx.visibility(field_id))
2143 .collect();
2144 (ctor_res, ctor_vis, field_visibilities)
2145 })
2146 }
2147 };
2148
2149 let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
2150 if let PathSource::Expr(Some(parent)) = source
2151 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2152 {
2153 bad_struct_syntax_suggestion(self, err, def_id);
2154 return true;
2155 }
2156 struct_ctor
2157 } else {
2158 bad_struct_syntax_suggestion(self, err, def_id);
2159 return true;
2160 };
2161
2162 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
2163 if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
2164 && is_accessible
2165 {
2166 err.span_note(
2167 *use_span,
2168 "the type is accessed through this re-export, but the type's constructor \
2169 is not visible in this import's scope due to private fields",
2170 );
2171 if is_accessible
2172 && fields
2173 .iter()
2174 .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
2175 {
2176 err.span_suggestion_verbose(
2177 span,
2178 "the type can be constructed directly, because its fields are \
2179 available from the current scope",
2180 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2184 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2186 ),
2187 Applicability::MachineApplicable,
2188 );
2189 }
2190 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2191 }
2192 if !is_expected(ctor_def) || is_accessible {
2193 return true;
2194 }
2195
2196 let field_spans =
2197 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2198
2199 if let Some(spans) =
2200 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2201 {
2202 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2203 .filter(|(vis, _)| {
2204 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2205 })
2206 .map(|(_, span)| *span)
2207 .collect();
2208
2209 if non_visible_spans.len() > 0 {
2210 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2211 err.multipart_suggestion_verbose(
2212 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2213 "consider making the field{} publicly accessible",
2214 pluralize!(fields.len())
2215 ),
2216 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2217 Applicability::MaybeIncorrect,
2218 );
2219 }
2220
2221 let mut m: MultiSpan = non_visible_spans.clone().into();
2222 non_visible_spans
2223 .into_iter()
2224 .for_each(|s| m.push_span_label(s, "private field"));
2225 err.span_note(m, "constructor is not visible here due to private fields");
2226 }
2227
2228 return true;
2229 }
2230
2231 err.span_label(span, "constructor is not visible here due to private fields");
2232 }
2233 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2234 bad_struct_syntax_suggestion(self, err, def_id);
2235 }
2236 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2237 match source {
2238 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2239 let span = find_span(&source, err);
2240 err.span_label(
2241 self.r.def_span(def_id),
2242 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2243 );
2244 err.span_suggestion(
2245 span,
2246 "use this syntax instead",
2247 path_str,
2248 Applicability::MaybeIncorrect,
2249 );
2250 }
2251 _ => return false,
2252 }
2253 }
2254 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2255 let def_id = self.r.tcx.parent(ctor_def_id);
2256 err.span_label(self.r.def_span(def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"));
2257 let fields = self.r.field_idents(def_id).map_or_else(
2258 || "/* fields */".to_string(),
2259 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2260 );
2261 err.span_suggestion(
2262 span,
2263 "use the tuple variant pattern syntax instead",
2264 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2265 Applicability::HasPlaceholders,
2266 );
2267 }
2268 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2269 err.span_label(span, fallback_label.to_string());
2270 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2271 }
2272 (
2273 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2274 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2275 ) => {
2276 err.note("can't use a type alias as tuple pattern");
2277
2278 let mut suggestion = Vec::new();
2279
2280 if let &&[first, ..] = args
2281 && let &&[.., last] = args
2282 {
2283 suggestion.extend([
2284 (span.between(first), " { 0: ".to_owned()),
2290 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2291 ]);
2292
2293 suggestion.extend(
2294 args.iter()
2295 .enumerate()
2296 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2298 )
2299 } else {
2300 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2301 }
2302
2303 err.multipart_suggestion(
2304 "use struct pattern instead",
2305 suggestion,
2306 Applicability::MachineApplicable,
2307 );
2308 }
2309 (
2310 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2311 PathSource::TraitItem(
2312 ValueNS,
2313 PathSource::Expr(Some(ast::Expr {
2314 span: whole,
2315 kind: ast::ExprKind::Call(_, args),
2316 ..
2317 })),
2318 ),
2319 ) => {
2320 err.note("can't use a type alias as a constructor");
2321
2322 let mut suggestion = Vec::new();
2323
2324 if let [first, ..] = &**args
2325 && let [.., last] = &**args
2326 {
2327 suggestion.extend([
2328 (span.between(first.span), " { 0: ".to_owned()),
2334 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2335 ]);
2336
2337 suggestion.extend(
2338 args.iter()
2339 .enumerate()
2340 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2342 )
2343 } else {
2344 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2345 }
2346
2347 err.multipart_suggestion(
2348 "use struct expression instead",
2349 suggestion,
2350 Applicability::MachineApplicable,
2351 );
2352 }
2353 _ => return false,
2354 }
2355 true
2356 }
2357
2358 fn suggest_alternative_construction_methods(
2359 &mut self,
2360 def_id: DefId,
2361 err: &mut Diag<'_>,
2362 path_span: Span,
2363 call_span: Span,
2364 args: &[Box<Expr>],
2365 ) {
2366 if def_id.is_local() {
2367 return;
2369 }
2370 let mut items = self
2373 .r
2374 .tcx
2375 .inherent_impls(def_id)
2376 .iter()
2377 .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
2378 .filter(|item| item.is_fn() && !item.is_method())
2380 .filter_map(|item| {
2381 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2383 let ret_ty = fn_sig.output().skip_binder();
2385 let ty::Adt(def, _args) = ret_ty.kind() else {
2386 return None;
2387 };
2388 let input_len = fn_sig.inputs().skip_binder().len();
2389 if def.did() != def_id {
2390 return None;
2391 }
2392 let name = item.name();
2393 let order = !name.as_str().starts_with("new");
2394 Some((order, name, input_len))
2395 })
2396 .collect::<Vec<_>>();
2397 items.sort_by_key(|(order, _, _)| *order);
2398 let suggestion = |name, args| {
2399 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{1}({0})",
std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
name))
})format!("::{name}({})", std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "))
2400 };
2401 match &items[..] {
2402 [] => {}
2403 [(_, name, len)] if *len == args.len() => {
2404 err.span_suggestion_verbose(
2405 path_span.shrink_to_hi(),
2406 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
name))
})format!("you might have meant to use the `{name}` associated function",),
2407 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2408 Applicability::MaybeIncorrect,
2409 );
2410 }
2411 [(_, name, len)] => {
2412 err.span_suggestion_verbose(
2413 path_span.shrink_to_hi().with_hi(call_span.hi()),
2414 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
name))
})format!("you might have meant to use the `{name}` associated function",),
2415 suggestion(name, *len),
2416 Applicability::MaybeIncorrect,
2417 );
2418 }
2419 _ => {
2420 err.span_suggestions_with_style(
2421 path_span.shrink_to_hi().with_hi(call_span.hi()),
2422 "you might have meant to use an associated function to build this type",
2423 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2424 Applicability::MaybeIncorrect,
2425 SuggestionStyle::ShowAlways,
2426 );
2427 }
2428 }
2429 let default_trait = self
2437 .r
2438 .lookup_import_candidates(
2439 Ident::with_dummy_span(sym::Default),
2440 Namespace::TypeNS,
2441 &self.parent_scope,
2442 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2443 )
2444 .iter()
2445 .filter_map(|candidate| candidate.did)
2446 .find(|did| {
2447 self.r
2448 .tcx
2449 .get_attrs(*did, sym::rustc_diagnostic_item)
2450 .any(|attr| attr.value_str() == Some(sym::Default))
2451 });
2452 let Some(default_trait) = default_trait else {
2453 return;
2454 };
2455 if self
2456 .r
2457 .extern_crate_map
2458 .items()
2459 .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2461 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2462 .filter_map(|simplified_self_ty| match simplified_self_ty {
2463 SimplifiedType::Adt(did) => Some(did),
2464 _ => None,
2465 })
2466 .any(|did| did == def_id)
2467 {
2468 err.multipart_suggestion(
2469 "consider using the `Default` trait",
2470 <[_]>::into_vec(::alloc::boxed::box_new([(path_span.shrink_to_lo(),
"<".to_string()),
(path_span.shrink_to_hi().with_hi(call_span.hi()),
" as std::default::Default>::default()".to_string())]))vec![
2471 (path_span.shrink_to_lo(), "<".to_string()),
2472 (
2473 path_span.shrink_to_hi().with_hi(call_span.hi()),
2474 " as std::default::Default>::default()".to_string(),
2475 ),
2476 ],
2477 Applicability::MaybeIncorrect,
2478 );
2479 }
2480 }
2481
2482 fn has_private_fields(&self, def_id: DefId) -> bool {
2483 let fields = match def_id.as_local() {
2484 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2485 None => Some(
2486 self.r
2487 .tcx
2488 .associated_item_def_ids(def_id)
2489 .iter()
2490 .map(|field_id| self.r.tcx.visibility(field_id))
2491 .collect(),
2492 ),
2493 };
2494
2495 fields.is_some_and(|fields| {
2496 fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2497 })
2498 }
2499
2500 pub(crate) fn find_similarly_named_assoc_item(
2503 &mut self,
2504 ident: Symbol,
2505 kind: &AssocItemKind,
2506 ) -> Option<Symbol> {
2507 let (module, _) = self.current_trait_ref.as_ref()?;
2508 if ident == kw::Underscore {
2509 return None;
2511 }
2512
2513 let targets = self
2514 .r
2515 .resolutions(*module)
2516 .borrow()
2517 .iter()
2518 .filter_map(|(key, res)| res.borrow().best_decl().map(|binding| (key, binding.res())))
2519 .filter(|(_, res)| match (kind, res) {
2520 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2521 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2522 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2523 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2524 _ => false,
2525 })
2526 .map(|(key, _)| key.ident.name)
2527 .collect::<Vec<_>>();
2528
2529 find_best_match_for_name(&targets, ident, None)
2530 }
2531
2532 fn lookup_assoc_candidate<FilterFn>(
2533 &mut self,
2534 ident: Ident,
2535 ns: Namespace,
2536 filter_fn: FilterFn,
2537 called: bool,
2538 ) -> Option<AssocSuggestion>
2539 where
2540 FilterFn: Fn(Res) -> bool,
2541 {
2542 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2543 match t.kind {
2544 TyKind::Path(None, _) => Some(t.id),
2545 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2546 _ => None,
2550 }
2551 }
2552 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2554 if let Some(node_id) =
2555 self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2556 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2557 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2558 && let Some(fields) = self.r.field_idents(did)
2559 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2560 {
2561 return Some(AssocSuggestion::Field(field.span));
2563 }
2564 }
2565
2566 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2567 for assoc_item in items {
2568 if let Some(assoc_ident) = assoc_item.kind.ident()
2569 && assoc_ident == ident
2570 {
2571 return Some(match &assoc_item.kind {
2572 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2573 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2574 AssocSuggestion::MethodWithSelf { called }
2575 }
2576 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2577 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2578 ast::AssocItemKind::Delegation(..)
2579 if self
2580 .r
2581 .delegation_fn_sigs
2582 .get(&self.r.local_def_id(assoc_item.id))
2583 .is_some_and(|sig| sig.has_self) =>
2584 {
2585 AssocSuggestion::MethodWithSelf { called }
2586 }
2587 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2588 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2589 continue;
2590 }
2591 });
2592 }
2593 }
2594 }
2595
2596 if let Some((module, _)) = self.current_trait_ref
2598 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2599 ModuleOrUniformRoot::Module(module),
2600 ident,
2601 ns,
2602 &self.parent_scope,
2603 None,
2604 )
2605 {
2606 let res = binding.res();
2607 if filter_fn(res) {
2608 match res {
2609 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2610 let has_self = match def_id.as_local() {
2611 Some(def_id) => self
2612 .r
2613 .delegation_fn_sigs
2614 .get(&def_id)
2615 .is_some_and(|sig| sig.has_self),
2616 None => {
2617 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2618 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2619 })
2620 }
2621 };
2622 if has_self {
2623 return Some(AssocSuggestion::MethodWithSelf { called });
2624 } else {
2625 return Some(AssocSuggestion::AssocFn { called });
2626 }
2627 }
2628 Res::Def(DefKind::AssocConst, _) => {
2629 return Some(AssocSuggestion::AssocConst);
2630 }
2631 Res::Def(DefKind::AssocTy, _) => {
2632 return Some(AssocSuggestion::AssocType);
2633 }
2634 _ => {}
2635 }
2636 }
2637 }
2638
2639 None
2640 }
2641
2642 fn lookup_typo_candidate(
2643 &mut self,
2644 path: &[Segment],
2645 following_seg: Option<&Segment>,
2646 ns: Namespace,
2647 filter_fn: &impl Fn(Res) -> bool,
2648 ) -> TypoCandidate {
2649 let mut names = Vec::new();
2650 if let [segment] = path {
2651 let mut ctxt = segment.ident.span.ctxt();
2652
2653 for rib in self.ribs[ns].iter().rev() {
2656 let rib_ctxt = if rib.kind.contains_params() {
2657 ctxt.normalize_to_macros_2_0()
2658 } else {
2659 ctxt.normalize_to_macro_rules()
2660 };
2661
2662 for (ident, &res) in &rib.bindings {
2664 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2665 names.push(TypoSuggestion::typo_from_ident(*ident, res));
2666 }
2667 }
2668
2669 if let RibKind::Block(Some(module)) = rib.kind {
2670 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2671 } else if let RibKind::Module(module) = rib.kind {
2672 let parent_scope = &ParentScope { module, ..self.parent_scope };
2674 self.r.add_scope_set_candidates(
2675 &mut names,
2676 ScopeSet::All(ns),
2677 parent_scope,
2678 ctxt,
2679 filter_fn,
2680 );
2681 break;
2682 }
2683
2684 if let RibKind::MacroDefinition(def) = rib.kind
2685 && def == self.r.macro_def(ctxt)
2686 {
2687 ctxt.remove_mark();
2690 }
2691 }
2692 } else {
2693 let mod_path = &path[..path.len() - 1];
2695 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2696 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2697 {
2698 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2699 }
2700 }
2701
2702 if let Some(following_seg) = following_seg {
2704 names.retain(|suggestion| match suggestion.res {
2705 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2706 suggestion.candidate != following_seg.ident.name
2708 }
2709 Res::Def(DefKind::Mod, def_id) => {
2710 let module = self.r.expect_module(def_id);
2711 self.r
2712 .resolutions(module)
2713 .borrow()
2714 .iter()
2715 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2716 }
2717 _ => true,
2718 });
2719 }
2720 let name = path[path.len() - 1].ident.name;
2721 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2723
2724 match find_best_match_for_name(
2725 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2726 name,
2727 None,
2728 ) {
2729 Some(found) => {
2730 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2731 else {
2732 return TypoCandidate::None;
2733 };
2734 if found == name {
2735 TypoCandidate::Shadowed(sugg.res, sugg.span)
2736 } else {
2737 TypoCandidate::Typo(sugg)
2738 }
2739 }
2740 _ => TypoCandidate::None,
2741 }
2742 }
2743
2744 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2747 let name = path[path.len() - 1].ident.as_str();
2748 Some(match name {
2750 "byte" => sym::u8, "short" => sym::i16,
2752 "Bool" => sym::bool,
2753 "Boolean" => sym::bool,
2754 "boolean" => sym::bool,
2755 "int" => sym::i32,
2756 "long" => sym::i64,
2757 "float" => sym::f32,
2758 "double" => sym::f64,
2759 _ => return None,
2760 })
2761 }
2762
2763 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2766 if ident_span.from_expansion() {
2767 return false;
2768 }
2769
2770 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2772 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2773 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2774 {
2775 let (span, text) = match path.segments.first() {
2776 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2777 let name = name.trim_prefix('_');
2779 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
2780 }
2781 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2782 };
2783
2784 err.span_suggestion_verbose(
2785 span,
2786 "you might have meant to introduce a new binding",
2787 text,
2788 Applicability::MaybeIncorrect,
2789 );
2790 return true;
2791 }
2792
2793 if err.code == Some(E0423)
2796 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2797 && val_span.contains(ident_span)
2798 && val_span.lo() == ident_span.lo()
2799 {
2800 err.span_suggestion_verbose(
2801 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2802 "you might have meant to use `:` for type annotation",
2803 ": ",
2804 Applicability::MaybeIncorrect,
2805 );
2806 return true;
2807 }
2808 false
2809 }
2810
2811 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2812 let mut result = None;
2813 let mut seen_modules = FxHashSet::default();
2814 let root_did = self.r.graph_root.def_id();
2815 let mut worklist = <[_]>::into_vec(::alloc::boxed::box_new([(self.r.graph_root, ThinVec::new(),
root_did.is_local() ||
!self.r.tcx.is_doc_hidden(root_did))]))vec![(
2816 self.r.graph_root,
2817 ThinVec::new(),
2818 root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2819 )];
2820
2821 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2822 if result.is_some() {
2824 break;
2825 }
2826
2827 in_module.for_each_child(self.r, |r, ident, _, name_binding| {
2828 if result.is_some() || !name_binding.vis().is_visible_locally() {
2830 return;
2831 }
2832 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
2833 let mut path_segments = path_segments.clone();
2835 path_segments.push(ast::PathSegment::from_ident(ident.0));
2836 let doc_visible = doc_visible
2837 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2838 if module_def_id == def_id {
2839 let path =
2840 Path { span: name_binding.span, segments: path_segments, tokens: None };
2841 result = Some((
2842 r.expect_module(module_def_id),
2843 ImportSuggestion {
2844 did: Some(def_id),
2845 descr: "module",
2846 path,
2847 accessible: true,
2848 doc_visible,
2849 note: None,
2850 via_import: false,
2851 is_stable: true,
2852 },
2853 ));
2854 } else {
2855 if seen_modules.insert(module_def_id) {
2857 let module = r.expect_module(module_def_id);
2858 worklist.push((module, path_segments, doc_visible));
2859 }
2860 }
2861 }
2862 });
2863 }
2864
2865 result
2866 }
2867
2868 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2869 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2870 let mut variants = Vec::new();
2871 enum_module.for_each_child(self.r, |_, ident, _, name_binding| {
2872 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2873 let mut segms = enum_import_suggestion.path.segments.clone();
2874 segms.push(ast::PathSegment::from_ident(ident.0));
2875 let path = Path { span: name_binding.span, segments: segms, tokens: None };
2876 variants.push((path, def_id, kind));
2877 }
2878 });
2879 variants
2880 })
2881 }
2882
2883 fn suggest_using_enum_variant(
2885 &self,
2886 err: &mut Diag<'_>,
2887 source: PathSource<'_, '_, '_>,
2888 def_id: DefId,
2889 span: Span,
2890 ) {
2891 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2892 err.note("you might have meant to use one of the enum's variants");
2893 return;
2894 };
2895
2896 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2901 PathSource::TupleStruct(..) => (None, true),
2903 PathSource::Expr(Some(expr)) => match &expr.kind {
2904 ExprKind::Call(..) => (None, true),
2906 ExprKind::MethodCall(box MethodCall {
2909 receiver,
2910 span,
2911 seg: PathSegment { ident, .. },
2912 ..
2913 }) => {
2914 let dot_span = receiver.span.between(*span);
2915 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2916 *ctor_kind == CtorKind::Fn
2917 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2918 });
2919 (found_tuple_variant.then_some(dot_span), false)
2920 }
2921 ExprKind::Field(base, ident) => {
2924 let dot_span = base.span.between(ident.span);
2925 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2926 path.segments.last().is_some_and(|seg| seg.ident == *ident)
2927 });
2928 (found_tuple_or_unit_variant.then_some(dot_span), false)
2929 }
2930 _ => (None, false),
2931 },
2932 _ => (None, false),
2933 };
2934
2935 if let Some(dot_span) = suggest_path_sep_dot_span {
2936 err.span_suggestion_verbose(
2937 dot_span,
2938 "use the path separator to refer to a variant",
2939 "::",
2940 Applicability::MaybeIncorrect,
2941 );
2942 } else if suggest_only_tuple_variants {
2943 let mut suggestable_variants = variant_ctors
2946 .iter()
2947 .filter(|(.., kind)| *kind == CtorKind::Fn)
2948 .map(|(variant, ..)| path_names_to_string(variant))
2949 .collect::<Vec<_>>();
2950 suggestable_variants.sort();
2951
2952 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2953
2954 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
2955 "to match against"
2956 } else {
2957 "to construct"
2958 };
2959
2960 if !suggestable_variants.is_empty() {
2961 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2962 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try {0} the enum\'s variant",
source_msg))
})format!("try {source_msg} the enum's variant")
2963 } else {
2964 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try {0} one of the enum\'s variants",
source_msg))
})format!("try {source_msg} one of the enum's variants")
2965 };
2966
2967 err.span_suggestions(
2968 span,
2969 msg,
2970 suggestable_variants,
2971 Applicability::MaybeIncorrect,
2972 );
2973 }
2974
2975 if non_suggestable_variant_count == variant_ctors.len() {
2977 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the enum has no tuple variants {0}",
source_msg))
})format!("the enum has no tuple variants {source_msg}"));
2978 }
2979
2980 if non_suggestable_variant_count == 1 {
2982 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant {0} the enum\'s non-tuple variant",
source_msg))
})format!("you might have meant {source_msg} the enum's non-tuple variant"));
2983 } else if non_suggestable_variant_count >= 1 {
2984 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant {0} one of the enum\'s non-tuple variants",
source_msg))
})format!(
2985 "you might have meant {source_msg} one of the enum's non-tuple variants"
2986 ));
2987 }
2988 } else {
2989 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2990 let def_id = self.r.tcx.parent(ctor_def_id);
2991 match kind {
2992 CtorKind::Const => false,
2993 CtorKind::Fn => {
2994 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2995 }
2996 }
2997 };
2998
2999 let mut suggestable_variants = variant_ctors
3000 .iter()
3001 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3002 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3003 .map(|(variant, kind)| match kind {
3004 CtorKind::Const => variant,
3005 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3006 })
3007 .collect::<Vec<_>>();
3008 suggestable_variants.sort();
3009 let no_suggestable_variant = suggestable_variants.is_empty();
3010
3011 if !no_suggestable_variant {
3012 let msg = if suggestable_variants.len() == 1 {
3013 "you might have meant to use the following enum variant"
3014 } else {
3015 "you might have meant to use one of the following enum variants"
3016 };
3017
3018 err.span_suggestions(
3019 span,
3020 msg,
3021 suggestable_variants,
3022 Applicability::MaybeIncorrect,
3023 );
3024 }
3025
3026 let mut suggestable_variants_with_placeholders = variant_ctors
3027 .iter()
3028 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3029 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3030 .filter_map(|(variant, kind)| match kind {
3031 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3032 _ => None,
3033 })
3034 .collect::<Vec<_>>();
3035 suggestable_variants_with_placeholders.sort();
3036
3037 if !suggestable_variants_with_placeholders.is_empty() {
3038 let msg =
3039 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3040 (true, 1) => "the following enum variant is available",
3041 (true, _) => "the following enum variants are available",
3042 (false, 1) => "alternatively, the following enum variant is available",
3043 (false, _) => {
3044 "alternatively, the following enum variants are also available"
3045 }
3046 };
3047
3048 err.span_suggestions(
3049 span,
3050 msg,
3051 suggestable_variants_with_placeholders,
3052 Applicability::HasPlaceholders,
3053 );
3054 }
3055 };
3056
3057 if def_id.is_local() {
3058 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3059 }
3060 }
3061
3062 pub(crate) fn suggest_adding_generic_parameter(
3063 &self,
3064 path: &[Segment],
3065 source: PathSource<'_, '_, '_>,
3066 ) -> Option<(Span, &'static str, String, Applicability)> {
3067 let (ident, span) = match path {
3068 [segment]
3069 if !segment.has_generic_args
3070 && segment.ident.name != kw::SelfUpper
3071 && segment.ident.name != kw::Dyn =>
3072 {
3073 (segment.ident.to_string(), segment.ident.span)
3074 }
3075 _ => return None,
3076 };
3077 let mut iter = ident.chars().map(|c| c.is_uppercase());
3078 let single_uppercase_char =
3079 #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
Some(true) => true,
_ => false,
}matches!(iter.next(), Some(true)) && #[allow(non_exhaustive_omitted_patterns)] match iter.next() {
None => true,
_ => false,
}matches!(iter.next(), None);
3080 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3081 return None;
3082 }
3083 match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
3084 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3085 }
3087 (
3088 Some(Item {
3089 kind:
3090 kind @ ItemKind::Fn(..)
3091 | kind @ ItemKind::Enum(..)
3092 | kind @ ItemKind::Struct(..)
3093 | kind @ ItemKind::Union(..),
3094 ..
3095 }),
3096 true, _
3097 )
3098 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3100 | (Some(Item { kind, .. }), false, _) => {
3101 if let Some(generics) = kind.generics() {
3102 if span.overlaps(generics.span) {
3103 return None;
3112 }
3113
3114 let (msg, sugg) = match source {
3115 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3116 ("you might be missing a type parameter", ident)
3117 }
3118 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3119 "you might be missing a const parameter",
3120 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3121 ),
3122 _ => return None,
3123 };
3124 let (span, sugg) = if let [.., param] = &generics.params[..] {
3125 let span = if let [.., bound] = ¶m.bounds[..] {
3126 bound.span()
3127 } else if let GenericParam {
3128 kind: GenericParamKind::Const { ty, span: _, default }, ..
3129 } = param {
3130 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3131 } else {
3132 param.ident.span
3133 };
3134 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3135 } else {
3136 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3137 };
3138 if span.can_be_used_for_suggestions() {
3140 return Some((
3141 span.shrink_to_hi(),
3142 msg,
3143 sugg,
3144 Applicability::MaybeIncorrect,
3145 ));
3146 }
3147 }
3148 }
3149 _ => {}
3150 }
3151 None
3152 }
3153
3154 pub(crate) fn suggestion_for_label_in_rib(
3157 &self,
3158 rib_index: usize,
3159 label: Ident,
3160 ) -> Option<LabelSuggestion> {
3161 let within_scope = self.is_label_valid_from_rib(rib_index);
3163
3164 let rib = &self.label_ribs[rib_index];
3165 let names = rib
3166 .bindings
3167 .iter()
3168 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3169 .map(|(id, _)| id.name)
3170 .collect::<Vec<Symbol>>();
3171
3172 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3173 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3177 (*ident, within_scope)
3178 })
3179 }
3180
3181 pub(crate) fn maybe_report_lifetime_uses(
3182 &mut self,
3183 generics_span: Span,
3184 params: &[ast::GenericParam],
3185 ) {
3186 for (param_index, param) in params.iter().enumerate() {
3187 let GenericParamKind::Lifetime = param.kind else { continue };
3188
3189 let def_id = self.r.local_def_id(param.id);
3190
3191 let use_set = self.lifetime_uses.remove(&def_id);
3192 {
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/diagnostics.rs:3192",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3192u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Use set for {0:?}({1:?} at {2:?}) is {3:?}",
def_id, param.ident, param.ident.span, use_set) as
&dyn Value))])
});
} else { ; }
};debug!(
3193 "Use set for {:?}({:?} at {:?}) is {:?}",
3194 def_id, param.ident, param.ident.span, use_set
3195 );
3196
3197 let deletion_span = || {
3198 if params.len() == 1 {
3199 Some(generics_span)
3201 } else if param_index == 0 {
3202 match (
3205 param.span().find_ancestor_inside(generics_span),
3206 params[param_index + 1].span().find_ancestor_inside(generics_span),
3207 ) {
3208 (Some(param_span), Some(next_param_span)) => {
3209 Some(param_span.to(next_param_span.shrink_to_lo()))
3210 }
3211 _ => None,
3212 }
3213 } else {
3214 match (
3217 param.span().find_ancestor_inside(generics_span),
3218 params[param_index - 1].span().find_ancestor_inside(generics_span),
3219 ) {
3220 (Some(param_span), Some(prev_param_span)) => {
3221 Some(prev_param_span.shrink_to_hi().to(param_span))
3222 }
3223 _ => None,
3224 }
3225 }
3226 };
3227 match use_set {
3228 Some(LifetimeUseSet::Many) => {}
3229 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3230 {
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/diagnostics.rs:3230",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3230u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["param.ident",
"param.ident.span", "use_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident.span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&use_span)
as &dyn Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span, ?use_span);
3231
3232 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3233 let deletion_span =
3234 if param.bounds.is_empty() { deletion_span() } else { None };
3235
3236 self.r.lint_buffer.buffer_lint(
3237 lint::builtin::SINGLE_USE_LIFETIMES,
3238 param.id,
3239 param.ident.span,
3240 lint::BuiltinLintDiag::SingleUseLifetime {
3241 param_span: param.ident.span,
3242 use_span: Some((use_span, elidable)),
3243 deletion_span,
3244 ident: param.ident,
3245 },
3246 );
3247 }
3248 None => {
3249 {
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/diagnostics.rs:3249",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3249u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["param.ident",
"param.ident.span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m.ident.span)
as &dyn Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span);
3250 let deletion_span = deletion_span();
3251
3252 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3254 self.r.lint_buffer.buffer_lint(
3255 lint::builtin::UNUSED_LIFETIMES,
3256 param.id,
3257 param.ident.span,
3258 lint::BuiltinLintDiag::SingleUseLifetime {
3259 param_span: param.ident.span,
3260 use_span: None,
3261 deletion_span,
3262 ident: param.ident,
3263 },
3264 );
3265 }
3266 }
3267 }
3268 }
3269 }
3270
3271 pub(crate) fn emit_undeclared_lifetime_error(
3272 &self,
3273 lifetime_ref: &ast::Lifetime,
3274 outer_lifetime_ref: Option<Ident>,
3275 ) {
3276 if true {
match (&lifetime_ref.ident.name, &kw::UnderscoreLifetime) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
3277 let mut err = if let Some(outer) = outer_lifetime_ref {
3278 {
self.r.dcx().struct_span_err(lifetime_ref.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("can\'t use generic parameters from outer item"))
})).with_code(E0401)
}struct_span_code_err!(
3279 self.r.dcx(),
3280 lifetime_ref.ident.span,
3281 E0401,
3282 "can't use generic parameters from outer item",
3283 )
3284 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3285 .with_span_label(outer.span, "lifetime parameter from outer item")
3286 } else {
3287 {
self.r.dcx().struct_span_err(lifetime_ref.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of undeclared lifetime name `{0}`",
lifetime_ref.ident))
})).with_code(E0261)
}struct_span_code_err!(
3288 self.r.dcx(),
3289 lifetime_ref.ident.span,
3290 E0261,
3291 "use of undeclared lifetime name `{}`",
3292 lifetime_ref.ident
3293 )
3294 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3295 };
3296
3297 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3299 err.span_suggestion_verbose(
3300 lifetime_ref.ident.span,
3301 "you may have misspelled the `'static` lifetime",
3302 "'static",
3303 Applicability::MachineApplicable,
3304 );
3305 } else {
3306 self.suggest_introducing_lifetime(
3307 &mut err,
3308 Some(lifetime_ref.ident),
3309 |err, _, span, message, suggestion, span_suggs| {
3310 err.multipart_suggestion_verbose(
3311 message,
3312 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3313 Applicability::MaybeIncorrect,
3314 );
3315 true
3316 },
3317 );
3318 }
3319
3320 err.emit();
3321 }
3322
3323 fn suggest_introducing_lifetime(
3324 &self,
3325 err: &mut Diag<'_>,
3326 name: Option<Ident>,
3327 suggest: impl Fn(
3328 &mut Diag<'_>,
3329 bool,
3330 Span,
3331 Cow<'static, str>,
3332 String,
3333 Vec<(Span, String)>,
3334 ) -> bool,
3335 ) {
3336 let mut suggest_note = true;
3337 for rib in self.lifetime_ribs.iter().rev() {
3338 let mut should_continue = true;
3339 match rib.kind {
3340 LifetimeRibKind::Generics { binder, span, kind } => {
3341 if let LifetimeBinderKind::ConstItem = kind
3344 && !self.r.tcx().features().generic_const_items()
3345 {
3346 continue;
3347 }
3348 if let LifetimeBinderKind::ImplAssocType = kind {
3349 continue;
3350 }
3351
3352 if !span.can_be_used_for_suggestions()
3353 && suggest_note
3354 && let Some(name) = name
3355 {
3356 suggest_note = false; err.span_label(
3358 span,
3359 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
3360 "lifetime `{name}` is missing in item created through this procedural macro",
3361 ),
3362 );
3363 continue;
3364 }
3365
3366 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3367 kind,
3368 LifetimeBinderKind::FnPtrType
3369 | LifetimeBinderKind::PolyTrait
3370 | LifetimeBinderKind::WhereBound
3371 );
3372
3373 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3374 let (span, sugg) = if span.is_empty() {
3375 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3376 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3377
3378 if let LifetimeBinderKind::WhereBound = kind
3385 && let Some(predicate) = self.diag_metadata.current_where_predicate
3386 && let ast::WherePredicateKind::BoundPredicate(
3387 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3388 ) = &predicate.kind
3389 && bounded_ty.id == binder
3390 {
3391 for bound in bounds {
3392 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3393 && let span = poly_trait_ref
3394 .span
3395 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3396 && !span.is_empty()
3397 {
3398 rm_inner_binders.insert(span);
3399 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3400 binder_idents.insert(v.ident);
3401 });
3402 }
3403 }
3404 }
3405
3406 let binders_sugg: String = binder_idents
3407 .into_iter()
3408 .map(|ident| ident.to_string())
3409 .intersperse(", ".to_owned())
3410 .collect();
3411 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}<{1}>{2}",
if higher_ranked { "for" } else { "" }, binders_sugg,
if higher_ranked { " " } else { "" }))
})format!(
3412 "{}<{}>{}",
3413 if higher_ranked { "for" } else { "" },
3414 binders_sugg,
3415 if higher_ranked { " " } else { "" },
3416 );
3417 (span, sugg)
3418 } else {
3419 let span = self
3420 .r
3421 .tcx
3422 .sess
3423 .source_map()
3424 .span_through_char(span, '<')
3425 .shrink_to_hi();
3426 let sugg =
3427 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ",
name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
})format!("{}, ", name.map(|i| i.to_string()).as_deref().unwrap_or("'a"));
3428 (span, sugg)
3429 };
3430
3431 if higher_ranked {
3432 let message = Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the {0} lifetime-generic with a new `{1}` lifetime",
kind.descr(),
name.map(|i| i.to_string()).as_deref().unwrap_or("'a")))
})format!(
3433 "consider making the {} lifetime-generic with a new `{}` lifetime",
3434 kind.descr(),
3435 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3436 ));
3437 should_continue = suggest(
3438 err,
3439 true,
3440 span,
3441 message,
3442 sugg,
3443 if !rm_inner_binders.is_empty() {
3444 rm_inner_binders
3445 .into_iter()
3446 .map(|v| (v, "".to_string()))
3447 .collect::<Vec<_>>()
3448 } else {
3449 ::alloc::vec::Vec::new()vec![]
3450 },
3451 );
3452 err.note_once(
3453 "for more information on higher-ranked polymorphism, visit \
3454 https://doc.rust-lang.org/nomicon/hrtb.html",
3455 );
3456 } else if let Some(name) = name {
3457 let message =
3458 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
3459 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3460 } else {
3461 let message = Cow::from("consider introducing a named lifetime parameter");
3462 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3463 }
3464 }
3465 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3466 _ => {}
3467 }
3468 if !should_continue {
3469 break;
3470 }
3471 }
3472 }
3473
3474 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3475 self.r
3476 .dcx()
3477 .create_err(errors::ParamInTyOfConstParam {
3478 span: lifetime_ref.ident.span,
3479 name: lifetime_ref.ident.name,
3480 })
3481 .emit();
3482 }
3483
3484 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3488 &self,
3489 cause: NoConstantGenericsReason,
3490 lifetime_ref: &ast::Lifetime,
3491 ) {
3492 match cause {
3493 NoConstantGenericsReason::IsEnumDiscriminant => {
3494 self.r
3495 .dcx()
3496 .create_err(errors::ParamInEnumDiscriminant {
3497 span: lifetime_ref.ident.span,
3498 name: lifetime_ref.ident.name,
3499 param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3500 })
3501 .emit();
3502 }
3503 NoConstantGenericsReason::NonTrivialConstArg => {
3504 if !!self.r.tcx.features().generic_const_exprs() {
::core::panicking::panic("assertion failed: !self.r.tcx.features().generic_const_exprs()")
};assert!(!self.r.tcx.features().generic_const_exprs());
3505 self.r
3506 .dcx()
3507 .create_err(errors::ParamInNonTrivialAnonConst {
3508 span: lifetime_ref.ident.span,
3509 name: lifetime_ref.ident.name,
3510 param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3511 help: self
3512 .r
3513 .tcx
3514 .sess
3515 .is_nightly_build()
3516 .then_some(errors::ParamInNonTrivialAnonConstHelp),
3517 })
3518 .emit();
3519 }
3520 }
3521 }
3522
3523 pub(crate) fn report_missing_lifetime_specifiers(
3524 &mut self,
3525 lifetime_refs: Vec<MissingLifetime>,
3526 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3527 ) -> ErrorGuaranteed {
3528 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3529 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3530
3531 let mut err = {
self.r.dcx().struct_span_err(spans,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing lifetime specifier{0}",
if num_lifetimes == 1 { "" } else { "s" }))
})).with_code(E0106)
}struct_span_code_err!(
3532 self.r.dcx(),
3533 spans,
3534 E0106,
3535 "missing lifetime specifier{}",
3536 pluralize!(num_lifetimes)
3537 );
3538 self.add_missing_lifetime_specifiers_label(
3539 &mut err,
3540 lifetime_refs,
3541 function_param_lifetimes,
3542 );
3543 err.emit()
3544 }
3545
3546 fn add_missing_lifetime_specifiers_label(
3547 &mut self,
3548 err: &mut Diag<'_>,
3549 lifetime_refs: Vec<MissingLifetime>,
3550 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3551 ) {
3552 for < in &lifetime_refs {
3553 err.span_label(
3554 lt.span,
3555 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} lifetime parameter{1}",
if lt.count == 1 {
"named".to_string()
} else { lt.count.to_string() },
if lt.count == 1 { "" } else { "s" }))
})format!(
3556 "expected {} lifetime parameter{}",
3557 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3558 pluralize!(lt.count),
3559 ),
3560 );
3561 }
3562
3563 let mut in_scope_lifetimes: Vec<_> = self
3564 .lifetime_ribs
3565 .iter()
3566 .rev()
3567 .take_while(|rib| {
3568 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3569 })
3570 .flat_map(|rib| rib.bindings.iter())
3571 .map(|(&ident, &res)| (ident, res))
3572 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3573 .collect();
3574 {
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/diagnostics.rs:3574",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3574u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["in_scope_lifetimes"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&in_scope_lifetimes)
as &dyn Value))])
});
} else { ; }
};debug!(?in_scope_lifetimes);
3575
3576 let mut maybe_static = false;
3577 {
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/diagnostics.rs:3577",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3577u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["function_param_lifetimes"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&function_param_lifetimes)
as &dyn Value))])
});
} else { ; }
};debug!(?function_param_lifetimes);
3578 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3579 let elided_len = param_lifetimes.len();
3580 let num_params = params.len();
3581
3582 let mut m = String::new();
3583
3584 for (i, info) in params.iter().enumerate() {
3585 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3586 if true {
match (&lifetime_count, &0) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(lifetime_count, 0);
3587
3588 err.span_label(span, "");
3589
3590 if i != 0 {
3591 if i + 1 < num_params {
3592 m.push_str(", ");
3593 } else if num_params == 2 {
3594 m.push_str(" or ");
3595 } else {
3596 m.push_str(", or ");
3597 }
3598 }
3599
3600 let help_name = if let Some(ident) = ident {
3601 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
3602 } else {
3603 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
3604 };
3605
3606 if lifetime_count == 1 {
3607 m.push_str(&help_name[..])
3608 } else {
3609 m.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("one of {0}\'s {1} lifetimes",
help_name, lifetime_count))
})format!("one of {help_name}'s {lifetime_count} lifetimes")[..])
3610 }
3611 }
3612
3613 if num_params == 0 {
3614 err.help(
3615 "this function's return type contains a borrowed value, but there is no value \
3616 for it to be borrowed from",
3617 );
3618 if in_scope_lifetimes.is_empty() {
3619 maybe_static = true;
3620 in_scope_lifetimes = <[_]>::into_vec(::alloc::boxed::box_new([(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
3621 Ident::with_dummy_span(kw::StaticLifetime),
3622 (DUMMY_NODE_ID, LifetimeRes::Static),
3623 )];
3624 }
3625 } else if elided_len == 0 {
3626 err.help(
3627 "this function's return type contains a borrowed value with an elided \
3628 lifetime, but the lifetime cannot be derived from the arguments",
3629 );
3630 if in_scope_lifetimes.is_empty() {
3631 maybe_static = true;
3632 in_scope_lifetimes = <[_]>::into_vec(::alloc::boxed::box_new([(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
3633 Ident::with_dummy_span(kw::StaticLifetime),
3634 (DUMMY_NODE_ID, LifetimeRes::Static),
3635 )];
3636 }
3637 } else if num_params == 1 {
3638 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say which {0} it is borrowed from",
m))
})format!(
3639 "this function's return type contains a borrowed value, but the signature does \
3640 not say which {m} it is borrowed from",
3641 ));
3642 } else {
3643 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this function\'s return type contains a borrowed value, but the signature does not say whether it is borrowed from {0}",
m))
})format!(
3644 "this function's return type contains a borrowed value, but the signature does \
3645 not say whether it is borrowed from {m}",
3646 ));
3647 }
3648 }
3649
3650 #[allow(rustc::symbol_intern_string_literal)]
3651 let existing_name = match &in_scope_lifetimes[..] {
3652 [] => Symbol::intern("'a"),
3653 [(existing, _)] => existing.name,
3654 _ => Symbol::intern("'lifetime"),
3655 };
3656
3657 let mut spans_suggs: Vec<_> = Vec::new();
3658 let build_sugg = |lt: MissingLifetime| match lt.kind {
3659 MissingLifetimeKind::Underscore => {
3660 if true {
match (<.count, &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(lt.count, 1);
3661 (lt.span, existing_name.to_string())
3662 }
3663 MissingLifetimeKind::Ampersand => {
3664 if true {
match (<.count, &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(lt.count, 1);
3665 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
3666 }
3667 MissingLifetimeKind::Comma => {
3668 let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3669 .flatten()
3670 .collect();
3671 (lt.span.shrink_to_hi(), sugg)
3672 }
3673 MissingLifetimeKind::Brackets => {
3674 let sugg: String = std::iter::once("<")
3675 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3676 .chain([">"])
3677 .collect();
3678 (lt.span.shrink_to_hi(), sugg)
3679 }
3680 };
3681 for < in &lifetime_refs {
3682 spans_suggs.push(build_sugg(lt));
3683 }
3684 {
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/diagnostics.rs:3684",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(3684u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["spans_suggs"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&spans_suggs)
as &dyn Value))])
});
} else { ; }
};debug!(?spans_suggs);
3685 match in_scope_lifetimes.len() {
3686 0 => {
3687 if let Some((param_lifetimes, _)) = function_param_lifetimes {
3688 for lt in param_lifetimes {
3689 spans_suggs.push(build_sugg(lt))
3690 }
3691 }
3692 self.suggest_introducing_lifetime(
3693 err,
3694 None,
3695 |err, higher_ranked, span, message, intro_sugg, _| {
3696 err.multipart_suggestion_verbose(
3697 message,
3698 std::iter::once((span, intro_sugg))
3699 .chain(spans_suggs.clone())
3700 .collect(),
3701 Applicability::MaybeIncorrect,
3702 );
3703 higher_ranked
3704 },
3705 );
3706 }
3707 1 => {
3708 let post = if maybe_static {
3709 let owned = if let [lt] = &lifetime_refs[..]
3710 && lt.kind != MissingLifetimeKind::Ampersand
3711 {
3712 ", or if you will only have owned values"
3713 } else {
3714 ""
3715 };
3716 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", but this is uncommon unless you\'re returning a borrowed value from a `const` or a `static`{0}",
owned))
})format!(
3717 ", but this is uncommon unless you're returning a borrowed value from a \
3718 `const` or a `static`{owned}",
3719 )
3720 } else {
3721 String::new()
3722 };
3723 err.multipart_suggestion_verbose(
3724 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider using the `{0}` lifetime{1}",
existing_name, post))
})format!("consider using the `{existing_name}` lifetime{post}"),
3725 spans_suggs,
3726 Applicability::MaybeIncorrect,
3727 );
3728 if maybe_static {
3729 if let [lt] = &lifetime_refs[..]
3735 && (lt.kind == MissingLifetimeKind::Ampersand
3736 || lt.kind == MissingLifetimeKind::Underscore)
3737 {
3738 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
3739 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3740 && !sig.decl.inputs.is_empty()
3741 && let sugg = sig
3742 .decl
3743 .inputs
3744 .iter()
3745 .filter_map(|param| {
3746 if param.ty.span.contains(lt.span) {
3747 None
3750 } else if let TyKind::CVarArgs = param.ty.kind {
3751 None
3753 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
3754 None
3756 } else {
3757 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3758 }
3759 })
3760 .collect::<Vec<_>>()
3761 && !sugg.is_empty()
3762 {
3763 let (the, s) = if sig.decl.inputs.len() == 1 {
3764 ("the", "")
3765 } else {
3766 ("one of the", "s")
3767 };
3768 let dotdotdot =
3769 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
3770 err.multipart_suggestion_verbose(
3771 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("instead, you are more likely to want to change {0} argument{1} to be borrowed{2}",
the, s, dotdotdot))
})format!(
3772 "instead, you are more likely to want to change {the} \
3773 argument{s} to be borrowed{dotdotdot}",
3774 ),
3775 sugg,
3776 Applicability::MaybeIncorrect,
3777 );
3778 "...or alternatively, you might want"
3779 } else if (lt.kind == MissingLifetimeKind::Ampersand
3780 || lt.kind == MissingLifetimeKind::Underscore)
3781 && let Some((kind, _span)) = self.diag_metadata.current_function
3782 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3783 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3784 && !sig.decl.inputs.is_empty()
3785 && let arg_refs = sig
3786 .decl
3787 .inputs
3788 .iter()
3789 .filter_map(|param| match ¶m.ty.kind {
3790 TyKind::ImplTrait(_, bounds) => Some(bounds),
3791 _ => None,
3792 })
3793 .flat_map(|bounds| bounds.into_iter())
3794 .collect::<Vec<_>>()
3795 && !arg_refs.is_empty()
3796 {
3797 let mut lt_finder =
3803 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
3804 for bound in arg_refs {
3805 if let ast::GenericBound::Trait(trait_ref) = bound {
3806 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3807 }
3808 }
3809 lt_finder.visit_ty(ret_ty);
3810 let spans_suggs: Vec<_> = lt_finder
3811 .seen
3812 .iter()
3813 .filter_map(|ty| match &ty.kind {
3814 TyKind::Ref(_, mut_ty) => {
3815 let span = ty.span.with_hi(mut_ty.ty.span.lo());
3816 Some((span, "&'a ".to_string()))
3817 }
3818 _ => None,
3819 })
3820 .collect();
3821 self.suggest_introducing_lifetime(
3822 err,
3823 None,
3824 |err, higher_ranked, span, message, intro_sugg, _| {
3825 err.multipart_suggestion_verbose(
3826 message,
3827 std::iter::once((span, intro_sugg))
3828 .chain(spans_suggs.clone())
3829 .collect(),
3830 Applicability::MaybeIncorrect,
3831 );
3832 higher_ranked
3833 },
3834 );
3835 "alternatively, you might want"
3836 } else {
3837 "instead, you are more likely to want"
3838 };
3839 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3840 let mut sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span, String::new())]))vec![(lt.span, String::new())];
3841 if let Some((kind, _span)) = self.diag_metadata.current_function
3842 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3843 && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3844 {
3845 let mut lt_finder =
3846 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
3847 lt_finder.visit_ty(&ty);
3848
3849 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3850 <_finder.seen[..]
3851 {
3852 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(span.with_hi(mut_ty.ty.span.lo()),
String::new())]))vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
3858 owned_sugg = true;
3859 }
3860 if let Some(ty) = lt_finder.found {
3861 if let TyKind::Path(None, path) = &ty.kind {
3862 let path: Vec<_> = Segment::from_path(path);
3864 match self.resolve_path(
3865 &path,
3866 Some(TypeNS),
3867 None,
3868 PathSource::Type,
3869 ) {
3870 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3871 match module.res() {
3872 Some(Res::PrimTy(PrimTy::Str)) => {
3873 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span.with_hi(ty.span.hi()),
"String".to_string())]))vec![(
3875 lt.span.with_hi(ty.span.hi()),
3876 "String".to_string(),
3877 )];
3878 }
3879 Some(Res::PrimTy(..)) => {}
3880 Some(Res::Def(
3881 DefKind::Struct
3882 | DefKind::Union
3883 | DefKind::Enum
3884 | DefKind::ForeignTy
3885 | DefKind::AssocTy
3886 | DefKind::OpaqueTy
3887 | DefKind::TyParam,
3888 _,
3889 )) => {}
3890 _ => {
3891 owned_sugg = false;
3893 }
3894 }
3895 }
3896 PathResult::NonModule(res) => {
3897 match res.base_res() {
3898 Res::PrimTy(PrimTy::Str) => {
3899 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span.with_hi(ty.span.hi()),
"String".to_string())]))vec![(
3901 lt.span.with_hi(ty.span.hi()),
3902 "String".to_string(),
3903 )];
3904 }
3905 Res::PrimTy(..) => {}
3906 Res::Def(
3907 DefKind::Struct
3908 | DefKind::Union
3909 | DefKind::Enum
3910 | DefKind::ForeignTy
3911 | DefKind::AssocTy
3912 | DefKind::OpaqueTy
3913 | DefKind::TyParam,
3914 _,
3915 ) => {}
3916 _ => {
3917 owned_sugg = false;
3919 }
3920 }
3921 }
3922 _ => {
3923 owned_sugg = false;
3925 }
3926 }
3927 }
3928 if let TyKind::Slice(inner_ty) = &ty.kind {
3929 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span.with_hi(inner_ty.span.lo()),
"Vec<".to_string()),
(ty.span.with_lo(inner_ty.span.hi()), ">".to_string())]))vec![
3931 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3932 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3933 ];
3934 }
3935 }
3936 }
3937 if owned_sugg {
3938 err.multipart_suggestion_verbose(
3939 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
3940 sugg,
3941 Applicability::MaybeIncorrect,
3942 );
3943 }
3944 }
3945 }
3946 }
3947 _ => {
3948 let lifetime_spans: Vec<_> =
3949 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3950 err.span_note(lifetime_spans, "these named lifetimes are available to use");
3951
3952 if spans_suggs.len() > 0 {
3953 err.multipart_suggestion_verbose(
3956 "consider using one of the available lifetimes here",
3957 spans_suggs,
3958 Applicability::HasPlaceholders,
3959 );
3960 }
3961 }
3962 }
3963 }
3964}
3965
3966fn mk_where_bound_predicate(
3967 path: &Path,
3968 poly_trait_ref: &ast::PolyTraitRef,
3969 ty: &Ty,
3970) -> Option<ast::WhereBoundPredicate> {
3971 let modified_segments = {
3972 let mut segments = path.segments.clone();
3973 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3974 return None;
3975 };
3976 let mut segments = ThinVec::from(preceding);
3977
3978 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3979 id: DUMMY_NODE_ID,
3980 ident: last.ident,
3981 gen_args: None,
3982 kind: ast::AssocItemConstraintKind::Equality {
3983 term: ast::Term::Ty(Box::new(ast::Ty {
3984 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3985 id: DUMMY_NODE_ID,
3986 span: DUMMY_SP,
3987 tokens: None,
3988 })),
3989 },
3990 span: DUMMY_SP,
3991 });
3992
3993 match second_last.args.as_deref_mut() {
3994 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3995 args.push(added_constraint);
3996 }
3997 Some(_) => return None,
3998 None => {
3999 second_last.args =
4000 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4001 args: ThinVec::from([added_constraint]),
4002 span: DUMMY_SP,
4003 })));
4004 }
4005 }
4006
4007 segments.push(second_last.clone());
4008 segments
4009 };
4010
4011 let new_where_bound_predicate = ast::WhereBoundPredicate {
4012 bound_generic_params: ThinVec::new(),
4013 bounded_ty: Box::new(ty.clone()),
4014 bounds: <[_]>::into_vec(::alloc::boxed::box_new([ast::GenericBound::Trait(ast::PolyTraitRef {
bound_generic_params: ThinVec::new(),
modifiers: ast::TraitBoundModifiers::NONE,
trait_ref: ast::TraitRef {
path: ast::Path {
segments: modified_segments,
span: DUMMY_SP,
tokens: None,
},
ref_id: DUMMY_NODE_ID,
},
span: DUMMY_SP,
parens: ast::Parens::No,
})]))vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4015 bound_generic_params: ThinVec::new(),
4016 modifiers: ast::TraitBoundModifiers::NONE,
4017 trait_ref: ast::TraitRef {
4018 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
4019 ref_id: DUMMY_NODE_ID,
4020 },
4021 span: DUMMY_SP,
4022 parens: ast::Parens::No,
4023 })],
4024 };
4025
4026 Some(new_where_bound_predicate)
4027}
4028
4029pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
4031 {
sess.dcx().struct_span_err(shadower.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime name `{0}` shadows a lifetime name that is already in scope",
orig.name))
})).with_code(E0496)
}struct_span_code_err!(
4032 sess.dcx(),
4033 shadower.span,
4034 E0496,
4035 "lifetime name `{}` shadows a lifetime name that is already in scope",
4036 orig.name,
4037 )
4038 .with_span_label(orig.span, "first declared here")
4039 .with_span_label(shadower.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` already in scope",
orig.name))
})format!("lifetime `{}` already in scope", orig.name))
4040 .emit();
4041}
4042
4043struct LifetimeFinder<'ast> {
4044 lifetime: Span,
4045 found: Option<&'ast Ty>,
4046 seen: Vec<&'ast Ty>,
4047}
4048
4049impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4050 fn visit_ty(&mut self, t: &'ast Ty) {
4051 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4052 self.seen.push(t);
4053 if t.span.lo() == self.lifetime.lo() {
4054 self.found = Some(&mut_ty.ty);
4055 }
4056 }
4057 walk_ty(self, t)
4058 }
4059}
4060
4061pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4064 let name = shadower.name;
4065 let shadower = shadower.span;
4066 sess.dcx()
4067 .struct_span_warn(
4068 shadower,
4069 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("label name `{0}` shadows a label name that is already in scope",
name))
})format!("label name `{name}` shadows a label name that is already in scope"),
4070 )
4071 .with_span_label(orig, "first declared here")
4072 .with_span_label(shadower, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("label `{0}` already in scope",
name))
})format!("label `{name}` already in scope"))
4073 .emit();
4074}