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, AngleBracketedArg, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericArg,
10 GenericArgs, GenericParam, GenericParamKind, Item, ItemKind, MethodCall, NodeId, Path,
11 PathSegment, Ty, TyKind,
12};
13use rustc_ast_pretty::pprust::{path_to_string, where_bound_predicate_to_string};
14use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
15use rustc_data_structures::unord::UnordItems;
16use rustc_errors::codes::*;
17use rustc_errors::{
18 Applicability, Diag, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
19 struct_span_code_err,
20};
21use rustc_hir as hir;
22use rustc_hir::def::Namespace::{self, *};
23use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds};
24use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
25use rustc_hir::{MissingLifetimeKind, PrimTy, find_attr};
26use rustc_middle::ty;
27use rustc_session::{Session, lint};
28use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
29use rustc_span::edition::Edition;
30use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
31use thin_vec::{ThinVec, thin_vec};
32use tracing::debug;
33
34use super::NoConstantGenericsReason;
35use crate::error_helper::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
36use crate::late::{
37 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
38 LifetimeUseSet, QSelf, RibKind,
39};
40use crate::ty::fast_reject::SimplifiedType;
41use crate::{
42 Finalize, Module, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Res, Resolver,
43 ScopeSet, Segment, diagnostics, path_names_to_string,
44};
45
46enum AssocSuggestion {
48 Field(Span),
49 MethodWithSelf { called: bool },
50 AssocFn { called: bool },
51 AssocType,
52 AssocConst,
53}
54
55impl AssocSuggestion {
56 fn action(&self) -> &'static str {
57 match self {
58 AssocSuggestion::Field(_) => "use the available field",
59 AssocSuggestion::MethodWithSelf { called: true } => {
60 "call the method with the fully-qualified path"
61 }
62 AssocSuggestion::MethodWithSelf { called: false } => {
63 "refer to the method with the fully-qualified path"
64 }
65 AssocSuggestion::AssocFn { called: true } => "call the associated function",
66 AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
67 AssocSuggestion::AssocConst => "use the associated `const`",
68 AssocSuggestion::AssocType => "use the associated type",
69 }
70 }
71}
72
73fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
74 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
75}
76
77fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
78 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
79}
80
81fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
82 let mut path = path.clone();
83 for segment in &mut path.segments {
84 let mut remove_args = false;
85 if let Some(args) = segment.args.as_deref_mut()
86 && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
87 {
88 angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
ast::AngleBracketedArg::Arg(_) => true,
_ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
89 remove_args = angle_bracketed.args.is_empty();
90 }
91 if remove_args {
92 segment.args = None;
93 }
94 }
95 path_to_string(&path)
96}
97
98fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
100 let variant_path = &suggestion.path;
101 let variant_path_string = path_names_to_string(variant_path);
102
103 let path_len = suggestion.path.segments.len();
104 let enum_path = ast::Path {
105 span: suggestion.path.span,
106 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
107 tokens: None,
108 };
109 let enum_path_string = path_names_to_string(&enum_path);
110
111 (variant_path_string, enum_path_string)
112}
113
114#[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_fields_are_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> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}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)]
116pub(super) struct MissingLifetime {
117 pub id: NodeId,
119 pub id_for_lint: NodeId,
126 pub span: Span,
128 pub kind: MissingLifetimeKind,
130 pub count: usize,
132}
133
134#[derive(#[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)]
137pub(super) struct ElisionFnParameter {
138 pub index: usize,
140 pub ident: Option<Ident>,
142 pub lifetime_count: usize,
144 pub span: Span,
146}
147
148#[derive(#[automatically_derived]
impl ::core::clone::Clone for LifetimeElisionCandidate {
#[inline]
fn clone(&self) -> LifetimeElisionCandidate {
let _: ::core::clone::AssertParamIsClone<MissingLifetime>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LifetimeElisionCandidate { }Copy, #[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::Missing(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Missing", &__self_0),
}
}
}Debug)]
151pub(super) enum LifetimeElisionCandidate {
152 Ignore,
154 Missing(MissingLifetime),
155}
156
157#[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)]
159struct BaseError {
160 msg: String,
161 fallback_label: String,
162 span: Span,
163 span_label: Option<(Span, &'static str)>,
164 could_be_expr: bool,
165 suggestion: Option<(Span, &'static str, String)>,
166 module: Option<DefId>,
167}
168
169#[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)]
170enum TypoCandidate {
171 Typo(TypoSuggestion),
172 Shadowed(Res, Option<Span>),
173 None,
174}
175
176impl TypoCandidate {
177 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
178 match self {
179 TypoCandidate::Typo(sugg) => Some(sugg),
180 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
181 }
182 }
183}
184
185impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
186 fn trait_assoc_type_def_id_by_name(
187 &mut self,
188 trait_def_id: DefId,
189 assoc_name: Symbol,
190 ) -> Option<DefId> {
191 let module = self.r.get_module(trait_def_id)?;
192 self.r.resolutions(module).borrow().iter().find_map(|(key, resolution)| {
193 if key.ident.name != assoc_name {
194 return None;
195 }
196 let resolution = resolution.borrow();
197 let binding = resolution.best_decl()?;
198 match binding.res() {
199 Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
200 _ => None,
201 }
202 })
203 }
204
205 fn suggest_assoc_type_from_bounds(
207 &mut self,
208 err: &mut Diag<'_>,
209 source: PathSource<'_, 'ast, 'ra>,
210 path: &[Segment],
211 ident_span: Span,
212 ) -> bool {
213 if source.namespace() != TypeNS {
215 return false;
216 }
217 let [segment] = path else { return false };
218 if segment.has_generic_args {
219 return false;
220 }
221 if !ident_span.can_be_used_for_suggestions() {
222 return false;
223 }
224 let assoc_name = segment.ident.name;
225 if assoc_name == kw::Underscore {
226 return false;
227 }
228
229 let mut matching_bounds: FxIndexMap<
233 Symbol,
234 FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
235 > = FxIndexMap::default();
236
237 let mut record_bound = |this: &mut Self,
238 ty_param: Symbol,
239 poly_trait_ref: &ast::PolyTraitRef| {
240 if !poly_trait_ref.bound_generic_params.is_empty() {
242 return;
243 }
244 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
245 return;
246 }
247 let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
248 return;
249 };
250 let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
251 return;
252 };
253 let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
254 return;
255 };
256 let Some(assoc_type_def_id) =
257 this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
258 else {
259 return;
260 };
261
262 let trait_path =
266 path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
267 let trait_bounds = matching_bounds.entry(ty_param).or_default();
268 let trait_bounds = trait_bounds
269 .entry(trait_def_id)
270 .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
271 if true {
{
match (&trait_bounds.0, &assoc_type_def_id) {
(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!(trait_bounds.0, assoc_type_def_id);
272 trait_bounds.1.insert(trait_path);
273 };
274
275 let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
276 for param in &generics.params {
277 let ast::GenericParamKind::Type { .. } = param.kind else { continue };
278 for bound in ¶m.bounds {
279 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
280 record_bound(this, param.ident.name, poly_trait_ref);
281 }
282 }
283
284 for predicate in &generics.where_clause.predicates {
285 let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
286 continue;
287 };
288
289 let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
290 continue;
291 };
292 let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
293 else {
294 continue;
295 };
296
297 let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
299 else {
300 continue;
301 };
302 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::TyParam, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
303 continue;
304 }
305
306 for bound in &where_bound.bounds {
307 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
308 record_bound(this, ident.name, poly_trait_ref);
309 }
310 }
311 };
312
313 if let Some(item) = self.diag_metadata.current_item
314 && let Some(generics) = item.kind.generics()
315 {
316 record_from_generics(self, generics);
317 }
318
319 if let Some(item) = self.diag_metadata.current_item
320 && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Impl(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Impl(..))
321 && let Some(assoc) = self.diag_metadata.current_impl_item
322 {
323 let generics = match &assoc.kind {
324 AssocItemKind::Const(ast::ConstItem { generics, .. })
325 | AssocItemKind::Fn(ast::Fn { generics, .. })
326 | AssocItemKind::Type(ast::TyAlias { generics, .. }) => Some(generics),
327 AssocItemKind::Delegation(..)
328 | AssocItemKind::MacCall(..)
329 | AssocItemKind::DelegationMac(..) => None,
330 };
331 if let Some(generics) = generics {
332 record_from_generics(self, generics);
333 }
334 }
335
336 let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
337 for (ty_param, traits) in matching_bounds {
338 let ty_param = ty_param.to_ident_string();
339 let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
340 if traits.len() == 1 && trait_paths_len == 1 {
341 let assoc_type_def_id = traits.values().next().unwrap().0;
342 let assoc_segment = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
})format!(
343 "{}{}",
344 assoc_name,
345 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
346 );
347 suggestions.insert(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
assoc_segment))
})format!("{ty_param}::{assoc_segment}"));
348 } else {
349 for (assoc_type_def_id, trait_paths) in traits.into_values() {
350 let assoc_segment = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
})format!(
351 "{}{}",
352 assoc_name,
353 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
354 );
355 for trait_path in trait_paths {
356 suggestions
357 .insert(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as {1}>::{2}", ty_param,
trait_path, assoc_segment))
})format!("<{ty_param} as {trait_path}>::{assoc_segment}"));
358 }
359 }
360 }
361 }
362
363 if suggestions.is_empty() {
364 return false;
365 }
366
367 let mut suggestions: Vec<String> = suggestions.into_iter().collect();
368 suggestions.sort();
369
370 err.span_suggestions_with_style(
371 ident_span,
372 "you might have meant to use an associated type of the same name",
373 suggestions,
374 Applicability::MaybeIncorrect,
375 SuggestionStyle::ShowAlways,
376 );
377
378 true
379 }
380
381 fn make_base_error(
382 &mut self,
383 path: &[Segment],
384 span: Span,
385 source: PathSource<'_, 'ast, 'ra>,
386 res: Option<Res>,
387 ) -> BaseError {
388 let mut expected = source.descr_expected();
390 let path_str = Segment::names_to_string(path);
391 let item_str = path.last().unwrap().ident;
392
393 if let Some(res) = res {
394 BaseError {
395 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),
396 fallback_label: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"),
397 span,
398 span_label: match res {
399 Res::Def(DefKind::TyParam, def_id) => {
400 Some((self.r.def_span(def_id), "found this type parameter"))
401 }
402 _ => None,
403 },
404 could_be_expr: match res {
405 Res::Def(DefKind::Fn, _) => {
406 self.r
408 .tcx
409 .sess
410 .source_map()
411 .span_to_snippet(span)
412 .is_ok_and(|snippet| snippet.ends_with(')'))
413 }
414 Res::Def(
415 DefKind::Ctor(..)
416 | DefKind::AssocFn
417 | DefKind::Const { .. }
418 | DefKind::AssocConst { .. },
419 _,
420 )
421 | Res::SelfCtor(_)
422 | Res::PrimTy(_)
423 | Res::Local(_) => true,
424 _ => false,
425 },
426 suggestion: None,
427 module: None,
428 }
429 } else {
430 let mut span_label = None;
431 let item_ident = path.last().unwrap().ident;
432 let item_span = item_ident.span;
433 let (mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
434 {
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:434",
"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(434u32),
::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);
435 {
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:435",
"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(435u32),
::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);
436 let suggestion = if self.current_trait_ref.is_none()
437 && let Some((fn_kind, _)) = self.diag_metadata.current_function
438 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
439 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
440 && let Some(items) = self.diag_metadata.current_impl_items
441 && let Some(item) = items.iter().find(|i| {
442 i.kind.ident().is_some_and(|ident| {
443 ident.name == item_str.name && !sig.span.contains(item_span)
445 })
446 }) {
447 let sp = item_span.shrink_to_lo();
448
449 let field = match source {
452 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
453 expr.fields.iter().find(|f| f.ident == item_ident)
454 }
455 _ => None,
456 };
457 let pre = if let Some(field) = field
458 && field.is_shorthand
459 {
460 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", item_ident))
})format!("{item_ident}: ")
461 } else {
462 String::new()
463 };
464 let is_call = match field {
467 Some(ast::ExprField { expr, .. }) => {
468 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Call(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Call(..))
469 }
470 _ => #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(
471 source,
472 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
473 ),
474 };
475
476 match &item.kind {
477 AssocItemKind::Fn(fn_)
478 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
479 {
480 span_label = Some((
484 fn_.ident.span,
485 "a method by that name is available on `Self` here",
486 ));
487 None
488 }
489 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
490 span_label = Some((
491 fn_.ident.span,
492 "an associated function by that name is available on `Self` here",
493 ));
494 None
495 }
496 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
497 Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self.")))
498 }
499 AssocItemKind::Fn(_) => Some((
500 sp,
501 "consider using the associated function on `Self`",
502 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
503 )),
504 AssocItemKind::Const(..) => Some((
505 sp,
506 "consider using the associated constant on `Self`",
507 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
508 )),
509 _ => None,
510 }
511 } else {
512 None
513 };
514 (String::new(), "this scope".to_string(), None, suggestion)
515 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
516 if self.r.tcx.sess.edition() > Edition::Edition2015 {
517 expected = "crate";
520 (String::new(), "the list of imported crates".to_string(), None, None)
521 } else {
522 (
523 String::new(),
524 "the crate root".to_string(),
525 Some(CRATE_DEF_ID.to_def_id()),
526 None,
527 )
528 }
529 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
530 (String::new(), "the crate root".to_string(), Some(CRATE_DEF_ID.to_def_id()), None)
531 } else {
532 let mod_path = &path[..path.len() - 1];
533 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
534 let mod_prefix = match mod_res {
535 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
536 _ => None,
537 };
538
539 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
540
541 let mod_prefix =
542 mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", res.descr()))
})format!("{} ", res.descr()));
543 (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)
544 };
545
546 let (fallback_label, suggestion) = if path_str == "async"
547 && expected.starts_with("struct")
548 {
549 ("`async` blocks are only allowed in Rust 2018 or later".to_string(), suggestion)
550 } else {
551 let override_suggestion =
553 if ["true", "false"].contains(&item_str.to_string().to_lowercase().as_str()) {
554 let item_typo = item_str.to_string().to_lowercase();
555 Some((item_span, "you may want to use a bool value instead", item_typo))
556 } else if item_str.as_str() == "printf" {
559 Some((
560 item_span,
561 "you may have meant to use the `print` macro",
562 "print!".to_owned(),
563 ))
564 } else {
565 suggestion
566 };
567 (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not found in {0}", mod_str))
})format!("not found in {mod_str}"), override_suggestion)
568 };
569
570 BaseError {
571 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}"),
572 fallback_label,
573 span: item_span,
574 span_label,
575 could_be_expr: false,
576 suggestion,
577 module,
578 }
579 }
580 }
581
582 pub(crate) fn smart_resolve_partial_mod_path_errors(
590 &mut self,
591 prefix_path: &[Segment],
592 following_seg: Option<&Segment>,
593 ) -> Vec<ImportSuggestion> {
594 if let Some(segment) = prefix_path.last()
595 && let Some(following_seg) = following_seg
596 {
597 let candidates = self.r.lookup_import_candidates(
598 segment.ident,
599 Namespace::TypeNS,
600 &self.parent_scope,
601 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
602 );
603 candidates
605 .into_iter()
606 .filter(|candidate| {
607 if let Some(def_id) = candidate.did
608 && let Some(module) = self.r.get_module(def_id)
609 {
610 Some(def_id) != self.parent_scope.module.opt_def_id()
611 && self
612 .r
613 .resolutions(module)
614 .borrow()
615 .iter()
616 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
617 } else {
618 false
619 }
620 })
621 .collect::<Vec<_>>()
622 } else {
623 Vec::new()
624 }
625 }
626
627 #[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(629u32),
::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:639",
"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(639u32),
::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")]
630 pub(crate) fn smart_resolve_report_errors(
631 &mut self,
632 path: &[Segment],
633 following_seg: Option<&Segment>,
634 span: Span,
635 source: PathSource<'_, 'ast, 'ra>,
636 res: Option<Res>,
637 qself: Option<&QSelf>,
638 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
639 debug!(?res, ?source);
640 let base_error = self.make_base_error(path, span, source, res);
641
642 let code = source.error_code(res.is_some());
643 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
644 err.code(code);
645
646 if let Some(within_macro_span) =
649 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
650 {
651 err.span_label(within_macro_span, "due to this macro variable");
652 }
653
654 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
655 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
656 self.suggest_range_struct_destructuring(&mut err, path, source);
657 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
658
659 if let Some((span, label)) = base_error.span_label {
660 err.span_label(span, label);
661 }
662
663 if let Some(ref sugg) = base_error.suggestion {
664 err.span_suggestion_verbose(sugg.0, sugg.1, &sugg.2, Applicability::MaybeIncorrect);
665 }
666
667 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
668 self.explain_functions_in_pattern(&mut err, res, source);
669
670 if self.suggest_pattern_match_with_let(&mut err, source, span) {
671 err.span_label(base_error.span, base_error.fallback_label);
673 return (err, Vec::new());
674 }
675
676 self.suggest_self_or_self_ref(&mut err, path, span);
677 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
678 self.detect_rtn_with_fully_qualified_path(
679 &mut err,
680 path,
681 following_seg,
682 span,
683 source,
684 res,
685 qself,
686 );
687 if self.suggest_self_ty(&mut err, source, path, span)
688 || self.suggest_self_value(&mut err, source, path, span)
689 {
690 return (err, Vec::new());
691 }
692
693 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
694 let item_name = item.name;
695 let suggestion_name = self.r.tcx.item_name(did);
696 err.span_suggestion(
697 item.span,
698 format!("`{suggestion_name}` has a name defined in the doc alias attribute as `{item_name}`"),
699 suggestion_name,
700 Applicability::MaybeIncorrect
701 );
702
703 return (err, Vec::new());
704 };
705
706 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
707 &mut err,
708 source,
709 path,
710 following_seg,
711 span,
712 res,
713 &base_error,
714 );
715 if found {
716 return (err, candidates);
717 }
718
719 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
720 candidates.clear();
722 }
723
724 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
725 fallback |= self.suggest_typo(
726 &mut err,
727 source,
728 path,
729 following_seg,
730 span,
731 &base_error,
732 suggested_candidates,
733 );
734
735 if fallback {
736 err.span_label(base_error.span, base_error.fallback_label);
738 }
739 self.err_code_special_cases(&mut err, source, path, span);
740
741 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
742 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
743
744 (err, candidates)
745 }
746
747 fn detect_rtn_with_fully_qualified_path(
748 &self,
749 err: &mut Diag<'_>,
750 path: &[Segment],
751 following_seg: Option<&Segment>,
752 span: Span,
753 source: PathSource<'_, '_, '_>,
754 res: Option<Res>,
755 qself: Option<&QSelf>,
756 ) {
757 if let Some(Res::Def(DefKind::AssocFn, _)) = res
758 && let PathSource::TraitItem(TypeNS, _) = source
759 && let None = following_seg
760 && let Some(qself) = qself
761 && let TyKind::Path(None, ty_path) = &qself.ty.kind
762 && ty_path.segments.len() == 1
763 && self.diag_metadata.current_where_predicate.is_some()
764 {
765 err.span_suggestion_verbose(
766 span,
767 "you might have meant to use the return type notation syntax",
768 ::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),
769 Applicability::MaybeIncorrect,
770 );
771 }
772 }
773
774 fn detect_assoc_type_constraint_meant_as_path(
775 &self,
776 err: &mut Diag<'_>,
777 base_error: &BaseError,
778 ) {
779 let Some(ty) = self.diag_metadata.current_type_path else {
780 return;
781 };
782 let TyKind::Path(_, path) = &ty.kind else {
783 return;
784 };
785 for segment in &path.segments {
786 let Some(params) = &segment.args else {
787 continue;
788 };
789 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
790 continue;
791 };
792 for param in ¶ms.args {
793 let ast::AngleBracketedArg::Constraint(constraint) = param else {
794 continue;
795 };
796 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
797 continue;
798 };
799 for bound in bounds {
800 let ast::GenericBound::Trait(trait_ref) = bound else {
801 continue;
802 };
803 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
804 && base_error.span == trait_ref.span
805 {
806 err.span_suggestion_verbose(
807 constraint.ident.span.between(trait_ref.span),
808 "you might have meant to write a path instead of an associated type bound",
809 "::",
810 Applicability::MachineApplicable,
811 );
812 }
813 }
814 }
815 }
816 }
817
818 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
819 if !self.self_type_is_available() {
820 return;
821 }
822 let Some(path_last_segment) = path.last() else { return };
823 let item_str = path_last_segment.ident;
824 if ["this", "my"].contains(&item_str.as_str()) {
826 err.span_suggestion_short(
827 span,
828 "you might have meant to use `self` here instead",
829 "self",
830 Applicability::MaybeIncorrect,
831 );
832 if !self.self_value_is_available(path[0].ident.span) {
833 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
834 &self.diag_metadata.current_function
835 {
836 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
837 (param.span.shrink_to_lo(), "&self, ")
838 } else {
839 (
840 self.r
841 .tcx
842 .sess
843 .source_map()
844 .span_through_char(*fn_span, '(')
845 .shrink_to_hi(),
846 "&self",
847 )
848 };
849 err.span_suggestion_verbose(
850 span,
851 "if you meant to use `self`, you are also missing a `self` receiver \
852 argument",
853 sugg,
854 Applicability::MaybeIncorrect,
855 );
856 }
857 }
858 }
859 }
860
861 fn try_lookup_name_relaxed(
862 &mut self,
863 err: &mut Diag<'_>,
864 source: PathSource<'_, '_, '_>,
865 path: &[Segment],
866 following_seg: Option<&Segment>,
867 span: Span,
868 res: Option<Res>,
869 base_error: &BaseError,
870 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
871 let span = match following_seg {
872 Some(_) if path[0].ident.span.eq_ctxt(path[path.len() - 1].ident.span) => {
873 path[0].ident.span.to(path[path.len() - 1].ident.span)
876 }
877 _ => span,
878 };
879 let mut suggested_candidates = FxHashSet::default();
880 let ident = path.last().unwrap().ident;
882 let is_expected = &|res| source.is_expected(res);
883 let ns = source.namespace();
884 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
885 let path_str = Segment::names_to_string(path);
886 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
887 let mut candidates = self
888 .r
889 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
890 .into_iter()
891 .filter(|ImportSuggestion { did, .. }| {
892 match (did, res.and_then(|res| res.opt_def_id())) {
893 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
894 _ => true,
895 }
896 })
897 .collect::<Vec<_>>();
898 let intrinsic_candidates: Vec<_> = candidates
901 .extract_if(.., |sugg| {
902 let path = path_names_to_string(&sugg.path);
903 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
904 })
905 .collect();
906 if candidates.is_empty() {
907 candidates = intrinsic_candidates;
909 }
910 let crate_def_id = CRATE_DEF_ID.to_def_id();
911 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
912 let mut enum_candidates: Vec<_> = self
913 .r
914 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
915 .into_iter()
916 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
917 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
918 .collect();
919 if !enum_candidates.is_empty() {
920 enum_candidates.sort();
921
922 let preamble = if res.is_none() {
925 let others = match enum_candidates.len() {
926 1 => String::new(),
927 2 => " and 1 other".to_owned(),
928 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
929 };
930 ::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)
931 } else {
932 String::new()
933 };
934 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");
935
936 suggested_candidates.extend(
937 enum_candidates
938 .iter()
939 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
940 );
941 err.span_suggestions(
942 span,
943 msg,
944 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
945 Applicability::MachineApplicable,
946 );
947 }
948 }
949
950 let typo_sugg = self
952 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
953 .to_opt_suggestion()
954 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
955 if let [segment] = path
956 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
957 && self.self_type_is_available()
958 {
959 if let Some(candidate) =
960 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
961 {
962 let self_is_available = self.self_value_is_available(segment.ident.span);
963 let pre = match source {
966 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
967 if expr
968 .fields
969 .iter()
970 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
971 {
972 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
973 }
974 _ => String::new(),
975 };
976 match candidate {
977 AssocSuggestion::Field(field_span) => {
978 if self_is_available {
979 let source_map = self.r.tcx.sess.source_map();
980 let field_is_format_named_arg = #[allow(non_exhaustive_omitted_patterns)] match span.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(
981 span.desugaring_kind(),
982 Some(DesugaringKind::FormatLiteral { .. })
983 ) && source_map
984 .span_to_source(span, |s, start, _| {
985 Ok(s.get(start.saturating_sub(1)..start) == Some("{"))
986 })
987 .unwrap_or(false);
988 if field_is_format_named_arg {
989 err.help(
990 ::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),
991 );
992 } else {
993 err.span_suggestion_verbose(
994 span.shrink_to_lo(),
995 "you might have meant to use the available field",
996 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
997 Applicability::MaybeIncorrect,
998 );
999 }
1000 } else {
1001 err.span_label(field_span, "a field by that name exists in `Self`");
1002 }
1003 }
1004 AssocSuggestion::MethodWithSelf { called } if self_is_available => {
1005 let msg = if called {
1006 "you might have meant to call the method"
1007 } else {
1008 "you might have meant to refer to the method"
1009 };
1010 err.span_suggestion_verbose(
1011 span.shrink_to_lo(),
1012 msg,
1013 "self.",
1014 Applicability::MachineApplicable,
1015 );
1016 }
1017 AssocSuggestion::MethodWithSelf { .. }
1018 | AssocSuggestion::AssocFn { .. }
1019 | AssocSuggestion::AssocConst
1020 | AssocSuggestion::AssocType => {
1021 err.span_suggestion_verbose(
1022 span.shrink_to_lo(),
1023 ::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()),
1024 "Self::",
1025 Applicability::MachineApplicable,
1026 );
1027 }
1028 }
1029 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1030 return (true, suggested_candidates, candidates);
1031 }
1032
1033 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1035 let mut args_snippet = String::new();
1036 if let Some(args_span) = args_span
1037 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1038 {
1039 args_snippet = snippet;
1040 }
1041
1042 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1043 if let Some(ctor) = self.r.struct_ctor(def_id)
1044 && ctor.has_private_fields(self.parent_scope.module, self.r)
1045 {
1046 if #[allow(non_exhaustive_omitted_patterns)] match ctor.res {
Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1047 ctor.res,
1048 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1049 ) {
1050 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1051 }
1052 err.note("constructor is not visible here due to private fields");
1053 }
1054 } else {
1055 err.span_suggestion(
1056 call_span,
1057 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
1058 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
1059 Applicability::MachineApplicable,
1060 );
1061 }
1062
1063 return (true, suggested_candidates, candidates);
1064 }
1065 }
1066
1067 if let Some(res) = res {
1069 if self.smart_resolve_context_dependent_help(
1070 err,
1071 span,
1072 source,
1073 path,
1074 res,
1075 &path_str,
1076 &base_error.fallback_label,
1077 ) {
1078 self.r.add_typo_suggestion(err, typo_sugg, ident_span);
1080 return (true, suggested_candidates, candidates);
1081 }
1082 }
1083
1084 if let Some(rib) = &self.last_block_rib {
1086 for (ident, &res) in &rib.bindings {
1087 if let Res::Local(_) = res
1088 && path.len() == 1
1089 && ident.span.eq_ctxt(path[0].ident.span)
1090 && ident.name == path[0].ident.name
1091 {
1092 err.span_help(
1093 ident.span,
1094 ::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"),
1095 );
1096 return (true, suggested_candidates, candidates);
1097 }
1098 }
1099 }
1100
1101 if candidates.is_empty() {
1102 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1103 }
1104
1105 (false, suggested_candidates, candidates)
1106 }
1107
1108 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1109 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1110 for resolution in r.resolutions(m).borrow().values() {
1111 let Some(did) =
1112 resolution.borrow().best_decl().and_then(|binding| binding.res().opt_def_id())
1113 else {
1114 continue;
1115 };
1116 if did.is_local() {
1117 continue;
1121 }
1122 if let Some(d) = {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &r.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Doc(d)) => {
break 'done Some(d);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}hir::find_attr!(r.tcx, did, Doc(d) => d)
1123 && d.aliases.contains_key(&item_name)
1124 {
1125 return Some(did);
1126 }
1127 }
1128 None
1129 };
1130
1131 if path.len() == 1 {
1132 for rib in self.ribs[ns].iter().rev() {
1133 let item = path[0].ident;
1134 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1135 && let Some(did) = find_doc_alias_name(self.r, module.to_module(), item.name)
1136 {
1137 return Some((did, item));
1138 }
1139 }
1140 } else {
1141 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1150 let Some(id) = seg.id else {
1151 continue;
1152 };
1153 let Some(res) = self.r.partial_res_map.get(&id) else {
1154 continue;
1155 };
1156 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1157 && let module = self.r.expect_module(module)
1158 && let item = path[idx + 1].ident
1159 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1160 {
1161 return Some((did, item));
1162 }
1163 break;
1164 }
1165 }
1166 None
1167 }
1168
1169 fn suggest_trait_and_bounds(
1170 &self,
1171 err: &mut Diag<'_>,
1172 source: PathSource<'_, '_, '_>,
1173 res: Option<Res>,
1174 span: Span,
1175 base_error: &BaseError,
1176 ) -> bool {
1177 let is_macro =
1178 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1179 let mut fallback = false;
1180
1181 if let (
1182 PathSource::Trait(AliasPossibility::Maybe),
1183 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1184 false,
1185 ) = (source, res, is_macro)
1186 && let Some(bounds @ [first_bound, .., last_bound]) =
1187 self.diag_metadata.current_trait_object
1188 {
1189 fallback = true;
1190 let spans: Vec<Span> = bounds
1191 .iter()
1192 .map(|bound| bound.span())
1193 .filter(|&sp| sp != base_error.span)
1194 .collect();
1195
1196 let start_span = first_bound.span();
1197 let end_span = last_bound.span();
1199 let last_bound_span = spans.last().cloned().unwrap();
1201 let mut multi_span: MultiSpan = spans.clone().into();
1202 for sp in spans {
1203 let msg = if sp == last_bound_span {
1204 ::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!(
1205 "...because of {these} bound{s}",
1206 these = pluralize!("this", bounds.len() - 1),
1207 s = pluralize!(bounds.len() - 1),
1208 )
1209 } else {
1210 String::new()
1211 };
1212 multi_span.push_span_label(sp, msg);
1213 }
1214 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1215 err.span_help(
1216 multi_span,
1217 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1218 auto-traits; structs and enums can't be bound in that way",
1219 );
1220 if bounds.iter().all(|bound| match bound {
1221 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1222 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1223 }) {
1224 let mut sugg = ::alloc::vec::Vec::new()vec![];
1225 if base_error.span != start_span {
1226 sugg.push((start_span.until(base_error.span), String::new()));
1227 }
1228 if base_error.span != end_span {
1229 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1230 }
1231
1232 err.multipart_suggestion(
1233 "if you meant to use a type and not a trait here, remove the bounds",
1234 sugg,
1235 Applicability::MaybeIncorrect,
1236 );
1237 }
1238 }
1239
1240 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1241 fallback
1242 }
1243
1244 fn suggest_typo(
1245 &mut self,
1246 err: &mut Diag<'_>,
1247 source: PathSource<'_, 'ast, 'ra>,
1248 path: &[Segment],
1249 following_seg: Option<&Segment>,
1250 span: Span,
1251 base_error: &BaseError,
1252 suggested_candidates: FxHashSet<String>,
1253 ) -> bool {
1254 let is_expected = &|res| source.is_expected(res);
1255 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1256
1257 if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1261 return false;
1262 }
1263
1264 let typo_sugg =
1265 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1266 let mut fallback = false;
1267 let typo_sugg = typo_sugg
1268 .to_opt_suggestion()
1269 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1270 if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
1271 fallback = true;
1272 match self.diag_metadata.current_let_binding {
1273 Some((pat_sp, Some(ty_sp), None))
1274 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1275 {
1276 err.span_suggestion_verbose(
1277 pat_sp.between(ty_sp),
1278 "use `=` if you meant to assign",
1279 " = ",
1280 Applicability::MaybeIncorrect,
1281 );
1282 }
1283 _ => {}
1284 }
1285
1286 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1288 self.r.add_typo_suggestion(err, suggestion, ident_span);
1289 }
1290
1291 if self.let_binding_suggestion(err, ident_span) {
1292 fallback = false;
1293 }
1294
1295 fallback
1296 }
1297
1298 fn suggest_shadowed(
1299 &mut self,
1300 err: &mut Diag<'_>,
1301 source: PathSource<'_, '_, '_>,
1302 path: &[Segment],
1303 following_seg: Option<&Segment>,
1304 span: Span,
1305 ) -> bool {
1306 let is_expected = &|res| source.is_expected(res);
1307 let typo_sugg =
1308 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1309 let is_in_same_file = &|sp1, sp2| {
1310 let source_map = self.r.tcx.sess.source_map();
1311 let file1 = source_map.span_to_filename(sp1);
1312 let file2 = source_map.span_to_filename(sp2);
1313 file1 == file2
1314 };
1315 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1320 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1321 {
1322 err.span_label(
1323 sugg_span,
1324 ::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()),
1325 );
1326 return true;
1327 }
1328 false
1329 }
1330
1331 fn err_code_special_cases(
1332 &mut self,
1333 err: &mut Diag<'_>,
1334 source: PathSource<'_, '_, '_>,
1335 path: &[Segment],
1336 span: Span,
1337 ) {
1338 if let Some(err_code) = err.code {
1339 if err_code == E0425 {
1340 for label_rib in &self.label_ribs {
1341 for (label_ident, node_id) in &label_rib.bindings {
1342 let ident = path.last().unwrap().ident;
1343 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1344 err.span_label(label_ident.span, "a label with a similar name exists");
1345 if let PathSource::Expr(Some(Expr {
1346 kind: ExprKind::Break(None, Some(_)),
1347 ..
1348 })) = source
1349 {
1350 err.span_suggestion(
1351 span,
1352 "use the similarly named label",
1353 label_ident.name,
1354 Applicability::MaybeIncorrect,
1355 );
1356 self.diag_metadata.unused_labels.swap_remove(node_id);
1358 }
1359 }
1360 }
1361 }
1362
1363 self.suggest_ident_hidden_by_hygiene(err, path, span);
1364 if let Some(correct) = Self::likely_rust_type(path) {
1366 err.span_suggestion(
1367 span,
1368 "perhaps you intended to use this type",
1369 correct,
1370 Applicability::MaybeIncorrect,
1371 );
1372 }
1373 }
1374 }
1375 }
1376
1377 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1378 let [segment] = path else { return };
1379
1380 let ident = segment.ident;
1381 let callsite_span = span.source_callsite();
1382 for rib in self.ribs[ValueNS].iter().rev() {
1383 for (binding_ident, _) in &rib.bindings {
1384 if binding_ident.name == ident.name
1386 && !binding_ident.span.eq_ctxt(span)
1387 && !binding_ident.span.from_expansion()
1388 && binding_ident.span.lo() < callsite_span.lo()
1389 {
1390 err.span_help(
1391 binding_ident.span,
1392 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1393 );
1394 return;
1395 }
1396
1397 if binding_ident.name == ident.name
1399 && binding_ident.span.from_expansion()
1400 && binding_ident.span.source_callsite().eq_ctxt(callsite_span)
1401 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1402 {
1403 err.span_help(
1404 binding_ident.span,
1405 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1406 );
1407 return;
1408 }
1409 }
1410 }
1411 }
1412
1413 fn suggest_self_ty(
1415 &self,
1416 err: &mut Diag<'_>,
1417 source: PathSource<'_, '_, '_>,
1418 path: &[Segment],
1419 span: Span,
1420 ) -> bool {
1421 if !is_self_type(path, source.namespace()) {
1422 return false;
1423 }
1424 err.code(E0411);
1425 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1426 if let Some(item) = self.diag_metadata.current_item
1427 && let Some(ident) = item.kind.ident()
1428 {
1429 err.span_label(
1430 ident.span,
1431 ::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()),
1432 );
1433 }
1434 true
1435 }
1436
1437 fn suggest_self_value(
1438 &mut self,
1439 err: &mut Diag<'_>,
1440 source: PathSource<'_, '_, '_>,
1441 path: &[Segment],
1442 span: Span,
1443 ) -> bool {
1444 if !is_self_value(path, source.namespace()) {
1445 return false;
1446 }
1447
1448 {
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:1448",
"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(1448u32),
::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);
1449 err.code(E0424);
1450 err.span_label(
1451 span,
1452 match source {
1453 PathSource::Pat => {
1454 "`self` value is a keyword and may not be bound to variables or shadowed"
1455 }
1456 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1457 },
1458 );
1459
1460 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1463 return true;
1464 }
1465
1466 let is_assoc_fn = self.self_type_is_available();
1467 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1468 access identifiers it receives from parameters";
1469 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1470 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1475 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}"));
1476 } else {
1477 let doesnt = if is_assoc_fn {
1478 let (span, sugg) = fn_kind
1479 .decl()
1480 .inputs
1481 .get(0)
1482 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1483 .unwrap_or_else(|| {
1484 let span = fn_kind
1487 .ident()
1488 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1489 (
1490 self.r
1491 .tcx
1492 .sess
1493 .source_map()
1494 .span_through_char(span, '(')
1495 .shrink_to_hi(),
1496 "&self",
1497 )
1498 });
1499 err.span_suggestion_verbose(
1500 span,
1501 "add a `self` receiver parameter to make the associated `fn` a method",
1502 sugg,
1503 Applicability::MaybeIncorrect,
1504 );
1505 "doesn't"
1506 } else {
1507 "can't"
1508 };
1509 if let Some(ident) = fn_kind.ident() {
1510 err.span_label(
1511 ident.span,
1512 ::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"),
1513 );
1514 }
1515 }
1516 } else if let Some(item) = self.diag_metadata.current_item {
1517 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1518 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}"));
1519 } else {
1520 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1521 err.span_label(
1522 span,
1523 ::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()),
1524 );
1525 }
1526 }
1527 true
1528 }
1529
1530 fn detect_missing_binding_available_from_pattern(
1531 &self,
1532 err: &mut Diag<'_>,
1533 path: &[Segment],
1534 following_seg: Option<&Segment>,
1535 ) {
1536 let [segment] = path else { return };
1537 let None = following_seg else { return };
1538 for rib in self.ribs[ValueNS].iter().rev() {
1539 let patterns_with_skipped_bindings =
1540 self.r.tcx.with_stable_hashing_context(|mut hcx| {
1541 rib.patterns_with_skipped_bindings.to_sorted(&mut hcx, true)
1542 });
1543 for (def_id, spans) in patterns_with_skipped_bindings {
1544 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1545 && let Some(fields) = self.r.field_idents(*def_id)
1546 {
1547 for field in fields {
1548 if field.name == segment.ident.name {
1549 if spans.iter().all(|(_, had_error)| had_error.is_err()) {
1550 let multispan: MultiSpan =
1553 spans.iter().map(|(s, _)| *s).collect::<Vec<_>>().into();
1554 err.span_note(
1555 multispan,
1556 "this pattern had a recovered parse error which likely lost \
1557 the expected fields",
1558 );
1559 err.downgrade_to_delayed_bug();
1560 }
1561 let ty = self.r.tcx.item_name(*def_id);
1562 for (span, _) in spans {
1563 err.span_label(
1564 *span,
1565 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1566 "this pattern doesn't include `{field}`, which is \
1567 available in `{ty}`",
1568 ),
1569 );
1570 }
1571 }
1572 }
1573 }
1574 }
1575 }
1576 }
1577
1578 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1579 let Some(pat) = self.diag_metadata.current_pat else { return };
1580 let (bound, side, range) = match &pat.kind {
1581 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1582 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1583 _ => return,
1584 };
1585 if let ExprKind::Path(None, range_path) = &bound.kind
1586 && let [segment] = &range_path.segments[..]
1587 && let [s] = path
1588 && segment.ident == s.ident
1589 && segment.ident.span.eq_ctxt(range.span)
1590 {
1591 let (span, snippet) = match side {
1594 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
1595 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
1596 };
1597 err.subdiagnostic(diagnostics::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1598 span,
1599 ident: segment.ident,
1600 snippet,
1601 });
1602 }
1603
1604 enum Side {
1605 Start,
1606 End,
1607 }
1608 }
1609
1610 fn suggest_range_struct_destructuring(
1611 &mut self,
1612 err: &mut Diag<'_>,
1613 path: &[Segment],
1614 source: PathSource<'_, '_, '_>,
1615 ) {
1616 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
1617 return;
1618 }
1619
1620 let Some(pat) = self.diag_metadata.current_pat else { return };
1621 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
1622
1623 let [segment] = path else { return };
1624 let failing_span = segment.ident.span;
1625
1626 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
1627 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
1628
1629 if !in_start && !in_end {
1630 return;
1631 }
1632
1633 let start_snippet =
1634 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1635 let end_snippet =
1636 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
1637
1638 let field = |name: &str, val: String| {
1639 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
1640 };
1641
1642 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
1643 let ident = Ident::with_dummy_span(short);
1644 let path = Segment::from_path(&Path::from_ident(ident));
1645
1646 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
1647 PathResult::NonModule(..) => short.to_string(),
1648 _ => full.to_string(),
1649 }
1650 };
1651 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
1653 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
1654 resolve_short_name(sym::Range, "std::ops::Range"),
1655 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1656 ),
1657 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
1658 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
1659 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start), field("end", end)]))vec![field("start", start), field("end", end)],
1660 ),
1661 (Some(start), None, _) => (
1662 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
1663 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("start", start)]))vec![field("start", start)],
1664 ),
1665 (None, Some(end), ast::RangeEnd::Excluded) => {
1666 (resolve_short_name(sym::RangeTo, "std::ops::RangeTo"), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("end", end)]))vec![field("end", end)])
1667 }
1668 (None, Some(end), ast::RangeEnd::Included(_)) => (
1669 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
1670 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[field("end", end)]))vec![field("end", end)],
1671 ),
1672 _ => return,
1673 };
1674
1675 err.span_suggestion_verbose(
1676 pat.span,
1677 ::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"),
1678 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
1679 Applicability::MaybeIncorrect,
1680 );
1681
1682 err.note(
1683 "range patterns match against the start and end of a range; \
1684 to bind the components, use a struct pattern",
1685 );
1686 }
1687
1688 fn suggest_swapping_misplaced_self_ty_and_trait(
1689 &mut self,
1690 err: &mut Diag<'_>,
1691 source: PathSource<'_, 'ast, 'ra>,
1692 res: Option<Res>,
1693 span: Span,
1694 ) {
1695 if let Some((trait_ref, self_ty)) =
1696 self.diag_metadata.currently_processing_impl_trait.clone()
1697 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
1698 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1699 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
1700 && module.def_kind() == Some(DefKind::Trait)
1701 && trait_ref.path.span == span
1702 && let PathSource::Trait(_) = source
1703 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
1704 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
1705 && let Ok(trait_ref_str) =
1706 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
1707 {
1708 err.multipart_suggestion(
1709 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
1710 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(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)],
1711 Applicability::MaybeIncorrect,
1712 );
1713 }
1714 }
1715
1716 fn explain_functions_in_pattern(
1717 &self,
1718 err: &mut Diag<'_>,
1719 res: Option<Res>,
1720 source: PathSource<'_, '_, '_>,
1721 ) {
1722 let PathSource::TupleStruct(_, _) = source else { return };
1723 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
1724 err.primary_message("expected a pattern, found a function call");
1725 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
1726 }
1727
1728 fn suggest_changing_type_to_const_param(
1729 &self,
1730 err: &mut Diag<'_>,
1731 res: Option<Res>,
1732 source: PathSource<'_, '_, '_>,
1733 path: &[Segment],
1734 following_seg: Option<&Segment>,
1735 span: Span,
1736 ) {
1737 if let PathSource::Expr(None) = source
1738 && let Some(Res::Def(DefKind::TyParam, _)) = res
1739 && following_seg.is_none()
1740 && let [segment] = path
1741 {
1742 let Some(item) = self.diag_metadata.current_item else { return };
1750 let Some(generics) = item.kind.generics() else { return };
1751 let Some(span) = generics.params.iter().find_map(|param| {
1752 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
1754 Some(param.ident.span)
1755 } else {
1756 None
1757 }
1758 }) else {
1759 return;
1760 };
1761 err.subdiagnostic(diagnostics::UnexpectedResChangeTyParamToConstParamSugg {
1762 before: span.shrink_to_lo(),
1763 after: span.shrink_to_hi(),
1764 });
1765 return;
1766 }
1767 let PathSource::Trait(_) = source else { return };
1768
1769 let applicability = match res {
1771 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
1772 Applicability::MachineApplicable
1773 }
1774 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
1778 if self.r.features.adt_const_params() || self.r.features.min_adt_const_params() =>
1779 {
1780 Applicability::MaybeIncorrect
1781 }
1782 _ => return,
1783 };
1784
1785 let Some(item) = self.diag_metadata.current_item else { return };
1786 let Some(generics) = item.kind.generics() else { return };
1787
1788 let param = generics.params.iter().find_map(|param| {
1789 if let [bound] = &*param.bounds
1791 && let ast::GenericBound::Trait(tref) = bound
1792 && tref.modifiers == ast::TraitBoundModifiers::NONE
1793 && tref.span == span
1794 && param.ident.span.eq_ctxt(span)
1795 {
1796 Some(param.ident.span)
1797 } else {
1798 None
1799 }
1800 });
1801
1802 if let Some(param) = param {
1803 err.subdiagnostic(diagnostics::UnexpectedResChangeTyToConstParamSugg {
1804 span: param.shrink_to_lo(),
1805 applicability,
1806 });
1807 }
1808 }
1809
1810 fn suggest_pattern_match_with_let(
1811 &self,
1812 err: &mut Diag<'_>,
1813 source: PathSource<'_, '_, '_>,
1814 span: Span,
1815 ) -> bool {
1816 if let PathSource::Expr(_) = source
1817 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
1818 self.diag_metadata.in_if_condition
1819 {
1820 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
1824 err.span_suggestion_verbose(
1825 expr_span.shrink_to_lo(),
1826 "you might have meant to use pattern matching",
1827 "let ",
1828 Applicability::MaybeIncorrect,
1829 );
1830 return true;
1831 }
1832 }
1833 false
1834 }
1835
1836 fn get_single_associated_item(
1837 &mut self,
1838 path: &[Segment],
1839 source: &PathSource<'_, 'ast, 'ra>,
1840 filter_fn: &impl Fn(Res) -> bool,
1841 ) -> Option<TypoSuggestion> {
1842 if let crate::PathSource::TraitItem(_, _) = source {
1843 let mod_path = &path[..path.len() - 1];
1844 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
1845 self.resolve_path(mod_path, None, None, *source)
1846 {
1847 let targets: Vec<_> = self
1848 .r
1849 .resolutions(module)
1850 .borrow()
1851 .iter()
1852 .filter_map(|(key, resolution)| {
1853 let resolution = resolution.borrow();
1854 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
1855 if filter_fn(res) {
1856 Some((key.ident.name, resolution.orig_ident_span, res))
1857 } else {
1858 None
1859 }
1860 })
1861 })
1862 .collect();
1863 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
1864 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
1865 }
1866 }
1867 }
1868 None
1869 }
1870
1871 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
1873 let Some(ast::WherePredicate {
1875 kind:
1876 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
1877 bounded_ty,
1878 bound_generic_params,
1879 bounds,
1880 }),
1881 span: where_span,
1882 ..
1883 }) = self.diag_metadata.current_where_predicate
1884 else {
1885 return false;
1886 };
1887 if !bound_generic_params.is_empty() {
1888 return false;
1889 }
1890
1891 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
1893 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
1895 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::AssocTy, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::AssocTy, _))) {
1896 return false;
1897 }
1898
1899 let peeled_ty = qself.ty.peel_refs();
1900 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
1901 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
1903 return false;
1904 };
1905 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::TyParam, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::TyParam, _))) {
1906 return false;
1907 }
1908 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
1909 (&type_param_path.segments[..], &bounds[..])
1910 else {
1911 return false;
1912 };
1913 let [ast::PathSegment { ident, args: None, id }] =
1914 &poly_trait_ref.trait_ref.path.segments[..]
1915 else {
1916 return false;
1917 };
1918 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
1919 return false;
1920 }
1921 if ident.span == span {
1922 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
1923 return false;
1924 };
1925 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(..))) {
1926 return false;
1927 }
1928
1929 let Some(new_where_bound_predicate) =
1930 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
1931 else {
1932 return false;
1933 };
1934 err.span_suggestion_verbose(
1935 *where_span,
1936 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
1937 where_bound_predicate_to_string(&new_where_bound_predicate),
1938 Applicability::MaybeIncorrect,
1939 );
1940 }
1941 true
1942 }
1943
1944 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
1947 let mut has_self_arg = None;
1948 if let PathSource::Expr(Some(parent)) = source
1949 && let ExprKind::Call(_, args) = &parent.kind
1950 && !args.is_empty()
1951 {
1952 let mut expr_kind = &args[0].kind;
1953 loop {
1954 match expr_kind {
1955 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
1956 if arg_name.segments[0].ident.name == kw::SelfLower {
1957 let call_span = parent.span;
1958 let tail_args_span = if args.len() > 1 {
1959 Some(Span::new(
1960 args[1].span.lo(),
1961 args.last().unwrap().span.hi(),
1962 call_span.ctxt(),
1963 None,
1964 ))
1965 } else {
1966 None
1967 };
1968 has_self_arg = Some((call_span, tail_args_span));
1969 }
1970 break;
1971 }
1972 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
1973 _ => break,
1974 }
1975 }
1976 }
1977 has_self_arg
1978 }
1979
1980 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
1981 let sm = self.r.tcx.sess.source_map();
1986 if let Some(open_brace_span) = sm.span_followed_by(span, "{") {
1987 let close_brace_span =
1990 sm.span_to_next_source(open_brace_span).ok().and_then(|next_source| {
1991 let mut depth: u32 = 1;
1993 let offset = next_source.char_indices().find_map(|(i, c)| {
1994 match c {
1995 '{' => depth += 1,
1996 '}' if depth == 1 => return Some(i),
1997 '}' => depth -= 1,
1998 _ => {}
1999 }
2000 None
2001 })?;
2002 let start = open_brace_span.hi() + rustc_span::BytePos(offset as u32);
2003 Some(open_brace_span.with_lo(start).with_hi(start + rustc_span::BytePos(1)))
2004 });
2005 let closing_brace = close_brace_span.map(|sp| span.to(sp));
2006 (true, closing_brace)
2007 } else {
2008 (false, None)
2009 }
2010 }
2011
2012 fn update_err_for_private_tuple_struct_fields(
2013 &mut self,
2014 err: &mut Diag<'_>,
2015 source: &PathSource<'_, '_, '_>,
2016 def_id: DefId,
2017 ) -> Option<Vec<Span>> {
2018 match source {
2019 PathSource::TupleStruct(_, pattern_spans) => {
2021 err.primary_message(
2022 "cannot match against a tuple struct which contains private fields",
2023 );
2024
2025 Some(Vec::from(*pattern_spans))
2027 }
2028 PathSource::Expr(Some(Expr {
2030 kind: ExprKind::Call(path, args),
2031 span: call_span,
2032 ..
2033 })) => {
2034 err.primary_message(
2035 "cannot initialize a tuple struct which contains private fields",
2036 );
2037 self.suggest_alternative_construction_methods(
2038 def_id,
2039 err,
2040 path.span,
2041 *call_span,
2042 &args[..],
2043 );
2044
2045 self.r
2046 .field_idents(def_id)
2047 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2048 }
2049 _ => None,
2050 }
2051 }
2052
2053 fn smart_resolve_context_dependent_help(
2057 &mut self,
2058 err: &mut Diag<'_>,
2059 span: Span,
2060 source: PathSource<'_, '_, '_>,
2061 path: &[Segment],
2062 res: Res,
2063 path_str: &str,
2064 fallback_label: &str,
2065 ) -> bool {
2066 let ns = source.namespace();
2067 let is_expected = &|res| source.is_expected(res);
2068
2069 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2070 const MESSAGE: &str = "use the path separator to refer to an item";
2071
2072 let (lhs_span, rhs_span) = match &expr.kind {
2073 ExprKind::Field(base, ident) => (base.span, ident.span),
2074 ExprKind::MethodCall(MethodCall { receiver, span, .. }) => (receiver.span, *span),
2075 _ => return false,
2076 };
2077
2078 if lhs_span.eq_ctxt(rhs_span) {
2079 err.span_suggestion_verbose(
2080 lhs_span.between(rhs_span),
2081 MESSAGE,
2082 "::",
2083 Applicability::MaybeIncorrect,
2084 );
2085 true
2086 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2087 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2088 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2089 {
2090 err.span_suggestion_verbose(
2094 lhs_source_span.until(rhs_span),
2095 MESSAGE,
2096 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
2097 Applicability::MaybeIncorrect,
2098 );
2099 true
2100 } else {
2101 false
2107 }
2108 };
2109
2110 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2111 match source {
2112 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2113 | PathSource::TupleStruct(span, _) => {
2114 err.span(*span);
2117 *span
2118 }
2119 _ => span,
2120 }
2121 };
2122
2123 let bad_struct_syntax_suggestion = |this: &mut Self, err: &mut Diag<'_>, def_id: DefId| {
2124 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2125
2126 match source {
2127 PathSource::Expr(Some(
2128 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2129 )) if path_sep(this, err, parent, DefKind::Struct) => {}
2130 PathSource::Expr(
2131 None
2132 | Some(Expr {
2133 kind:
2134 ExprKind::Path(..)
2135 | ExprKind::Binary(..)
2136 | ExprKind::Unary(..)
2137 | ExprKind::If(..)
2138 | ExprKind::While(..)
2139 | ExprKind::ForLoop { .. }
2140 | ExprKind::Match(..),
2141 ..
2142 }),
2143 ) if followed_by_brace => {
2144 if let Some(sp) = closing_brace {
2145 err.span_label(span, fallback_label.to_string());
2146 err.multipart_suggestion(
2147 "surround the struct literal with parentheses",
2148 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(sp.shrink_to_lo(), "(".to_string()),
(sp.shrink_to_hi(), ")".to_string())]))vec![
2149 (sp.shrink_to_lo(), "(".to_string()),
2150 (sp.shrink_to_hi(), ")".to_string()),
2151 ],
2152 Applicability::MaybeIncorrect,
2153 );
2154 } else {
2155 err.span_label(
2156 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!(
2158 "you might want to surround a struct literal with parentheses: \
2159 `({path_str} {{ /* fields */ }})`?"
2160 ),
2161 );
2162 }
2163 }
2164 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2165 let span = find_span(&source, err);
2166 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"));
2167
2168 let (tail, descr, applicability, old_fields) = match source {
2169 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2170 PathSource::TupleStruct(_, args) => (
2171 "",
2172 "pattern",
2173 Applicability::MachineApplicable,
2174 Some(
2175 args.iter()
2176 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2177 .collect::<Vec<Option<String>>>(),
2178 ),
2179 ),
2180 _ => (": val", "literal", Applicability::HasPlaceholders, None),
2181 };
2182
2183 let has_private_fields = match def_id.as_local() {
2185 Some(def_id) => this.r.struct_ctors.get(&def_id).is_some_and(|ctor| {
2186 ctor.has_private_fields(this.parent_scope.module, this.r)
2187 }),
2188 None => this.r.tcx.associated_item_def_ids(def_id).iter().any(|field_id| {
2189 let vis = this.r.tcx.visibility(*field_id);
2190 !this.r.is_accessible_from(vis, this.parent_scope.module)
2191 }),
2192 };
2193 if !has_private_fields {
2194 let fields = this.r.field_idents(def_id);
2197 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2198
2199 if let PathSource::Expr(Some(Expr {
2200 kind: ExprKind::Call(path, args),
2201 span,
2202 ..
2203 })) = source
2204 && !args.is_empty()
2205 && let Some(fields) = &fields
2206 && args.len() == fields.len()
2207 {
2209 let path_span = path.span;
2210 let mut parts = Vec::new();
2211
2212 parts.push((
2214 path_span.shrink_to_hi().until(args[0].span),
2215 "{".to_owned(),
2216 ));
2217
2218 for (field, arg) in fields.iter().zip(args.iter()) {
2219 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
2221 }
2222
2223 parts.push((
2225 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2226 "}".to_owned(),
2227 ));
2228
2229 err.multipart_suggestion(
2230 ::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"),
2231 parts,
2232 applicability,
2233 );
2234 } else {
2235 let (fields, applicability) = match fields {
2236 Some(fields) => {
2237 let fields = if let Some(old_fields) = old_fields {
2238 fields
2239 .iter()
2240 .enumerate()
2241 .map(|(idx, new)| (new, old_fields.get(idx)))
2242 .map(|(new, old)| {
2243 if let Some(Some(old)) = old
2244 && new.as_str() != old
2245 {
2246 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2247 } else {
2248 new.to_string()
2249 }
2250 })
2251 .collect::<Vec<String>>()
2252 } else {
2253 fields
2254 .iter()
2255 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2256 .collect::<Vec<String>>()
2257 };
2258
2259 (fields.join(", "), applicability)
2260 }
2261 None => {
2262 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2263 }
2264 };
2265 let pad = if has_fields { " " } else { "" };
2266 err.span_suggestion(
2267 span,
2268 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2269 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}"),
2270 applicability,
2271 );
2272 }
2273 }
2274 if let PathSource::Expr(Some(Expr {
2275 kind: ExprKind::Call(path, args),
2276 span: call_span,
2277 ..
2278 })) = source
2279 {
2280 this.suggest_alternative_construction_methods(
2281 def_id,
2282 err,
2283 path.span,
2284 *call_span,
2285 &args[..],
2286 );
2287 }
2288 }
2289 _ => {
2290 err.span_label(span, fallback_label.to_string());
2291 }
2292 }
2293 };
2294
2295 match (res, source) {
2296 (
2297 Res::Def(DefKind::Macro(kinds), def_id),
2298 PathSource::Expr(Some(Expr {
2299 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2300 }))
2301 | PathSource::Struct(_),
2302 ) if kinds.contains(MacroKinds::BANG) => {
2303 let suggestable = def_id.is_local()
2305 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2306
2307 err.span_label(span, fallback_label.to_string());
2308
2309 if path
2311 .last()
2312 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2313 && suggestable
2314 {
2315 err.span_suggestion_verbose(
2316 span.shrink_to_hi(),
2317 "use `!` to invoke the macro",
2318 "!",
2319 Applicability::MaybeIncorrect,
2320 );
2321 }
2322
2323 if path_str == "try" && span.is_rust_2015() {
2324 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2325 }
2326 }
2327 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2328 err.span_label(span, fallback_label.to_string());
2329 }
2330 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2331 err.span_label(span, "type aliases cannot be used as traits");
2332 if self.r.tcx.sess.is_nightly_build() {
2333 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2334 `type` alias";
2335 let span = self.r.def_span(def_id);
2336 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2337 let snip = snip.replacen("type", "trait", 1);
2340 err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
2341 } else {
2342 err.span_help(span, msg);
2343 }
2344 }
2345 }
2346 (
2347 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2348 PathSource::Expr(Some(parent)),
2349 ) if path_sep(self, err, parent, kind) => {
2350 return true;
2351 }
2352 (
2353 Res::Def(DefKind::Enum, def_id),
2354 PathSource::TupleStruct(..) | PathSource::Expr(..),
2355 ) => {
2356 self.suggest_using_enum_variant(err, source, def_id, span);
2357 }
2358 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2359 if let PathSource::Expr(Some(parent)) = source
2360 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2361 {
2362 bad_struct_syntax_suggestion(self, err, def_id);
2363 return true;
2364 }
2365 let Some(ctor) = self.r.struct_ctor(def_id) else {
2366 bad_struct_syntax_suggestion(self, err, def_id);
2367 return true;
2368 };
2369
2370 let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2373 if is_accessible
2374 && let mod_path = &path[..path.len() - 1]
2375 && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2376 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2377 && ctor.has_private_fields(import_mod, self.r)
2378 && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2379 ModuleOrUniformRoot::Module(import_mod),
2380 path.last().unwrap().ident,
2381 TypeNS,
2382 &self.parent_scope,
2383 None,
2384 )
2385 {
2386 err.span_note(
2387 import_decl.span,
2388 "the type is accessed through this re-export, but the type's constructor \
2389 is not visible in this import's scope due to private fields",
2390 );
2391 if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2392 err.span_suggestion_verbose(
2393 span,
2394 "the type can be constructed directly, because its fields are \
2395 available from the current scope",
2396 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2400 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2402 ),
2403 Applicability::MachineApplicable,
2404 );
2405 }
2406 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2407 }
2408 if !is_expected(ctor.res) || is_accessible {
2409 return true;
2410 }
2411
2412 let field_spans =
2413 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2414
2415 if let Some(spans) = field_spans
2416 .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2417 {
2418 let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2419 .filter(|(vis, _)| {
2420 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2421 })
2422 .map(|(_, span)| *span)
2423 .collect();
2424
2425 if non_visible_spans.len() > 0 {
2426 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2427 err.multipart_suggestion(
2428 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2429 "consider making the field{} publicly accessible",
2430 pluralize!(fields.len())
2431 ),
2432 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2433 Applicability::MaybeIncorrect,
2434 );
2435 }
2436
2437 let mut m: MultiSpan = non_visible_spans.clone().into();
2438 non_visible_spans
2439 .into_iter()
2440 .for_each(|s| m.push_span_label(s, "private field"));
2441 err.span_note(m, "constructor is not visible here due to private fields");
2442 }
2443
2444 return true;
2445 }
2446
2447 err.span_label(span, "constructor is not visible here due to private fields");
2448 }
2449 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2450 bad_struct_syntax_suggestion(self, err, def_id);
2451 }
2452 (Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id), _) if ns == ValueNS => {
2453 match source {
2454 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2455 let span = find_span(&source, err);
2456 err.span_label(
2457 self.r.def_span(def_id),
2458 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2459 );
2460 err.span_suggestion(
2461 span,
2462 "use this syntax instead",
2463 path_str,
2464 Applicability::MaybeIncorrect,
2465 );
2466 }
2467 _ => return false,
2468 }
2469 }
2470 (Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2471 let def_id = self.r.tcx.parent(ctor_def_id);
2472 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"));
2473 let fields = self.r.field_idents(def_id).map_or_else(
2474 || "/* fields */".to_string(),
2475 |field_ids| ::alloc::vec::from_elem("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2476 );
2477 err.span_suggestion(
2478 span,
2479 "use the tuple variant pattern syntax instead",
2480 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2481 Applicability::HasPlaceholders,
2482 );
2483 }
2484 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2485 err.span_label(span, fallback_label.to_string());
2486 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2487 }
2488 (
2489 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2490 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2491 ) => {
2492 err.note("can't use a type alias as tuple pattern");
2493
2494 let mut suggestion = Vec::new();
2495
2496 if let &&[first, ..] = args
2497 && let &&[.., last] = args
2498 {
2499 suggestion.extend([
2500 (span.between(first), " { 0: ".to_owned()),
2506 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2507 ]);
2508
2509 suggestion.extend(
2510 args.iter()
2511 .enumerate()
2512 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2514 )
2515 } else {
2516 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2517 }
2518
2519 err.multipart_suggestion(
2520 "use struct pattern instead",
2521 suggestion,
2522 Applicability::MachineApplicable,
2523 );
2524 }
2525 (
2526 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2527 PathSource::TraitItem(
2528 ValueNS,
2529 PathSource::Expr(Some(ast::Expr {
2530 span: whole,
2531 kind: ast::ExprKind::Call(_, args),
2532 ..
2533 })),
2534 ),
2535 ) => {
2536 err.note("can't use a type alias as a constructor");
2537
2538 let mut suggestion = Vec::new();
2539
2540 if let [first, ..] = &**args
2541 && let [.., last] = &**args
2542 {
2543 suggestion.extend([
2544 (span.between(first.span), " { 0: ".to_owned()),
2550 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
2551 ]);
2552
2553 suggestion.extend(
2554 args.iter()
2555 .enumerate()
2556 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2558 )
2559 } else {
2560 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2561 }
2562
2563 err.multipart_suggestion(
2564 "use struct expression instead",
2565 suggestion,
2566 Applicability::MachineApplicable,
2567 );
2568 }
2569 _ => return false,
2570 }
2571 true
2572 }
2573
2574 fn suggest_alternative_construction_methods(
2575 &mut self,
2576 def_id: DefId,
2577 err: &mut Diag<'_>,
2578 path_span: Span,
2579 call_span: Span,
2580 args: &[Box<Expr>],
2581 ) {
2582 if def_id.is_local() {
2583 return;
2585 }
2586 let mut items = self
2589 .r
2590 .tcx
2591 .inherent_impls(def_id)
2592 .iter()
2593 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
2594 .filter(|item| item.is_fn() && !item.is_method())
2596 .filter_map(|item| {
2597 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
2599 let ret_ty = fn_sig.output().skip_binder();
2601 let ty::Adt(def, _args) = ret_ty.kind() else {
2602 return None;
2603 };
2604 let input_len = fn_sig.inputs().skip_binder().len();
2605 if def.did() != def_id {
2606 return None;
2607 }
2608 let name = item.name();
2609 let order = !name.as_str().starts_with("new");
2610 Some((order, name, input_len))
2611 })
2612 .collect::<Vec<_>>();
2613 items.sort_by_key(|(order, _, _)| *order);
2614 let suggestion = |name, args| {
2615 ::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(", "))
2616 };
2617 match &items[..] {
2618 [] => {}
2619 [(_, name, len)] if *len == args.len() => {
2620 err.span_suggestion_verbose(
2621 path_span.shrink_to_hi(),
2622 ::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",),
2623 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
2624 Applicability::MaybeIncorrect,
2625 );
2626 }
2627 [(_, name, len)] => {
2628 err.span_suggestion_verbose(
2629 path_span.shrink_to_hi().with_hi(call_span.hi()),
2630 ::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",),
2631 suggestion(name, *len),
2632 Applicability::MaybeIncorrect,
2633 );
2634 }
2635 _ => {
2636 err.span_suggestions_with_style(
2637 path_span.shrink_to_hi().with_hi(call_span.hi()),
2638 "you might have meant to use an associated function to build this type",
2639 items.iter().map(|(_, name, len)| suggestion(name, *len)),
2640 Applicability::MaybeIncorrect,
2641 SuggestionStyle::ShowAlways,
2642 );
2643 }
2644 }
2645 let default_trait = self
2653 .r
2654 .lookup_import_candidates(
2655 Ident::with_dummy_span(sym::Default),
2656 Namespace::TypeNS,
2657 &self.parent_scope,
2658 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
2659 )
2660 .iter()
2661 .filter_map(|candidate| candidate.did)
2662 .find(|did| {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(*did, &self.r.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
=> {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
2663 let Some(default_trait) = default_trait else {
2664 return;
2665 };
2666 if self
2667 .r
2668 .extern_crate_map
2669 .items()
2670 .flat_map(|(_, crate_)| {
2672 UnordItems::new(
2673 self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
2674 )
2675 })
2676 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
2677 .filter_map(|simplified_self_ty| match simplified_self_ty {
2678 SimplifiedType::Adt(did) => Some(did),
2679 _ => None,
2680 })
2681 .any(|did| did == def_id)
2682 {
2683 err.multipart_suggestion(
2684 "consider using the `Default` trait",
2685 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(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![
2686 (path_span.shrink_to_lo(), "<".to_string()),
2687 (
2688 path_span.shrink_to_hi().with_hi(call_span.hi()),
2689 " as std::default::Default>::default()".to_string(),
2690 ),
2691 ],
2692 Applicability::MaybeIncorrect,
2693 );
2694 }
2695 }
2696
2697 pub(crate) fn find_similarly_named_assoc_item(
2700 &mut self,
2701 ident: Symbol,
2702 kind: &AssocItemKind,
2703 ) -> Option<Symbol> {
2704 let (module, _) = self.current_trait_ref.as_ref()?;
2705 if ident == kw::Underscore {
2706 return None;
2708 }
2709
2710 let targets = self
2711 .r
2712 .resolutions(*module)
2713 .borrow()
2714 .iter()
2715 .filter_map(|(key, res)| res.borrow().best_decl().map(|binding| (key, binding.res())))
2716 .filter(|(_, res)| match (kind, res) {
2717 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst { .. }, _)) => true,
2718 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
2719 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
2720 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
2721 _ => false,
2722 })
2723 .map(|(key, _)| key.ident.name)
2724 .collect::<Vec<_>>();
2725
2726 find_best_match_for_name(&targets, ident, None)
2727 }
2728
2729 fn lookup_assoc_candidate<FilterFn>(
2730 &mut self,
2731 ident: Ident,
2732 ns: Namespace,
2733 filter_fn: FilterFn,
2734 called: bool,
2735 ) -> Option<AssocSuggestion>
2736 where
2737 FilterFn: Fn(Res) -> bool,
2738 {
2739 fn extract_node_id(t: &Ty) -> Option<NodeId> {
2740 match t.kind {
2741 TyKind::Path(None, _) => Some(t.id),
2742 TyKind::Ref(_, ref mut_ty) => extract_node_id(&mut_ty.ty),
2743 _ => None,
2747 }
2748 }
2749 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
2751 if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
2752 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
2753 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
2754 && let Some(fields) = self.r.field_idents(did)
2755 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
2756 {
2757 return Some(AssocSuggestion::Field(field.span));
2759 }
2760 }
2761
2762 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
2763 for assoc_item in items {
2764 if let Some(assoc_ident) = assoc_item.kind.ident()
2765 && assoc_ident == ident
2766 {
2767 return Some(match &assoc_item.kind {
2768 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
2769 ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
2770 AssocSuggestion::MethodWithSelf { called }
2771 }
2772 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
2773 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
2774 ast::AssocItemKind::Delegation(..)
2775 if self
2776 .r
2777 .owners
2778 .get(&assoc_item.id)
2779 .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
2780 .is_some_and(|sig| sig.has_self) =>
2781 {
2782 AssocSuggestion::MethodWithSelf { called }
2783 }
2784 ast::AssocItemKind::Delegation(..) => AssocSuggestion::AssocFn { called },
2785 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
2786 continue;
2787 }
2788 });
2789 }
2790 }
2791 }
2792
2793 if let Some((module, _)) = self.current_trait_ref
2795 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
2796 ModuleOrUniformRoot::Module(module),
2797 ident,
2798 ns,
2799 &self.parent_scope,
2800 None,
2801 )
2802 {
2803 let res = binding.res();
2804 if filter_fn(res) {
2805 match res {
2806 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
2807 let has_self = match def_id.as_local() {
2808 Some(def_id) => self
2809 .r
2810 .delegation_fn_sigs
2811 .get(&def_id)
2812 .is_some_and(|sig| sig.has_self),
2813 None => {
2814 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
2815 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
2816 })
2817 }
2818 };
2819 if has_self {
2820 return Some(AssocSuggestion::MethodWithSelf { called });
2821 } else {
2822 return Some(AssocSuggestion::AssocFn { called });
2823 }
2824 }
2825 Res::Def(DefKind::AssocConst { .. }, _) => {
2826 return Some(AssocSuggestion::AssocConst);
2827 }
2828 Res::Def(DefKind::AssocTy, _) => {
2829 return Some(AssocSuggestion::AssocType);
2830 }
2831 _ => {}
2832 }
2833 }
2834 }
2835
2836 None
2837 }
2838
2839 fn lookup_typo_candidate(
2840 &mut self,
2841 path: &[Segment],
2842 following_seg: Option<&Segment>,
2843 ns: Namespace,
2844 filter_fn: &impl Fn(Res) -> bool,
2845 ) -> TypoCandidate {
2846 let mut names = Vec::new();
2847 if let [segment] = path {
2848 let mut ctxt = segment.ident.span.ctxt();
2849
2850 for rib in self.ribs[ns].iter().rev() {
2853 let rib_ctxt = if rib.kind.contains_params() {
2854 ctxt.normalize_to_macros_2_0()
2855 } else {
2856 ctxt.normalize_to_macro_rules()
2857 };
2858
2859 for (ident, &res) in &rib.bindings {
2861 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
2862 names.push(TypoSuggestion::new(ident.name, ident.span, res));
2863 }
2864 }
2865
2866 if let RibKind::Block(Some(module)) = rib.kind {
2867 self.r.add_module_candidates(
2868 module.to_module(),
2869 &mut names,
2870 &filter_fn,
2871 Some(ctxt),
2872 );
2873 } else if let RibKind::Module(module) = rib.kind {
2874 let parent_scope =
2876 &ParentScope { module: module.to_module(), ..self.parent_scope };
2877 self.r.add_scope_set_candidates(
2878 &mut names,
2879 ScopeSet::All(ns),
2880 parent_scope,
2881 segment.ident.span.with_ctxt(ctxt),
2882 filter_fn,
2883 );
2884 break;
2885 }
2886
2887 if let RibKind::MacroDefinition(def) = rib.kind
2888 && def == self.r.macro_def(ctxt)
2889 {
2890 ctxt.remove_mark();
2893 }
2894 }
2895 } else {
2896 let mod_path = &path[..path.len() - 1];
2898 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2899 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
2900 {
2901 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
2902 }
2903 }
2904
2905 if let Some(following_seg) = following_seg {
2907 names.retain(|suggestion| match suggestion.res {
2908 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
2909 suggestion.candidate != following_seg.ident.name
2911 }
2912 Res::Def(DefKind::Mod, def_id) => {
2913 let module = self.r.expect_module(def_id);
2914 self.r
2915 .resolutions(module)
2916 .borrow()
2917 .iter()
2918 .any(|(key, _)| key.ident.name == following_seg.ident.name)
2919 }
2920 _ => true,
2921 });
2922 }
2923 let name = path[path.len() - 1].ident.name;
2924 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
2926
2927 match find_best_match_for_name(
2928 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
2929 name,
2930 None,
2931 ) {
2932 Some(found) => {
2933 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
2934 else {
2935 return TypoCandidate::None;
2936 };
2937 if found == name {
2938 TypoCandidate::Shadowed(sugg.res, sugg.span)
2939 } else {
2940 TypoCandidate::Typo(sugg)
2941 }
2942 }
2943 _ => TypoCandidate::None,
2944 }
2945 }
2946
2947 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
2950 let name = path[path.len() - 1].ident.as_str();
2951 Some(match name {
2953 "byte" => sym::u8, "short" => sym::i16,
2955 "Bool" => sym::bool,
2956 "Boolean" => sym::bool,
2957 "boolean" => sym::bool,
2958 "int" => sym::i32,
2959 "long" => sym::i64,
2960 "float" => sym::f32,
2961 "double" => sym::f64,
2962 _ => return None,
2963 })
2964 }
2965
2966 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
2969 if ident_span.from_expansion() {
2970 return false;
2971 }
2972
2973 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
2975 && let ast::ExprKind::Path(None, ref path) = lhs.kind
2976 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
2977 {
2978 let (span, text) = match path.segments.first() {
2979 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
2980 let name = name.trim_prefix('_');
2982 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
2983 }
2984 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
2985 };
2986
2987 err.span_suggestion_verbose(
2988 span,
2989 "you might have meant to introduce a new binding",
2990 text,
2991 Applicability::MaybeIncorrect,
2992 );
2993 return true;
2994 }
2995
2996 if err.code == Some(E0423)
2999 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3000 && val_span.contains(ident_span)
3001 && val_span.lo() == ident_span.lo()
3002 {
3003 err.span_suggestion_verbose(
3004 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3005 "you might have meant to use `:` for type annotation",
3006 ": ",
3007 Applicability::MaybeIncorrect,
3008 );
3009 return true;
3010 }
3011 false
3012 }
3013
3014 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3015 let mut result = None;
3016 let mut seen_modules = FxHashSet::default();
3017 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.r.graph_root.to_module(), ThinVec::new(), true)]))vec![(self.r.graph_root.to_module(), ThinVec::new(), true)];
3018
3019 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3020 if result.is_some() {
3022 break;
3023 }
3024
3025 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3026 if result.is_some() || !name_binding.vis().is_visible_locally() {
3028 return;
3029 }
3030 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3031 let mut path_segments = path_segments.clone();
3033 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3034 let doc_visible = doc_visible
3035 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3036 if module_def_id == def_id {
3037 let path =
3038 Path { span: name_binding.span, segments: path_segments, tokens: None };
3039 result = Some((
3040 r.expect_module(module_def_id),
3041 ImportSuggestion {
3042 did: Some(def_id),
3043 descr: "module",
3044 path,
3045 accessible: true,
3046 doc_visible,
3047 note: None,
3048 via_import: false,
3049 is_stable: true,
3050 },
3051 ));
3052 } else {
3053 if seen_modules.insert(module_def_id) {
3055 let module = r.expect_module(module_def_id);
3056 worklist.push((module, path_segments, doc_visible));
3057 }
3058 }
3059 }
3060 });
3061 }
3062
3063 result
3064 }
3065
3066 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3067 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3068 let mut variants = Vec::new();
3069 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3070 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3071 let mut segms = enum_import_suggestion.path.segments.clone();
3072 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3073 let path = Path { span: name_binding.span, segments: segms, tokens: None };
3074 variants.push((path, def_id, kind));
3075 }
3076 });
3077 variants
3078 })
3079 }
3080
3081 fn suggest_using_enum_variant(
3083 &self,
3084 err: &mut Diag<'_>,
3085 source: PathSource<'_, '_, '_>,
3086 def_id: DefId,
3087 span: Span,
3088 ) {
3089 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3090 err.note("you might have meant to use one of the enum's variants");
3091 return;
3092 };
3093
3094 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3099 PathSource::TupleStruct(..) => (None, true),
3101 PathSource::Expr(Some(expr)) => match &expr.kind {
3102 ExprKind::Call(..) => (None, true),
3104 ExprKind::MethodCall(MethodCall {
3107 receiver,
3108 span,
3109 seg: PathSegment { ident, .. },
3110 ..
3111 }) => {
3112 let dot_span = receiver.span.between(*span);
3113 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3114 *ctor_kind == CtorKind::Fn
3115 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3116 });
3117 (found_tuple_variant.then_some(dot_span), false)
3118 }
3119 ExprKind::Field(base, ident) => {
3122 let dot_span = base.span.between(ident.span);
3123 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3124 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3125 });
3126 (found_tuple_or_unit_variant.then_some(dot_span), false)
3127 }
3128 _ => (None, false),
3129 },
3130 _ => (None, false),
3131 };
3132
3133 if let Some(dot_span) = suggest_path_sep_dot_span {
3134 err.span_suggestion_verbose(
3135 dot_span,
3136 "use the path separator to refer to a variant",
3137 "::",
3138 Applicability::MaybeIncorrect,
3139 );
3140 } else if suggest_only_tuple_variants {
3141 let mut suggestable_variants = variant_ctors
3144 .iter()
3145 .filter(|(.., kind)| *kind == CtorKind::Fn)
3146 .map(|(variant, ..)| path_names_to_string(variant))
3147 .collect::<Vec<_>>();
3148 suggestable_variants.sort();
3149
3150 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3151
3152 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3153 "to match against"
3154 } else {
3155 "to construct"
3156 };
3157
3158 if !suggestable_variants.is_empty() {
3159 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3160 ::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")
3161 } else {
3162 ::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")
3163 };
3164
3165 err.span_suggestions(
3166 span,
3167 msg,
3168 suggestable_variants,
3169 Applicability::MaybeIncorrect,
3170 );
3171 }
3172
3173 if non_suggestable_variant_count == variant_ctors.len() {
3175 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}"));
3176 }
3177
3178 if non_suggestable_variant_count == 1 {
3180 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"));
3181 } else if non_suggestable_variant_count >= 1 {
3182 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!(
3183 "you might have meant {source_msg} one of the enum's non-tuple variants"
3184 ));
3185 }
3186 } else {
3187 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3188 let def_id = self.r.tcx.parent(ctor_def_id);
3189 match kind {
3190 CtorKind::Const => false,
3191 CtorKind::Fn => {
3192 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3193 }
3194 }
3195 };
3196
3197 let mut suggestable_variants = variant_ctors
3198 .iter()
3199 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3200 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3201 .map(|(variant, kind)| match kind {
3202 CtorKind::Const => variant,
3203 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3204 })
3205 .collect::<Vec<_>>();
3206 suggestable_variants.sort();
3207 let no_suggestable_variant = suggestable_variants.is_empty();
3208
3209 if !no_suggestable_variant {
3210 let msg = if suggestable_variants.len() == 1 {
3211 "you might have meant to use the following enum variant"
3212 } else {
3213 "you might have meant to use one of the following enum variants"
3214 };
3215
3216 err.span_suggestions(
3217 span,
3218 msg,
3219 suggestable_variants,
3220 Applicability::MaybeIncorrect,
3221 );
3222 }
3223
3224 let mut suggestable_variants_with_placeholders = variant_ctors
3225 .iter()
3226 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3227 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3228 .filter_map(|(variant, kind)| match kind {
3229 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3230 _ => None,
3231 })
3232 .collect::<Vec<_>>();
3233 suggestable_variants_with_placeholders.sort();
3234
3235 if !suggestable_variants_with_placeholders.is_empty() {
3236 let msg =
3237 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3238 (true, 1) => "the following enum variant is available",
3239 (true, _) => "the following enum variants are available",
3240 (false, 1) => "alternatively, the following enum variant is available",
3241 (false, _) => {
3242 "alternatively, the following enum variants are also available"
3243 }
3244 };
3245
3246 err.span_suggestions(
3247 span,
3248 msg,
3249 suggestable_variants_with_placeholders,
3250 Applicability::HasPlaceholders,
3251 );
3252 }
3253 };
3254
3255 if def_id.is_local() {
3256 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3257 }
3258 }
3259
3260 pub(crate) fn detect_and_suggest_const_parameter_error(
3291 &mut self,
3292 path: &[Segment],
3293 source: PathSource<'_, 'ast, 'ra>,
3294 ) -> Option<Diag<'tcx>> {
3295 let Some(item) = self.diag_metadata.current_item else { return None };
3296 let ItemKind::Impl(impl_) = &item.kind else { return None };
3297 let self_ty = &impl_.self_ty;
3298
3299 let [current_parameter] = path else {
3301 return None;
3302 };
3303
3304 let target_ident = current_parameter.ident;
3305
3306 let visitor = ParentPathVisitor::new(self_ty, target_ident);
3308
3309 let Some(parent_segment) = visitor.parent else {
3310 return None;
3311 };
3312
3313 let Some(args) = parent_segment.args.as_ref() else {
3314 return None;
3315 };
3316
3317 let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3318 return None;
3319 };
3320
3321 let usage_to_pos: FxHashMap<NodeId, usize> = angle
3324 .args
3325 .iter()
3326 .enumerate()
3327 .filter_map(|(pos, arg)| {
3328 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3329 && let TyKind::Path(_, path) = &ty.kind
3330 && let [segment] = path.segments.as_slice()
3331 {
3332 Some((segment.id, pos))
3333 } else {
3334 None
3335 }
3336 })
3337 .collect();
3338
3339 let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3342 return None;
3343 };
3344
3345 let ns = source.namespace();
3347 let segment = Segment::from(parent_segment);
3348 let segments = [segment];
3349 let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3350
3351 if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3352 &None,
3353 &segments,
3354 ns,
3355 source.defer_to_typeck(),
3356 finalize,
3357 source,
3358 ) && let Some(resolve) = resolve.full_res()
3359 && let Res::Def(_, def_id) = resolve
3360 && def_id.is_local()
3361 && let Some(local_def_id) = def_id.as_local()
3362 && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3363 && let Some(target_param) = &struct_generics.params.get(idx)
3364 && let GenericParamKind::Const { ty, .. } = &target_param.kind
3365 && let TyKind::Path(_, path) = &ty.kind
3366 {
3367 let full_type = path
3368 .segments
3369 .iter()
3370 .map(|seg| seg.ident.to_string())
3371 .collect::<Vec<_>>()
3372 .join("::");
3373
3374 let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3379 angle
3380 .args
3381 .iter()
3382 .find_map(|arg| {
3383 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3384 && let TyKind::Path(_, path) = &ty.kind
3385 && let [segment] = path.segments.as_slice()
3386 && segment.ident == impl_param.ident
3387 {
3388 usage_to_pos.get(&segment.id).copied()
3389 } else {
3390 None
3391 }
3392 })
3393 .map_or(false, |pos| pos > idx)
3394 });
3395
3396 let (insert_span, snippet) = match next_impl_param {
3397 Some(next_param) => {
3398 (
3401 next_param.span().shrink_to_lo(),
3402 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
full_type))
})format!("const {}: {}, ", target_ident, full_type),
3403 )
3404 }
3405 None => match impl_.generics.params.last() {
3406 Some(last) => {
3407 (
3410 last.span().shrink_to_hi(),
3411 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
full_type))
})format!(", const {}: {}", target_ident, full_type),
3412 )
3413 }
3414 None => {
3415 (
3418 impl_.generics.span.shrink_to_hi(),
3419 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
full_type))
})format!("<const {}: {}>", target_ident, full_type),
3420 )
3421 }
3422 },
3423 };
3424
3425 let mut err = self.r.dcx().struct_span_err(
3426 target_ident.span,
3427 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find const `{0}` in this scope",
target_ident))
})format!("cannot find const `{}` in this scope", target_ident),
3428 );
3429
3430 err.code(E0425);
3431
3432 err.span_label(target_ident.span, "not found in this scope");
3433
3434 err.span_label(
3435 target_param.span(),
3436 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("corresponding const parameter on the type defined here"))
})format!("corresponding const parameter on the type defined here",),
3437 );
3438
3439 err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3440 span: insert_span,
3441 snippet,
3442 item_name: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", target_ident))
})format!("{}", target_ident),
3443 item_location: String::from("impl"),
3444 });
3445
3446 return Some(err);
3447 }
3448
3449 None
3450 }
3451
3452 pub(crate) fn suggest_adding_generic_parameter(
3453 &mut self,
3454 path: &[Segment],
3455 source: PathSource<'_, 'ast, 'ra>,
3456 ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3457 let (ident, span) = match path {
3458 [segment]
3459 if !segment.has_generic_args
3460 && segment.ident.name != kw::SelfUpper
3461 && segment.ident.name != kw::Dyn =>
3462 {
3463 (segment.ident.to_string(), segment.ident.span)
3464 }
3465 _ => return (None, None),
3466 };
3467 let mut iter = ident.chars().map(|c| c.is_uppercase());
3468 let single_uppercase_char =
3469 #[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);
3470 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3471 return (None, None);
3472 }
3473 match (
3474 self.diag_metadata.current_item,
3475 single_uppercase_char,
3476 self.diag_metadata.currently_processing_generic_args,
3477 ) {
3478 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3479 }
3481 (
3482 Some(Item {
3483 kind:
3484 kind @ ItemKind::Fn(..)
3485 | kind @ ItemKind::Enum(..)
3486 | kind @ ItemKind::Struct(..)
3487 | kind @ ItemKind::Union(..),
3488 ..
3489 }),
3490 true,
3491 _,
3492 )
3493 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3495 | (Some(Item { kind, .. }), false, _) => {
3496 if let Some(generics) = kind.generics() {
3497 if span.overlaps(generics.span) {
3498 return (None, None);
3507 }
3508
3509 let (msg, sugg) = match source {
3510 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3511 if let Some(err) =
3512 self.detect_and_suggest_const_parameter_error(path, source)
3513 {
3514 return (None, Some(err));
3515 }
3516 ("you might be missing a type parameter", ident)
3517 }
3518 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3519 "you might be missing a const parameter",
3520 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3521 ),
3522 _ => return (None, None),
3523 };
3524 let (span, sugg) = if let [.., param] = &generics.params[..] {
3525 let span = if let [.., bound] = ¶m.bounds[..] {
3526 bound.span()
3527 } else if let GenericParam {
3528 kind: GenericParamKind::Const { ty, span: _, default },
3529 ..
3530 } = param
3531 {
3532 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3533 } else {
3534 param.ident.span
3535 };
3536 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
3537 } else {
3538 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
3539 };
3540 if span.can_be_used_for_suggestions() {
3542 return (
3543 Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
3544 None,
3545 );
3546 }
3547 }
3548 }
3549 _ => {}
3550 }
3551 (None, None)
3552 }
3553
3554 pub(crate) fn suggestion_for_label_in_rib(
3557 &self,
3558 rib_index: usize,
3559 label: Ident,
3560 ) -> Option<LabelSuggestion> {
3561 let within_scope = self.is_label_valid_from_rib(rib_index);
3563
3564 let rib = &self.label_ribs[rib_index];
3565 let names = rib
3566 .bindings
3567 .iter()
3568 .filter(|(id, _)| id.span.eq_ctxt(label.span))
3569 .map(|(id, _)| id.name)
3570 .collect::<Vec<Symbol>>();
3571
3572 find_best_match_for_name(&names, label.name, None).map(|symbol| {
3573 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
3577 (*ident, within_scope)
3578 })
3579 }
3580
3581 pub(crate) fn maybe_report_lifetime_uses(
3582 &mut self,
3583 generics_span: Span,
3584 params: &[ast::GenericParam],
3585 ) {
3586 for (param_index, param) in params.iter().enumerate() {
3587 let GenericParamKind::Lifetime = param.kind else { continue };
3588
3589 let def_id = self.r.local_def_id(param.id);
3590
3591 let use_set = self.lifetime_uses.remove(&def_id);
3592 {
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:3592",
"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(3592u32),
::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!(
3593 "Use set for {:?}({:?} at {:?}) is {:?}",
3594 def_id, param.ident, param.ident.span, use_set
3595 );
3596
3597 let deletion_span = || {
3598 if params.len() == 1 {
3599 Some(generics_span)
3601 } else if param_index == 0 {
3602 match (
3605 param.span().find_ancestor_inside(generics_span),
3606 params[param_index + 1].span().find_ancestor_inside(generics_span),
3607 ) {
3608 (Some(param_span), Some(next_param_span)) => {
3609 Some(param_span.to(next_param_span.shrink_to_lo()))
3610 }
3611 _ => None,
3612 }
3613 } else {
3614 match (
3617 param.span().find_ancestor_inside(generics_span),
3618 params[param_index - 1].span().find_ancestor_inside(generics_span),
3619 ) {
3620 (Some(param_span), Some(prev_param_span)) => {
3621 Some(prev_param_span.shrink_to_hi().to(param_span))
3622 }
3623 _ => None,
3624 }
3625 }
3626 };
3627 match use_set {
3628 Some(LifetimeUseSet::Many) => {}
3629 Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
3632 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
3633 let param_ident = param.ident;
3634 let deletion_span =
3635 if param.bounds.is_empty() { deletion_span() } else { None };
3636 self.r.lint_buffer.dyn_buffer_lint_any(
3637 lint::builtin::SINGLE_USE_LIFETIMES,
3638 param.id,
3639 param_ident.span,
3640 move |dcx, level, sess| {
3641 {
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:3641",
"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(3641u32),
::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);
3642
3643 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
3644 let suggestion = if let Some(deletion_span) = deletion_span {
3645 let (use_span, replace_lt) = if elidable {
3646 let use_span = sess
3647 .downcast_ref::<Session>()
3648 .expect("expected a `Session`")
3649 .source_map()
3650 .span_extend_while_whitespace(use_span);
3651 (use_span, String::new())
3652 } else {
3653 (use_span, "'_".to_owned())
3654 };
3655 {
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:3655",
"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(3655u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["deletion_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(&deletion_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!(?deletion_span, ?use_span);
3656
3657 let deletion_span = if deletion_span.is_empty() {
3660 None
3661 } else {
3662 Some(deletion_span)
3663 };
3664 Some(diagnostics::SingleUseLifetimeSugg {
3665 deletion_span,
3666 use_span,
3667 replace_lt,
3668 })
3669 } else {
3670 None
3671 };
3672 diagnostics::SingleUseLifetime {
3673 suggestion,
3674 param_span: param_ident.span,
3675 use_span,
3676 ident: param_ident,
3677 }
3678 .into_diag(dcx, level)
3679 },
3680 );
3681 }
3682 None => {
3683 {
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:3683",
"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(3683u32),
::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);
3684 let deletion_span = deletion_span();
3685
3686 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
3688 self.r.lint_buffer.buffer_lint(
3689 lint::builtin::UNUSED_LIFETIMES,
3690 param.id,
3691 param.ident.span,
3692 diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
3693 );
3694 }
3695 }
3696 }
3697 }
3698 }
3699
3700 pub(crate) fn emit_undeclared_lifetime_error(
3701 &self,
3702 lifetime_ref: &ast::Lifetime,
3703 outer_lifetime_ref: Option<Ident>,
3704 ) -> ErrorGuaranteed {
3705 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);
3706 let mut err = if let Some(outer) = outer_lifetime_ref {
3707 {
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!(
3708 self.r.dcx(),
3709 lifetime_ref.ident.span,
3710 E0401,
3711 "can't use generic parameters from outer item",
3712 )
3713 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
3714 .with_span_label(outer.span, "lifetime parameter from outer item")
3715 } else {
3716 {
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!(
3717 self.r.dcx(),
3718 lifetime_ref.ident.span,
3719 E0261,
3720 "use of undeclared lifetime name `{}`",
3721 lifetime_ref.ident
3722 )
3723 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
3724 };
3725
3726 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
3728 err.span_suggestion_verbose(
3729 lifetime_ref.ident.span,
3730 "you may have misspelled the `'static` lifetime",
3731 "'static",
3732 Applicability::MachineApplicable,
3733 );
3734 } else {
3735 self.suggest_introducing_lifetime(
3736 &mut err,
3737 Some(lifetime_ref.ident),
3738 |err, _, span, message, suggestion, span_suggs| {
3739 err.multipart_suggestion(
3740 message,
3741 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
3742 Applicability::MaybeIncorrect,
3743 );
3744 true
3745 },
3746 );
3747 }
3748
3749 err.emit()
3750 }
3751
3752 fn suggest_introducing_lifetime(
3753 &self,
3754 err: &mut Diag<'_>,
3755 name: Option<Ident>,
3756 suggest: impl Fn(
3757 &mut Diag<'_>,
3758 bool,
3759 Span,
3760 Cow<'static, str>,
3761 String,
3762 Vec<(Span, String)>,
3763 ) -> bool,
3764 ) {
3765 self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
3766 }
3767
3768 pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
3769 &self,
3770 err: &mut Diag<'_>,
3771 lifetime: Span,
3772 ) {
3773 self.suggest_introducing_lifetime_filtered(
3774 err,
3775 None,
3776 |kind| {
3777 !#[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3778 kind,
3779 LifetimeBinderKind::FnPtrType
3780 | LifetimeBinderKind::PolyTrait
3781 | LifetimeBinderKind::WhereBound
3782 )
3783 },
3784 |err, _higher_ranked, span, message, intro_sugg, _| {
3785 err.multipart_suggestion(
3786 message,
3787 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())],
3788 Applicability::MaybeIncorrect,
3789 );
3790 false
3791 },
3792 );
3793 }
3794
3795 fn suggest_introducing_lifetime_filtered(
3796 &self,
3797 err: &mut Diag<'_>,
3798 name: Option<Ident>,
3799 mut consider: impl FnMut(LifetimeBinderKind) -> bool,
3800 suggest: impl Fn(
3801 &mut Diag<'_>,
3802 bool,
3803 Span,
3804 Cow<'static, str>,
3805 String,
3806 Vec<(Span, String)>,
3807 ) -> bool,
3808 ) {
3809 let mut suggest_note = true;
3810 for rib in self.lifetime_ribs.iter().rev() {
3811 let mut should_continue = true;
3812 match rib.kind {
3813 LifetimeRibKind::Generics { binder, span, kind } => {
3814 if let LifetimeBinderKind::ConstItem = kind
3817 && !self.r.tcx().features().generic_const_items()
3818 {
3819 continue;
3820 }
3821 if #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::ImplAssocType => true,
_ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
3822 continue;
3823 }
3824
3825 if !span.can_be_used_for_suggestions()
3826 && suggest_note
3827 && let Some(name) = name
3828 {
3829 suggest_note = false; err.span_label(
3831 span,
3832 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
3833 "lifetime `{name}` is missing in item created through this procedural macro",
3834 ),
3835 );
3836 continue;
3837 }
3838
3839 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
3840 kind,
3841 LifetimeBinderKind::FnPtrType
3842 | LifetimeBinderKind::PolyTrait
3843 | LifetimeBinderKind::WhereBound
3844 );
3845
3846 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
3847 let (span, sugg) = if span.is_empty() {
3848 let mut binder_idents: FxIndexSet<Ident> = Default::default();
3849 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
3850
3851 if let LifetimeBinderKind::WhereBound = kind
3858 && let Some(predicate) = self.diag_metadata.current_where_predicate
3859 && let ast::WherePredicateKind::BoundPredicate(
3860 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
3861 ) = &predicate.kind
3862 && bounded_ty.id == binder
3863 {
3864 for bound in bounds {
3865 if let ast::GenericBound::Trait(poly_trait_ref) = bound
3866 && let span = poly_trait_ref
3867 .span
3868 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
3869 && !span.is_empty()
3870 {
3871 rm_inner_binders.insert(span);
3872 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
3873 binder_idents.insert(v.ident);
3874 });
3875 }
3876 }
3877 }
3878
3879 let binders_sugg: String = binder_idents
3880 .into_iter()
3881 .map(|ident| ident.to_string())
3882 .intersperse(", ".to_owned())
3883 .collect();
3884 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!(
3885 "{}<{}>{}",
3886 if higher_ranked { "for" } else { "" },
3887 binders_sugg,
3888 if higher_ranked { " " } else { "" },
3889 );
3890 (span, sugg)
3891 } else {
3892 let span = self
3893 .r
3894 .tcx
3895 .sess
3896 .source_map()
3897 .span_through_char(span, '<')
3898 .shrink_to_hi();
3899 let sugg =
3900 ::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"));
3901 (span, sugg)
3902 };
3903
3904 if higher_ranked {
3905 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!(
3906 "consider making the {} lifetime-generic with a new `{}` lifetime",
3907 kind.descr(),
3908 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
3909 ));
3910 should_continue = suggest(
3911 err,
3912 true,
3913 span,
3914 message,
3915 sugg,
3916 if !rm_inner_binders.is_empty() {
3917 rm_inner_binders
3918 .into_iter()
3919 .map(|v| (v, "".to_string()))
3920 .collect::<Vec<_>>()
3921 } else {
3922 ::alloc::vec::Vec::new()vec![]
3923 },
3924 );
3925 err.note_once(
3926 "for more information on higher-ranked polymorphism, visit \
3927 https://doc.rust-lang.org/nomicon/hrtb.html",
3928 );
3929 } else if let Some(name) = name {
3930 let message =
3931 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
3932 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3933 } else {
3934 let message = Cow::from("consider introducing a named lifetime parameter");
3935 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
3936 }
3937 }
3938 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
3939 _ => {}
3940 }
3941 if !should_continue {
3942 break;
3943 }
3944 }
3945 }
3946
3947 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
3948 &self,
3949 lifetime_ref: &ast::Lifetime,
3950 ) -> ErrorGuaranteed {
3951 self.r
3952 .dcx()
3953 .create_err(diagnostics::ParamInTyOfConstParam {
3954 span: lifetime_ref.ident.span,
3955 name: lifetime_ref.ident.name,
3956 })
3957 .emit()
3958 }
3959
3960 pub(crate) fn emit_forbidden_non_static_lifetime_error(
3964 &self,
3965 cause: NoConstantGenericsReason,
3966 lifetime_ref: &ast::Lifetime,
3967 ) -> ErrorGuaranteed {
3968 match cause {
3969 NoConstantGenericsReason::IsEnumDiscriminant => self
3970 .r
3971 .dcx()
3972 .create_err(diagnostics::ParamInEnumDiscriminant {
3973 span: lifetime_ref.ident.span,
3974 name: lifetime_ref.ident.name,
3975 param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
3976 })
3977 .emit(),
3978 NoConstantGenericsReason::NonTrivialConstArg => {
3979 if !!self.r.features.generic_const_exprs() {
::core::panicking::panic("assertion failed: !self.r.features.generic_const_exprs()")
};assert!(!self.r.features.generic_const_exprs());
3980 self.r
3981 .dcx()
3982 .create_err(diagnostics::ParamInNonTrivialAnonConst {
3983 span: lifetime_ref.ident.span,
3984 name: lifetime_ref.ident.name,
3985 param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
3986 help: self.r.tcx.sess.is_nightly_build(),
3987 is_gca: self.r.features.generic_const_args(),
3988 help_gca: self.r.features.generic_const_args(),
3989 })
3990 .emit()
3991 }
3992 }
3993 }
3994
3995 pub(crate) fn report_missing_lifetime_specifiers<'a>(
3996 &mut self,
3997 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
3998 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
3999 ) -> ErrorGuaranteed {
4000 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4001 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4002
4003 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!(
4004 self.r.dcx(),
4005 spans,
4006 E0106,
4007 "missing lifetime specifier{}",
4008 pluralize!(num_lifetimes)
4009 );
4010 self.add_missing_lifetime_specifiers_label(
4011 &mut err,
4012 lifetime_refs,
4013 function_param_lifetimes,
4014 );
4015 err.emit()
4016 }
4017
4018 fn add_missing_lifetime_specifiers_label<'a>(
4019 &mut self,
4020 err: &mut Diag<'_>,
4021 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4022 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4023 ) {
4024 for < in lifetime_refs.clone() {
4025 err.span_label(
4026 lt.span,
4027 ::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!(
4028 "expected {} lifetime parameter{}",
4029 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4030 pluralize!(lt.count),
4031 ),
4032 );
4033 }
4034
4035 let mut in_scope_lifetimes: Vec<_> = self
4036 .lifetime_ribs
4037 .iter()
4038 .rev()
4039 .take_while(|rib| {
4040 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4041 })
4042 .flat_map(|rib| rib.bindings.iter())
4043 .map(|(&ident, &res)| (ident, res))
4044 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4045 .collect();
4046 {
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:4046",
"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(4046u32),
::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);
4047
4048 let mut maybe_static = false;
4049 {
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:4049",
"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(4049u32),
::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);
4050 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4051 let elided_len = param_lifetimes.len();
4052 let num_params = params.len();
4053
4054 let mut m = String::new();
4055
4056 for (i, info) in params.iter().enumerate() {
4057 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4058 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);
4059
4060 err.span_label(span, "");
4061
4062 if i != 0 {
4063 if i + 1 < num_params {
4064 m.push_str(", ");
4065 } else if num_params == 2 {
4066 m.push_str(" or ");
4067 } else {
4068 m.push_str(", or ");
4069 }
4070 }
4071
4072 let help_name = if let Some(ident) = ident {
4073 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
4074 } else {
4075 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
4076 };
4077
4078 if lifetime_count == 1 {
4079 m.push_str(&help_name[..])
4080 } else {
4081 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")[..])
4082 }
4083 }
4084
4085 if num_params == 0 {
4086 err.help(
4087 "this function's return type contains a borrowed value, but there is no value \
4088 for it to be borrowed from",
4089 );
4090 if in_scope_lifetimes.is_empty() {
4091 maybe_static = true;
4092 in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4093 Ident::with_dummy_span(kw::StaticLifetime),
4094 (DUMMY_NODE_ID, LifetimeRes::Static),
4095 )];
4096 }
4097 } else if elided_len == 0 {
4098 err.help(
4099 "this function's return type contains a borrowed value with an elided \
4100 lifetime, but the lifetime cannot be derived from the arguments",
4101 );
4102 if in_scope_lifetimes.is_empty() {
4103 maybe_static = true;
4104 in_scope_lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(Ident::with_dummy_span(kw::StaticLifetime),
(DUMMY_NODE_ID, LifetimeRes::Static))]))vec![(
4105 Ident::with_dummy_span(kw::StaticLifetime),
4106 (DUMMY_NODE_ID, LifetimeRes::Static),
4107 )];
4108 }
4109 } else if num_params == 1 {
4110 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!(
4111 "this function's return type contains a borrowed value, but the signature does \
4112 not say which {m} it is borrowed from",
4113 ));
4114 } else {
4115 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!(
4116 "this function's return type contains a borrowed value, but the signature does \
4117 not say whether it is borrowed from {m}",
4118 ));
4119 }
4120 }
4121
4122 #[allow(rustc::symbol_intern_string_literal)]
4123 let existing_name = match &in_scope_lifetimes[..] {
4124 [] => Symbol::intern("'a"),
4125 [(existing, _)] => existing.name,
4126 _ => Symbol::intern("'lifetime"),
4127 };
4128
4129 let mut spans_suggs: Vec<_> = Vec::new();
4130 let source_map = self.r.tcx.sess.source_map();
4131 let build_sugg = |lt: MissingLifetime| match lt.kind {
4132 MissingLifetimeKind::Underscore => {
4133 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);
4134 (lt.span, existing_name.to_string())
4135 }
4136 MissingLifetimeKind::Ampersand => {
4137 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);
4138 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
4139 }
4140 MissingLifetimeKind::Comma => {
4141 let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4142 .intersperse(", ")
4143 .collect();
4144 let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4145 let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", sugg))
})format!("{sugg}, ") };
4146 (lt.span.shrink_to_hi(), sugg)
4147 }
4148 MissingLifetimeKind::Brackets => {
4149 let sugg: String = std::iter::once("<")
4150 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4151 .chain([">"])
4152 .collect();
4153 (lt.span.shrink_to_hi(), sugg)
4154 }
4155 };
4156 for < in lifetime_refs.clone() {
4157 spans_suggs.push(build_sugg(lt));
4158 }
4159 {
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:4159",
"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(4159u32),
::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);
4160 match in_scope_lifetimes.len() {
4161 0 => {
4162 if let Some((param_lifetimes, _)) = function_param_lifetimes {
4163 for lt in param_lifetimes {
4164 spans_suggs.push(build_sugg(lt))
4165 }
4166 }
4167 self.suggest_introducing_lifetime(
4168 err,
4169 None,
4170 |err, higher_ranked, span, message, intro_sugg, _| {
4171 err.multipart_suggestion(
4172 message,
4173 std::iter::once((span, intro_sugg))
4174 .chain(spans_suggs.clone())
4175 .collect(),
4176 Applicability::MaybeIncorrect,
4177 );
4178 higher_ranked
4179 },
4180 );
4181 }
4182 1 => {
4183 let post = if maybe_static {
4184 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4185 let owned = if let Some(lt) = lifetime_refs.next()
4186 && lifetime_refs.next().is_none()
4187 && lt.kind != MissingLifetimeKind::Ampersand
4188 {
4189 ", or if you will only have owned values"
4190 } else {
4191 ""
4192 };
4193 ::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!(
4194 ", but this is uncommon unless you're returning a borrowed value from a \
4195 `const` or a `static`{owned}",
4196 )
4197 } else {
4198 String::new()
4199 };
4200 err.multipart_suggestion(
4201 ::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}"),
4202 spans_suggs,
4203 Applicability::MaybeIncorrect,
4204 );
4205 if maybe_static {
4206 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4212 if let Some(lt) = lifetime_refs.next()
4213 && lifetime_refs.next().is_none()
4214 && (lt.kind == MissingLifetimeKind::Ampersand
4215 || lt.kind == MissingLifetimeKind::Underscore)
4216 {
4217 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4218 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4219 && !sig.decl.inputs.is_empty()
4220 && let sugg = sig
4221 .decl
4222 .inputs
4223 .iter()
4224 .filter_map(|param| {
4225 if param.ty.span.contains(lt.span) {
4226 None
4229 } else if let TyKind::CVarArgs = param.ty.kind {
4230 None
4232 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
4233 None
4235 } else {
4236 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4237 }
4238 })
4239 .collect::<Vec<_>>()
4240 && !sugg.is_empty()
4241 {
4242 let (the, s) = if sig.decl.inputs.len() == 1 {
4243 ("the", "")
4244 } else {
4245 ("one of the", "s")
4246 };
4247 let dotdotdot =
4248 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4249 err.multipart_suggestion(
4250 ::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!(
4251 "instead, you are more likely to want to change {the} \
4252 argument{s} to be borrowed{dotdotdot}",
4253 ),
4254 sugg,
4255 Applicability::MaybeIncorrect,
4256 );
4257 "...or alternatively, you might want"
4258 } else if (lt.kind == MissingLifetimeKind::Ampersand
4259 || lt.kind == MissingLifetimeKind::Underscore)
4260 && let Some((kind, _span)) = self.diag_metadata.current_function
4261 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4262 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4263 && !sig.decl.inputs.is_empty()
4264 && let arg_refs = sig
4265 .decl
4266 .inputs
4267 .iter()
4268 .filter_map(|param| match ¶m.ty.kind {
4269 TyKind::ImplTrait(_, bounds) => Some(bounds),
4270 _ => None,
4271 })
4272 .flat_map(|bounds| bounds.into_iter())
4273 .collect::<Vec<_>>()
4274 && !arg_refs.is_empty()
4275 {
4276 let mut lt_finder =
4282 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4283 for bound in arg_refs {
4284 if let ast::GenericBound::Trait(trait_ref) = bound {
4285 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4286 }
4287 }
4288 lt_finder.visit_ty(ret_ty);
4289 let spans_suggs: Vec<_> = lt_finder
4290 .seen
4291 .iter()
4292 .filter_map(|ty| match &ty.kind {
4293 TyKind::Ref(_, mut_ty) => {
4294 let span = ty.span.with_hi(mut_ty.ty.span.lo());
4295 Some((span, "&'a ".to_string()))
4296 }
4297 _ => None,
4298 })
4299 .collect();
4300 self.suggest_introducing_lifetime(
4301 err,
4302 None,
4303 |err, higher_ranked, span, message, intro_sugg, _| {
4304 err.multipart_suggestion(
4305 message,
4306 std::iter::once((span, intro_sugg))
4307 .chain(spans_suggs.clone())
4308 .collect(),
4309 Applicability::MaybeIncorrect,
4310 );
4311 higher_ranked
4312 },
4313 );
4314 "alternatively, you might want"
4315 } else {
4316 "instead, you are more likely to want"
4317 };
4318 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4319 let mut sugg_is_str_to_string = false;
4320 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span, String::new())]))vec![(lt.span, String::new())];
4321 if let Some((kind, _span)) = self.diag_metadata.current_function
4322 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4323 {
4324 let mut lt_finder =
4325 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4326 for param in &sig.decl.inputs {
4327 lt_finder.visit_ty(¶m.ty);
4328 }
4329 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4330 lt_finder.visit_ty(ret_ty);
4331 let mut ret_lt_finder =
4332 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4333 ret_lt_finder.visit_ty(ret_ty);
4334 if let [Ty { span, kind: TyKind::Ref(_, mut_ty), .. }] =
4335 &ret_lt_finder.seen[..]
4336 {
4337 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.with_hi(mut_ty.ty.span.lo()), String::new())]))vec![(span.with_hi(mut_ty.ty.span.lo()), String::new())];
4343 owned_sugg = true;
4344 }
4345 }
4346 if let Some(ty) = lt_finder.found {
4347 if let TyKind::Path(None, path) = &ty.kind {
4348 let path: Vec<_> = Segment::from_path(path);
4350 match self.resolve_path(
4351 &path,
4352 Some(TypeNS),
4353 None,
4354 PathSource::Type,
4355 ) {
4356 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4357 match module.res() {
4358 Some(Res::PrimTy(PrimTy::Str)) => {
4359 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4361 lt.span.with_hi(ty.span.hi()),
4362 "String".to_string(),
4363 )];
4364 sugg_is_str_to_string = true;
4365 }
4366 Some(Res::PrimTy(..)) => {}
4367 Some(Res::Def(
4368 DefKind::Struct
4369 | DefKind::Union
4370 | DefKind::Enum
4371 | DefKind::ForeignTy
4372 | DefKind::AssocTy
4373 | DefKind::OpaqueTy
4374 | DefKind::TyParam,
4375 _,
4376 )) => {}
4377 _ => {
4378 owned_sugg = false;
4380 }
4381 }
4382 }
4383 PathResult::NonModule(res) => {
4384 match res.base_res() {
4385 Res::PrimTy(PrimTy::Str) => {
4386 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(ty.span.hi()), "String".to_string())]))vec![(
4388 lt.span.with_hi(ty.span.hi()),
4389 "String".to_string(),
4390 )];
4391 sugg_is_str_to_string = true;
4392 }
4393 Res::PrimTy(..) => {}
4394 Res::Def(
4395 DefKind::Struct
4396 | DefKind::Union
4397 | DefKind::Enum
4398 | DefKind::ForeignTy
4399 | DefKind::AssocTy
4400 | DefKind::OpaqueTy
4401 | DefKind::TyParam,
4402 _,
4403 ) => {}
4404 _ => {
4405 owned_sugg = false;
4407 }
4408 }
4409 }
4410 _ => {
4411 owned_sugg = false;
4413 }
4414 }
4415 }
4416 if let TyKind::Slice(inner_ty) = &ty.kind {
4417 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
(ty.span.with_lo(inner_ty.span.hi()), ">".to_string())]))vec![
4419 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4420 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4421 ];
4422 }
4423 }
4424 }
4425 if owned_sugg {
4426 if let Some(span) =
4427 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4428 && !sugg_is_str_to_string
4429 {
4430 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, String::new())]))vec![(span, String::new())];
4431 }
4432 err.multipart_suggestion(
4433 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4434 sugg,
4435 Applicability::MaybeIncorrect,
4436 );
4437 }
4438 }
4439 }
4440 }
4441 _ => {
4442 let lifetime_spans: Vec<_> =
4443 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4444 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4445
4446 if spans_suggs.len() > 0 {
4447 err.multipart_suggestion(
4450 "consider using one of the available lifetimes here",
4451 spans_suggs,
4452 Applicability::HasPlaceholders,
4453 );
4454 }
4455 }
4456 }
4457 }
4458
4459 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4460 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4461 if let Some(item) = self.diag_metadata.current_item {
4462 finder.visit_item(item);
4463 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4464 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4465 {
4466 for param in &sig.decl.inputs {
4467 finder.visit_ty(¶m.ty);
4468 }
4469 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4470 finder.visit_ty(ret_ty);
4471 }
4472 }
4473 finder.span
4474 }
4475}
4476
4477fn mk_where_bound_predicate(
4478 path: &Path,
4479 poly_trait_ref: &ast::PolyTraitRef,
4480 ty: &Ty,
4481) -> Option<ast::WhereBoundPredicate> {
4482 let modified_segments = {
4483 let mut segments = path.segments.clone();
4484 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4485 return None;
4486 };
4487 let mut segments = ThinVec::from(preceding);
4488
4489 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4490 id: DUMMY_NODE_ID,
4491 ident: last.ident,
4492 gen_args: None,
4493 kind: ast::AssocItemConstraintKind::Equality {
4494 term: ast::Term::Ty(Box::new(ast::Ty {
4495 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4496 id: DUMMY_NODE_ID,
4497 span: DUMMY_SP,
4498 tokens: None,
4499 })),
4500 },
4501 span: DUMMY_SP,
4502 });
4503
4504 match second_last.args.as_deref_mut() {
4505 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4506 args.push(added_constraint);
4507 }
4508 Some(_) => return None,
4509 None => {
4510 second_last.args =
4511 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4512 args: ThinVec::from([added_constraint]),
4513 span: DUMMY_SP,
4514 })));
4515 }
4516 }
4517
4518 segments.push(second_last.clone());
4519 segments
4520 };
4521
4522 let new_where_bound_predicate = ast::WhereBoundPredicate {
4523 bound_generic_params: ThinVec::new(),
4524 bounded_ty: Box::new(ty.clone()),
4525 bounds: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(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
}thin_vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4526 bound_generic_params: ThinVec::new(),
4527 modifiers: ast::TraitBoundModifiers::NONE,
4528 trait_ref: ast::TraitRef {
4529 path: ast::Path { segments: modified_segments, span: DUMMY_SP, tokens: None },
4530 ref_id: DUMMY_NODE_ID,
4531 },
4532 span: DUMMY_SP,
4533 parens: ast::Parens::No,
4534 })],
4535 };
4536
4537 Some(new_where_bound_predicate)
4538}
4539
4540pub(super) fn signal_lifetime_shadowing(
4542 sess: &Session,
4543 orig: Ident,
4544 shadower: Ident,
4545) -> ErrorGuaranteed {
4546 {
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!(
4547 sess.dcx(),
4548 shadower.span,
4549 E0496,
4550 "lifetime name `{}` shadows a lifetime name that is already in scope",
4551 orig.name,
4552 )
4553 .with_span_label(orig.span, "first declared here")
4554 .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))
4555 .emit()
4556}
4557
4558struct LifetimeFinder<'ast> {
4559 lifetime: Span,
4560 found: Option<&'ast Ty>,
4561 seen: Vec<&'ast Ty>,
4562}
4563
4564impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
4565 fn visit_ty(&mut self, t: &'ast Ty) {
4566 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind {
4567 self.seen.push(t);
4568 if t.span.lo() == self.lifetime.lo() {
4569 self.found = Some(&mut_ty.ty);
4570 }
4571 }
4572 walk_ty(self, t)
4573 }
4574}
4575
4576struct RefPrefixSpanFinder {
4577 lifetime: Span,
4578 span: Option<Span>,
4579}
4580
4581impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
4582 fn visit_ty(&mut self, t: &'ast Ty) {
4583 if self.span.is_some() {
4584 return;
4585 }
4586 if let TyKind::Ref(_, mut_ty) | TyKind::PinnedRef(_, mut_ty) = &t.kind
4587 && t.span.lo() == self.lifetime.lo()
4588 {
4589 self.span = Some(t.span.with_hi(mut_ty.ty.span.lo()));
4590 return;
4591 }
4592 walk_ty(self, t);
4593 }
4594}
4595
4596pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
4599 let name = shadower.name;
4600 let shadower = shadower.span;
4601 sess.dcx()
4602 .struct_span_warn(
4603 shadower,
4604 ::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"),
4605 )
4606 .with_span_label(orig, "first declared here")
4607 .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"))
4608 .emit();
4609}
4610
4611struct ParentPathVisitor<'a> {
4612 target: Ident,
4613 parent: Option<&'a PathSegment>,
4614 stack: Vec<&'a Ty>,
4615}
4616
4617impl<'a> ParentPathVisitor<'a> {
4618 fn new(self_ty: &'a Ty, target: Ident) -> Self {
4619 let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
4620
4621 v.visit_ty(self_ty);
4622 v
4623 }
4624}
4625
4626impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
4627 fn visit_ty(&mut self, ty: &'a Ty) {
4628 if self.parent.is_some() {
4629 return;
4630 }
4631
4632 self.stack.push(ty);
4634
4635 if let TyKind::Path(_, path) = &ty.kind
4636 && let [segment] = path.segments.as_slice()
4638 && segment.ident == self.target
4639 && let [.., parent_ty, _ty] = self.stack.as_slice()
4641 && let TyKind::Path(_, parent_path) = &parent_ty.kind
4642 {
4643 self.parent = parent_path.segments.first();
4644 }
4645
4646 walk_ty(self, ty);
4647
4648 self.stack.pop();
4649 }
4650}