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