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