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<_> = self
1624 .r
1625 .resolutions(module)
1626 .borrow()
1627 .iter()
1628 .filter_map(|(key, resolution)| {
1629 let resolution = resolution.borrow();
1630 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1631 if filter_fn(res) {
1632 Some((key.ident.name, resolution.orig_ident_span, res))
1633 } else {
1634 None
1635 }
1636 })
1637 })
1638 .collect();
1639 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1640 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1641 }
1642 }
1643 }
1644 None
1645 }
1646
1647 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1649 let Some(ast::WherePredicate {
1651 kind:
1652 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1653 bounded_ty,
1654 bound_generic_params,
1655 bounds,
1656 }),
1657 span: where_span,
1658 ..
1659 }) = self.diag_metadata.current_where_predicate
1660 else {
1661 return false;
1662 };
1663 if !bound_generic_params.is_empty() {
1664 return false;
1665 }
1666
1667 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1669 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1671 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _)) => true,
_ => false,
}matches!(
1672 partial_res.full_res(),
1673 Some(hir::def::Res::Def(hir::def::DefKind::AssocTy, _))
1674 ) {
1675 return false;
1676 }
1677
1678 let peeled_ty = qself.ty.peel_refs();
1679 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1680 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1682 return false;
1683 };
1684 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _)) => true,
_ => false,
}matches!(
1685 partial_res.full_res(),
1686 Some(hir::def::Res::Def(hir::def::DefKind::TyParam, _))
1687 ) {
1688 return false;
1689 }
1690 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1691 (&type_param_path.segments[..], &bounds[..])
1692 else {
1693 return false;
1694 };
1695 let [ast::PathSegment { ident, args: None, id }] =
1696 &poly_trait_ref.trait_ref.path.segments[..]
1697 else {
1698 return false;
1699 };
1700 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1701 return false;
1702 }
1703 if ident.span == span {
1704 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1705 return false;
1706 };
1707 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(..))) {
1708 return false;
1709 }
1710
1711 let Some(new_where_bound_predicate) =
1712 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1713 else {
1714 return false;
1715 };
1716 err.span_suggestion_verbose(
1717 *where_span,
1718 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
1719 where_bound_predicate_to_string(&new_where_bound_predicate),
1720 Applicability::MaybeIncorrect,
1721 );
1722 }
1723 true
1724 }
1725
1726 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1729 let mut has_self_arg = None;
1730 if let PathSource::Expr(Some(parent)) = source
1731 && let ExprKind::Call(_, args) = &parent.kind
1732 && !args.is_empty()
1733 {
1734 let mut expr_kind = &args[0].kind;
1735 loop {
1736 match expr_kind {
1737 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1738 if arg_name.segments[0].ident.name == kw::SelfLower {
1739 let call_span = parent.span;
1740 let tail_args_span = if args.len() > 1 {
1741 Some(Span::new(
1742 args[1].span.lo(),
1743 args.last().unwrap().span.hi(),
1744 call_span.ctxt(),
1745 None,
1746 ))
1747 } else {
1748 None
1749 };
1750 has_self_arg = Some((call_span, tail_args_span));
1751 }
1752 break;
1753 }
1754 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1755 _ => break,
1756 }
1757 }
1758 }
1759 has_self_arg
1760 }
1761
1762 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1763 let sm = self.r.tcx.sess.source_map();
1768 if let Some(followed_brace_span) = sm.span_look_ahead(span, "{", Some(50)) {
1769 let close_brace_span = sm.span_look_ahead(followed_brace_span, "}", Some(50));
1772 let closing_brace = close_brace_span.map(|sp| span.to(sp));
1773 (true, closing_brace)
1774 } else {
1775 (false, None)
1776 }
1777 }
1778
1779 fn is_struct_with_fn_ctor(&mut self, def_id: DefId) -> bool {
1780 def_id
1781 .as_local()
1782 .and_then(|local_id| self.r.struct_constructors.get(&local_id))
1783 .map(|struct_ctor| {
1784 #[allow(non_exhaustive_omitted_patterns)] match struct_ctor.0 {
def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1785 struct_ctor.0,
1786 def::Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1787 )
1788 })
1789 .unwrap_or(false)
1790 }
1791
1792 fn update_err_for_private_tuple_struct_fields(
1793 &mut self,
1794 err: &mut Diag<'_>,
1795 source: &PathSource<'_, '_, '_>,
1796 def_id: DefId,
1797 ) -> Option<Vec<Span>> {
1798 match source {
1799 PathSource::TupleStruct(_, pattern_spans) => {
1801 err.primary_message(
1802 "cannot match against a tuple struct which contains private fields",
1803 );
1804
1805 Some(Vec::from(*pattern_spans))
1807 }
1808 PathSource::Expr(Some(Expr {
1810 kind: ExprKind::Call(path, args),
1811 span: call_span,
1812 ..
1813 })) => {
1814 err.primary_message(
1815 "cannot initialize a tuple struct which contains private fields",
1816 );
1817 self.suggest_alternative_construction_methods(
1818 def_id,
1819 err,
1820 path.span,
1821 *call_span,
1822 &args[..],
1823 );
1824
1825 self.r
1826 .field_idents(def_id)
1827 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
1828 }
1829 _ => None,
1830 }
1831 }
1832
1833 fn smart_resolve_context_dependent_help(
1837 &mut self,
1838 err: &mut Diag<'_>,
1839 span: Span,
1840 source: PathSource<'_, '_, '_>,
1841 path: &[Segment],
1842 res: Res,
1843 path_str: &str,
1844 fallback_label: &str,
1845 ) -> bool {
1846 let ns = source.namespace();
1847 let is_expected = &|res| source.is_expected(res);
1848
1849 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
1850 const MESSAGE: &str = "use the path separator to refer to an item";
1851
1852 let (lhs_span, rhs_span) = match &expr.kind {
1853 ExprKind::Field(base, ident) => (base.span, ident.span),
1854 ExprKind::MethodCall(box MethodCall { receiver, span, .. }) => {
1855 (receiver.span, *span)
1856 }
1857 _ => return false,
1858 };
1859
1860 if lhs_span.eq_ctxt(rhs_span) {
1861 err.span_suggestion_verbose(
1862 lhs_span.between(rhs_span),
1863 MESSAGE,
1864 "::",
1865 Applicability::MaybeIncorrect,
1866 );
1867 true
1868 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
1869 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
1870 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
1871 {
1872 err.span_suggestion_verbose(
1876 lhs_source_span.until(rhs_span),
1877 MESSAGE,
1878 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
1879 Applicability::MaybeIncorrect,
1880 );
1881 true
1882 } else {
1883 false
1889 }
1890 };
1891
1892 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
1893 match source {
1894 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
1895 | PathSource::TupleStruct(span, _) => {
1896 err.span(*span);
1899 *span
1900 }
1901 _ => span,
1902 }
1903 };
1904
1905 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
1906 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
1907
1908 match source {
1909 PathSource::Expr(Some(
1910 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
1911 )) if path_sep(this, err, parent, DefKind::Struct) => {}
1912 PathSource::Expr(
1913 None
1914 | Some(Expr {
1915 kind:
1916 ExprKind::Path(..)
1917 | ExprKind::Binary(..)
1918 | ExprKind::Unary(..)
1919 | ExprKind::If(..)
1920 | ExprKind::While(..)
1921 | ExprKind::ForLoop { .. }
1922 | ExprKind::Match(..),
1923 ..
1924 }),
1925 ) if followed_by_brace => {
1926 if let Some(sp) = closing_brace {
1927 err.span_label(span, fallback_label.to_string());
1928 err.multipart_suggestion(
1929 "surround the struct literal with parentheses",
1930 <[_]>::into_vec(::alloc::boxed::box_new([(sp.shrink_to_lo(), "(".to_string()),
(sp.shrink_to_hi(), ")".to_string())]))vec![
1931 (sp.shrink_to_lo(), "(".to_string()),
1932 (sp.shrink_to_hi(), ")".to_string()),
1933 ],
1934 Applicability::MaybeIncorrect,
1935 );
1936 } else {
1937 err.span_label(
1938 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!(
1940 "you might want to surround a struct literal with parentheses: \
1941 `({path_str} {{ /* fields */ }})`?"
1942 ),
1943 );
1944 }
1945 }
1946 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
1947 let span = find_span(&source, err);
1948 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"));
1949
1950 let (tail, descr, applicability, old_fields) = match source {
1951 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
1952 PathSource::TupleStruct(_, args) => (
1953 "",
1954 "pattern",
1955 Applicability::MachineApplicable,
1956 Some(
1957 args.iter()
1958 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
1959 .collect::<Vec<Option<String>>>(),
1960 ),
1961 ),
1962 _ => (": val", "literal", Applicability::HasPlaceholders, None),
1963 };
1964
1965 if !this.has_private_fields(def_id) {
1966 let fields = this.r.field_idents(def_id);
1969 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
1970
1971 if let PathSource::Expr(Some(Expr {
1972 kind: ExprKind::Call(path, args),
1973 span,
1974 ..
1975 })) = source
1976 && !args.is_empty()
1977 && let Some(fields) = &fields
1978 && args.len() == fields.len()
1979 {
1981 let path_span = path.span;
1982 let mut parts = Vec::new();
1983
1984 parts.push((
1986 path_span.shrink_to_hi().until(args[0].span),
1987 "{".to_owned(),
1988 ));
1989
1990 for (field, arg) in fields.iter().zip(args.iter()) {
1991 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
1993 }
1994
1995 parts.push((
1997 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
1998 "}".to_owned(),
1999 ));
2000
2001 err.multipart_suggestion_verbose(
2002 ::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"),
2003 parts,
2004 applicability,
2005 );
2006 } else {
2007 let (fields, applicability) = match fields {
2008 Some(fields) => {
2009 let fields = if let Some(old_fields) = old_fields {
2010 fields
2011 .iter()
2012 .enumerate()
2013 .map(|(idx, new)| (new, old_fields.get(idx)))
2014 .map(|(new, old)| {
2015 if let Some(Some(old)) = old
2016 && new.as_str() != old
2017 {
2018 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2019 } else {
2020 new.to_string()
2021 }
2022 })
2023 .collect::<Vec<String>>()
2024 } else {
2025 fields
2026 .iter()
2027 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2028 .collect::<Vec<String>>()
2029 };
2030
2031 (fields.join(", "), applicability)
2032 }
2033 None => {
2034 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2035 }
2036 };
2037 let pad = if has_fields { " " } else { "" };
2038 err.span_suggestion(
2039 span,
2040 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2041 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}"),
2042 applicability,
2043 );
2044 }
2045 }
2046 if let PathSource::Expr(Some(Expr {
2047 kind: ExprKind::Call(path, args),
2048 span: call_span,
2049 ..
2050 })) = source
2051 {
2052 this.suggest_alternative_construction_methods(
2053 def_id,
2054 err,
2055 path.span,
2056 *call_span,
2057 &args[..],
2058 );
2059 }
2060 }
2061 _ => {
2062 err.span_label(span, fallback_label.to_string());
2063 }
2064 }
2065 };
2066
2067 match (res, source) {
2068 (
2069 Res::Def(DefKind::Macro(kinds), def_id),
2070 PathSource::Expr(Some(Expr {
2071 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2072 }))
2073 | PathSource::Struct(_),
2074 ) if kinds.contains(MacroKinds::BANG) => {
2075 let suggestable = def_id.is_local()
2077 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2078
2079 err.span_label(span, fallback_label.to_string());
2080
2081 if path
2083 .last()
2084 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2085 && suggestable
2086 {
2087 err.span_suggestion_verbose(
2088 span.shrink_to_hi(),
2089 "use `!` to invoke the macro",
2090 "!",
2091 Applicability::MaybeIncorrect,
2092 );
2093 }
2094
2095 if path_str == "try" && span.is_rust_2015() {
2096 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2097 }
2098 }
2099 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2100 err.span_label(span, fallback_label.to_string());
2101 }
2102 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2103 err.span_label(span, "type aliases cannot be used as traits");
2104 if self.r.tcx.sess.is_nightly_build() {
2105 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2106 `type` alias";
2107 let span = self.r.def_span(def_id);
2108 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2109 let snip = snip.replacen("type", "trait", 1);
2112 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2113 } else {
2114 err.span_help(span, msg);
2115 }
2116 }
2117 }
2118 (
2119 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2120 PathSource::Expr(Some(parent)),
2121 ) if path_sep(self, err, parent, kind) => {
2122 return true;
2123 }
2124 (
2125 Res::Def(DefKind::Enum, def_id),
2126 PathSource::TupleStruct(..) | PathSource::Expr(..),
2127 ) => {
2128 self.suggest_using_enum_variant(err, source, def_id, span);
2129 }
2130 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2131 let struct_ctor = match def_id.as_local() {
2132 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned(),
2133 None => {
2134 let ctor = self.r.cstore().ctor_untracked(self.r.tcx(), def_id);
2135 ctor.map(|(ctor_kind, ctor_def_id)| {
2136 let ctor_res =
2137 Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
2138 let ctor_vis = self.r.tcx.visibility(ctor_def_id);
2139 let field_visibilities = self
2140 .r
2141 .tcx
2142 .associated_item_def_ids(def_id)
2143 .iter()
2144 .map(|field_id| self.r.tcx.visibility(field_id))
2145 .collect();
2146 (ctor_res, ctor_vis, field_visibilities)
2147 })
2148 }
2149 };
2150
2151 let (ctor_def, ctor_vis, fields) = if let Some(struct_ctor) = struct_ctor {
2152 if let PathSource::Expr(Some(parent)) = source
2153 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2154 {
2155 bad_struct_syntax_suggestion(self, err, def_id);
2156 return true;
2157 }
2158 struct_ctor
2159 } else {
2160 bad_struct_syntax_suggestion(self, err, def_id);
2161 return true;
2162 };
2163
2164 let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);
2165 if let Some(use_span) = self.r.inaccessible_ctor_reexport.get(&span)
2166 && is_accessible
2167 {
2168 err.span_note(
2169 *use_span,
2170 "the type is accessed through this re-export, but the type's constructor \
2171 is not visible in this import's scope due to private fields",
2172 );
2173 if is_accessible
2174 && fields
2175 .iter()
2176 .all(|vis| self.r.is_accessible_from(*vis, self.parent_scope.module))
2177 {
2178 err.span_suggestion_verbose(
2179 span,
2180 "the type can be constructed directly, because its fields are \
2181 available from the current scope",
2182 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2186 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2188 ),
2189 Applicability::MachineApplicable,
2190 );
2191 }
2192 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2193 }
2194 if !is_expected(ctor_def) || is_accessible {
2195 return true;
2196 }
2197
2198 let field_spans =
2199 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2200
2201 if let Some(spans) =
2202 field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())
2203 {
2204 let non_visible_spans: Vec<Span> = iter::zip(&fields, &spans)
2205 .filter(|(vis, _)| {
2206 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2207 })
2208 .map(|(_, span)| *span)
2209 .collect();
2210
2211 if non_visible_spans.len() > 0 {
2212 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2213 err.multipart_suggestion_verbose(
2214 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2215 "consider making the field{} publicly accessible",
2216 pluralize!(fields.len())
2217 ),
2218 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2219 Applicability::MaybeIncorrect,
2220 );
2221 }
2222
2223 let mut m: MultiSpan = non_visible_spans.clone().into();
2224 non_visible_spans
2225 .into_iter()
2226 .for_each(|s| m.push_span_label(s, "private field"));
2227 err.span_note(m, "constructor is not visible here due to private fields");
2228 }
2229
2230 return true;
2231 }
2232
2233 err.span_label(span, "constructor is not visible here due to private fields");
2234 }
2235 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2236 bad_struct_syntax_suggestion(self, err, def_id);
2237 }
2238 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2239 match source {
2240 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2241 let span = find_span(&source, err);
2242 err.span_label(
2243 self.r.def_span(def_id),
2244 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2245 );
2246 err.span_suggestion(
2247 span,
2248 "use this syntax instead",
2249 path_str,
2250 Applicability::MaybeIncorrect,
2251 );
2252 }
2253 _ => return false,
2254 }
2255 }
2256 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2257 let def_id = self.r.tcx.parent(ctor_def_id);
2258 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"));
2259 let fields = self.r.field_idents(def_id).map_or_else(
2260 || "/* fields */".to_string(),
2261 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2262 );
2263 err.span_suggestion(
2264 span,
2265 "use the tuple variant pattern syntax instead",
2266 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2267 Applicability::HasPlaceholders,
2268 );
2269 }
2270 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2271 err.span_label(span, fallback_label.to_string());
2272 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2273 }
2274 (
2275 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2276 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2277 ) => {
2278 err.note("can't use a type alias as tuple pattern");
2279
2280 let mut suggestion = Vec::new();
2281
2282 if let &&[first, ..] = args
2283 && let &&[.., last] = args
2284 {
2285 suggestion.extend([
2286 (span.between(first), " { 0: ".to_owned()),
2292 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2293 ]);
2294
2295 suggestion.extend(
2296 args.iter()
2297 .enumerate()
2298 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2300 )
2301 } else {
2302 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2303 }
2304
2305 err.multipart_suggestion(
2306 "use struct pattern instead",
2307 suggestion,
2308 Applicability::MachineApplicable,
2309 );
2310 }
2311 (
2312 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2313 PathSource::TraitItem(
2314 ValueNS,
2315 PathSource::Expr(Some(ast::Expr {
2316 span: whole,
2317 kind: ast::ExprKind::Call(_, args),
2318 ..
2319 })),
2320 ),
2321 ) => {
2322 err.note("can't use a type alias as a constructor");
2323
2324 let mut suggestion = Vec::new();
2325
2326 if let [first, ..] = &**args
2327 && let [.., last] = &**args
2328 {
2329 suggestion.extend([
2330 (span.between(first.span), " { 0: ".to_owned()),
2336 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2337 ]);
2338
2339 suggestion.extend(
2340 args.iter()
2341 .enumerate()
2342 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2344 )
2345 } else {
2346 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2347 }
2348
2349 err.multipart_suggestion(
2350 "use struct expression instead",
2351 suggestion,
2352 Applicability::MachineApplicable,
2353 );
2354 }
2355 _ => return false,
2356 }
2357 true
2358 }
2359
2360 fn suggest_alternative_construction_methods(
2361 &mut self,
2362 def_id: DefId,
2363 err: &mut Diag<'_>,
2364 path_span: Span,
2365 call_span: Span,
2366 args: &[Box<Expr>],
2367 ) {
2368 if def_id.is_local() {
2369 return;
2371 }
2372 let mut items = self
2375 .r
2376 .tcx
2377 .inherent_impls(def_id)
2378 .iter()
2379 .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order())
2380 .filter(|item| item.is_fn() && !item.is_method())
2382 .filter_map(|item| {
2383 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2385 let ret_ty = fn_sig.output().skip_binder();
2387 let ty::Adt(def, _args) = ret_ty.kind() else {
2388 return None;
2389 };
2390 let input_len = fn_sig.inputs().skip_binder().len();
2391 if def.did() != def_id {
2392 return None;
2393 }
2394 let name = item.name();
2395 let order = !name.as_str().starts_with("new");
2396 Some((order, name, input_len))
2397 })
2398 .collect::<Vec<_>>();
2399 items.sort_by_key(|(order, _, _)| *order);
2400 let suggestion = |name, args| {
2401 ::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(", "))
2402 };
2403 match &items[..] {
2404 [] => {}
2405 [(_, name, len)] if *len == args.len() => {
2406 err.span_suggestion_verbose(
2407 path_span.shrink_to_hi(),
2408 ::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",),
2409 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2410 Applicability::MaybeIncorrect,
2411 );
2412 }
2413 [(_, name, len)] => {
2414 err.span_suggestion_verbose(
2415 path_span.shrink_to_hi().with_hi(call_span.hi()),
2416 ::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",),
2417 suggestion(name, *len),
2418 Applicability::MaybeIncorrect,
2419 );
2420 }
2421 _ => {
2422 err.span_suggestions_with_style(
2423 path_span.shrink_to_hi().with_hi(call_span.hi()),
2424 "you might have meant to use an associated function to build this type",
2425 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2426 Applicability::MaybeIncorrect,
2427 SuggestionStyle::ShowAlways,
2428 );
2429 }
2430 }
2431 let default_trait = self
2439 .r
2440 .lookup_import_candidates(
2441 Ident::with_dummy_span(sym::Default),
2442 Namespace::TypeNS,
2443 &self.parent_scope,
2444 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2445 )
2446 .iter()
2447 .filter_map(|candidate| candidate.did)
2448 .find(|did| {
2449 self.r
2450 .tcx
2451 .get_attrs(*did, sym::rustc_diagnostic_item)
2452 .any(|attr| attr.value_str() == Some(sym::Default))
2453 });
2454 let Some(default_trait) = default_trait else {
2455 return;
2456 };
2457 if self
2458 .r
2459 .extern_crate_map
2460 .items()
2461 .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait)))
2463 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2464 .filter_map(|simplified_self_ty| match simplified_self_ty {
2465 SimplifiedType::Adt(did) => Some(did),
2466 _ => None,
2467 })
2468 .any(|did| did == def_id)
2469 {
2470 err.multipart_suggestion(
2471 "consider using the `Default` trait",
2472 <[_]>::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![
2473 (path_span.shrink_to_lo(), "<".to_string()),
2474 (
2475 path_span.shrink_to_hi().with_hi(call_span.hi()),
2476 " as std::default::Default>::default()".to_string(),
2477 ),
2478 ],
2479 Applicability::MaybeIncorrect,
2480 );
2481 }
2482 }
2483
2484 fn has_private_fields(&self, def_id: DefId) -> bool {
2485 let fields = match def_id.as_local() {
2486 Some(def_id) => self.r.struct_constructors.get(&def_id).cloned().map(|(_, _, f)| f),
2487 None => Some(
2488 self.r
2489 .tcx
2490 .associated_item_def_ids(def_id)
2491 .iter()
2492 .map(|field_id| self.r.tcx.visibility(field_id))
2493 .collect(),
2494 ),
2495 };
2496
2497 fields.is_some_and(|fields| {
2498 fields.iter().any(|vis| !self.r.is_accessible_from(*vis, self.parent_scope.module))
2499 })
2500 }
2501
2502 pub(crate) fn find_similarly_named_assoc_item(
2505 &mut self,
2506 ident: Symbol,
2507 kind: &AssocItemKind,
2508 ) -> Option<Symbol> {
2509 let (module, _) = self.current_trait_ref.as_ref()?;
2510 if ident == kw::Underscore {
2511 return None;
2513 }
2514
2515 let targets = self
2516 .r
2517 .resolutions(*module)
2518 .borrow()
2519 .iter()
2520 .filter_map(|(key, res)| res.borrow().best_decl().map(|binding| (key, binding.res())))
2521 .filter(|(_, res)| match (kind, res) {
2522 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
2523 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2524 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2525 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2526 _ => false,
2527 })
2528 .map(|(key, _)| key.ident.name)
2529 .collect::<Vec<_>>();
2530
2531 find_best_match_for_name(&targets, ident, None)
2532 }
2533
2534 fn lookup_assoc_candidate<FilterFn>(
2535 &mut self,
2536 ident: Ident,
2537 ns: Namespace,
2538 filter_fn: FilterFn,
2539 called: bool,
2540 ) -> Option<AssocSuggestion>
2541 where
2542 FilterFn: Fn(Res) -> bool,
2543 {
2544 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2545 match t.kind {
2546 TyKind::Path(None, _) => Some(t.id),
2547 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2548 _ => None,
2552 }
2553 }
2554 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2556 if let Some(node_id) =
2557 self.diag_metadata.current_self_type.as_ref().and_then(extract_node_id)
2558 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2559 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2560 && let Some(fields) = self.r.field_idents(did)
2561 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2562 {
2563 return Some(AssocSuggestion::Field(field.span));
2565 }
2566 }
2567
2568 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2569 for assoc_item in items {
2570 if let Some(assoc_ident) = assoc_item.kind.ident()
2571 && assoc_ident == ident
2572 {
2573 return Some(match &assoc_item.kind {
2574 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2575 ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
2576 AssocSuggestion::MethodWithSelf { called }
2577 }
2578 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2579 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2580 ast::AssocItemKind::Delegation(..)
2581 if self
2582 .r
2583 .delegation_fn_sigs
2584 .get(&self.r.local_def_id(assoc_item.id))
2585 .is_some_and(|sig| sig.has_self) =>
2586 {
2587 AssocSuggestion::MethodWithSelf { called }
2588 }
2589 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2590 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2591 continue;
2592 }
2593 });
2594 }
2595 }
2596 }
2597
2598 if let Some((module, _)) = self.current_trait_ref
2600 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2601 ModuleOrUniformRoot::Module(module),
2602 ident,
2603 ns,
2604 &self.parent_scope,
2605 None,
2606 )
2607 {
2608 let res = binding.res();
2609 if filter_fn(res) {
2610 match res {
2611 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2612 let has_self = match def_id.as_local() {
2613 Some(def_id) => self
2614 .r
2615 .delegation_fn_sigs
2616 .get(&def_id)
2617 .is_some_and(|sig| sig.has_self),
2618 None => {
2619 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2620 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2621 })
2622 }
2623 };
2624 if has_self {
2625 return Some(AssocSuggestion::MethodWithSelf { called });
2626 } else {
2627 return Some(AssocSuggestion::AssocFn { called });
2628 }
2629 }
2630 Res::Def(DefKind::AssocConst, _) => {
2631 return Some(AssocSuggestion::AssocConst);
2632 }
2633 Res::Def(DefKind::AssocTy, _) => {
2634 return Some(AssocSuggestion::AssocType);
2635 }
2636 _ => {}
2637 }
2638 }
2639 }
2640
2641 None
2642 }
2643
2644 fn lookup_typo_candidate(
2645 &mut self,
2646 path: &[Segment],
2647 following_seg: Option<&Segment>,
2648 ns: Namespace,
2649 filter_fn: &impl Fn(Res) -> bool,
2650 ) -> TypoCandidate {
2651 let mut names = Vec::new();
2652 if let [segment] = path {
2653 let mut ctxt = segment.ident.span.ctxt();
2654
2655 for rib in self.ribs[ns].iter().rev() {
2658 let rib_ctxt = if rib.kind.contains_params() {
2659 ctxt.normalize_to_macros_2_0()
2660 } else {
2661 ctxt.normalize_to_macro_rules()
2662 };
2663
2664 for (ident, &res) in &rib.bindings {
2666 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2667 names.push(TypoSuggestion::new(ident.name, ident.span, res));
2668 }
2669 }
2670
2671 if let RibKind::Block(Some(module)) = rib.kind {
2672 self.r.add_module_candidates(module, &mut names, &filter_fn, Some(ctxt));
2673 } else if let RibKind::Module(module) = rib.kind {
2674 let parent_scope = &ParentScope { module, ..self.parent_scope };
2676 self.r.add_scope_set_candidates(
2677 &mut names,
2678 ScopeSet::All(ns),
2679 parent_scope,
2680 segment.ident.span.with_ctxt(ctxt),
2681 filter_fn,
2682 );
2683 break;
2684 }
2685
2686 if let RibKind::MacroDefinition(def) = rib.kind
2687 && def == self.r.macro_def(ctxt)
2688 {
2689 ctxt.remove_mark();
2692 }
2693 }
2694 } else {
2695 let mod_path = &path[..path.len() - 1];
2697 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2698 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2699 {
2700 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2701 }
2702 }
2703
2704 if let Some(following_seg) = following_seg {
2706 names.retain(|suggestion| match suggestion.res {
2707 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2708 suggestion.candidate != following_seg.ident.name
2710 }
2711 Res::Def(DefKind::Mod, def_id) => {
2712 let module = self.r.expect_module(def_id);
2713 self.r
2714 .resolutions(module)
2715 .borrow()
2716 .iter()
2717 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2718 }
2719 _ => true,
2720 });
2721 }
2722 let name = path[path.len() - 1].ident.name;
2723 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2725
2726 match find_best_match_for_name(
2727 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2728 name,
2729 None,
2730 ) {
2731 Some(found) => {
2732 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2733 else {
2734 return TypoCandidate::None;
2735 };
2736 if found == name {
2737 TypoCandidate::Shadowed(sugg.res, sugg.span)
2738 } else {
2739 TypoCandidate::Typo(sugg)
2740 }
2741 }
2742 _ => TypoCandidate::None,
2743 }
2744 }
2745
2746 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2749 let name = path[path.len() - 1].ident.as_str();
2750 Some(match name {
2752 "byte" => sym::u8, "short" => sym::i16,
2754 "Bool" => sym::bool,
2755 "Boolean" => sym::bool,
2756 "boolean" => sym::bool,
2757 "int" => sym::i32,
2758 "long" => sym::i64,
2759 "float" => sym::f32,
2760 "double" => sym::f64,
2761 _ => return None,
2762 })
2763 }
2764
2765 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2768 if ident_span.from_expansion() {
2769 return false;
2770 }
2771
2772 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2774 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2775 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2776 {
2777 let (span, text) = match path.segments.first() {
2778 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2779 let name = name.trim_prefix('_');
2781 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
2782 }
2783 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2784 };
2785
2786 err.span_suggestion_verbose(
2787 span,
2788 "you might have meant to introduce a new binding",
2789 text,
2790 Applicability::MaybeIncorrect,
2791 );
2792 return true;
2793 }
2794
2795 if err.code == Some(E0423)
2798 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
2799 && val_span.contains(ident_span)
2800 && val_span.lo() == ident_span.lo()
2801 {
2802 err.span_suggestion_verbose(
2803 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
2804 "you might have meant to use `:` for type annotation",
2805 ": ",
2806 Applicability::MaybeIncorrect,
2807 );
2808 return true;
2809 }
2810 false
2811 }
2812
2813 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
2814 let mut result = None;
2815 let mut seen_modules = FxHashSet::default();
2816 let root_did = self.r.graph_root.def_id();
2817 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![(
2818 self.r.graph_root,
2819 ThinVec::new(),
2820 root_did.is_local() || !self.r.tcx.is_doc_hidden(root_did),
2821 )];
2822
2823 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
2824 if result.is_some() {
2826 break;
2827 }
2828
2829 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
2830 if result.is_some() || !name_binding.vis().is_visible_locally() {
2832 return;
2833 }
2834 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
2835 let mut path_segments = path_segments.clone();
2837 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
2838 let doc_visible = doc_visible
2839 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
2840 if module_def_id == def_id {
2841 let path =
2842 Path { span: name_binding.span, segments: path_segments, tokens: None };
2843 result = Some((
2844 r.expect_module(module_def_id),
2845 ImportSuggestion {
2846 did: Some(def_id),
2847 descr: "module",
2848 path,
2849 accessible: true,
2850 doc_visible,
2851 note: None,
2852 via_import: false,
2853 is_stable: true,
2854 },
2855 ));
2856 } else {
2857 if seen_modules.insert(module_def_id) {
2859 let module = r.expect_module(module_def_id);
2860 worklist.push((module, path_segments, doc_visible));
2861 }
2862 }
2863 }
2864 });
2865 }
2866
2867 result
2868 }
2869
2870 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
2871 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
2872 let mut variants = Vec::new();
2873 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
2874 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
2875 let mut segms = enum_import_suggestion.path.segments.clone();
2876 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
2877 let path = Path { span: name_binding.span, segments: segms, tokens: None };
2878 variants.push((path, def_id, kind));
2879 }
2880 });
2881 variants
2882 })
2883 }
2884
2885 fn suggest_using_enum_variant(
2887 &self,
2888 err: &mut Diag<'_>,
2889 source: PathSource<'_, '_, '_>,
2890 def_id: DefId,
2891 span: Span,
2892 ) {
2893 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
2894 err.note("you might have meant to use one of the enum's variants");
2895 return;
2896 };
2897
2898 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
2903 PathSource::TupleStruct(..) => (None, true),
2905 PathSource::Expr(Some(expr)) => match &expr.kind {
2906 ExprKind::Call(..) => (None, true),
2908 ExprKind::MethodCall(box MethodCall {
2911 receiver,
2912 span,
2913 seg: PathSegment { ident, .. },
2914 ..
2915 }) => {
2916 let dot_span = receiver.span.between(*span);
2917 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
2918 *ctor_kind == CtorKind::Fn
2919 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
2920 });
2921 (found_tuple_variant.then_some(dot_span), false)
2922 }
2923 ExprKind::Field(base, ident) => {
2926 let dot_span = base.span.between(ident.span);
2927 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
2928 path.segments.last().is_some_and(|seg| seg.ident == *ident)
2929 });
2930 (found_tuple_or_unit_variant.then_some(dot_span), false)
2931 }
2932 _ => (None, false),
2933 },
2934 _ => (None, false),
2935 };
2936
2937 if let Some(dot_span) = suggest_path_sep_dot_span {
2938 err.span_suggestion_verbose(
2939 dot_span,
2940 "use the path separator to refer to a variant",
2941 "::",
2942 Applicability::MaybeIncorrect,
2943 );
2944 } else if suggest_only_tuple_variants {
2945 let mut suggestable_variants = variant_ctors
2948 .iter()
2949 .filter(|(.., kind)| *kind == CtorKind::Fn)
2950 .map(|(variant, ..)| path_names_to_string(variant))
2951 .collect::<Vec<_>>();
2952 suggestable_variants.sort();
2953
2954 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
2955
2956 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
2957 "to match against"
2958 } else {
2959 "to construct"
2960 };
2961
2962 if !suggestable_variants.is_empty() {
2963 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
2964 ::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")
2965 } else {
2966 ::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")
2967 };
2968
2969 err.span_suggestions(
2970 span,
2971 msg,
2972 suggestable_variants,
2973 Applicability::MaybeIncorrect,
2974 );
2975 }
2976
2977 if non_suggestable_variant_count == variant_ctors.len() {
2979 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}"));
2980 }
2981
2982 if non_suggestable_variant_count == 1 {
2984 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"));
2985 } else if non_suggestable_variant_count >= 1 {
2986 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!(
2987 "you might have meant {source_msg} one of the enum's non-tuple variants"
2988 ));
2989 }
2990 } else {
2991 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
2992 let def_id = self.r.tcx.parent(ctor_def_id);
2993 match kind {
2994 CtorKind::Const => false,
2995 CtorKind::Fn => {
2996 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
2997 }
2998 }
2999 };
3000
3001 let mut suggestable_variants = variant_ctors
3002 .iter()
3003 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3004 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3005 .map(|(variant, kind)| match kind {
3006 CtorKind::Const => variant,
3007 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3008 })
3009 .collect::<Vec<_>>();
3010 suggestable_variants.sort();
3011 let no_suggestable_variant = suggestable_variants.is_empty();
3012
3013 if !no_suggestable_variant {
3014 let msg = if suggestable_variants.len() == 1 {
3015 "you might have meant to use the following enum variant"
3016 } else {
3017 "you might have meant to use one of the following enum variants"
3018 };
3019
3020 err.span_suggestions(
3021 span,
3022 msg,
3023 suggestable_variants,
3024 Applicability::MaybeIncorrect,
3025 );
3026 }
3027
3028 let mut suggestable_variants_with_placeholders = variant_ctors
3029 .iter()
3030 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3031 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3032 .filter_map(|(variant, kind)| match kind {
3033 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3034 _ => None,
3035 })
3036 .collect::<Vec<_>>();
3037 suggestable_variants_with_placeholders.sort();
3038
3039 if !suggestable_variants_with_placeholders.is_empty() {
3040 let msg =
3041 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3042 (true, 1) => "the following enum variant is available",
3043 (true, _) => "the following enum variants are available",
3044 (false, 1) => "alternatively, the following enum variant is available",
3045 (false, _) => {
3046 "alternatively, the following enum variants are also available"
3047 }
3048 };
3049
3050 err.span_suggestions(
3051 span,
3052 msg,
3053 suggestable_variants_with_placeholders,
3054 Applicability::HasPlaceholders,
3055 );
3056 }
3057 };
3058
3059 if def_id.is_local() {
3060 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3061 }
3062 }
3063
3064 pub(crate) fn suggest_adding_generic_parameter(
3065 &self,
3066 path: &[Segment],
3067 source: PathSource<'_, '_, '_>,
3068 ) -> Option<(Span, &'static str, String, Applicability)> {
3069 let (ident, span) = match path {
3070 [segment]
3071 if !segment.has_generic_args
3072 && segment.ident.name != kw::SelfUpper
3073 && segment.ident.name != kw::Dyn =>
3074 {
3075 (segment.ident.to_string(), segment.ident.span)
3076 }
3077 _ => return None,
3078 };
3079 let mut iter = ident.chars().map(|c| c.is_uppercase());
3080 let single_uppercase_char =
3081 #[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);
3082 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3083 return None;
3084 }
3085 match (self.diag_metadata.current_item, single_uppercase_char, self.diag_metadata.currently_processing_generic_args) {
3086 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3087 }
3089 (
3090 Some(Item {
3091 kind:
3092 kind @ ItemKind::Fn(..)
3093 | kind @ ItemKind::Enum(..)
3094 | kind @ ItemKind::Struct(..)
3095 | kind @ ItemKind::Union(..),
3096 ..
3097 }),
3098 true, _
3099 )
3100 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3102 | (Some(Item { kind, .. }), false, _) => {
3103 if let Some(generics) = kind.generics() {
3104 if span.overlaps(generics.span) {
3105 return None;
3114 }
3115
3116 let (msg, sugg) = match source {
3117 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3118 ("you might be missing a type parameter", ident)
3119 }
3120 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3121 "you might be missing a const parameter",
3122 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3123 ),
3124 _ => return None,
3125 };
3126 let (span, sugg) = if let [.., param] = &generics.params[..] {
3127 let span = if let [.., bound] = ¶m.bounds[..] {
3128 bound.span()
3129 } else if let GenericParam {
3130 kind: GenericParamKind::Const { ty, span: _, default }, ..
3131 } = param {
3132 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3133 } else {
3134 param.ident.span
3135 };
3136 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3137 } else {
3138 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3139 };
3140 if span.can_be_used_for_suggestions() {
3142 return Some((
3143 span.shrink_to_hi(),
3144 msg,
3145 sugg,
3146 Applicability::MaybeIncorrect,
3147 ));
3148 }
3149 }
3150 }
3151 _ => {}
3152 }
3153 None
3154 }
3155
3156 pub(crate) fn suggestion_for_label_in_rib(
3159 &self,
3160 rib_index: usize,
3161 label: Ident,
3162 ) -> Option<LabelSuggestion> {
3163 let within_scope = self.is_label_valid_from_rib(rib_index);
3165
3166 let rib = &self.label_ribs[rib_index];
3167 let names = rib
3168 .bindings
3169 .iter()
3170 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3171 .map(|(id, _)| id.name)
3172 .collect::<Vec<Symbol>>();
3173
3174 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3175 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3179 (*ident, within_scope)
3180 })
3181 }
3182
3183 pub(crate) fn maybe_report_lifetime_uses(
3184 &mut self,
3185 generics_span: Span,
3186 params: &[ast::GenericParam],
3187 ) {
3188 for (param_index, param) in params.iter().enumerate() {
3189 let GenericParamKind::Lifetime = param.kind else { continue };
3190
3191 let def_id = self.r.local_def_id(param.id);
3192
3193 let use_set = self.lifetime_uses.remove(&def_id);
3194 {
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:3194",
"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(3194u32),
::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!(
3195 "Use set for {:?}({:?} at {:?}) is {:?}",
3196 def_id, param.ident, param.ident.span, use_set
3197 );
3198
3199 let deletion_span = || {
3200 if params.len() == 1 {
3201 Some(generics_span)
3203 } else if param_index == 0 {
3204 match (
3207 param.span().find_ancestor_inside(generics_span),
3208 params[param_index + 1].span().find_ancestor_inside(generics_span),
3209 ) {
3210 (Some(param_span), Some(next_param_span)) => {
3211 Some(param_span.to(next_param_span.shrink_to_lo()))
3212 }
3213 _ => None,
3214 }
3215 } else {
3216 match (
3219 param.span().find_ancestor_inside(generics_span),
3220 params[param_index - 1].span().find_ancestor_inside(generics_span),
3221 ) {
3222 (Some(param_span), Some(prev_param_span)) => {
3223 Some(prev_param_span.shrink_to_hi().to(param_span))
3224 }
3225 _ => None,
3226 }
3227 }
3228 };
3229 match use_set {
3230 Some(LifetimeUseSet::Many) => {}
3231 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3232 {
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:3232",
"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(3232u32),
::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);
3233
3234 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3235 let deletion_span =
3236 if param.bounds.is_empty() { deletion_span() } else { None };
3237
3238 self.r.lint_buffer.buffer_lint(
3239 lint::builtin::SINGLE_USE_LIFETIMES,
3240 param.id,
3241 param.ident.span,
3242 lint::BuiltinLintDiag::SingleUseLifetime {
3243 param_span: param.ident.span,
3244 use_span: Some((use_span, elidable)),
3245 deletion_span,
3246 ident: param.ident,
3247 },
3248 );
3249 }
3250 None => {
3251 {
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:3251",
"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(3251u32),
::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);
3252 let deletion_span = deletion_span();
3253
3254 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3256 self.r.lint_buffer.buffer_lint(
3257 lint::builtin::UNUSED_LIFETIMES,
3258 param.id,
3259 param.ident.span,
3260 lint::BuiltinLintDiag::SingleUseLifetime {
3261 param_span: param.ident.span,
3262 use_span: None,
3263 deletion_span,
3264 ident: param.ident,
3265 },
3266 );
3267 }
3268 }
3269 }
3270 }
3271 }
3272
3273 pub(crate) fn emit_undeclared_lifetime_error(
3274 &self,
3275 lifetime_ref: &ast::Lifetime,
3276 outer_lifetime_ref: Option<Ident>,
3277 ) {
3278 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);
3279 let mut err = if let Some(outer) = outer_lifetime_ref {
3280 {
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!(
3281 self.r.dcx(),
3282 lifetime_ref.ident.span,
3283 E0401,
3284 "can't use generic parameters from outer item",
3285 )
3286 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3287 .with_span_label(outer.span, "lifetime parameter from outer item")
3288 } else {
3289 {
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!(
3290 self.r.dcx(),
3291 lifetime_ref.ident.span,
3292 E0261,
3293 "use of undeclared lifetime name `{}`",
3294 lifetime_ref.ident
3295 )
3296 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3297 };
3298
3299 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3301 err.span_suggestion_verbose(
3302 lifetime_ref.ident.span,
3303 "you may have misspelled the `'static` lifetime",
3304 "'static",
3305 Applicability::MachineApplicable,
3306 );
3307 } else {
3308 self.suggest_introducing_lifetime(
3309 &mut err,
3310 Some(lifetime_ref.ident),
3311 |err, _, span, message, suggestion, span_suggs| {
3312 err.multipart_suggestion_verbose(
3313 message,
3314 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3315 Applicability::MaybeIncorrect,
3316 );
3317 true
3318 },
3319 );
3320 }
3321
3322 err.emit();
3323 }
3324
3325 fn suggest_introducing_lifetime(
3326 &self,
3327 err: &mut Diag<'_>,
3328 name: Option<Ident>,
3329 suggest: impl Fn(
3330 &mut Diag<'_>,
3331 bool,
3332 Span,
3333 Cow<'static, str>,
3334 String,
3335 Vec<(Span, String)>,
3336 ) -> bool,
3337 ) {
3338 let mut suggest_note = true;
3339 for rib in self.lifetime_ribs.iter().rev() {
3340 let mut should_continue = true;
3341 match rib.kind {
3342 LifetimeRibKind::Generics { binder, span, kind } => {
3343 if let LifetimeBinderKind::ConstItem = kind
3346 && !self.r.tcx().features().generic_const_items()
3347 {
3348 continue;
3349 }
3350 if let LifetimeBinderKind::ImplAssocType = kind {
3351 continue;
3352 }
3353
3354 if !span.can_be_used_for_suggestions()
3355 && suggest_note
3356 && let Some(name) = name
3357 {
3358 suggest_note = false; err.span_label(
3360 span,
3361 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
3362 "lifetime `{name}` is missing in item created through this procedural macro",
3363 ),
3364 );
3365 continue;
3366 }
3367
3368 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3369 kind,
3370 LifetimeBinderKind::FnPtrType
3371 | LifetimeBinderKind::PolyTrait
3372 | LifetimeBinderKind::WhereBound
3373 );
3374
3375 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3376 let (span, sugg) = if span.is_empty() {
3377 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3378 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3379
3380 if let LifetimeBinderKind::WhereBound = kind
3387 && let Some(predicate) = self.diag_metadata.current_where_predicate
3388 && let ast::WherePredicateKind::BoundPredicate(
3389 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3390 ) = &predicate.kind
3391 && bounded_ty.id == binder
3392 {
3393 for bound in bounds {
3394 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3395 && let span = poly_trait_ref
3396 .span
3397 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3398 && !span.is_empty()
3399 {
3400 rm_inner_binders.insert(span);
3401 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3402 binder_idents.insert(v.ident);
3403 });
3404 }
3405 }
3406 }
3407
3408 let binders_sugg: String = binder_idents
3409 .into_iter()
3410 .map(|ident| ident.to_string())
3411 .intersperse(", ".to_owned())
3412 .collect();
3413 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!(
3414 "{}<{}>{}",
3415 if higher_ranked { "for" } else { "" },
3416 binders_sugg,
3417 if higher_ranked { " " } else { "" },
3418 );
3419 (span, sugg)
3420 } else {
3421 let span = self
3422 .r
3423 .tcx
3424 .sess
3425 .source_map()
3426 .span_through_char(span, '<')
3427 .shrink_to_hi();
3428 let sugg =
3429 ::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"));
3430 (span, sugg)
3431 };
3432
3433 if higher_ranked {
3434 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!(
3435 "consider making the {} lifetime-generic with a new `{}` lifetime",
3436 kind.descr(),
3437 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3438 ));
3439 should_continue = suggest(
3440 err,
3441 true,
3442 span,
3443 message,
3444 sugg,
3445 if !rm_inner_binders.is_empty() {
3446 rm_inner_binders
3447 .into_iter()
3448 .map(|v| (v, "".to_string()))
3449 .collect::<Vec<_>>()
3450 } else {
3451 ::alloc::vec::Vec::new()vec![]
3452 },
3453 );
3454 err.note_once(
3455 "for more information on higher-ranked polymorphism, visit \
3456 https://doc.rust-lang.org/nomicon/hrtb.html",
3457 );
3458 } else if let Some(name) = name {
3459 let message =
3460 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
3461 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3462 } else {
3463 let message = Cow::from("consider introducing a named lifetime parameter");
3464 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3465 }
3466 }
3467 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3468 _ => {}
3469 }
3470 if !should_continue {
3471 break;
3472 }
3473 }
3474 }
3475
3476 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(&self, lifetime_ref: &ast::Lifetime) {
3477 self.r
3478 .dcx()
3479 .create_err(errors::ParamInTyOfConstParam {
3480 span: lifetime_ref.ident.span,
3481 name: lifetime_ref.ident.name,
3482 })
3483 .emit();
3484 }
3485
3486 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3490 &self,
3491 cause: NoConstantGenericsReason,
3492 lifetime_ref: &ast::Lifetime,
3493 ) {
3494 match cause {
3495 NoConstantGenericsReason::IsEnumDiscriminant => {
3496 self.r
3497 .dcx()
3498 .create_err(errors::ParamInEnumDiscriminant {
3499 span: lifetime_ref.ident.span,
3500 name: lifetime_ref.ident.name,
3501 param_kind: errors::ParamKindInEnumDiscriminant::Lifetime,
3502 })
3503 .emit();
3504 }
3505 NoConstantGenericsReason::NonTrivialConstArg => {
3506 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());
3507 self.r
3508 .dcx()
3509 .create_err(errors::ParamInNonTrivialAnonConst {
3510 span: lifetime_ref.ident.span,
3511 name: lifetime_ref.ident.name,
3512 param_kind: errors::ParamKindInNonTrivialAnonConst::Lifetime,
3513 help: self
3514 .r
3515 .tcx
3516 .sess
3517 .is_nightly_build()
3518 .then_some(errors::ParamInNonTrivialAnonConstHelp),
3519 })
3520 .emit();
3521 }
3522 }
3523 }
3524
3525 pub(crate) fn report_missing_lifetime_specifiers(
3526 &mut self,
3527 lifetime_refs: Vec<MissingLifetime>,
3528 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3529 ) -> ErrorGuaranteed {
3530 let num_lifetimes: usize = lifetime_refs.iter().map(|lt| lt.count).sum();
3531 let spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
3532
3533 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!(
3534 self.r.dcx(),
3535 spans,
3536 E0106,
3537 "missing lifetime specifier{}",
3538 pluralize!(num_lifetimes)
3539 );
3540 self.add_missing_lifetime_specifiers_label(
3541 &mut err,
3542 lifetime_refs,
3543 function_param_lifetimes,
3544 );
3545 err.emit()
3546 }
3547
3548 fn add_missing_lifetime_specifiers_label(
3549 &mut self,
3550 err: &mut Diag<'_>,
3551 lifetime_refs: Vec<MissingLifetime>,
3552 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3553 ) {
3554 for < in &lifetime_refs {
3555 err.span_label(
3556 lt.span,
3557 ::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!(
3558 "expected {} lifetime parameter{}",
3559 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
3560 pluralize!(lt.count),
3561 ),
3562 );
3563 }
3564
3565 let mut in_scope_lifetimes: Vec<_> = self
3566 .lifetime_ribs
3567 .iter()
3568 .rev()
3569 .take_while(|rib| {
3570 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
3571 })
3572 .flat_map(|rib| rib.bindings.iter())
3573 .map(|(&ident, &res)| (ident, res))
3574 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
3575 .collect();
3576 {
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:3576",
"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(3576u32),
::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);
3577
3578 let mut maybe_static = false;
3579 {
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:3579",
"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(3579u32),
::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);
3580 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
3581 let elided_len = param_lifetimes.len();
3582 let num_params = params.len();
3583
3584 let mut m = String::new();
3585
3586 for (i, info) in params.iter().enumerate() {
3587 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
3588 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);
3589
3590 err.span_label(span, "");
3591
3592 if i != 0 {
3593 if i + 1 < num_params {
3594 m.push_str(", ");
3595 } else if num_params == 2 {
3596 m.push_str(" or ");
3597 } else {
3598 m.push_str(", or ");
3599 }
3600 }
3601
3602 let help_name = if let Some(ident) = ident {
3603 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
3604 } else {
3605 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
3606 };
3607
3608 if lifetime_count == 1 {
3609 m.push_str(&help_name[..])
3610 } else {
3611 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")[..])
3612 }
3613 }
3614
3615 if num_params == 0 {
3616 err.help(
3617 "this function's return type contains a borrowed value, but there is no value \
3618 for it to be borrowed from",
3619 );
3620 if in_scope_lifetimes.is_empty() {
3621 maybe_static = true;
3622 in_scope_lifetimes = <[_]>::into_vec(::alloc::boxed::box_new([(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
3623 Ident::with_dummy_span(kw::StaticLifetime),
3624 (DUMMY_NODE_ID, LifetimeRes::Static),
3625 )];
3626 }
3627 } else if elided_len == 0 {
3628 err.help(
3629 "this function's return type contains a borrowed value with an elided \
3630 lifetime, but the lifetime cannot be derived from the arguments",
3631 );
3632 if in_scope_lifetimes.is_empty() {
3633 maybe_static = true;
3634 in_scope_lifetimes = <[_]>::into_vec(::alloc::boxed::box_new([(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
3635 Ident::with_dummy_span(kw::StaticLifetime),
3636 (DUMMY_NODE_ID, LifetimeRes::Static),
3637 )];
3638 }
3639 } else if num_params == 1 {
3640 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!(
3641 "this function's return type contains a borrowed value, but the signature does \
3642 not say which {m} it is borrowed from",
3643 ));
3644 } else {
3645 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!(
3646 "this function's return type contains a borrowed value, but the signature does \
3647 not say whether it is borrowed from {m}",
3648 ));
3649 }
3650 }
3651
3652 #[allow(rustc::symbol_intern_string_literal)]
3653 let existing_name = match &in_scope_lifetimes[..] {
3654 [] => Symbol::intern("'a"),
3655 [(existing, _)] => existing.name,
3656 _ => Symbol::intern("'lifetime"),
3657 };
3658
3659 let mut spans_suggs: Vec<_> = Vec::new();
3660 let build_sugg = |lt: MissingLifetime| match lt.kind {
3661 MissingLifetimeKind::Underscore => {
3662 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);
3663 (lt.span, existing_name.to_string())
3664 }
3665 MissingLifetimeKind::Ampersand => {
3666 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);
3667 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
3668 }
3669 MissingLifetimeKind::Comma => {
3670 let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count)
3671 .flatten()
3672 .collect();
3673 (lt.span.shrink_to_hi(), sugg)
3674 }
3675 MissingLifetimeKind::Brackets => {
3676 let sugg: String = std::iter::once("<")
3677 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
3678 .chain([">"])
3679 .collect();
3680 (lt.span.shrink_to_hi(), sugg)
3681 }
3682 };
3683 for < in &lifetime_refs {
3684 spans_suggs.push(build_sugg(lt));
3685 }
3686 {
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:3686",
"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(3686u32),
::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);
3687 match in_scope_lifetimes.len() {
3688 0 => {
3689 if let Some((param_lifetimes, _)) = function_param_lifetimes {
3690 for lt in param_lifetimes {
3691 spans_suggs.push(build_sugg(lt))
3692 }
3693 }
3694 self.suggest_introducing_lifetime(
3695 err,
3696 None,
3697 |err, higher_ranked, span, message, intro_sugg, _| {
3698 err.multipart_suggestion_verbose(
3699 message,
3700 std::iter::once((span, intro_sugg))
3701 .chain(spans_suggs.clone())
3702 .collect(),
3703 Applicability::MaybeIncorrect,
3704 );
3705 higher_ranked
3706 },
3707 );
3708 }
3709 1 => {
3710 let post = if maybe_static {
3711 let owned = if let [lt] = &lifetime_refs[..]
3712 && lt.kind != MissingLifetimeKind::Ampersand
3713 {
3714 ", or if you will only have owned values"
3715 } else {
3716 ""
3717 };
3718 ::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!(
3719 ", but this is uncommon unless you're returning a borrowed value from a \
3720 `const` or a `static`{owned}",
3721 )
3722 } else {
3723 String::new()
3724 };
3725 err.multipart_suggestion_verbose(
3726 ::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}"),
3727 spans_suggs,
3728 Applicability::MaybeIncorrect,
3729 );
3730 if maybe_static {
3731 if let [lt] = &lifetime_refs[..]
3737 && (lt.kind == MissingLifetimeKind::Ampersand
3738 || lt.kind == MissingLifetimeKind::Underscore)
3739 {
3740 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
3741 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3742 && !sig.decl.inputs.is_empty()
3743 && let sugg = sig
3744 .decl
3745 .inputs
3746 .iter()
3747 .filter_map(|param| {
3748 if param.ty.span.contains(lt.span) {
3749 None
3752 } else if let TyKind::CVarArgs = param.ty.kind {
3753 None
3755 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
3756 None
3758 } else {
3759 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
3760 }
3761 })
3762 .collect::<Vec<_>>()
3763 && !sugg.is_empty()
3764 {
3765 let (the, s) = if sig.decl.inputs.len() == 1 {
3766 ("the", "")
3767 } else {
3768 ("one of the", "s")
3769 };
3770 let dotdotdot =
3771 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
3772 err.multipart_suggestion_verbose(
3773 ::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!(
3774 "instead, you are more likely to want to change {the} \
3775 argument{s} to be borrowed{dotdotdot}",
3776 ),
3777 sugg,
3778 Applicability::MaybeIncorrect,
3779 );
3780 "...or alternatively, you might want"
3781 } else if (lt.kind == MissingLifetimeKind::Ampersand
3782 || lt.kind == MissingLifetimeKind::Underscore)
3783 && let Some((kind, _span)) = self.diag_metadata.current_function
3784 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3785 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
3786 && !sig.decl.inputs.is_empty()
3787 && let arg_refs = sig
3788 .decl
3789 .inputs
3790 .iter()
3791 .filter_map(|param| match ¶m.ty.kind {
3792 TyKind::ImplTrait(_, bounds) => Some(bounds),
3793 _ => None,
3794 })
3795 .flat_map(|bounds| bounds.into_iter())
3796 .collect::<Vec<_>>()
3797 && !arg_refs.is_empty()
3798 {
3799 let mut lt_finder =
3805 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
3806 for bound in arg_refs {
3807 if let ast::GenericBound::Trait(trait_ref) = bound {
3808 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
3809 }
3810 }
3811 lt_finder.visit_ty(ret_ty);
3812 let spans_suggs: Vec<_> = lt_finder
3813 .seen
3814 .iter()
3815 .filter_map(|ty| match &ty.kind {
3816 TyKind::Ref(_, mut_ty) => {
3817 let span = ty.span.with_hi(mut_ty.ty.span.lo());
3818 Some((span, "&'a ".to_string()))
3819 }
3820 _ => None,
3821 })
3822 .collect();
3823 self.suggest_introducing_lifetime(
3824 err,
3825 None,
3826 |err, higher_ranked, span, message, intro_sugg, _| {
3827 err.multipart_suggestion_verbose(
3828 message,
3829 std::iter::once((span, intro_sugg))
3830 .chain(spans_suggs.clone())
3831 .collect(),
3832 Applicability::MaybeIncorrect,
3833 );
3834 higher_ranked
3835 },
3836 );
3837 "alternatively, you might want"
3838 } else {
3839 "instead, you are more likely to want"
3840 };
3841 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
3842 let mut sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span, String::new())]))vec![(lt.span, String::new())];
3843 if let Some((kind, _span)) = self.diag_metadata.current_function
3844 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
3845 && let ast::FnRetTy::Ty(ty) = &sig.decl.output
3846 {
3847 let mut lt_finder =
3848 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
3849 lt_finder.visit_ty(&ty);
3850
3851 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
3852 <_finder.seen[..]
3853 {
3854 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())];
3860 owned_sugg = true;
3861 }
3862 if let Some(ty) = lt_finder.found {
3863 if let TyKind::Path(None, path) = &ty.kind {
3864 let path: Vec<_> = Segment::from_path(path);
3866 match self.resolve_path(
3867 &path,
3868 Some(TypeNS),
3869 None,
3870 PathSource::Type,
3871 ) {
3872 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3873 match module.res() {
3874 Some(Res::PrimTy(PrimTy::Str)) => {
3875 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span.with_hi(ty.span.hi()),
"String".to_string())]))vec![(
3877 lt.span.with_hi(ty.span.hi()),
3878 "String".to_string(),
3879 )];
3880 }
3881 Some(Res::PrimTy(..)) => {}
3882 Some(Res::Def(
3883 DefKind::Struct
3884 | DefKind::Union
3885 | DefKind::Enum
3886 | DefKind::ForeignTy
3887 | DefKind::AssocTy
3888 | DefKind::OpaqueTy
3889 | DefKind::TyParam,
3890 _,
3891 )) => {}
3892 _ => {
3893 owned_sugg = false;
3895 }
3896 }
3897 }
3898 PathResult::NonModule(res) => {
3899 match res.base_res() {
3900 Res::PrimTy(PrimTy::Str) => {
3901 sugg = <[_]>::into_vec(::alloc::boxed::box_new([(lt.span.with_hi(ty.span.hi()),
"String".to_string())]))vec![(
3903 lt.span.with_hi(ty.span.hi()),
3904 "String".to_string(),
3905 )];
3906 }
3907 Res::PrimTy(..) => {}
3908 Res::Def(
3909 DefKind::Struct
3910 | DefKind::Union
3911 | DefKind::Enum
3912 | DefKind::ForeignTy
3913 | DefKind::AssocTy
3914 | DefKind::OpaqueTy
3915 | DefKind::TyParam,
3916 _,
3917 ) => {}
3918 _ => {
3919 owned_sugg = false;
3921 }
3922 }
3923 }
3924 _ => {
3925 owned_sugg = false;
3927 }
3928 }
3929 }
3930 if let TyKind::Slice(inner_ty) = &ty.kind {
3931 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![
3933 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
3934 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
3935 ];
3936 }
3937 }
3938 }
3939 if owned_sugg {
3940 err.multipart_suggestion_verbose(
3941 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
3942 sugg,
3943 Applicability::MaybeIncorrect,
3944 );
3945 }
3946 }
3947 }
3948 }
3949 _ => {
3950 let lifetime_spans: Vec<_> =
3951 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
3952 err.span_note(lifetime_spans, "these named lifetimes are available to use");
3953
3954 if spans_suggs.len() > 0 {
3955 err.multipart_suggestion_verbose(
3958 "consider using one of the available lifetimes here",
3959 spans_suggs,
3960 Applicability::HasPlaceholders,
3961 );
3962 }
3963 }
3964 }
3965 }
3966}
3967
3968fn mk_where_bound_predicate(
3969 path: &Path,
3970 poly_trait_ref: &ast::PolyTraitRef,
3971 ty: &Ty,
3972) -> Option<ast::WhereBoundPredicate> {
3973 let modified_segments = {
3974 let mut segments = path.segments.clone();
3975 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
3976 return None;
3977 };
3978 let mut segments = ThinVec::from(preceding);
3979
3980 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
3981 id: DUMMY_NODE_ID,
3982 ident: last.ident,
3983 gen_args: None,
3984 kind: ast::AssocItemConstraintKind::Equality {
3985 term: ast::Term::Ty(Box::new(ast::Ty {
3986 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
3987 id: DUMMY_NODE_ID,
3988 span: DUMMY_SP,
3989 tokens: None,
3990 })),
3991 },
3992 span: DUMMY_SP,
3993 });
3994
3995 match second_last.args.as_deref_mut() {
3996 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
3997 args.push(added_constraint);
3998 }
3999 Some(_) => return None,
4000 None => {
4001 second_last.args =
4002 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4003 args: ThinVec::from([added_constraint]),
4004 span: DUMMY_SP,
4005 })));
4006 }
4007 }
4008
4009 segments.push(second_last.clone());
4010 segments
4011 };
4012
4013 let new_where_bound_predicate = ast::WhereBoundPredicate {
4014 bound_generic_params: ThinVec::new(),
4015 bounded_ty: Box::new(ty.clone()),
4016 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 {
4017 bound_generic_params: ThinVec::new(),
4018 modifiers: ast::TraitBoundModifiers::NONE,
4019 trait_ref: ast::TraitRef {
4020 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
4021 ref_id: DUMMY_NODE_ID,
4022 },
4023 span: DUMMY_SP,
4024 parens: ast::Parens::No,
4025 })],
4026 };
4027
4028 Some(new_where_bound_predicate)
4029}
4030
4031pub(super) fn signal_lifetime_shadowing(sess: &Session, orig: Ident, shadower: Ident) {
4033 {
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!(
4034 sess.dcx(),
4035 shadower.span,
4036 E0496,
4037 "lifetime name `{}` shadows a lifetime name that is already in scope",
4038 orig.name,
4039 )
4040 .with_span_label(orig.span, "first declared here")
4041 .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))
4042 .emit();
4043}
4044
4045struct LifetimeFinder<'ast> {
4046 lifetime: Span,
4047 found: Option<&'ast Ty>,
4048 seen: Vec<&'ast Ty>,
4049}
4050
4051impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4052 fn visit_ty(&mut self, t: &'ast Ty) {
4053 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4054 self.seen.push(t);
4055 if t.span.lo() == self.lifetime.lo() {
4056 self.found = Some(&mut_ty.ty);
4057 }
4058 }
4059 walk_ty(self, t)
4060 }
4061}
4062
4063pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4066 let name = shadower.name;
4067 let shadower = shadower.span;
4068 sess.dcx()
4069 .struct_span_warn(
4070 shadower,
4071 ::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"),
4072 )
4073 .with_span_label(orig, "first declared here")
4074 .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"))
4075 .emit();
4076}