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_attr_ir::diagnostic::{CustomDiagnostic, FormatArgs};
15use rustc_attr_ir::find_attr;
16use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
17use rustc_data_structures::unord::UnordItems;
18use rustc_errors::codes::*;
19use rustc_errors::{
20 Applicability, Diag, Diagnostic, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize,
21 struct_span_code_err,
22};
23use rustc_hir::def::Namespace::{self, *};
24use rustc_hir::def::{CtorKind, CtorOf, DefKind, MacroKinds};
25use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
26use rustc_hir::{MissingLifetimeKind, PrimTy};
27use rustc_lint_defs::builtin::{SINGLE_USE_LIFETIMES, UNUSED_LIFETIMES};
28use rustc_middle::ty;
29use rustc_session::Session;
30use rustc_span::edit_distance::{edit_distance, find_best_match_for_name};
31use rustc_span::edition::Edition;
32use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
33use thin_vec::{ThinVec, thin_vec};
34use tracing::debug;
35
36use super::NoConstantGenericsReason;
37use crate::diagnostics::impls::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
38use crate::late::{
39 AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind,
40 LifetimeUseSet, QSelf, RibKind,
41};
42use crate::ty::fast_reject::SimplifiedType;
43use crate::{
44 Finalize, Module, ModuleOrUniformRoot, ParentScope, PathResult, PathSource, Res, Resolver,
45 ScopeSet, Segment, diagnostics, path_names_to_string,
46};
47
48#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for AssocFrom
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for AssocFrom {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for AssocFrom { }Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for AssocFrom {
}
#[automatically_derived]impl ::core::clone::Clone for AssocFrom {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for AssocFrom { }Copy)]
49enum AssocFrom {
50 Trait,
51 Impl,
52}
53
54enum AssocSuggestion {
56 Field,
57 MethodWithSelf { called: bool, from: AssocFrom },
58 AssocFn { called: bool, from: AssocFrom },
59 AssocType { from: AssocFrom },
60 AssocConst,
61}
62
63impl AssocSuggestion {
64 fn action(&self) -> &'static str {
65 match self {
66 AssocSuggestion::Field => "use the available field",
67 AssocSuggestion::MethodWithSelf { called: true, .. } => {
68 "call the method with the fully-qualified path"
69 }
70 AssocSuggestion::MethodWithSelf { called: false, .. } => {
71 "refer to the method with the fully-qualified path"
72 }
73 AssocSuggestion::AssocFn { called: true, .. } => "call the associated function",
74 AssocSuggestion::AssocFn { called: false, .. } => "refer to the associated function",
75 AssocSuggestion::AssocConst { .. } => "use the associated `const`",
76 AssocSuggestion::AssocType { .. } => "use the associated type",
77 }
78 }
79}
80
81fn is_self_type(path: &[Segment], namespace: Namespace) -> bool {
82 namespace == TypeNS && path.len() == 1 && path[0].ident.name == kw::SelfUpper
83}
84
85fn is_self_value(path: &[Segment], namespace: Namespace) -> bool {
86 namespace == ValueNS && path.len() == 1 && path[0].ident.name == kw::SelfLower
87}
88
89fn path_to_string_without_assoc_item_bindings(path: &Path) -> String {
90 let mut path = path.clone();
91 for segment in &mut path.segments {
92 let mut remove_args = false;
93 if let Some(args) = segment.args.as_deref_mut()
94 && let ast::GenericArgs::AngleBracketed(angle_bracketed) = args
95 {
96 angle_bracketed.args.retain(|arg| #[allow(non_exhaustive_omitted_patterns)] match arg {
ast::AngleBracketedArg::Arg(_) => true,
_ => false,
}matches!(arg, ast::AngleBracketedArg::Arg(_)));
97 remove_args = angle_bracketed.args.is_empty();
98 }
99 if remove_args {
100 segment.args = None;
101 }
102 }
103 path_to_string(&path)
104}
105
106fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, String) {
108 let variant_path = &suggestion.path;
109 let variant_path_string = path_names_to_string(variant_path);
110
111 let path_len = suggestion.path.segments.len();
112 let enum_path = ast::Path {
113 span: suggestion.path.span,
114 segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(),
115 };
116 let enum_path_string = path_names_to_string(&enum_path);
117
118 (variant_path_string, enum_path_string)
119}
120
121#[derive(#[automatically_derived]impl ::core::marker::Copy for MissingLifetime { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for MissingLifetime {
}
#[automatically_derived]impl ::core::clone::Clone for MissingLifetime {
#[inline]
fn clone(&self) -> Self {
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::marker::StructuralPartialEq for
MissingLifetime {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MissingLifetime {
#[inline]
fn eq(&self, other: &Self) -> 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::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 id_for_lint span kind count", &self.id,
&self.id_for_lint, &self.span, &self.kind, &&self.count)
}
}Debug)]
123pub(super) struct MissingLifetime {
124 pub id: NodeId,
126 pub id_for_lint: NodeId,
133 pub span: Span,
135 pub kind: MissingLifetimeKind,
137 pub count: usize,
139}
140
141#[derive(#[automatically_derived]impl ::core::fmt::Debug for ElisionFnParameter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"ElisionFnParameter index ident lifetime_count span", &self.index,
&self.ident, &self.lifetime_count, &&self.span)
}
}Debug)]
144pub(super) struct ElisionFnParameter {
145 pub index: usize,
147 pub ident: Option<Ident>,
149 pub lifetime_count: usize,
151 pub span: Span,
153}
154
155#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for LifetimeElisionCandidate {
}
#[automatically_derived]impl ::core::clone::Clone for LifetimeElisionCandidate
{
#[inline]
fn clone(&self) -> Self {
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 {
Self::Ignore => ::core::fmt::Formatter::write_str(f, "Ignore"),
Self::Missing(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Missing", &__self_0),
}
}
}Debug)]
158pub(super) enum LifetimeElisionCandidate {
159 Ignore,
161 Missing(MissingLifetime),
162}
163
164#[derive(#[automatically_derived]impl ::core::fmt::Debug for BaseError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
"BaseError msg fallback_label span span_label could_be_expr suggestion module notes";
let values: &[&dyn ::core::fmt::Debug] =
&[&self.msg, &self.fallback_label, &self.span, &self.span_label,
&self.could_be_expr, &self.suggestion, &self.module,
&&self.notes];
::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
}
}Debug)]
166struct BaseError {
167 msg: String,
168 fallback_label: String,
169 span: Span,
170 span_label: Option<(Span, &'static str)>,
171 could_be_expr: bool,
172 suggestion: Option<(Span, &'static str, String)>,
173 module: Option<DefId>,
174 notes: Vec<String>,
175}
176
177#[derive(#[automatically_derived]impl ::core::fmt::Debug for TypoCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Typo(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Typo",
&__self_0),
Self::Shadowed(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Shadowed", __self_0, &__self_1),
Self::None => ::core::fmt::Formatter::write_str(f, "None"),
}
}
}Debug)]
178enum TypoCandidate {
179 Typo(TypoSuggestion),
180 Shadowed(Res, Option<Span>),
181 None,
182}
183
184impl TypoCandidate {
185 fn to_opt_suggestion(self) -> Option<TypoSuggestion> {
186 match self {
187 TypoCandidate::Typo(sugg) => Some(sugg),
188 TypoCandidate::Shadowed(_, _) | TypoCandidate::None => None,
189 }
190 }
191}
192
193impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
194 fn trait_assoc_type_def_id_by_name(
195 &mut self,
196 trait_def_id: DefId,
197 assoc_name: Symbol,
198 ) -> Option<DefId> {
199 let module = self.r.get_module(trait_def_id)?;
200 self.r.resolutions(module).iter().find_map(|(key, resolution)| {
201 if key.ident.name != assoc_name {
202 return None;
203 }
204 let resolution = resolution.borrow(self.r);
205 let binding = resolution.best_decl()?;
206 match binding.res() {
207 Res::Def(DefKind::AssocTy, def_id) => Some(def_id),
208 _ => None,
209 }
210 })
211 }
212
213 fn suggest_assoc_type_from_bounds(
215 &mut self,
216 err: &mut Diag<'_>,
217 source: PathSource<'_, 'ast, 'ra>,
218 path: &[Segment],
219 ident_span: Span,
220 ) -> bool {
221 if source.namespace() != TypeNS {
223 return false;
224 }
225 let [segment] = path else { return false };
226 if segment.has_generic_args {
227 return false;
228 }
229 if !ident_span.can_be_used_for_suggestions() {
230 return false;
231 }
232 let assoc_name = segment.ident.name;
233 if assoc_name == kw::Underscore {
234 return false;
235 }
236
237 let mut matching_bounds: FxIndexMap<
241 Symbol,
242 FxIndexMap<DefId, (DefId, FxIndexSet<String>)>,
243 > = FxIndexMap::default();
244
245 let mut record_bound = |this: &mut Self,
246 ty_param: Symbol,
247 poly_trait_ref: &ast::PolyTraitRef| {
248 if !poly_trait_ref.bound_generic_params.is_empty() {
250 return;
251 }
252 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
253 return;
254 }
255 let Some(trait_seg) = poly_trait_ref.trait_ref.path.segments.last() else {
256 return;
257 };
258 let Some(partial_res) = this.r.partial_res_map.get(&trait_seg.id) else {
259 return;
260 };
261 let Some(trait_def_id) = partial_res.full_res().and_then(|res| res.opt_def_id()) else {
262 return;
263 };
264 let Some(assoc_type_def_id) =
265 this.trait_assoc_type_def_id_by_name(trait_def_id, assoc_name)
266 else {
267 return;
268 };
269
270 let trait_path =
274 path_to_string_without_assoc_item_bindings(&poly_trait_ref.trait_ref.path);
275 let trait_bounds = matching_bounds.entry(ty_param).or_default();
276 let trait_bounds = trait_bounds
277 .entry(trait_def_id)
278 .or_insert_with(|| (assoc_type_def_id, FxIndexSet::default()));
279 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);
280 trait_bounds.1.insert(trait_path);
281 };
282
283 let mut record_from_generics = |this: &mut Self, generics: &ast::Generics| {
284 for param in &generics.params {
285 let ast::GenericParamKind::Type { .. } = param.kind else { continue };
286 for bound in ¶m.bounds {
287 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
288 record_bound(this, param.ident.name, poly_trait_ref);
289 }
290 }
291
292 for predicate in &generics.where_clause.predicates {
293 let ast::WherePredicateKind::BoundPredicate(where_bound) = &predicate.kind else {
294 continue;
295 };
296
297 let ast::TyKind::Path(None, bounded_path) = &where_bound.bounded_ty.kind else {
298 continue;
299 };
300 let [ast::PathSegment { ident, args: None, .. }] = &bounded_path.segments[..]
301 else {
302 continue;
303 };
304
305 let Some(partial_res) = this.r.partial_res_map.get(&where_bound.bounded_ty.id)
307 else {
308 continue;
309 };
310 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, _))) {
311 continue;
312 }
313
314 for bound in &where_bound.bounds {
315 let ast::GenericBound::Trait(poly_trait_ref) = bound else { continue };
316 record_bound(this, ident.name, poly_trait_ref);
317 }
318 }
319 };
320
321 if let Some(item) = self.diag_metadata.current_item
322 && let Some(generics) = item.kind.generics()
323 {
324 record_from_generics(self, generics);
325 }
326
327 if let Some(item) = self.diag_metadata.current_item
328 && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Impl(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Impl(..))
329 && let Some(assoc) = self.diag_metadata.current_impl_item
330 {
331 let generics = match &assoc.kind {
332 AssocItemKind::Const(ast::ConstItem { generics, .. })
333 | AssocItemKind::Fn(ast::Fn { generics, .. })
334 | AssocItemKind::Type(ast::TyAlias { generics, .. }) => Some(generics),
335 AssocItemKind::Delegation(..)
336 | AssocItemKind::MacCall(..)
337 | AssocItemKind::DelegationMac(..) => None,
338 };
339 if let Some(generics) = generics {
340 record_from_generics(self, generics);
341 }
342 }
343
344 let mut suggestions: FxIndexSet<String> = FxIndexSet::default();
345 for (ty_param, traits) in matching_bounds {
346 let ty_param = ty_param.to_ident_string();
347 let trait_paths_len: usize = traits.values().map(|(_, paths)| paths.len()).sum();
348 if traits.len() == 1 && trait_paths_len == 1 {
349 let assoc_type_def_id = traits.values().next().unwrap().0;
350 let assoc_segment = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", assoc_name,
self.r.item_required_generic_args_suggestion(assoc_type_def_id)))
})format!(
351 "{}{}",
352 assoc_name,
353 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
354 );
355 suggestions.insert(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}", ty_param,
assoc_segment))
})format!("{ty_param}::{assoc_segment}"));
356 } else {
357 for (assoc_type_def_id, trait_paths) in traits.into_values() {
358 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!(
359 "{}{}",
360 assoc_name,
361 self.r.item_required_generic_args_suggestion(assoc_type_def_id)
362 );
363 for trait_path in trait_paths {
364 suggestions
365 .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}"));
366 }
367 }
368 }
369 }
370
371 if suggestions.is_empty() {
372 return false;
373 }
374
375 let mut suggestions: Vec<String> = suggestions.into_iter().collect();
376 suggestions.sort();
377
378 err.span_suggestions_with_style(
379 ident_span,
380 "you might have meant to use an associated type of the same name",
381 suggestions,
382 Applicability::MaybeIncorrect,
383 SuggestionStyle::ShowAlways,
384 );
385
386 true
387 }
388
389 fn make_base_error(
390 &mut self,
391 path: &[Segment],
392 span: Span,
393 source: PathSource<'_, 'ast, 'ra>,
394 res: Option<Res>,
395 could_be_expr: bool,
396 ) -> BaseError {
397 let mut expected = source.descr_expected();
399 let path_str = Segment::names_to_string(path);
400
401 if let Some(res) = res {
402 BaseError {
403 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),
404 fallback_label: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"),
405 span,
406 span_label: match res {
407 Res::Def(DefKind::TyParam, def_id) => {
408 Some((self.r.def_span(def_id), "found this type parameter"))
409 }
410 _ => None,
411 },
412 could_be_expr,
413 suggestion: None,
414 module: None,
415 notes: Vec::new(),
416 }
417 } else {
418 let mut span_label = None;
419 let item_ident = path.last().unwrap().ident;
420 let item_span = item_ident.span;
421 let (tick, mod_prefix, mod_str, module, suggestion) = if path.len() == 1 {
422 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:422",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(422u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.diag_metadata.current_impl_items")
}> =
::tracing::__macro_support::FieldName::new("self.diag_metadata.current_impl_items");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_impl_items)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_impl_items);
423 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:423",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(423u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.diag_metadata.current_function")
}> =
::tracing::__macro_support::FieldName::new("self.diag_metadata.current_function");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.diag_metadata.current_function)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?self.diag_metadata.current_function);
424 let suggestion = if self.current_trait_ref.is_none()
425 && let Some((fn_kind, _)) = self.diag_metadata.current_function
426 && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
427 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = fn_kind
428 && let Some(items) = self.diag_metadata.current_impl_items
429 && let Some(item) = items.iter().find(|i| {
430 i.kind.ident().is_some_and(|ident| {
431 ident.name == item_ident.name && !sig.span.contains(item_span)
433 })
434 }) {
435 let sp = item_span.shrink_to_lo();
436
437 let field = match source {
440 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. })) => {
441 expr.fields.iter().find(|f| f.ident == item_ident)
442 }
443 _ => None,
444 };
445 let pre = if let Some(field) = field
446 && field.is_shorthand
447 {
448 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", item_ident))
})format!("{item_ident}: ")
449 } else {
450 String::new()
451 };
452 let is_call = match field {
455 Some(ast::ExprField { expr, .. }) => {
456 #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Call(..) => true,
_ => false,
}matches!(expr.kind, ExprKind::Call(..))
457 }
458 _ => #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}matches!(
459 source,
460 PathSource::Expr(Some(Expr { kind: ExprKind::Call(..), .. })),
461 ),
462 };
463
464 match &item.kind {
465 AssocItemKind::Fn(fn_)
466 if (!sig.decl.has_self() || !is_call) && fn_.sig.decl.has_self() =>
467 {
468 span_label = Some((
472 fn_.ident.span,
473 "a method by that name is available on `Self` here",
474 ));
475 None
476 }
477 AssocItemKind::Fn(fn_) if !fn_.sig.decl.has_self() && !is_call => {
478 span_label = Some((
479 fn_.ident.span,
480 "an associated function by that name is available on `Self` here",
481 ));
482 None
483 }
484 AssocItemKind::Fn(fn_) if fn_.sig.decl.has_self() => {
485 Some((sp, "consider using the method on `Self`", ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self.")))
486 }
487 AssocItemKind::Fn(_) => Some((
488 sp,
489 "consider using the associated function on `Self`",
490 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
491 )),
492 AssocItemKind::Const(..) => Some((
493 sp,
494 "consider using the associated constant on `Self`",
495 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}Self::", pre))
})format!("{pre}Self::"),
496 )),
497 _ => None,
498 }
499 } else {
500 None
501 };
502 ("", String::new(), "this scope".to_string(), None, suggestion)
503 } else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
504 if self.r.tcx.sess.edition() > Edition::Edition2015 {
505 expected = "crate";
508 ("", String::new(), "the list of imported crates".to_string(), None, None)
509 } else {
510 (
511 "",
512 String::new(),
513 "the crate root".to_string(),
514 Some(CRATE_DEF_ID.to_def_id()),
515 None,
516 )
517 }
518 } else if path.len() == 2 && path[0].ident.name == kw::Crate {
519 (
520 "",
521 String::new(),
522 "the crate root".to_string(),
523 Some(CRATE_DEF_ID.to_def_id()),
524 None,
525 )
526 } else {
527 let mod_path = &path[..path.len() - 1];
528 let mod_res = self.resolve_path(mod_path, Some(TypeNS), None, source);
529 let mod_prefix = match mod_res {
530 PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
531 _ => None,
532 };
533
534 let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id);
535
536 let mod_prefix =
537 mod_prefix.map_or_else(String::new, |res| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", res.descr()))
})format!("{} ", res.descr()));
538 ("`", mod_prefix, Segment::names_to_string(mod_path), module_did, None)
539 };
540
541 let suggestion =
542 if ["true", "false"].contains(&item_ident.to_string().to_lowercase().as_str()) {
543 let item_typo = item_ident.to_string().to_lowercase();
545 Some((item_span, "you may want to use a bool value instead", item_typo))
546 } else if item_ident.as_str() == "printf" {
549 Some((
550 item_span,
551 "you may have meant to use the `print` macro",
552 "print!".to_owned(),
553 ))
554 } else {
555 suggestion
556 };
557 let mut msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot find {0} `{1}` in {2}{3}{4}{3}",
expected, item_ident, mod_prefix, tick, mod_str))
})format!(
558 "cannot find {expected} `{item_ident}` in {mod_prefix}{tick}{mod_str}{tick}"
559 );
560 let mut fallback_label = if path_str == "async" && expected.starts_with("struct") {
561 "`async` blocks are only allowed in Rust 2018 or later".to_string()
562 } else {
563 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not found in {0}{1}{0}", tick,
mod_str))
})format!("not found in {tick}{mod_str}{tick}")
564 };
565 let mut notes = Vec::new();
566 if let Some(module_def_id) = module
567 && let Some((this, directive)) = self.r.on_unknown_data(module_def_id)
568 {
569 let args =
570 FormatArgs { unresolved: item_ident.to_string(), this: this.to_string(), .. };
571 let CustomDiagnostic {
572 message,
573 label,
574 notes: custom_notes,
575 parent_label: _unreachable,
576 } = directive.eval(None, &args);
577 if let Some(message) = message {
578 notes.push(msg);
579 msg = message;
580 }
581 if let Some(label) = label {
582 fallback_label = label;
583 if let Some((_, span_label)) = span_label.take() {
584 notes.push(span_label.to_string());
585 }
586 }
587 notes.extend(custom_notes);
588 }
589
590 BaseError {
591 msg,
592 fallback_label,
593 span: item_span,
594 span_label,
595 could_be_expr,
596 suggestion,
597 module,
598 notes,
599 }
600 }
601 }
602
603 fn could_be_expr(&self, res: Res, span: Span) -> bool {
604 match res {
605 Res::Def(DefKind::Fn, _) => self
607 .r
608 .tcx
609 .sess
610 .source_map()
611 .span_to_snippet(span)
612 .is_ok_and(|snippet| snippet.ends_with(')')),
613 Res::Def(
614 DefKind::Ctor(..) | DefKind::AssocFn | DefKind::Const | DefKind::AssocConst,
615 _,
616 )
617 | Res::SelfCtor(_)
618 | Res::PrimTy(_)
619 | Res::Local(_) => true,
620 _ => false,
621 }
622 }
623
624 pub(crate) fn smart_resolve_partial_mod_path_errors(
632 &mut self,
633 prefix_path: &[Segment],
634 following_seg: Option<&Segment>,
635 ) -> Vec<ImportSuggestion> {
636 if let Some(segment) = prefix_path.last()
637 && let Some(following_seg) = following_seg
638 {
639 let candidates = self.r.lookup_import_candidates(
640 segment.ident,
641 Namespace::TypeNS,
642 &self.parent_scope,
643 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Mod, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Mod, _)),
644 );
645 candidates
647 .into_iter()
648 .filter(|candidate| {
649 if let Some(def_id) = candidate.did
650 && let Some(module) = self.r.get_module(def_id)
651 {
652 Some(def_id) != self.parent_scope.module.opt_def_id()
653 && self
654 .r
655 .resolutions(module)
656 .iter()
657 .any(|(key, _r)| key.ident.name == following_seg.ident.name)
658 } else {
659 false
660 }
661 })
662 .collect::<Vec<_>>()
663 } else {
664 Vec::new()
665 }
666 }
667
668 {}
#[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("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(670u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("following_seg")
}> =
::tracing::__macro_support::FieldName::new("following_seg");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("res")
}> =
::tracing::__macro_support::FieldName::new("res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("qself")
}> =
::tracing::__macro_support::FieldName::new("qself");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&following_seg)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&qself)
as &dyn ::tracing::field::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;
}
{
let cross_namespace_res =
res.filter(|res| !res.matches_ns(source.namespace()));
let could_be_expr =
res.is_some_and(|res| self.could_be_expr(res, span));
let base_error =
self.make_base_error(path, span, source,
if cross_namespace_res.is_some() { None } else { res },
could_be_expr);
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 self.diag_metadata.currently_processing_generic_args &&
let PathSource::Type = source && let [segment] = path &&
!segment.has_generic_args {
source = PathSource::TypeParam;
}
if let Some(res) = cross_namespace_res {
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} named `{2}` exists in another namespace",
res.article(), res.descr(), Segment::names_to_string(path)))
}));
}
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);
self.detect_resolution_error_in_derive(&mut err, base_error.span);
if let Some((span, label)) = base_error.span_label {
err.span_label(span, label);
}
for note in &base_error.notes { err.note(note.clone()); }
if let Some((span, message, replacement)) = &base_error.suggestion
{
let ident = path.last().unwrap().ident;
let expression =
if span.is_empty() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", replacement,
ident))
})
} else { replacement.clone() };
if !self.suggest_named_format_argument(&mut err, source,
ident, &expression, Applicability::MaybeIncorrect) {
err.span_suggestion_verbose(*span, *message, replacement,
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_verbose(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")]
671 pub(crate) fn smart_resolve_report_errors(
672 &mut self,
673 path: &[Segment],
674 following_seg: Option<&Segment>,
675 span: Span,
676 mut source: PathSource<'_, 'ast, 'ra>,
677 res: Option<Res>,
678 qself: Option<&QSelf>,
679 ) -> (Diag<'tcx>, Vec<ImportSuggestion>) {
680 let cross_namespace_res = res.filter(|res| !res.matches_ns(source.namespace()));
681 let could_be_expr = res.is_some_and(|res| self.could_be_expr(res, span));
682 let base_error = self.make_base_error(
683 path,
684 span,
685 source,
686 if cross_namespace_res.is_some() { None } else { res },
687 could_be_expr,
688 );
689
690 let code = source.error_code(res.is_some());
691 let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
692 err.code(code);
693
694 if self.diag_metadata.currently_processing_generic_args
695 && let PathSource::Type = source
696 && let [segment] = path
697 && !segment.has_generic_args
698 {
699 source = PathSource::TypeParam;
700 }
701
702 if let Some(res) = cross_namespace_res {
703 err.note(format!(
704 "{} {} named `{}` exists in another namespace",
705 res.article(),
706 res.descr(),
707 Segment::names_to_string(path),
708 ));
709 }
710
711 if let Some(within_macro_span) =
714 base_error.span.within_macro(span, self.r.tcx.sess.source_map())
715 {
716 err.span_label(within_macro_span, "due to this macro variable");
717 }
718
719 self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
720 self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
721 self.suggest_range_struct_destructuring(&mut err, path, source);
722 self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);
723 self.detect_resolution_error_in_derive(&mut err, base_error.span);
724
725 if let Some((span, label)) = base_error.span_label {
726 err.span_label(span, label);
727 }
728 for note in &base_error.notes {
729 err.note(note.clone());
730 }
731
732 if let Some((span, message, replacement)) = &base_error.suggestion {
733 let ident = path.last().unwrap().ident;
734 let expression =
737 if span.is_empty() { format!("{replacement}{ident}") } else { replacement.clone() };
738 if !self.suggest_named_format_argument(
739 &mut err,
740 source,
741 ident,
742 &expression,
743 Applicability::MaybeIncorrect,
744 ) {
745 err.span_suggestion_verbose(
746 *span,
747 *message,
748 replacement,
749 Applicability::MaybeIncorrect,
750 );
751 }
752 }
753
754 self.suggest_changing_type_to_const_param(&mut err, res, source, path, following_seg, span);
755 self.explain_functions_in_pattern(&mut err, res, source);
756
757 if self.suggest_pattern_match_with_let(&mut err, source, span) {
758 err.span_label(base_error.span, base_error.fallback_label);
760 return (err, Vec::new());
761 }
762
763 self.suggest_self_or_self_ref(&mut err, path, span);
764 self.detect_assoc_type_constraint_meant_as_path(&mut err, &base_error);
765 self.detect_rtn_with_fully_qualified_path(
766 &mut err,
767 path,
768 following_seg,
769 span,
770 source,
771 res,
772 qself,
773 );
774 if self.suggest_self_ty(&mut err, source, path, span)
775 || self.suggest_self_value(&mut err, source, path, span)
776 {
777 return (err, Vec::new());
778 }
779
780 if let Some((did, item)) = self.lookup_doc_alias_name(path, source.namespace()) {
781 let item_name = item.name;
782 let suggestion_name = self.r.tcx.item_name(did);
783 err.span_suggestion_verbose(
784 item.span,
785 format!(
786 "`{suggestion_name}` has a name defined in the doc alias attribute as \
787 `{item_name}`",
788 ),
789 suggestion_name,
790 Applicability::MaybeIncorrect,
791 );
792
793 return (err, Vec::new());
794 };
795
796 let (found, suggested_candidates, mut candidates) = self.try_lookup_name_relaxed(
797 &mut err,
798 source,
799 path,
800 following_seg,
801 span,
802 res,
803 &base_error,
804 );
805 if found {
806 return (err, candidates);
807 }
808
809 if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
810 candidates.clear();
812 }
813
814 let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
815 fallback |= self.suggest_typo(
816 &mut err,
817 source,
818 path,
819 following_seg,
820 span,
821 &base_error,
822 suggested_candidates,
823 );
824
825 if fallback {
826 err.span_label(base_error.span, base_error.fallback_label);
828 }
829 self.err_code_special_cases(&mut err, source, path, span);
830
831 let module = base_error.module.unwrap_or_else(|| CRATE_DEF_ID.to_def_id());
832 self.r.find_cfg_stripped(&mut err, &path.last().unwrap().ident.name, module);
833
834 (err, candidates)
835 }
836
837 fn suggest_named_format_argument(
839 &self,
840 err: &mut Diag<'_>,
841 source: PathSource<'_, '_, '_>,
842 ident: Ident,
843 expression: &str,
844 applicability: Applicability,
845 ) -> bool {
846 let PathSource::Expr(Some(Expr {
847 kind: ExprKind::FormatArgs(args),
848 span: format_span,
849 ..
850 })) = source
851 else {
852 return false;
853 };
854 let argument = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} = {1}", ident, expression))
})format!("{ident} = {expression}");
855 let insertion = args
856 .arguments
857 .explicit_args()
858 .last()
859 .map_or(args.span, |arg| arg.original_span)
860 .shrink_to_hi();
861 let source_macro = format_span
863 .source_callee()
864 .and_then(|expn| expn.macro_def_id)
865 .filter(|def_id| !def_id.is_local())
867 .and_then(|def_id| self.r.tcx.get_diagnostic_name(def_id));
868 if #[allow(non_exhaustive_omitted_patterns)] match source_macro {
Some(sym::format_macro | sym::format_args_macro | sym::print_macro |
sym::println_macro | sym::eprint_macro | sym::eprintln_macro |
sym::write_macro | sym::writeln_macro | sym::assert_macro |
sym::assert_eq_macro | sym::assert_ne_macro | sym::debug_assert_macro
| sym::debug_assert_eq_macro | sym::debug_assert_ne_macro |
sym::core_panic_macro | sym::std_panic_macro | sym::unreachable_macro
| sym::todo_macro | sym::unimplemented_macro) => true,
_ => false,
}matches!(
869 source_macro,
870 Some(
871 sym::format_macro
872 | sym::format_args_macro
873 | sym::print_macro
874 | sym::println_macro
875 | sym::eprint_macro
876 | sym::eprintln_macro
877 | sym::write_macro
878 | sym::writeln_macro
879 | sym::assert_macro
880 | sym::assert_eq_macro
881 | sym::assert_ne_macro
882 | sym::debug_assert_macro
883 | sym::debug_assert_eq_macro
884 | sym::debug_assert_ne_macro
885 | sym::core_panic_macro
886 | sym::std_panic_macro
887 | sym::unreachable_macro
888 | sym::todo_macro
889 | sym::unimplemented_macro
890 )
891 ) && !insertion.from_expansion()
892 && !args.span.from_expansion()
893 {
894 err.span_suggestion_verbose(
895 insertion,
896 "you might have meant to add a named formatting argument",
897 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", argument))
})format!(", {argument}"),
898 applicability,
899 );
900 } else {
901 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to add a named formatting argument: `{0}`",
argument))
})format!(
902 "you might have meant to add a named formatting argument: `{argument}`"
903 ));
904 }
905 true
906 }
907
908 fn detect_rtn_with_fully_qualified_path(
909 &self,
910 err: &mut Diag<'_>,
911 path: &[Segment],
912 following_seg: Option<&Segment>,
913 span: Span,
914 source: PathSource<'_, '_, '_>,
915 res: Option<Res>,
916 qself: Option<&QSelf>,
917 ) {
918 if let Some(Res::Def(DefKind::AssocFn, _)) = res
919 && let PathSource::TraitItem(TypeNS, _) = source
920 && let None = following_seg
921 && let Some(qself) = qself
922 && let TyKind::Path(None, ty_path) = &qself.ty.kind
923 && ty_path.segments.len() == 1
924 && self.diag_metadata.current_where_predicate.is_some()
925 {
926 err.span_suggestion_verbose(
927 span,
928 "you might have meant to use the return type notation syntax",
929 ::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),
930 Applicability::MaybeIncorrect,
931 );
932 }
933 }
934
935 fn detect_assoc_type_constraint_meant_as_path(
936 &self,
937 err: &mut Diag<'_>,
938 base_error: &BaseError,
939 ) {
940 let Some(ty) = self.diag_metadata.current_type_path else {
941 return;
942 };
943 let TyKind::Path(_, path) = &ty.kind else {
944 return;
945 };
946 for segment in &path.segments {
947 let Some(params) = &segment.args else {
948 continue;
949 };
950 let ast::GenericArgs::AngleBracketed(params) = params.deref() else {
951 continue;
952 };
953 for param in ¶ms.args {
954 let ast::AngleBracketedArg::Constraint(constraint) = param else {
955 continue;
956 };
957 let ast::AssocItemConstraintKind::Bound { bounds } = &constraint.kind else {
958 continue;
959 };
960 for bound in bounds {
961 let ast::GenericBound::Trait(trait_ref) = bound else {
962 continue;
963 };
964 if trait_ref.modifiers == ast::TraitBoundModifiers::NONE
965 && base_error.span == trait_ref.span
966 {
967 err.span_suggestion_verbose(
968 constraint.ident.span.between(trait_ref.span),
969 "you might have meant to write a path instead of an associated type bound",
970 "::",
971 Applicability::MachineApplicable,
972 );
973 }
974 }
975 }
976 }
977 }
978
979 fn suggest_self_or_self_ref(&mut self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
980 if self.self_type_is_available().is_none() {
981 return;
982 }
983 let Some(path_last_segment) = path.last() else { return };
984 let item_str = path_last_segment.ident;
985 if ["this", "my"].contains(&item_str.as_str()) {
987 err.span_suggestion_short(
988 span,
989 "you might have meant to use `self` here instead",
990 "self",
991 Applicability::MaybeIncorrect,
992 );
993 if !self.self_value_is_available(path[0].ident.span) {
994 if let Some((FnKind::Fn(_, _, ast::Fn { sig, .. }), fn_span)) =
995 &self.diag_metadata.current_function
996 {
997 let (span, sugg) = if let Some(param) = sig.decl.inputs.get(0) {
998 (param.span.shrink_to_lo(), "&self, ")
999 } else {
1000 (
1001 self.r
1002 .tcx
1003 .sess
1004 .source_map()
1005 .span_through_char(*fn_span, '(')
1006 .shrink_to_hi(),
1007 "&self",
1008 )
1009 };
1010 err.span_suggestion_verbose(
1011 span,
1012 "if you meant to use `self`, you are also missing a `self` receiver \
1013 argument",
1014 sugg,
1015 Applicability::MaybeIncorrect,
1016 );
1017 }
1018 }
1019 }
1020 }
1021
1022 fn try_lookup_name_relaxed(
1023 &mut self,
1024 err: &mut Diag<'_>,
1025 source: PathSource<'_, '_, '_>,
1026 path: &[Segment],
1027 following_seg: Option<&Segment>,
1028 span: Span,
1029 res: Option<Res>,
1030 base_error: &BaseError,
1031 ) -> (bool, FxHashSet<String>, Vec<ImportSuggestion>) {
1032 let span = match following_seg {
1033 Some(_) if path[0].ident.span.ctxt() == path[path.len() - 1].ident.span.ctxt() => {
1034 path[0].ident.span.to(path[path.len() - 1].ident.span)
1037 }
1038 _ => span,
1039 };
1040 let mut suggested_candidates = FxHashSet::default();
1041 let ident = path.last().unwrap().ident;
1043 let is_expected = &|res| source.is_expected(res);
1044 let ns = source.namespace();
1045 let is_enum_variant = &|res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Variant, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Variant, _));
1046 let path_str = Segment::names_to_string(path);
1047 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1048 let mut candidates = self
1049 .r
1050 .lookup_import_candidates(ident, ns, &self.parent_scope, is_expected)
1051 .into_iter()
1052 .filter(|ImportSuggestion { did, .. }| {
1053 match (did, res.and_then(|res| res.opt_def_id())) {
1054 (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did,
1055 _ => true,
1056 }
1057 })
1058 .collect::<Vec<_>>();
1059 let intrinsic_candidates: Vec<_> = candidates
1062 .extract_if(.., |sugg| {
1063 let path = path_names_to_string(&sugg.path);
1064 path.starts_with("core::intrinsics::") || path.starts_with("std::intrinsics::")
1065 })
1066 .collect();
1067 if candidates.is_empty() {
1068 candidates = intrinsic_candidates;
1070 }
1071 let crate_def_id = CRATE_DEF_ID.to_def_id();
1072 if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
1073 let mut enum_candidates: Vec<_> = self
1074 .r
1075 .lookup_import_candidates(ident, ns, &self.parent_scope, is_enum_variant)
1076 .into_iter()
1077 .map(|suggestion| import_candidate_to_enum_paths(&suggestion))
1078 .filter(|(_, enum_ty_path)| !enum_ty_path.starts_with("std::prelude::"))
1079 .collect();
1080 if !enum_candidates.is_empty() {
1081 enum_candidates.sort();
1082
1083 let preamble = if res.is_none() {
1086 let others = match enum_candidates.len() {
1087 1 => String::new(),
1088 2 => " and 1 other".to_owned(),
1089 n => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} others", n))
})format!(" and {n} others"),
1090 };
1091 ::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)
1092 } else {
1093 String::new()
1094 };
1095 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");
1096
1097 suggested_candidates.extend(
1098 enum_candidates
1099 .iter()
1100 .map(|(_variant_path, enum_ty_path)| enum_ty_path.clone()),
1101 );
1102 err.span_suggestions(
1103 span,
1104 msg,
1105 enum_candidates.into_iter().map(|(_variant_path, enum_ty_path)| enum_ty_path),
1106 Applicability::MachineApplicable,
1107 );
1108 }
1109 }
1110
1111 let typo_sugg = self
1113 .lookup_typo_candidate(path, following_seg, source.namespace(), is_expected)
1114 .to_opt_suggestion()
1115 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1116 if let [segment] = path
1117 && !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Delegation => true,
_ => false,
}matches!(source, PathSource::Delegation)
1118 && let Some(def_id) = self.self_type_is_available()
1119 {
1120 if let Some((candidate, def_span)) =
1121 self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
1122 {
1123 let self_is_available = self.self_value_is_available(segment.ident.span);
1124 let pre = match source {
1127 PathSource::Expr(Some(Expr { kind: ExprKind::Struct(expr), .. }))
1128 if expr
1129 .fields
1130 .iter()
1131 .any(|f| f.ident == segment.ident && f.is_shorthand) =>
1132 {
1133 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", path_str))
})format!("{path_str}: ")
1134 }
1135 _ => String::new(),
1136 };
1137 match candidate {
1138 AssocSuggestion::Field => {
1139 if self_is_available {
1140 if !self.suggest_named_format_argument(
1141 err,
1142 source,
1143 segment.ident,
1144 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}", segment.ident))
})format!("self.{}", segment.ident),
1145 Applicability::MaybeIncorrect,
1146 ) {
1147 err.span_suggestion_verbose(
1148 span.shrink_to_lo(),
1149 "you might have meant to use the available field",
1150 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}self.", pre))
})format!("{pre}self."),
1151 Applicability::MaybeIncorrect,
1152 );
1153 }
1154 } else {
1155 err.span_context(self.r.def_span(def_id).shrink_to_lo());
1157 if let Some(item) = self.diag_metadata.current_impl_item {
1158 err.span_context(item.span.shrink_to_lo());
1160 }
1161 let mut span: MultiSpan = def_span.into();
1162 if let Some(ty) = self.diag_metadata.current_self_type
1163 && let Some(res) = self.r.partial_res_map.get(&ty.id)
1164 && let Some(res) = res.full_res()
1165 && let Res::Def(
1166 DefKind::Struct | DefKind::Union | DefKind::Enum,
1167 def_id,
1168 ) = res
1169 {
1170 span.push_span_context(self.r.def_span(def_id).shrink_to_lo());
1171 }
1172
1173 err.span_note(span, "a field by that name exists in `Self`");
1174 }
1175 }
1176 AssocSuggestion::MethodWithSelf { from, .. }
1177 | AssocSuggestion::AssocFn { from, .. }
1178 | AssocSuggestion::AssocType { from, .. }
1179 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Expr(Some(Expr { kind: ExprKind::FormatArgs(_), .. })) =>
true,
_ => false,
}matches!(
1180 source,
1181 PathSource::Expr(Some(Expr { kind: ExprKind::FormatArgs(_), .. }))
1182 ) =>
1183 {
1184 let kind = match candidate {
1185 AssocSuggestion::MethodWithSelf { .. } => "a method",
1186 AssocSuggestion::AssocFn { .. } => "an associated function",
1187 AssocSuggestion::AssocType { .. } => "an associated type",
1188 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1189 };
1190 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} by that name is available on `Self`",
kind))
})format!("{kind} by that name is available on `Self`");
1191 err.span_context(self.r.def_span(def_id).shrink_to_lo());
1193 if let Some(item) = self.diag_metadata.current_impl_item {
1194 err.span_context(item.span.shrink_to_lo());
1196 }
1197 if let AssocFrom::Trait = from
1198 && let Some((module, _)) = &self.current_trait_ref
1199 {
1200 let mut span: MultiSpan = def_span.into();
1203 span.push_span_context(module.span.shrink_to_lo());
1204 err.span_note(span, msg);
1205 } else {
1206 err.span_label(def_span, msg);
1209 }
1210 }
1211 AssocSuggestion::MethodWithSelf { called, .. } if self_is_available => {
1212 let msg = if called {
1213 "you might have meant to call the method"
1214 } else {
1215 "you might have meant to refer to the method"
1216 };
1217 err.span_suggestion_verbose(
1218 span.shrink_to_lo(),
1219 msg,
1220 "self.",
1221 Applicability::MachineApplicable,
1222 );
1223 }
1224 AssocSuggestion::MethodWithSelf { .. }
1225 | AssocSuggestion::AssocFn { .. }
1226 | AssocSuggestion::AssocConst { .. }
1227 | AssocSuggestion::AssocType { .. } => {
1228 if !#[allow(non_exhaustive_omitted_patterns)] match candidate {
AssocSuggestion::AssocConst { .. } => true,
_ => false,
}matches!(candidate, AssocSuggestion::AssocConst { .. })
1229 || !self.suggest_named_format_argument(
1230 err,
1231 source,
1232 segment.ident,
1233 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Self::{0}", segment.ident))
})format!("Self::{}", segment.ident),
1234 Applicability::MaybeIncorrect,
1235 )
1236 {
1237 err.span_suggestion_verbose(
1238 span.shrink_to_lo(),
1239 ::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()),
1240 "Self::",
1241 Applicability::MachineApplicable,
1242 );
1243 }
1244 }
1245 }
1246 self.r.add_typo_suggestion(err, typo_sugg, ident_span, None);
1247 return (true, suggested_candidates, candidates);
1248 }
1249
1250 if let Some((call_span, args_span)) = self.call_has_self_arg(source) {
1252 let mut args_snippet = String::new();
1253 if let Some(args_span) = args_span
1254 && let Ok(snippet) = self.r.tcx.sess.source_map().span_to_snippet(args_span)
1255 {
1256 args_snippet = snippet;
1257 }
1258
1259 if let Some(Res::Def(DefKind::Struct, def_id)) = res {
1260 if let Some(ctor) = self.r.struct_ctor(def_id)
1261 && ctor.has_private_fields(self.parent_scope.module, self.r)
1262 {
1263 if #[allow(non_exhaustive_omitted_patterns)] match ctor.res {
Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _) => true,
_ => false,
}matches!(
1264 ctor.res,
1265 Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
1266 ) {
1267 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
1268 }
1269 err.note("constructor is not visible here due to private fields");
1270 }
1271 } else {
1272 err.span_suggestion_verbose(
1273 call_span,
1274 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try calling `{0}` as a method",
ident))
})format!("try calling `{ident}` as a method"),
1275 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("self.{0}({1})", path_str,
args_snippet))
})format!("self.{path_str}({args_snippet})"),
1276 Applicability::MachineApplicable,
1277 );
1278 }
1279
1280 return (true, suggested_candidates, candidates);
1281 }
1282 }
1283
1284 if let Some(res) = res {
1286 if self.smart_resolve_context_dependent_help(
1287 err,
1288 span,
1289 source,
1290 path,
1291 res,
1292 &path_str,
1293 &base_error.fallback_label,
1294 ) {
1295 if let Some(sugg) = &typo_sugg
1296 && let Res::Local(_) = sugg.res
1297 {
1298 if let PathSource::Expr(Some(expr)) = source
1299 && let ExprKind::Call(..) = expr.kind
1300 {
1301 } else if path.len() == 1 {
1305 self.r.add_typo_suggestion(err, typo_sugg, ident_span, None);
1310 }
1311 } else {
1312 self.r.add_typo_suggestion(err, typo_sugg, ident_span, None);
1313 }
1314 return (true, suggested_candidates, candidates);
1315 }
1316 }
1317
1318 if let Some(rib) = &self.last_block_rib {
1320 for (ident, &res) in &rib.bindings {
1321 if let Res::Local(_) = res
1322 && path.len() == 1
1323 && ident.span.ctxt() == path[0].ident.span.ctxt()
1324 && ident.name == path[0].ident.name
1325 {
1326 err.span_help(
1327 ident.span,
1328 ::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"),
1329 );
1330 return (true, suggested_candidates, candidates);
1331 }
1332 }
1333 }
1334
1335 if candidates.is_empty() {
1336 candidates = self.smart_resolve_partial_mod_path_errors(path, following_seg);
1337 }
1338
1339 (false, suggested_candidates, candidates)
1340 }
1341
1342 fn lookup_doc_alias_name(&mut self, path: &[Segment], ns: Namespace) -> Option<(DefId, Ident)> {
1343 let find_doc_alias_name = |r: &mut Resolver<'ra, '_>, m: Module<'ra>, item_name: Symbol| {
1344 for resolution in r.resolutions(m).values() {
1345 let Some(did) =
1346 resolution.borrow(r).best_decl().and_then(|binding| binding.res().opt_def_id())
1347 else {
1348 continue;
1349 };
1350 if did.is_local() {
1351 continue;
1355 }
1356 if let Some(d) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &r.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Doc(d)) => {
break 'done Some(d);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(r.tcx, did, Doc(d) => d)
1357 && d.aliases.contains_key(&item_name)
1358 {
1359 return Some(did);
1360 }
1361 }
1362 None
1363 };
1364
1365 if path.len() == 1 {
1366 for rib in self.ribs[ns].iter().rev() {
1367 let item = path[0].ident;
1368 if let RibKind::Module(module) | RibKind::Block(Some(module)) = rib.kind
1369 && let Some(did) = find_doc_alias_name(self.r, module.to_module(), item.name)
1370 {
1371 return Some((did, item));
1372 }
1373 }
1374 } else {
1375 for (idx, seg) in path.iter().enumerate().rev().skip(1) {
1384 let Some(id) = seg.id else {
1385 continue;
1386 };
1387 let Some(res) = self.r.partial_res_map.get(&id) else {
1388 continue;
1389 };
1390 if let Res::Def(DefKind::Mod, module) = res.expect_full_res()
1391 && let module = self.r.expect_module(module)
1392 && let item = path[idx + 1].ident
1393 && let Some(did) = find_doc_alias_name(self.r, module, item.name)
1394 {
1395 return Some((did, item));
1396 }
1397 break;
1398 }
1399 }
1400 None
1401 }
1402
1403 fn suggest_trait_and_bounds(
1404 &self,
1405 err: &mut Diag<'_>,
1406 source: PathSource<'_, '_, '_>,
1407 res: Option<Res>,
1408 span: Span,
1409 base_error: &BaseError,
1410 ) -> bool {
1411 let is_macro =
1412 base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
1413 let mut fallback = false;
1414
1415 if let (
1416 PathSource::Trait(AliasPossibility::Maybe),
1417 Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)),
1418 false,
1419 ) = (source, res, is_macro)
1420 && let Some(bounds @ [first_bound, .., last_bound]) =
1421 self.diag_metadata.current_trait_object
1422 {
1423 fallback = true;
1424 let spans: Vec<Span> = bounds
1425 .iter()
1426 .map(|bound| bound.span())
1427 .filter(|&sp| sp != base_error.span)
1428 .collect();
1429
1430 let start_span = first_bound.span();
1431 let end_span = last_bound.span();
1433 let last_bound_span = spans.last().cloned().unwrap();
1435 let mut multi_span: MultiSpan = spans.clone().into();
1436 for sp in spans {
1437 let msg = if sp == last_bound_span {
1438 ::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!(
1439 "...because of {these} bound{s}",
1440 these = pluralize!("this", bounds.len() - 1),
1441 s = pluralize!(bounds.len() - 1),
1442 )
1443 } else {
1444 String::new()
1445 };
1446 multi_span.push_span_label(sp, msg);
1447 }
1448 multi_span.push_span_label(base_error.span, "expected this type to be a trait...");
1449 err.span_help(
1450 multi_span,
1451 "`+` is used to constrain a \"trait object\" type with lifetimes or \
1452 auto-traits; structs and enums can't be bound in that way",
1453 );
1454 if bounds.iter().all(|bound| match bound {
1455 ast::GenericBound::Outlives(_) | ast::GenericBound::Use(..) => true,
1456 ast::GenericBound::Trait(tr) => tr.span == base_error.span,
1457 }) {
1458 let mut sugg = ::alloc::vec::Vec::new()vec![];
1459 if base_error.span != start_span {
1460 sugg.push((start_span.until(base_error.span), String::new()));
1461 }
1462 if base_error.span != end_span {
1463 sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
1464 }
1465
1466 err.multipart_suggestion(
1467 "if you meant to use a type and not a trait here, remove the bounds",
1468 sugg,
1469 Applicability::MaybeIncorrect,
1470 );
1471 }
1472 }
1473
1474 fallback |= self.restrict_assoc_type_in_where_clause(span, err);
1475 fallback
1476 }
1477
1478 fn suggest_typo(
1479 &mut self,
1480 err: &mut Diag<'_>,
1481 source: PathSource<'_, 'ast, 'ra>,
1482 path: &[Segment],
1483 following_seg: Option<&Segment>,
1484 span: Span,
1485 base_error: &BaseError,
1486 suggested_candidates: FxHashSet<String>,
1487 ) -> bool {
1488 let is_expected = &|res| source.is_expected(res);
1489 let ident_span = path.last().map_or(span, |ident| ident.ident.span);
1490
1491 if self.suggest_assoc_type_from_bounds(err, source, path, ident_span) {
1495 return false;
1496 }
1497
1498 let mut prefix = None;
1500 if let PathSource::Expr(Some(ast::Expr { kind: ExprKind::Struct(expr), .. })) = source
1501 && let Some(ident) = path.last().map(|seg| seg.ident)
1502 && expr.fields.iter().any(|f| f.ident == ident && f.is_shorthand)
1503 {
1504 prefix = Some(ident);
1505 }
1506
1507 let typo_sugg =
1508 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1509 let mut fallback = true;
1510 let typo_sugg = typo_sugg
1511 .to_opt_suggestion()
1512 .filter(|sugg| !suggested_candidates.contains(sugg.candidate.as_str()));
1513 self.r.add_typo_suggestion(err, typo_sugg, ident_span, prefix);
1514
1515 match self.diag_metadata.current_let_binding {
1516 Some((pat_sp, Some(ty_sp), None))
1517 if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
1518 {
1519 err.span_suggestion_verbose(
1520 pat_sp.between(ty_sp),
1521 "use `=` if you meant to assign",
1522 " = ",
1523 Applicability::MaybeIncorrect,
1524 );
1525 }
1526 _ => {}
1527 }
1528
1529 let suggestion = self.get_single_associated_item(path, &source, is_expected);
1531 self.r.add_typo_suggestion(err, suggestion, ident_span, prefix);
1532
1533 if self.let_binding_suggestion(err, ident_span) {
1534 fallback = false;
1535 }
1536
1537 fallback
1538 }
1539
1540 fn suggest_shadowed(
1541 &mut self,
1542 err: &mut Diag<'_>,
1543 source: PathSource<'_, '_, '_>,
1544 path: &[Segment],
1545 following_seg: Option<&Segment>,
1546 span: Span,
1547 ) -> bool {
1548 let is_expected = &|res| source.is_expected(res);
1549 let typo_sugg =
1550 self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
1551 let is_in_same_file = &|sp1, sp2| {
1552 let source_map = self.r.tcx.sess.source_map();
1553 let file1 = source_map.span_to_filename(sp1);
1554 let file2 = source_map.span_to_filename(sp2);
1555 file1 == file2
1556 };
1557 if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
1562 && res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
1563 {
1564 err.span_label(
1565 sugg_span,
1566 ::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()),
1567 );
1568 return true;
1569 }
1570 false
1571 }
1572
1573 fn err_code_special_cases(
1574 &mut self,
1575 err: &mut Diag<'_>,
1576 source: PathSource<'_, '_, '_>,
1577 path: &[Segment],
1578 span: Span,
1579 ) {
1580 if let Some(err_code) = err.code {
1581 if err_code == E0425 {
1582 for label_rib in &self.label_ribs {
1583 for (label_ident, node_id) in &label_rib.bindings {
1584 let ident = path.last().unwrap().ident;
1585 if ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}", ident))
})format!("'{ident}") == label_ident.to_string() {
1586 err.span_label(label_ident.span, "a label with a similar name exists");
1587 if let PathSource::Expr(Some(Expr {
1588 kind: ExprKind::Break(None, Some(_)),
1589 ..
1590 })) = source
1591 {
1592 err.span_suggestion_verbose(
1593 span,
1594 "use the similarly named label",
1595 label_ident.name,
1596 Applicability::MaybeIncorrect,
1597 );
1598 self.diag_metadata.unused_labels.swap_remove(node_id);
1600 }
1601 }
1602 }
1603 }
1604
1605 self.suggest_ident_hidden_by_hygiene(err, path, span);
1606 if let Some(correct) = Self::likely_rust_type(path) {
1608 err.span_suggestion_verbose(
1609 span,
1610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have intended to use the `{0}` primitive type",
correct))
})format!("you might have intended to use the `{correct}` primitive type"),
1611 correct,
1612 Applicability::MaybeIncorrect,
1613 );
1614 }
1615 }
1616 }
1617 }
1618
1619 fn suggest_ident_hidden_by_hygiene(&self, err: &mut Diag<'_>, path: &[Segment], span: Span) {
1620 let [segment] = path else { return };
1621
1622 let ident = segment.ident;
1623 let callsite_span = span.source_callsite();
1624 for rib in self.ribs[ValueNS].iter().rev() {
1625 for (binding_ident, _) in &rib.bindings {
1626 if binding_ident.name == ident.name
1628 && binding_ident.span.ctxt() != span.ctxt()
1629 && !binding_ident.span.from_expansion()
1630 && binding_ident.span.lo() < callsite_span.lo()
1631 {
1632 err.span_help(
1633 binding_ident.span,
1634 "an identifier with the same name exists, but is not accessible due to macro hygiene",
1635 );
1636 return;
1637 }
1638
1639 if binding_ident.name == ident.name
1641 && binding_ident.span.from_expansion()
1642 && binding_ident.span.source_callsite().ctxt() == callsite_span.ctxt()
1643 && binding_ident.span.source_callsite().lo() < callsite_span.lo()
1644 {
1645 err.span_help(
1646 binding_ident.span,
1647 "an identifier with the same name is defined here, but is not accessible due to macro hygiene",
1648 );
1649 return;
1650 }
1651 }
1652 }
1653 }
1654
1655 fn suggest_self_ty(
1657 &self,
1658 err: &mut Diag<'_>,
1659 source: PathSource<'_, '_, '_>,
1660 path: &[Segment],
1661 span: Span,
1662 ) -> bool {
1663 if !is_self_type(path, source.namespace()) {
1664 return false;
1665 }
1666 err.code(E0411);
1667 err.span_label(span, "`Self` is only available in impls, traits, and type definitions");
1668 if let Some(item) = self.diag_metadata.current_item
1669 && let Some(ident) = item.kind.ident()
1670 {
1671 err.span_label(
1672 ident.span,
1673 ::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()),
1674 );
1675 }
1676 true
1677 }
1678
1679 fn suggest_self_value(
1680 &mut self,
1681 err: &mut Diag<'_>,
1682 source: PathSource<'_, '_, '_>,
1683 path: &[Segment],
1684 span: Span,
1685 ) -> bool {
1686 if !is_self_value(path, source.namespace()) {
1687 return false;
1688 }
1689
1690 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:1690",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(1690u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("smart_resolve_path_fragment: E0424, source={0:?}",
source) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
1691 err.code(E0424);
1692 err.span_label(
1693 span,
1694 match source {
1695 PathSource::Pat => {
1696 "`self` value is a keyword and may not be bound to variables or shadowed"
1697 }
1698 _ => "`self` value is a keyword only available in methods with a `self` parameter",
1699 },
1700 );
1701
1702 if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat => true,
_ => false,
}matches!(source, PathSource::Pat) {
1705 return true;
1706 }
1707
1708 let is_assoc_fn = self.self_type_is_available().is_some();
1709 let self_from_macro = "a `self` parameter, but a macro invocation can only \
1710 access identifiers it receives from parameters";
1711 if let Some((fn_kind, fn_span)) = &self.diag_metadata.current_function {
1712 if fn_kind.decl().inputs.get(0).is_some_and(|p| p.is_self()) {
1717 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}"));
1718 } else {
1719 let doesnt = if is_assoc_fn {
1720 let (span, sugg) = fn_kind
1721 .decl()
1722 .inputs
1723 .get(0)
1724 .map(|p| (p.span.shrink_to_lo(), "&self, "))
1725 .unwrap_or_else(|| {
1726 let span = fn_kind
1729 .ident()
1730 .map_or(*fn_span, |ident| fn_span.with_lo(ident.span.hi()));
1731 (
1732 self.r
1733 .tcx
1734 .sess
1735 .source_map()
1736 .span_through_char(span, '(')
1737 .shrink_to_hi(),
1738 "&self",
1739 )
1740 });
1741 err.span_suggestion_verbose(
1742 span,
1743 "add a `self` receiver parameter to make the associated `fn` a method",
1744 sugg,
1745 Applicability::MaybeIncorrect,
1746 );
1747 "doesn't"
1748 } else {
1749 "can't"
1750 };
1751 if let Some(ident) = fn_kind.ident() {
1752 err.span_label(
1753 ident.span,
1754 ::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"),
1755 );
1756 }
1757 }
1758 } else if let Some(item) = self.diag_metadata.current_item {
1759 if #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ItemKind::Delegation(..) => true,
_ => false,
}matches!(item.kind, ItemKind::Delegation(..)) {
1760 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}"));
1761 } else {
1762 let span = if let Some(ident) = item.kind.ident() { ident.span } else { item.span };
1763 err.span_label(
1764 span,
1765 ::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()),
1766 );
1767 }
1768 }
1769 true
1770 }
1771
1772 fn detect_missing_binding_available_from_pattern(
1773 &self,
1774 err: &mut Diag<'_>,
1775 path: &[Segment],
1776 following_seg: Option<&Segment>,
1777 ) {
1778 let [segment] = path else { return };
1779 let None = following_seg else { return };
1780 for rib in self.ribs[ValueNS].iter().rev() {
1781 let patterns_with_skipped_bindings =
1782 self.r.tcx.with_stable_hashing_context(|mut hcx| {
1783 rib.patterns_with_skipped_bindings.to_sorted(&mut hcx, true)
1784 });
1785 for (def_id, spans) in patterns_with_skipped_bindings {
1786 if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id)
1787 && let Some(fields) = self.r.field_idents(*def_id)
1788 {
1789 for field in fields {
1790 if field.name == segment.ident.name {
1791 if spans.iter().all(|(.., had_error)| had_error.is_err()) {
1792 let multispan: MultiSpan =
1795 spans.iter().map(|(s, ..)| *s).collect::<Vec<_>>().into();
1796 err.span_note(
1797 multispan,
1798 "this pattern had a recovered parse error which likely lost \
1799 the expected fields",
1800 );
1801 err.downgrade_to_delayed_bug();
1802 }
1803 let ty = self.r.tcx.item_name(*def_id);
1804 for (span, rest_span, _) in spans {
1805 err.span_label(
1806 *span,
1807 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this pattern doesn\'t include `{0}`, which is available in `{1}`",
field, ty))
})format!(
1808 "this pattern doesn't include `{field}`, which is \
1809 available in `{ty}`",
1810 ),
1811 );
1812 if let Some(rest_span) = rest_span {
1813 err.span_suggestion_verbose(
1814 *rest_span,
1815 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("include `{0}` in the pattern",
field))
})format!("include `{field}` in the pattern"),
1816 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ..", field))
})format!("{field}, .."),
1817 Applicability::MaybeIncorrect,
1818 );
1819 }
1820 }
1821 }
1822 }
1823 }
1824 }
1825 }
1826 }
1827
1828 pub(in crate::late) fn detect_missing_turbofish(&mut self, arguments: &'ast [Box<Expr>]) {
1831 if self.use_injections.is_empty() {
1832 return;
1835 }
1836 let mut iter = arguments.iter().peekable();
1837 while let Some(arg) = iter.next() {
1841 let ExprKind::Binary(lt, left, right) = &arg.kind else { continue };
1844 let ast::BinOpKind::Lt = lt.node else {
1847 continue;
1848 };
1849 let ExprKind::Path(_, lt_left) = &left.kind else { continue };
1852 let lt_left_segments: Vec<_> = lt_left.segments.iter().map(|seg| seg.into()).collect();
1855 let lt_res = if let PathResult::NonModule(res) =
1857 self.resolve_path(<_left_segments, Some(TypeNS), None, PathSource::Expr(None))
1858 && let Some(lt_res) = res.full_res()
1859 {
1860 lt_res
1861 } else {
1862 continue;
1863 };
1864
1865 let ExprKind::Path(_, lt_right) = &right.kind else { continue };
1869 let lt_right_segments: Vec<_> =
1870 lt_right.segments.iter().map(|seg| seg.into()).collect();
1871 if let PathResult::NonModule(res) =
1872 self.resolve_path(<_right_segments, Some(TypeNS), None, PathSource::Expr(None))
1873 && let Some(_res) = res.full_res()
1874 {
1875 } else {
1876 continue;
1877 }
1878
1879 let Some(mut next) = iter.next() else {
1882 break;
1883 };
1884 let mut other_path_spans = ::alloc::vec::Vec::new()vec![];
1885 loop {
1886 match &next.kind {
1887 ExprKind::Binary(gt, gt_left, gt_right)
1890 if let ast::BinOpKind::Gt = gt.node
1893 && let ExprKind::Path(_, gt_left) = >_left.kind
1896 && let ExprKind::Call(call_expr, _) = >_right.kind
1899 && let ExprKind::Path(_, call_path) = &call_expr.kind
1900 && let gt_left_segments = gt_left
1901 .segments
1902 .iter()
1903 .map(|seg| seg.into())
1904 .collect::<Vec<_>>()
1905 && let PathResult::NonModule(res) = self.resolve_path(
1906 >_left_segments,
1907 Some(TypeNS),
1908 None,
1909 PathSource::Expr(None),
1910 )
1911 && let Some(_res) = res.full_res() =>
1912 {
1913 let mut any = false;
1918 let spans: Vec<Span> = lt_left_segments
1919 .iter()
1920 .map(|s| s.ident.span)
1921 .chain(lt_right_segments.iter().map(|s| s.ident.span))
1922 .chain(gt_left_segments.iter().map(|s| s.ident.span))
1923 .chain(gt_left_segments.iter().map(|s| s.ident.span))
1924 .chain(call_path.segments.iter().map(|seg| seg.span()))
1925 .chain(other_path_spans.iter().cloned())
1926 .collect();
1927 for injection in self.use_injections.iter_mut() {
1928 if injection.path.iter().any(|s| spans.contains(&s.ident.span)) {
1931 any = true;
1932 injection.err.downgrade_to_delayed_bug();
1933 }
1934 }
1935 if any {
1936 let sp = MultiSpan::from(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[lt.span, gt.span]))vec![lt.span, gt.span]);
1937 let mut err =
1938 self.r.tcx.dcx().struct_span_err(sp, "can't compare two types");
1939 err.span_label(
1940 gt.span,
1941 "these are parsed as \"less than\" and \"greater than\"",
1942 );
1943 let name = if let Some(def_id) = lt_res.opt_def_id()
1944 && let Some(name) = self.r.tcx.opt_item_name(def_id)
1945 {
1946 name.to_string()
1947 } else {
1948 lt_right_segments
1949 .iter()
1950 .map(|s| s.ident.name.to_string())
1951 .collect::<Vec<String>>()
1952 .join("::")
1953 };
1954 err.span_suggestion_verbose(
1955 lt.span.shrink_to_lo(),
1956 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you likely intended to write type `{0}` with type parameters, but type parameters in expression contexts require the use of the \"turbofish\" `::<>`",
name))
})format!(
1957 "you likely intended to write type `{name}` with type parameters, but \
1958 type parameters in expression contexts require the use of the \
1959 \"turbofish\" `::<>`",
1960 ),
1961 "::".to_string(),
1962 Applicability::MachineApplicable,
1963 );
1964 err.emit();
1965 }
1966 }
1967
1968 ExprKind::Path(_, path) => {
1971 if let Some(n) = iter.next() {
1974 next = n;
1975 other_path_spans.extend(path.segments.iter().map(|seg| seg.ident.span));
1976 continue;
1980 }
1981 }
1982
1983 _ => {}
1984 }
1985 break;
1988 }
1989 }
1990 }
1991
1992 fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
1993 let Some(pat) = self.diag_metadata.current_pat else { return };
1994 let (bound, side, range) = match &pat.kind {
1995 ast::PatKind::Range(Some(bound), None, range) => (bound, Side::Start, range),
1996 ast::PatKind::Range(None, Some(bound), range) => (bound, Side::End, range),
1997 _ => return,
1998 };
1999 if let ExprKind::Path(None, range_path) = &bound.kind
2000 && let [segment] = &range_path.segments[..]
2001 && let [s] = path
2002 && segment.ident == s.ident
2003 && segment.ident.span.ctxt() == range.span.ctxt()
2004 {
2005 let (span, snippet) = match side {
2008 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
2009 Side::End => (range.span.to(segment.ident.span), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} @ ..", segment.ident))
})format!("{} @ ..", segment.ident)),
2010 };
2011 err.subdiagnostic(diagnostics::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
2012 span,
2013 ident: segment.ident,
2014 snippet,
2015 });
2016 }
2017
2018 enum Side {
2019 Start,
2020 End,
2021 }
2022 }
2023
2024 fn suggest_range_struct_destructuring(
2025 &mut self,
2026 err: &mut Diag<'_>,
2027 path: &[Segment],
2028 source: PathSource<'_, '_, '_>,
2029 ) {
2030 if !#[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..) =>
true,
_ => false,
}matches!(source, PathSource::Pat | PathSource::TupleStruct(..) | PathSource::Expr(..)) {
2031 return;
2032 }
2033
2034 let Some(pat) = self.diag_metadata.current_pat else { return };
2035 let ast::PatKind::Range(start, end, end_kind) = &pat.kind else { return };
2036
2037 let [segment] = path else { return };
2038 let failing_span = segment.ident.span;
2039
2040 let in_start = start.as_ref().is_some_and(|e| e.span.contains(failing_span));
2041 let in_end = end.as_ref().is_some_and(|e| e.span.contains(failing_span));
2042
2043 if !in_start && !in_end {
2044 return;
2045 }
2046
2047 let start_snippet =
2048 start.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
2049 let end_snippet =
2050 end.as_ref().and_then(|e| self.r.tcx.sess.source_map().span_to_snippet(e.span).ok());
2051
2052 let field = |name: &str, val: String| {
2053 if val == name { val } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", name, val))
})format!("{name}: {val}") }
2054 };
2055
2056 let mut resolve_short_name = |short: Symbol, full: &str| -> String {
2057 let ident = Ident::with_dummy_span(short);
2058 let path = Segment::from_path(&Path::from_ident(ident));
2059
2060 match self.resolve_path(&path, Some(TypeNS), None, PathSource::Type) {
2061 PathResult::NonModule(..) => short.to_string(),
2062 _ => full.to_string(),
2063 }
2064 };
2065 let (struct_path, fields) = match (start_snippet, end_snippet, &end_kind.node) {
2067 (Some(start), Some(end), ast::RangeEnd::Excluded) => (
2068 resolve_short_name(sym::Range, "std::ops::Range"),
2069 ::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)],
2070 ),
2071 (Some(start), Some(end), ast::RangeEnd::Included(_)) => (
2072 resolve_short_name(sym::RangeInclusive, "std::ops::RangeInclusive"),
2073 ::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)],
2074 ),
2075 (Some(start), None, _) => (
2076 resolve_short_name(sym::RangeFrom, "std::ops::RangeFrom"),
2077 ::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)],
2078 ),
2079 (None, Some(end), ast::RangeEnd::Excluded) => {
2080 (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)])
2081 }
2082 (None, Some(end), ast::RangeEnd::Included(_)) => (
2083 resolve_short_name(sym::RangeToInclusive, "std::ops::RangeToInclusive"),
2084 ::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)],
2085 ),
2086 _ => return,
2087 };
2088
2089 err.span_suggestion_verbose(
2090 pat.span,
2091 ::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"),
2092 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{ {1} }}", struct_path,
fields.join(", ")))
})format!("{} {{ {} }}", struct_path, fields.join(", ")),
2093 Applicability::MaybeIncorrect,
2094 );
2095
2096 err.note(
2097 "range patterns match against the start and end of a range; \
2098 to bind the components, use a struct pattern",
2099 );
2100 }
2101
2102 fn suggest_swapping_misplaced_self_ty_and_trait(
2103 &mut self,
2104 err: &mut Diag<'_>,
2105 source: PathSource<'_, 'ast, 'ra>,
2106 res: Option<Res>,
2107 span: Span,
2108 ) {
2109 if let Some((trait_ref, self_ty)) = self.diag_metadata.currently_processing_impl_trait
2110 && let TyKind::Path(_, self_ty_path) = &self_ty.kind
2111 && let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2112 self.resolve_path(&Segment::from_path(self_ty_path), Some(TypeNS), None, source)
2113 && module.def_kind() == Some(DefKind::Trait)
2114 && trait_ref.path.span == span
2115 && let PathSource::Trait(_) = source
2116 && let Some(Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) = res
2117 && let Ok(self_ty_str) = self.r.tcx.sess.source_map().span_to_snippet(self_ty.span)
2118 && let Ok(trait_ref_str) =
2119 self.r.tcx.sess.source_map().span_to_snippet(trait_ref.path.span)
2120 {
2121 err.multipart_suggestion(
2122 "`impl` items mention the trait being implemented first and the type it is being implemented for second",
2123 ::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)],
2124 Applicability::MaybeIncorrect,
2125 );
2126 }
2127 }
2128
2129 fn detect_resolution_error_in_derive(&self, err: &mut Diag<'_>, span: Span) {
2134 if let Some(item) = self.diag_metadata.current_item
2135 && item.span.ctxt() != span.ctxt()
2136 && item.span.in_derive_expansion()
2137 {
2138 err.span_label(item.span, "in this derive macro");
2146 }
2147 }
2148
2149 fn explain_functions_in_pattern(
2150 &self,
2151 err: &mut Diag<'_>,
2152 res: Option<Res>,
2153 source: PathSource<'_, '_, '_>,
2154 ) {
2155 let PathSource::TupleStruct(_, _) = source else { return };
2156 let Some(Res::Def(DefKind::Fn, _)) = res else { return };
2157 err.primary_message("expected a pattern, found a function call");
2158 err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
2159 }
2160
2161 fn suggest_changing_type_to_const_param(
2162 &self,
2163 err: &mut Diag<'_>,
2164 res: Option<Res>,
2165 source: PathSource<'_, '_, '_>,
2166 path: &[Segment],
2167 following_seg: Option<&Segment>,
2168 span: Span,
2169 ) {
2170 if let PathSource::Expr(None) = source
2171 && let Some(Res::Def(DefKind::TyParam, _)) = res
2172 && following_seg.is_none()
2173 && let [segment] = path
2174 {
2175 let Some(item) = self.diag_metadata.current_item else { return };
2183 let Some(generics) = item.kind.generics() else { return };
2184 let Some(span) = generics.params.iter().find_map(|param| {
2185 if param.bounds.is_empty() && param.ident.name == segment.ident.name {
2187 Some(param.ident.span)
2188 } else {
2189 None
2190 }
2191 }) else {
2192 return;
2193 };
2194 err.subdiagnostic(diagnostics::UnexpectedResChangeTyParamToConstParamSugg {
2195 before: span.shrink_to_lo(),
2196 after: span.shrink_to_hi(),
2197 });
2198 return;
2199 }
2200 let PathSource::Trait(_) = source else { return };
2201
2202 let applicability = match res {
2204 Some(Res::PrimTy(PrimTy::Int(_) | PrimTy::Uint(_) | PrimTy::Bool | PrimTy::Char)) => {
2205 Applicability::MachineApplicable
2206 }
2207 Some(Res::Def(DefKind::Struct | DefKind::Enum, _))
2211 if self.r.features.adt_const_params() || self.r.features.min_adt_const_params() =>
2212 {
2213 Applicability::MaybeIncorrect
2214 }
2215 _ => return,
2216 };
2217
2218 let Some(item) = self.diag_metadata.current_item else { return };
2219 let Some(generics) = item.kind.generics() else { return };
2220
2221 let param = generics.params.iter().find_map(|param| {
2222 if let [bound] = &*param.bounds
2224 && let ast::GenericBound::Trait(tref) = bound
2225 && tref.modifiers == ast::TraitBoundModifiers::NONE
2226 && tref.span == span
2227 && param.ident.span.ctxt() == span.ctxt()
2228 {
2229 Some(param.ident.span)
2230 } else {
2231 None
2232 }
2233 });
2234
2235 if let Some(param) = param {
2236 err.subdiagnostic(diagnostics::UnexpectedResChangeTyToConstParamSugg {
2237 span: param.shrink_to_lo(),
2238 applicability,
2239 });
2240 }
2241 }
2242
2243 fn suggest_pattern_match_with_let(
2244 &self,
2245 err: &mut Diag<'_>,
2246 source: PathSource<'_, '_, '_>,
2247 span: Span,
2248 ) -> bool {
2249 if let PathSource::Expr(_) = source
2250 && let Some(Expr { span: expr_span, kind: ExprKind::Assign(lhs, _, _), .. }) =
2251 self.diag_metadata.in_if_condition
2252 {
2253 if lhs.is_approximately_pattern() && lhs.span.contains(span) {
2257 err.span_suggestion_verbose(
2258 expr_span.shrink_to_lo(),
2259 "you might have meant to use pattern matching",
2260 "let ",
2261 Applicability::MaybeIncorrect,
2262 );
2263 return true;
2264 }
2265 }
2266 false
2267 }
2268
2269 fn get_single_associated_item(
2270 &mut self,
2271 path: &[Segment],
2272 source: &PathSource<'_, 'ast, 'ra>,
2273 filter_fn: &impl Fn(Res) -> bool,
2274 ) -> Option<TypoSuggestion> {
2275 if let crate::PathSource::TraitItem(_, _) = source {
2276 let mod_path = &path[..path.len() - 1];
2277 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
2278 self.resolve_path(mod_path, None, None, *source)
2279 {
2280 let targets: Vec<_> = self
2281 .r
2282 .resolutions(module)
2283 .iter()
2284 .filter_map(|(key, resolution)| {
2285 let resolution = resolution.borrow(self.r);
2286 resolution.best_decl().map(|binding| binding.res()).and_then(|res| {
2287 if filter_fn(res) {
2288 Some((key.ident.name, resolution.orig_ident_span, res))
2289 } else {
2290 None
2291 }
2292 })
2293 })
2294 .collect();
2295 if let &[(name, orig_ident_span, res)] = targets.as_slice() {
2296 return Some(TypoSuggestion::single_item(name, orig_ident_span, res));
2297 }
2298 }
2299 }
2300 None
2301 }
2302
2303 fn restrict_assoc_type_in_where_clause(&self, span: Span, err: &mut Diag<'_>) -> bool {
2305 let Some(ast::WherePredicate {
2307 kind:
2308 ast::WherePredicateKind::BoundPredicate(ast::WhereBoundPredicate {
2309 bounded_ty,
2310 bound_generic_params,
2311 bounds,
2312 }),
2313 span: where_span,
2314 ..
2315 }) = self.diag_metadata.current_where_predicate
2316 else {
2317 return false;
2318 };
2319 if !bound_generic_params.is_empty() {
2320 return false;
2321 }
2322
2323 let ast::TyKind::Path(Some(qself), path) = &bounded_ty.kind else { return false };
2325 let Some(partial_res) = self.r.partial_res_map.get(&bounded_ty.id) else { return false };
2327 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(DefKind::AssocTy, _)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(DefKind::AssocTy, _))) {
2328 return false;
2329 }
2330
2331 let peeled_ty = qself.ty.peel_refs();
2332 let ast::TyKind::Path(None, type_param_path) = &peeled_ty.kind else { return false };
2333 let Some(partial_res) = self.r.partial_res_map.get(&peeled_ty.id) else {
2335 return false;
2336 };
2337 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, _))) {
2338 return false;
2339 }
2340 let ([ast::PathSegment { args: None, .. }], [ast::GenericBound::Trait(poly_trait_ref)]) =
2341 (&type_param_path.segments[..], &bounds[..])
2342 else {
2343 return false;
2344 };
2345 let [ast::PathSegment { ident, args: None, id }] =
2346 &poly_trait_ref.trait_ref.path.segments[..]
2347 else {
2348 return false;
2349 };
2350 if poly_trait_ref.modifiers != ast::TraitBoundModifiers::NONE {
2351 return false;
2352 }
2353 if ident.span == span {
2354 let Some(partial_res) = self.r.partial_res_map.get(&id) else {
2355 return false;
2356 };
2357 if !#[allow(non_exhaustive_omitted_patterns)] match partial_res.full_res() {
Some(Res::Def(..)) => true,
_ => false,
}matches!(partial_res.full_res(), Some(Res::Def(..))) {
2358 return false;
2359 }
2360
2361 let Some(new_where_bound_predicate) =
2362 mk_where_bound_predicate(path, poly_trait_ref, &qself.ty)
2363 else {
2364 return false;
2365 };
2366 err.span_suggestion_verbose(
2367 *where_span,
2368 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("constrain the associated type to `{0}`",
ident))
})format!("constrain the associated type to `{ident}`"),
2369 where_bound_predicate_to_string(&new_where_bound_predicate),
2370 Applicability::MaybeIncorrect,
2371 );
2372 }
2373 true
2374 }
2375
2376 fn call_has_self_arg(&self, source: PathSource<'_, '_, '_>) -> Option<(Span, Option<Span>)> {
2379 let mut has_self_arg = None;
2380 if let PathSource::Expr(Some(parent)) = source
2381 && let ExprKind::Call(_, args) = &parent.kind
2382 && !args.is_empty()
2383 {
2384 let mut expr_kind = &args[0].kind;
2385 loop {
2386 match expr_kind {
2387 ExprKind::Path(_, arg_name) if arg_name.segments.len() == 1 => {
2388 if arg_name.segments[0].ident.name == kw::SelfLower {
2389 let call_span = parent.span;
2390 let tail_args_span = if args.len() > 1 {
2391 Some(Span::new(
2392 args[1].span.lo(),
2393 args.last().unwrap().span.hi(),
2394 call_span.ctxt(),
2395 None,
2396 ))
2397 } else {
2398 None
2399 };
2400 has_self_arg = Some((call_span, tail_args_span));
2401 }
2402 break;
2403 }
2404 ExprKind::AddrOf(_, _, expr) => expr_kind = &expr.kind,
2405 _ => break,
2406 }
2407 }
2408 }
2409 has_self_arg
2410 }
2411
2412 fn followed_by_brace(&self, span: Span) -> (bool, Option<Span>) {
2413 let sm = self.r.tcx.sess.source_map();
2418 if let Some(open_brace_span) = sm.span_followed_by(span, "{") {
2419 let close_brace_span =
2422 sm.span_to_next_source(open_brace_span).ok().and_then(|next_source| {
2423 let mut depth: u32 = 1;
2425 let offset = next_source.char_indices().find_map(|(i, c)| {
2426 match c {
2427 '{' => depth += 1,
2428 '}' if depth == 1 => return Some(i),
2429 '}' => depth -= 1,
2430 _ => {}
2431 }
2432 None
2433 })?;
2434 let start = open_brace_span.hi() + rustc_span::BytePos(offset as u32);
2435 Some(open_brace_span.with_lo(start).with_hi(start + rustc_span::BytePos(1)))
2436 });
2437 let closing_brace = close_brace_span.map(|sp| span.to(sp));
2438 (true, closing_brace)
2439 } else {
2440 (false, None)
2441 }
2442 }
2443
2444 fn update_err_for_private_tuple_struct_fields(
2445 &self,
2446 err: &mut Diag<'_>,
2447 source: &PathSource<'_, '_, '_>,
2448 def_id: DefId,
2449 ) -> Option<Vec<Span>> {
2450 match source {
2451 PathSource::TupleStruct(_, pattern_spans) => {
2453 err.primary_message(
2454 "cannot match against a tuple struct which contains private fields",
2455 );
2456
2457 Some(Vec::from(*pattern_spans))
2459 }
2460 PathSource::Expr(Some(Expr {
2462 kind: ExprKind::Call(path, args),
2463 span: call_span,
2464 ..
2465 })) => {
2466 err.primary_message(
2467 "cannot initialize a tuple struct which contains private fields",
2468 );
2469 self.suggest_alternative_construction_methods(
2470 def_id,
2471 err,
2472 path.span,
2473 *call_span,
2474 &args[..],
2475 );
2476
2477 self.r
2478 .field_idents(def_id)
2479 .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
2480 }
2481 _ => None,
2482 }
2483 }
2484
2485 fn smart_resolve_context_dependent_help(
2489 &mut self,
2490 err: &mut Diag<'_>,
2491 span: Span,
2492 source: PathSource<'_, '_, '_>,
2493 path: &[Segment],
2494 res: Res,
2495 path_str: &str,
2496 fallback_label: &str,
2497 ) -> bool {
2498 let ns = source.namespace();
2499 let is_expected = &|res| source.is_expected(res);
2500
2501 let path_sep = |this: &Self, err: &mut Diag<'_>, expr: &Expr, kind: DefKind| {
2502 const MESSAGE: &str = "use the path separator to refer to an item";
2503
2504 let (lhs_span, rhs_span) = match &expr.kind {
2505 ExprKind::Field(base, ident) => (base.span, ident.span),
2506 ExprKind::MethodCall(MethodCall { receiver, span, .. }) => (receiver.span, *span),
2507 _ => return false,
2508 };
2509
2510 if lhs_span.ctxt() == rhs_span.ctxt() {
2511 err.span_suggestion_verbose(
2512 lhs_span.between(rhs_span),
2513 MESSAGE,
2514 "::",
2515 Applicability::MaybeIncorrect,
2516 );
2517 true
2518 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::Struct | DefKind::TyAlias => true,
_ => false,
}matches!(kind, DefKind::Struct | DefKind::TyAlias)
2519 && let Some(lhs_source_span) = lhs_span.find_ancestor_inside(expr.span)
2520 && let Ok(snippet) = this.r.tcx.sess.source_map().span_to_snippet(lhs_source_span)
2521 {
2522 err.span_suggestion_verbose(
2526 lhs_source_span.until(rhs_span),
2527 MESSAGE,
2528 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>::", snippet))
})format!("<{snippet}>::"),
2529 Applicability::MaybeIncorrect,
2530 );
2531 true
2532 } else {
2533 false
2539 }
2540 };
2541
2542 let find_span = |source: &PathSource<'_, '_, '_>, err: &mut Diag<'_>| {
2543 match source {
2544 PathSource::Expr(Some(Expr { span, kind: ExprKind::Call(_, _), .. }))
2545 | PathSource::TupleStruct(span, _) => {
2546 err.span(*span);
2549 *span
2550 }
2551 _ => span,
2552 }
2553 };
2554
2555 let bad_struct_syntax_suggestion = |this: &Self, err: &mut Diag<'_>, def_id: DefId| {
2556 let (followed_by_brace, closing_brace) = this.followed_by_brace(span);
2557
2558 match source {
2559 PathSource::Expr(Some(
2560 parent @ Expr { kind: ExprKind::Field(..) | ExprKind::MethodCall(..), .. },
2561 )) if path_sep(this, err, parent, DefKind::Struct) => {}
2562 PathSource::Expr(
2563 None
2564 | Some(Expr {
2565 kind:
2566 ExprKind::Path(..)
2567 | ExprKind::Binary(..)
2568 | ExprKind::Unary(..)
2569 | ExprKind::If(..)
2570 | ExprKind::While(..)
2571 | ExprKind::ForLoop { .. }
2572 | ExprKind::Match(..),
2573 ..
2574 }),
2575 ) if followed_by_brace => {
2576 if let Some(sp) = closing_brace {
2577 err.span_label(span, fallback_label.to_string());
2578 err.multipart_suggestion(
2579 "surround the struct literal with parentheses",
2580 ::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![
2581 (sp.shrink_to_lo(), "(".to_string()),
2582 (sp.shrink_to_hi(), ")".to_string()),
2583 ],
2584 Applicability::MaybeIncorrect,
2585 );
2586 } else {
2587 err.span_label(
2588 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!(
2590 "you might want to surround a struct literal with parentheses: \
2591 `({path_str} {{ /* fields */ }})`?"
2592 ),
2593 );
2594 }
2595 }
2596 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2597 let span = find_span(&source, err);
2598 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"));
2599 if this.r.tcx.def_kind(def_id) == DefKind::Variant {
2600 err.span_context(this.r.def_span(this.r.tcx.parent(def_id)).shrink_to_lo());
2601 }
2602
2603 let (tail, descr, applicability, old_fields) = match source {
2604 PathSource::Pat => ("", "pattern", Applicability::MachineApplicable, None),
2605 PathSource::TupleStruct(_, args) => (
2606 "",
2607 "pattern",
2608 Applicability::MachineApplicable,
2609 Some(
2610 args.iter()
2611 .map(|a| this.r.tcx.sess.source_map().span_to_snippet(*a).ok())
2612 .collect::<Vec<Option<String>>>(),
2613 ),
2614 ),
2615 _ => (": val", "literal", Applicability::HasPlaceholders, None),
2616 };
2617
2618 let has_private_fields = match def_id.as_local() {
2620 Some(def_id) => this.r.struct_ctors.get(&def_id).is_some_and(|ctor| {
2621 ctor.has_private_fields(this.parent_scope.module, this.r)
2622 }),
2623 None => this.r.tcx.associated_item_def_ids(def_id).iter().any(|field_id| {
2624 let vis = this.r.tcx.visibility(*field_id);
2625 !this.r.is_accessible_from(vis, this.parent_scope.module)
2626 }),
2627 };
2628 if !has_private_fields {
2629 let fields = this.r.field_idents(def_id);
2632 let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
2633
2634 if let PathSource::Expr(Some(Expr {
2635 kind: ExprKind::Call(path, args),
2636 span,
2637 ..
2638 })) = source
2639 && !args.is_empty()
2640 && let Some(fields) = &fields
2641 && args.len() == fields.len()
2642 {
2644 let path_span = path.span;
2645 let mut parts = Vec::new();
2646
2647 parts.push((
2649 path_span.shrink_to_hi().until(args[0].span),
2650 "{".to_owned(),
2651 ));
2652
2653 for (field, arg) in fields.iter().zip(args.iter()) {
2654 parts.push((arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{}: ", field)));
2656 }
2657
2658 parts.push((
2660 args.last().unwrap().span.shrink_to_hi().until(span.shrink_to_hi()),
2661 "}".to_owned(),
2662 ));
2663
2664 err.multipart_suggestion(
2665 ::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"),
2666 parts,
2667 applicability,
2668 );
2669 } else {
2670 let (fields, applicability) = match fields {
2671 Some(fields) => {
2672 let fields = if let Some(old_fields) = old_fields {
2673 fields
2674 .iter()
2675 .enumerate()
2676 .map(|(idx, new)| (new, old_fields.get(idx)))
2677 .map(|(new, old)| {
2678 if let Some(Some(old)) = old
2679 && new.as_str() != old
2680 {
2681 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2682 } else {
2683 new.to_string()
2684 }
2685 })
2686 .collect::<Vec<String>>()
2687 } else {
2688 fields
2689 .iter()
2690 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2691 .collect::<Vec<String>>()
2692 };
2693
2694 (fields.join(", "), applicability)
2695 }
2696 None => {
2697 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2698 }
2699 };
2700 let pad = if has_fields { " " } else { "" };
2701 let expression = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {{{1}{2}{1}}}", path_str, pad,
fields))
})format!("{path_str} {{{pad}{fields}{pad}}}");
2702 if !this.suggest_named_format_argument(
2703 err,
2704 source,
2705 path.last().unwrap().ident,
2706 &expression,
2707 applicability,
2708 ) {
2709 err.span_suggestion_verbose(
2710 span,
2711 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2712 expression,
2713 applicability,
2714 );
2715 }
2716 }
2717 }
2718 if let PathSource::Expr(Some(Expr {
2719 kind: ExprKind::Call(path, args),
2720 span: call_span,
2721 ..
2722 })) = source
2723 {
2724 this.suggest_alternative_construction_methods(
2725 def_id,
2726 err,
2727 path.span,
2728 *call_span,
2729 &args[..],
2730 );
2731 }
2732 }
2733 _ => {
2734 err.span_label(span, fallback_label.to_string());
2735 }
2736 }
2737 };
2738
2739 match (res, source) {
2740 (
2741 Res::Def(DefKind::Macro(kinds), def_id),
2742 PathSource::Expr(Some(Expr {
2743 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2744 }))
2745 | PathSource::Struct(_),
2746 ) if kinds.contains(MacroKinds::BANG) => {
2747 let suggestable = def_id.is_local()
2749 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2750
2751 err.span_label(span, fallback_label.to_string());
2752
2753 if path
2755 .last()
2756 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2757 && suggestable
2758 {
2759 err.span_suggestion_verbose(
2760 span.shrink_to_hi(),
2761 "use `!` to invoke the macro",
2762 "!",
2763 Applicability::MaybeIncorrect,
2764 );
2765 }
2766
2767 if path_str == "try" && span.is_rust_2015() {
2768 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2769 }
2770 }
2771 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2772 err.span_label(span, fallback_label.to_string());
2773 }
2774 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2775 err.span_label(span, "type aliases cannot be used as traits");
2776 if self.r.tcx.sess.is_nightly_build() {
2777 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2778 `type` alias";
2779 let span = self.r.def_span(def_id);
2780 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2781 let snip = snip.replacen("type", "trait", 1);
2784 err.span_suggestion_verbose(span, msg, snip, Applicability::MaybeIncorrect);
2785 } else {
2786 err.span_help(span, msg);
2787 }
2788 }
2789 }
2790 (
2791 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2792 PathSource::Expr(Some(parent)),
2793 ) if path_sep(self, err, parent, kind) => {
2794 return true;
2795 }
2796 (
2797 Res::Def(DefKind::Enum, def_id),
2798 PathSource::TupleStruct(..) | PathSource::Expr(..),
2799 ) => {
2800 self.suggest_using_enum_variant(err, source, def_id, span);
2801 }
2802 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2803 if let PathSource::Expr(Some(parent)) = source
2804 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2805 {
2806 bad_struct_syntax_suggestion(self, err, def_id);
2807 return true;
2808 }
2809 let Some(ctor) = self.r.struct_ctor(def_id) else {
2810 bad_struct_syntax_suggestion(self, err, def_id);
2811 return true;
2812 };
2813
2814 let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2817 if is_accessible
2818 && let mod_path = &path[..path.len() - 1]
2819 && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2820 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2821 && ctor.has_private_fields(import_mod, self.r)
2822 && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2823 ModuleOrUniformRoot::Module(import_mod),
2824 path.last().unwrap().ident,
2825 TypeNS,
2826 &self.parent_scope,
2827 None,
2828 )
2829 {
2830 err.span_note(
2831 import_decl.span,
2832 "the type is accessed through this re-export, but the type's constructor \
2833 is not visible in this import's scope due to private fields",
2834 );
2835 if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2836 err.span_suggestion_verbose(
2837 span,
2838 "the type can be constructed directly, because its fields are \
2839 available from the current scope",
2840 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2844 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2846 ),
2847 Applicability::MachineApplicable,
2848 );
2849 }
2850 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2851 }
2852 if !is_expected(ctor.res) || is_accessible {
2853 return true;
2854 }
2855
2856 let field_spans =
2857 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2858
2859 if let Some(spans) = field_spans
2860 .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2861 {
2862 let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2863 .filter(|(vis, _)| {
2864 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2865 })
2866 .map(|(_, span)| *span)
2867 .collect();
2868
2869 if non_visible_spans.len() > 0 {
2870 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2871 err.multipart_suggestion(
2872 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2873 "consider making the field{} publicly accessible",
2874 pluralize!(fields.len())
2875 ),
2876 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2877 Applicability::MaybeIncorrect,
2878 );
2879 }
2880
2881 let mut m: MultiSpan = non_visible_spans.clone().into();
2882 non_visible_spans
2883 .into_iter()
2884 .for_each(|s| m.push_span_label(s, "private field"));
2885 err.span_note(m, "constructor is not visible here due to private fields");
2886 }
2887
2888 return true;
2889 }
2890
2891 err.span_label(span, "constructor is not visible here due to private fields");
2892 }
2893 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2894 bad_struct_syntax_suggestion(self, err, def_id);
2895 }
2896 (Res::Def(DefKind::Ctor(of, CtorKind::Const), def_id), _) if ns == ValueNS => {
2897 match source {
2898 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2899 let span = find_span(&source, err);
2900 err.span_label(
2901 self.r.def_span(def_id),
2902 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2903 );
2904 if of == CtorOf::Variant {
2905 err.span_context(
2906 self.r
2907 .def_span(self.r.tcx.parent(self.r.tcx.parent(def_id)))
2908 .shrink_to_lo(),
2909 );
2910 }
2911 err.span_suggestion_verbose(
2912 span,
2913 "use the unit struct syntax instead",
2914 path_str,
2915 Applicability::MaybeIncorrect,
2916 );
2917 }
2918 _ => return false,
2919 }
2920 }
2921 (Res::Def(DefKind::Ctor(of, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2922 let def_id = self.r.tcx.parent(ctor_def_id);
2923 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"));
2924 if of == CtorOf::Variant {
2925 err.span_context(self.r.def_span(self.r.tcx.parent(def_id)).shrink_to_lo());
2926 }
2927 let fields = self.r.field_idents(def_id).map_or_else(
2928 || "/* fields */".to_string(),
2929 |field_ids| ::alloc::vec::from_elem_global("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2930 );
2931 err.span_suggestion_verbose(
2932 span,
2933 "use the tuple variant pattern syntax instead",
2934 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2935 Applicability::HasPlaceholders,
2936 );
2937 }
2938 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2939 err.span_label(span, fallback_label.to_string());
2940 err.note("can't use `Self` as a constructor, you must use the implemented struct");
2941 }
2942 (
2943 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2944 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
2945 ) => {
2946 err.note("can't use a type alias as tuple pattern");
2947
2948 let mut suggestion = Vec::new();
2949
2950 if let &&[first, ..] = args
2951 && let &&[.., last] = args
2952 {
2953 suggestion.extend([
2954 (span.between(first), " { 0: ".to_owned()),
2960 (last.between(whole.shrink_to_hi()), " }".to_owned()),
2961 ]);
2962
2963 suggestion.extend(
2964 args.iter()
2965 .enumerate()
2966 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
2968 )
2969 } else {
2970 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
2971 }
2972
2973 err.multipart_suggestion(
2974 "use struct pattern instead",
2975 suggestion,
2976 Applicability::MachineApplicable,
2977 );
2978 }
2979 (
2980 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
2981 PathSource::TraitItem(
2982 ValueNS,
2983 PathSource::Expr(Some(ast::Expr {
2984 span: whole,
2985 kind: ast::ExprKind::Call(_, args),
2986 ..
2987 })),
2988 ),
2989 ) => {
2990 err.note("can't use a type alias as a constructor");
2991
2992 let mut suggestion = Vec::new();
2993
2994 if let [first, ..] = &**args
2995 && let [.., last] = &**args
2996 {
2997 suggestion.extend([
2998 (span.between(first.span), " { 0: ".to_owned()),
3004 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
3005 ]);
3006
3007 suggestion.extend(
3008 args.iter()
3009 .enumerate()
3010 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
3012 )
3013 } else {
3014 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
3015 }
3016
3017 err.multipart_suggestion(
3018 "use struct expression instead",
3019 suggestion,
3020 Applicability::MachineApplicable,
3021 );
3022 }
3023 _ => return false,
3024 }
3025 true
3026 }
3027
3028 fn suggest_alternative_construction_methods(
3029 &self,
3030 def_id: DefId,
3031 err: &mut Diag<'_>,
3032 path_span: Span,
3033 call_span: Span,
3034 args: &[Box<Expr>],
3035 ) {
3036 if def_id.is_local() {
3037 return;
3039 }
3040 let mut items = self
3043 .r
3044 .tcx
3045 .inherent_impls(def_id)
3046 .iter()
3047 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
3048 .filter(|item| item.is_fn() && !item.is_method())
3050 .filter_map(|item| {
3051 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
3053 let ret_ty = fn_sig.output().skip_binder();
3055 let ty::Adt(def, _args) = ret_ty.kind() else {
3056 return None;
3057 };
3058 let input_len = fn_sig.inputs().skip_binder().len();
3059 if def.did() != def_id {
3060 return None;
3061 }
3062 let name = item.name();
3063 let order = !name.as_str().starts_with("new");
3064 Some((order, name, input_len))
3065 })
3066 .collect::<Vec<_>>();
3067 items.sort_by_key(|(order, _, _)| *order);
3068 let suggestion = |name, args| {
3069 ::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(", "))
3070 };
3071 match &items[..] {
3072 [] => {}
3073 [(_, name, len)] if *len == args.len() => {
3074 err.span_suggestion_verbose(
3075 path_span.shrink_to_hi(),
3076 ::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",),
3077 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
3078 Applicability::MaybeIncorrect,
3079 );
3080 }
3081 [(_, name, len)] => {
3082 err.span_suggestion_verbose(
3083 path_span.shrink_to_hi().with_hi(call_span.hi()),
3084 ::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",),
3085 suggestion(name, *len),
3086 Applicability::MaybeIncorrect,
3087 );
3088 }
3089 _ => {
3090 err.span_suggestions_with_style(
3091 path_span.shrink_to_hi().with_hi(call_span.hi()),
3092 "you might have meant to use an associated function to build this type",
3093 items.iter().map(|(_, name, len)| suggestion(name, *len)),
3094 Applicability::MaybeIncorrect,
3095 SuggestionStyle::ShowAlways,
3096 );
3097 }
3098 }
3099 let default_trait = self
3107 .r
3108 .lookup_import_candidates(
3109 Ident::with_dummy_span(sym::Default),
3110 Namespace::TypeNS,
3111 &self.parent_scope,
3112 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
3113 )
3114 .iter()
3115 .filter_map(|candidate| candidate.did)
3116 .find(|did| {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(*did, &self.r.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDiagnosticItem(sym::Default))
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.r.tcx, *did, RustcDiagnosticItem(sym::Default)));
3117 let Some(default_trait) = default_trait else {
3118 return;
3119 };
3120 if self
3121 .r
3122 .extern_crate_map
3123 .items()
3124 .flat_map(|(_, crate_)| {
3126 UnordItems::new(
3127 self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
3128 )
3129 })
3130 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
3131 .filter_map(|simplified_self_ty| match simplified_self_ty {
3132 SimplifiedType::Adt(did) => Some(did),
3133 _ => None,
3134 })
3135 .any(|did| did == def_id)
3136 {
3137 err.multipart_suggestion(
3138 "consider using the `Default` trait",
3139 ::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![
3140 (path_span.shrink_to_lo(), "<".to_string()),
3141 (
3142 path_span.shrink_to_hi().with_hi(call_span.hi()),
3143 " as std::default::Default>::default()".to_string(),
3144 ),
3145 ],
3146 Applicability::MaybeIncorrect,
3147 );
3148 }
3149 }
3150
3151 pub(crate) fn find_similarly_named_assoc_item(
3154 &mut self,
3155 ident: Symbol,
3156 kind: &AssocItemKind,
3157 ) -> Option<Symbol> {
3158 let (module, _) = self.current_trait_ref?;
3159 if ident == kw::Underscore {
3160 return None;
3162 }
3163
3164 let targets = self
3165 .r
3166 .resolutions(module)
3167 .iter()
3168 .filter_map(|(key, res)| {
3169 res.borrow(self.r).best_decl().map(|binding| (key, binding.res()))
3170 })
3171 .filter(|(_, res)| match (kind, res) {
3172 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
3173 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
3174 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
3175 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
3176 _ => false,
3177 })
3178 .map(|(key, _)| key.ident.name)
3179 .collect::<Vec<_>>();
3180
3181 find_best_match_for_name(&targets, ident, None)
3182 }
3183
3184 fn lookup_assoc_candidate<FilterFn>(
3186 &self,
3187 ident: Ident,
3188 ns: Namespace,
3189 filter_fn: FilterFn,
3190 called: bool,
3191 ) -> Option<(AssocSuggestion, Span)>
3192 where
3193 FilterFn: Fn(Res) -> bool,
3194 {
3195 fn extract_node_id(t: &Ty) -> Option<NodeId> {
3196 match t.kind {
3197 TyKind::Path(None, _) => Some(t.id),
3198 TyKind::Ref(_, ref inner_ty, _) => extract_node_id(inner_ty),
3199 _ => None,
3203 }
3204 }
3205 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
3207 if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
3208 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
3209 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
3210 && let Some(fields) = self.r.field_idents(did)
3211 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
3212 {
3213 return Some((AssocSuggestion::Field, field.span));
3215 }
3216 }
3217
3218 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
3219 for assoc_item in items {
3220 if let Some(assoc_ident) = assoc_item.kind.ident()
3221 && assoc_ident == ident
3222 {
3223 let from = AssocFrom::Impl;
3224 let candidate = match &assoc_item.kind {
3225 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
3226 ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
3227 AssocSuggestion::MethodWithSelf { called, from }
3228 }
3229 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called, from },
3230 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType { from },
3231 ast::AssocItemKind::Delegation(..)
3232 if self
3233 .r
3234 .owners
3235 .get(&assoc_item.id)
3236 .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
3237 .is_some_and(|sig| sig.has_self) =>
3238 {
3239 AssocSuggestion::MethodWithSelf { called, from }
3240 }
3241 ast::AssocItemKind::Delegation(..) => {
3242 AssocSuggestion::AssocFn { called, from }
3243 }
3244 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
3245 continue;
3246 }
3247 };
3248 return Some((candidate, assoc_ident.span));
3249 }
3250 }
3251 }
3252
3253 if let Some((module, _)) = self.current_trait_ref
3255 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
3256 ModuleOrUniformRoot::Module(module),
3257 ident,
3258 ns,
3259 &self.parent_scope,
3260 None,
3261 )
3262 {
3263 let res = binding.res();
3264 if filter_fn(res) {
3265 let from = AssocFrom::Trait;
3266 match res {
3267 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
3268 let has_self = match def_id.as_local() {
3269 Some(def_id) => self
3270 .r
3271 .delegation_fn_sigs
3272 .get(&def_id)
3273 .is_some_and(|sig| sig.has_self),
3274 None => {
3275 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
3276 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
3277 })
3278 }
3279 };
3280 if has_self {
3281 return Some((
3282 AssocSuggestion::MethodWithSelf { called, from },
3283 binding.span,
3284 ));
3285 } else {
3286 return Some((AssocSuggestion::AssocFn { called, from }, binding.span));
3287 }
3288 }
3289 Res::Def(DefKind::AssocConst, _) => {
3290 return Some((AssocSuggestion::AssocConst, binding.span));
3291 }
3292 Res::Def(DefKind::AssocTy, _) => {
3293 return Some((AssocSuggestion::AssocType { from }, binding.span));
3294 }
3295 _ => {}
3296 }
3297 }
3298 }
3299
3300 None
3301 }
3302
3303 fn lookup_typo_candidate(
3304 &mut self,
3305 path: &[Segment],
3306 following_seg: Option<&Segment>,
3307 ns: Namespace,
3308 filter_fn: &impl Fn(Res) -> bool,
3309 ) -> TypoCandidate {
3310 let mut names = Vec::new();
3311 if let [segment] = path {
3312 let mut ctxt = segment.ident.span.ctxt();
3313
3314 for rib in self.ribs[ns].iter().rev() {
3317 let rib_ctxt = if rib.kind.contains_params() {
3318 ctxt.normalize_to_macros_2_0()
3319 } else {
3320 ctxt.normalize_to_macro_rules()
3321 };
3322
3323 for (ident, &res) in &rib.bindings {
3325 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
3326 names.push(TypoSuggestion::new(ident.name, ident.span, res));
3327 }
3328 }
3329
3330 if let RibKind::Block(Some(module)) = rib.kind {
3331 self.r.add_module_candidates(
3332 module.to_module(),
3333 &mut names,
3334 &filter_fn,
3335 Some(ctxt),
3336 );
3337 } else if let RibKind::Module(module) = rib.kind {
3338 let parent_scope =
3340 &ParentScope { module: module.to_module(), ..self.parent_scope };
3341 self.r.add_scope_set_candidates(
3342 &mut names,
3343 ScopeSet::All(ns),
3344 parent_scope,
3345 segment.ident.span.with_ctxt(ctxt),
3346 filter_fn,
3347 );
3348 break;
3349 }
3350
3351 if let RibKind::MacroDefinition(def) = rib.kind
3352 && def == self.r.macro_def(ctxt)
3353 {
3354 ctxt.remove_mark();
3357 }
3358 }
3359 } else {
3360 let mod_path = &path[..path.len() - 1];
3362 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
3363 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
3364 {
3365 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
3366 }
3367 }
3368
3369 if let Some(following_seg) = following_seg {
3371 names.retain(|suggestion| match suggestion.res {
3372 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
3373 suggestion.candidate != following_seg.ident.name
3375 }
3376 Res::Def(DefKind::Mod, def_id) => {
3377 let module = self.r.expect_module(def_id);
3378 self.r
3379 .resolutions(module)
3380 .iter()
3381 .any(|(key, _)| key.ident.name == following_seg.ident.name)
3382 }
3383 _ => true,
3384 });
3385 }
3386 let name = path[path.len() - 1].ident.name;
3387 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
3389
3390 match find_best_match_for_name(
3391 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
3392 name,
3393 None,
3394 ) {
3395 Some(found) => {
3396 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
3397 else {
3398 return TypoCandidate::None;
3399 };
3400 if found == name {
3401 TypoCandidate::Shadowed(sugg.res, sugg.span)
3402 } else {
3403 TypoCandidate::Typo(sugg)
3404 }
3405 }
3406 _ => TypoCandidate::None,
3407 }
3408 }
3409
3410 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
3413 let name = path[path.len() - 1].ident.as_str();
3414 Some(match name {
3416 "byte" => sym::u8, "short" => sym::i16,
3418 "Bool" => sym::bool,
3419 "Boolean" => sym::bool,
3420 "boolean" => sym::bool,
3421 "int" => sym::i32,
3422 "long" => sym::i64,
3423 "float" => sym::f32,
3424 "double" => sym::f64,
3425 _ => return None,
3426 })
3427 }
3428
3429 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
3432 if ident_span.from_expansion() {
3433 return false;
3434 }
3435
3436 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
3438 && let ast::ExprKind::Path(None, ref path) = lhs.kind
3439 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
3440 {
3441 let (span, text) = match path.segments.first() {
3442 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
3443 let name = name.trim_prefix('_');
3445 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
3446 }
3447 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3448 };
3449
3450 err.span_suggestion_verbose(
3451 span,
3452 "you might have meant to introduce a new binding",
3453 text,
3454 Applicability::MaybeIncorrect,
3455 );
3456 return true;
3457 }
3458
3459 if err.code == Some(E0423)
3462 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3463 && val_span.contains(ident_span)
3464 && val_span.lo() == ident_span.lo()
3465 {
3466 err.span_suggestion_verbose(
3467 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3468 "you might have meant to use `:` for type annotation",
3469 ": ",
3470 Applicability::MaybeIncorrect,
3471 );
3472 return true;
3473 }
3474 false
3475 }
3476
3477 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3478 let mut result = None;
3479 let mut seen_modules = FxHashSet::default();
3480 let mut worklist = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(self.r.graph_root.to_module(), ThinVec::new(), true)]))vec![(self.r.graph_root.to_module(), ThinVec::new(), true)];
3481
3482 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3483 if result.is_some() {
3485 break;
3486 }
3487
3488 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3489 if result.is_some() || !name_binding.vis().is_visible_locally() {
3491 return;
3492 }
3493 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3494 let mut path_segments = path_segments.clone();
3496 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3497 let doc_visible = doc_visible
3498 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3499 if module_def_id == def_id {
3500 let path = Path { span: name_binding.span, segments: path_segments };
3501 result = Some((
3502 r.expect_module(module_def_id),
3503 ImportSuggestion {
3504 did: Some(def_id),
3505 descr: "module",
3506 path,
3507 accessible: true,
3508 doc_visible,
3509 note: None,
3510 via_import: false,
3511 is_stable: true,
3512 },
3513 ));
3514 } else {
3515 if seen_modules.insert(module_def_id) {
3517 let module = r.expect_module(module_def_id);
3518 worklist.push((module, path_segments, doc_visible));
3519 }
3520 }
3521 }
3522 });
3523 }
3524
3525 result
3526 }
3527
3528 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3529 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3530 let mut variants = Vec::new();
3531 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3532 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3533 let mut segms = enum_import_suggestion.path.segments.clone();
3534 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3535 let path = Path { span: name_binding.span, segments: segms };
3536 variants.push((path, def_id, kind));
3537 }
3538 });
3539 variants
3540 })
3541 }
3542
3543 fn suggest_using_enum_variant(
3545 &self,
3546 err: &mut Diag<'_>,
3547 source: PathSource<'_, '_, '_>,
3548 def_id: DefId,
3549 span: Span,
3550 ) {
3551 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3552 err.note("you might have meant to use one of the enum's variants");
3553 return;
3554 };
3555
3556 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3561 PathSource::TupleStruct(..) => (None, true),
3563 PathSource::Expr(Some(expr)) => match &expr.kind {
3564 ExprKind::Call(..) => (None, true),
3566 ExprKind::MethodCall(MethodCall {
3569 receiver,
3570 span,
3571 seg: PathSegment { ident, .. },
3572 ..
3573 }) => {
3574 let dot_span = receiver.span.between(*span);
3575 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3576 *ctor_kind == CtorKind::Fn
3577 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3578 });
3579 (found_tuple_variant.then_some(dot_span), false)
3580 }
3581 ExprKind::Field(base, ident) => {
3584 let dot_span = base.span.between(ident.span);
3585 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3586 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3587 });
3588 (found_tuple_or_unit_variant.then_some(dot_span), false)
3589 }
3590 _ => (None, false),
3591 },
3592 _ => (None, false),
3593 };
3594
3595 if let Some(dot_span) = suggest_path_sep_dot_span {
3596 err.span_suggestion_verbose(
3597 dot_span,
3598 "use the path separator to refer to a variant",
3599 "::",
3600 Applicability::MaybeIncorrect,
3601 );
3602 } else if suggest_only_tuple_variants {
3603 let mut suggestable_variants = variant_ctors
3606 .iter()
3607 .filter(|(.., kind)| *kind == CtorKind::Fn)
3608 .map(|(variant, ..)| path_names_to_string(variant))
3609 .collect::<Vec<_>>();
3610 suggestable_variants.sort();
3611
3612 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3613
3614 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3615 "to match against"
3616 } else {
3617 "to construct"
3618 };
3619
3620 if !suggestable_variants.is_empty() {
3621 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3622 ::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")
3623 } else {
3624 ::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")
3625 };
3626
3627 err.span_suggestions(
3628 span,
3629 msg,
3630 suggestable_variants,
3631 Applicability::MaybeIncorrect,
3632 );
3633 }
3634
3635 if non_suggestable_variant_count == variant_ctors.len() {
3637 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}"));
3638 }
3639
3640 if non_suggestable_variant_count == 1 {
3642 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"));
3643 } else if non_suggestable_variant_count >= 1 {
3644 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!(
3645 "you might have meant {source_msg} one of the enum's non-tuple variants"
3646 ));
3647 }
3648 } else {
3649 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3650 let def_id = self.r.tcx.parent(ctor_def_id);
3651 match kind {
3652 CtorKind::Const => false,
3653 CtorKind::Fn => {
3654 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3655 }
3656 }
3657 };
3658
3659 let mut suggestable_variants = variant_ctors
3660 .iter()
3661 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3662 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3663 .map(|(variant, kind)| match kind {
3664 CtorKind::Const => variant,
3665 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3666 })
3667 .collect::<Vec<_>>();
3668 suggestable_variants.sort();
3669 let no_suggestable_variant = suggestable_variants.is_empty();
3670
3671 if !no_suggestable_variant {
3672 let msg = if suggestable_variants.len() == 1 {
3673 "you might have meant to use the following enum variant"
3674 } else {
3675 "you might have meant to use one of the following enum variants"
3676 };
3677
3678 err.span_suggestions(
3679 span,
3680 msg,
3681 suggestable_variants,
3682 Applicability::MaybeIncorrect,
3683 );
3684 }
3685
3686 let mut suggestable_variants_with_placeholders = variant_ctors
3687 .iter()
3688 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3689 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3690 .filter_map(|(variant, kind)| match kind {
3691 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3692 _ => None,
3693 })
3694 .collect::<Vec<_>>();
3695 suggestable_variants_with_placeholders.sort();
3696
3697 if !suggestable_variants_with_placeholders.is_empty() {
3698 let msg =
3699 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3700 (true, 1) => "the following enum variant is available",
3701 (true, _) => "the following enum variants are available",
3702 (false, 1) => "alternatively, the following enum variant is available",
3703 (false, _) => {
3704 "alternatively, the following enum variants are also available"
3705 }
3706 };
3707
3708 err.span_suggestions(
3709 span,
3710 msg,
3711 suggestable_variants_with_placeholders,
3712 Applicability::HasPlaceholders,
3713 );
3714 }
3715 };
3716
3717 if def_id.is_local() {
3718 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3719 }
3720 }
3721
3722 pub(crate) fn detect_and_suggest_const_parameter_error(
3753 &mut self,
3754 path: &[Segment],
3755 source: PathSource<'_, 'ast, 'ra>,
3756 ) -> Option<Diag<'tcx>> {
3757 let Some(item) = self.diag_metadata.current_item else { return None };
3758 let ItemKind::Impl(impl_) = &item.kind else { return None };
3759 let self_ty = &impl_.self_ty;
3760
3761 let [current_parameter] = path else {
3763 return None;
3764 };
3765
3766 let target_ident = current_parameter.ident;
3767
3768 let visitor = ParentPathVisitor::new(self_ty, target_ident);
3770
3771 let Some(parent_segment) = visitor.parent else {
3772 return None;
3773 };
3774
3775 let Some(args) = parent_segment.args.as_ref() else {
3776 return None;
3777 };
3778
3779 let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3780 return None;
3781 };
3782
3783 let usage_to_pos: FxHashMap<NodeId, usize> = angle
3786 .args
3787 .iter()
3788 .enumerate()
3789 .filter_map(|(pos, arg)| {
3790 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3791 && let TyKind::Path(_, path) = &ty.kind
3792 && let [segment] = path.segments.as_slice()
3793 {
3794 Some((segment.id, pos))
3795 } else {
3796 None
3797 }
3798 })
3799 .collect();
3800
3801 let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3804 return None;
3805 };
3806
3807 let ns = source.namespace();
3809 let segment = Segment::from(parent_segment);
3810 let segments = [segment];
3811 let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3812
3813 if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3814 &None,
3815 &segments,
3816 ns,
3817 source.defer_to_typeck(),
3818 finalize,
3819 source,
3820 ) && let Some(resolve) = resolve.full_res()
3821 && let Res::Def(_, def_id) = resolve
3822 && def_id.is_local()
3823 && let Some(local_def_id) = def_id.as_local()
3824 && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3825 && let Some(target_param) = &struct_generics.params.get(idx)
3826 && let GenericParamKind::Const { ty, .. } = &target_param.kind
3827 && let TyKind::Path(_, path) = &ty.kind
3828 {
3829 let full_type = path
3830 .segments
3831 .iter()
3832 .map(|seg| seg.ident.to_string())
3833 .collect::<Vec<_>>()
3834 .join("::");
3835
3836 let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3841 angle
3842 .args
3843 .iter()
3844 .find_map(|arg| {
3845 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3846 && let TyKind::Path(_, path) = &ty.kind
3847 && let [segment] = path.segments.as_slice()
3848 && segment.ident == impl_param.ident
3849 {
3850 usage_to_pos.get(&segment.id).copied()
3851 } else {
3852 None
3853 }
3854 })
3855 .is_some_and(|pos| pos > idx)
3856 });
3857
3858 let (insert_span, snippet) = match next_impl_param {
3859 Some(next_param) => {
3860 (
3863 next_param.span().shrink_to_lo(),
3864 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
full_type))
})format!("const {}: {}, ", target_ident, full_type),
3865 )
3866 }
3867 None => match impl_.generics.params.last() {
3868 Some(last) => {
3869 (
3872 last.span().shrink_to_hi(),
3873 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
full_type))
})format!(", const {}: {}", target_ident, full_type),
3874 )
3875 }
3876 None => {
3877 (
3880 impl_.generics.span.shrink_to_hi(),
3881 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
full_type))
})format!("<const {}: {}>", target_ident, full_type),
3882 )
3883 }
3884 },
3885 };
3886
3887 let mut err = self.r.dcx().struct_span_err(
3888 target_ident.span,
3889 ::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),
3890 );
3891
3892 err.code(E0425);
3893
3894 err.span_label(target_ident.span, "not found in this scope");
3895
3896 err.span_label(
3897 target_param.span(),
3898 ::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",),
3899 );
3900
3901 err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3902 span: insert_span,
3903 snippet,
3904 item_name: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", target_ident))
})format!("{}", target_ident),
3905 item_location: String::from("impl"),
3906 });
3907
3908 return Some(err);
3909 }
3910
3911 None
3912 }
3913
3914 pub(crate) fn suggest_adding_generic_parameter(
3915 &mut self,
3916 path: &[Segment],
3917 source: PathSource<'_, 'ast, 'ra>,
3918 ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3919 let (ident, span) = match path {
3920 [segment]
3921 if !segment.has_generic_args
3922 && segment.ident.name != kw::SelfUpper
3923 && segment.ident.name != kw::Dyn =>
3924 {
3925 (segment.ident.to_string(), segment.ident.span)
3926 }
3927 _ => return (None, None),
3928 };
3929 let mut iter = ident.chars().map(|c| c.is_uppercase());
3930 let single_uppercase_char =
3931 #[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);
3932 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3933 return (None, None);
3934 }
3935 match (
3936 self.diag_metadata.current_item,
3937 single_uppercase_char,
3938 self.diag_metadata.currently_processing_generic_args,
3939 ) {
3940 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
3941 }
3943 (Some(Item { span, .. }), _, _) if span.in_derive_expansion() => {
3944 return (None, None);
3945 }
3946 (
3947 Some(Item {
3948 kind:
3949 kind @ ItemKind::Fn(..)
3950 | kind @ ItemKind::Enum(..)
3951 | kind @ ItemKind::Struct(..)
3952 | kind @ ItemKind::Union(..),
3953 ..
3954 }),
3955 true,
3956 _,
3957 )
3958 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
3960 | (Some(Item { kind, .. }), false, _) => {
3961 if let Some(generics) = kind.generics() {
3962 if span.overlaps(generics.span) {
3963 return (None, None);
3972 }
3973
3974 let (msg, sugg) = match source {
3975 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
3976 if let Some(err) =
3977 self.detect_and_suggest_const_parameter_error(path, source)
3978 {
3979 return (None, Some(err));
3980 }
3981 ("you might be missing a type parameter", ident)
3982 }
3983 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
3984 "you might be missing a const parameter",
3985 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
3986 ),
3987 _ => return (None, None),
3988 };
3989 let (span, sugg) = if let [.., param] = &generics.params[..] {
3990 let span = if let [.., bound] = ¶m.bounds[..] {
3991 bound.span()
3992 } else if let GenericParam {
3993 kind: GenericParamKind::Const { ty, span: _, default },
3994 ..
3995 } = param
3996 {
3997 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
3998 } else {
3999 param.ident.span
4000 };
4001 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
4002 } else {
4003 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
4004 };
4005 if span.can_be_used_for_suggestions() {
4007 return (
4008 Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
4009 None,
4010 );
4011 }
4012 }
4013 }
4014 _ => {}
4015 }
4016 (None, None)
4017 }
4018
4019 pub(crate) fn suggestion_for_label_in_rib(
4022 &self,
4023 rib_index: usize,
4024 label: Ident,
4025 ) -> Option<LabelSuggestion> {
4026 let within_scope = self.is_label_valid_from_rib(rib_index);
4028
4029 let rib = &self.label_ribs[rib_index];
4030 let names = rib
4031 .bindings
4032 .iter()
4033 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
4034 .map(|(id, _)| id.name)
4035 .collect::<Vec<Symbol>>();
4036
4037 find_best_match_for_name(&names, label.name, None).map(|symbol| {
4038 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
4042 (*ident, within_scope)
4043 })
4044 }
4045
4046 pub(crate) fn maybe_report_lifetime_uses(
4047 &mut self,
4048 generics_span: Span,
4049 params: &[ast::GenericParam],
4050 ) {
4051 for (param_index, param) in params.iter().enumerate() {
4052 let GenericParamKind::Lifetime = param.kind else { continue };
4053
4054 let def_id = self.r.local_def_id(param.id);
4055
4056 let use_set = self.lifetime_uses.remove(&def_id);
4057 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4057",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4057u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
4058 "Use set for {:?}({:?} at {:?}) is {:?}",
4059 def_id, param.ident, param.ident.span, use_set
4060 );
4061
4062 let deletion_span = || {
4063 if params.len() == 1 {
4064 Some(generics_span)
4066 } else if param_index == 0 {
4067 match (
4070 param.span_with_attributes().find_ancestor_inside(generics_span),
4071 params[param_index + 1]
4072 .span_with_attributes()
4073 .find_ancestor_inside(generics_span),
4074 ) {
4075 (Some(param_span), Some(next_param_span)) => {
4076 Some(param_span.to(next_param_span.shrink_to_lo()))
4077 }
4078 _ => None,
4079 }
4080 } else {
4081 match (
4084 param.span_with_attributes().find_ancestor_inside(generics_span),
4085 params[param_index - 1]
4086 .span_with_attributes()
4087 .find_ancestor_inside(generics_span),
4088 ) {
4089 (Some(param_span), Some(prev_param_span)) => {
4090 Some(prev_param_span.shrink_to_hi().to(param_span))
4091 }
4092 _ => None,
4093 }
4094 }
4095 };
4096 match use_set {
4097 Some(LifetimeUseSet::Many) => {}
4098 Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
4101 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
4102 let param_ident = param.ident;
4103 let deletion_span =
4104 if param.bounds.is_empty() { deletion_span() } else { None };
4105 self.r.lint_buffer.dyn_buffer_lint_any(
4106 SINGLE_USE_LIFETIMES,
4107 param.id,
4108 param_ident.span,
4109 move |dcx, level, sess| {
4110 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4110",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4110u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_ident")
}> =
::tracing::__macro_support::FieldName::new("param_ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_ident.span")
}> =
::tracing::__macro_support::FieldName::new("param_ident.span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_span")
}> =
::tracing::__macro_support::FieldName::new("use_span");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_ident.span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?param_ident, ?param_ident.span, ?use_span);
4111
4112 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
4113 let suggestion = if let Some(deletion_span) = deletion_span {
4114 let (use_span, replace_lt) = if elidable {
4115 let use_span = sess
4116 .downcast_ref::<Session>()
4117 .expect("expected a `Session`")
4118 .source_map()
4119 .span_extend_while_whitespace(use_span);
4120 (use_span, String::new())
4121 } else {
4122 (use_span, "'_".to_owned())
4123 };
4124 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4124",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4124u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("deletion_span")
}> =
::tracing::__macro_support::FieldName::new("deletion_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("use_span")
}> =
::tracing::__macro_support::FieldName::new("use_span");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&deletion_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&use_span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?deletion_span, ?use_span);
4125
4126 let deletion_span = if deletion_span.is_empty() {
4129 None
4130 } else {
4131 Some(deletion_span)
4132 };
4133 Some(diagnostics::SingleUseLifetimeSugg {
4134 deletion_span,
4135 use_span,
4136 replace_lt,
4137 })
4138 } else {
4139 None
4140 };
4141 diagnostics::SingleUseLifetime {
4142 suggestion,
4143 param_span: param_ident.span,
4144 use_span,
4145 ident: param_ident,
4146 }
4147 .into_diag(dcx, level)
4148 },
4149 );
4150 }
4151 None => {
4152 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4152",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4152u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param.ident")
}> =
::tracing::__macro_support::FieldName::new("param.ident");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param.ident.span")
}> =
::tracing::__macro_support::FieldName::new("param.ident.span");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m.ident)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m.ident.span)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?param.ident, ?param.ident.span);
4153 let deletion_span = deletion_span();
4154
4155 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
4157 self.r.lint_buffer.buffer_lint(
4158 UNUSED_LIFETIMES,
4159 param.id,
4160 param.ident.span,
4161 diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
4162 );
4163 }
4164 }
4165 }
4166 }
4167 }
4168
4169 pub(crate) fn emit_undeclared_lifetime_error(
4170 &self,
4171 lifetime_ref: &ast::Lifetime,
4172 outer_lifetime_ref: Option<Ident>,
4173 ) -> ErrorGuaranteed {
4174 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);
4175 let mut err = if let Some(outer) = outer_lifetime_ref {
4176 {
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!(
4177 self.r.dcx(),
4178 lifetime_ref.ident.span,
4179 E0401,
4180 "can't use generic parameters from outer item",
4181 )
4182 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
4183 .with_span_label(outer.span, "lifetime parameter from outer item")
4184 } else {
4185 {
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!(
4186 self.r.dcx(),
4187 lifetime_ref.ident.span,
4188 E0261,
4189 "use of undeclared lifetime name `{}`",
4190 lifetime_ref.ident
4191 )
4192 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
4193 };
4194
4195 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
4197 err.span_suggestion_verbose(
4198 lifetime_ref.ident.span,
4199 "you may have misspelled the `'static` lifetime",
4200 "'static",
4201 Applicability::MachineApplicable,
4202 );
4203 } else {
4204 self.suggest_introducing_lifetime(
4205 &mut err,
4206 Some(lifetime_ref.ident),
4207 |err, _, span, message, suggestion, span_suggs| {
4208 err.multipart_suggestion(
4209 message,
4210 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
4211 Applicability::MaybeIncorrect,
4212 );
4213 true
4214 },
4215 );
4216 }
4217
4218 err.emit_err()
4219 }
4220
4221 fn suggest_introducing_lifetime(
4222 &self,
4223 err: &mut Diag<'_>,
4224 name: Option<Ident>,
4225 suggest: impl Fn(
4226 &mut Diag<'_>,
4227 bool,
4228 Span,
4229 Cow<'static, str>,
4230 String,
4231 Vec<(Span, String)>,
4232 ) -> bool,
4233 ) {
4234 self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
4235 }
4236
4237 pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
4238 &self,
4239 err: &mut Diag<'_>,
4240 lifetime: Span,
4241 ) {
4242 self.suggest_introducing_lifetime_filtered(
4243 err,
4244 None,
4245 |kind| {
4246 !#[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
4247 kind,
4248 LifetimeBinderKind::FnPtrType
4249 | LifetimeBinderKind::PolyTrait
4250 | LifetimeBinderKind::WhereBound
4251 )
4252 },
4253 |err, _higher_ranked, span, message, intro_sugg, _| {
4254 err.multipart_suggestion(
4255 message,
4256 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())]))vec![(span, intro_sugg), (lifetime.shrink_to_hi(), "'a ".to_string())],
4257 Applicability::MaybeIncorrect,
4258 );
4259 false
4260 },
4261 );
4262 }
4263
4264 fn suggest_introducing_lifetime_filtered(
4265 &self,
4266 err: &mut Diag<'_>,
4267 name: Option<Ident>,
4268 mut consider: impl FnMut(LifetimeBinderKind) -> bool,
4269 suggest: impl Fn(
4270 &mut Diag<'_>,
4271 bool,
4272 Span,
4273 Cow<'static, str>,
4274 String,
4275 Vec<(Span, String)>,
4276 ) -> bool,
4277 ) {
4278 let mut suggest_note = true;
4279 for rib in self.lifetime_ribs.iter().rev() {
4280 let mut should_continue = true;
4281 match rib.kind {
4282 LifetimeRibKind::Generics { binder, span, kind } => {
4283 if let LifetimeBinderKind::ConstItem = kind
4286 && !self.r.tcx().features().generic_const_items()
4287 {
4288 continue;
4289 }
4290 if #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::ImplAssocType => true,
_ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
4291 continue;
4292 }
4293
4294 if !span.can_be_used_for_suggestions()
4295 && suggest_note
4296 && let Some(name) = name
4297 {
4298 suggest_note = false; err.span_label(
4300 span,
4301 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
4302 "lifetime `{name}` is missing in item created through this procedural macro",
4303 ),
4304 );
4305 continue;
4306 }
4307
4308 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
4309 kind,
4310 LifetimeBinderKind::FnPtrType
4311 | LifetimeBinderKind::PolyTrait
4312 | LifetimeBinderKind::WhereBound
4313 );
4314
4315 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
4316 let (span, sugg) = if span.is_empty() {
4317 let mut binder_idents: FxIndexSet<Ident> = Default::default();
4318 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
4319
4320 if let LifetimeBinderKind::WhereBound = kind
4327 && let Some(predicate) = self.diag_metadata.current_where_predicate
4328 && let ast::WherePredicateKind::BoundPredicate(
4329 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
4330 ) = &predicate.kind
4331 && bounded_ty.id == binder
4332 {
4333 for bound in bounds {
4334 if let ast::GenericBound::Trait(poly_trait_ref) = bound
4335 && let span = poly_trait_ref
4336 .span
4337 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
4338 && !span.is_empty()
4339 {
4340 rm_inner_binders.insert(span);
4341 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
4342 binder_idents.insert(v.ident);
4343 });
4344 }
4345 }
4346 }
4347
4348 let binders_sugg: String = binder_idents
4349 .into_iter()
4350 .map(|ident| ident.to_string())
4351 .intersperse(", ".to_owned())
4352 .collect();
4353 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!(
4354 "{}<{}>{}",
4355 if higher_ranked { "for" } else { "" },
4356 binders_sugg,
4357 if higher_ranked { " " } else { "" },
4358 );
4359 (span, sugg)
4360 } else {
4361 let span = self
4362 .r
4363 .tcx
4364 .sess
4365 .source_map()
4366 .span_through_char(span, '<')
4367 .shrink_to_hi();
4368 let sugg =
4369 ::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"));
4370 (span, sugg)
4371 };
4372
4373 if higher_ranked {
4374 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!(
4375 "consider making the {} lifetime-generic with a new `{}` lifetime",
4376 kind.descr(),
4377 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
4378 ));
4379 should_continue = suggest(
4380 err,
4381 true,
4382 span,
4383 message,
4384 sugg,
4385 if !rm_inner_binders.is_empty() {
4386 rm_inner_binders
4387 .into_iter()
4388 .map(|v| (v, "".to_string()))
4389 .collect::<Vec<_>>()
4390 } else {
4391 ::alloc::vec::Vec::new()vec![]
4392 },
4393 );
4394 err.note_once(
4395 "for more information on higher-ranked polymorphism, visit \
4396 https://doc.rust-lang.org/nomicon/hrtb.html",
4397 );
4398 } else if let Some(name) = name {
4399 let message =
4400 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
4401 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4402 } else {
4403 let message = Cow::from("consider introducing a named lifetime parameter");
4404 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4405 }
4406 }
4407 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
4408 _ => {}
4409 }
4410 if !should_continue {
4411 break;
4412 }
4413 }
4414 }
4415
4416 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
4417 &self,
4418 lifetime_ref: &ast::Lifetime,
4419 ) -> ErrorGuaranteed {
4420 self.r.dcx().emit_err(diagnostics::ParamInTyOfConstParam {
4421 span: lifetime_ref.ident.span,
4422 name: lifetime_ref.ident.name,
4423 })
4424 }
4425
4426 pub(crate) fn emit_forbidden_non_static_lifetime_error(
4430 &self,
4431 cause: NoConstantGenericsReason,
4432 lifetime_ref: &ast::Lifetime,
4433 ) -> ErrorGuaranteed {
4434 match cause {
4435 NoConstantGenericsReason::IsEnumDiscriminant => {
4436 self.r.dcx().emit_err(diagnostics::ParamInEnumDiscriminant {
4437 span: lifetime_ref.ident.span,
4438 name: lifetime_ref.ident.name,
4439 param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
4440 })
4441 }
4442 NoConstantGenericsReason::NonTrivialConstArg => {
4443 if !!self.r.features.generic_const_exprs() {
::core::panicking::panic("assertion failed: !self.r.features.generic_const_exprs()")
};assert!(!self.r.features.generic_const_exprs());
4444 self.r.dcx().emit_err(diagnostics::ParamInNonTrivialAnonConst {
4445 span: lifetime_ref.ident.span,
4446 name: lifetime_ref.ident.name,
4447 param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
4448 help: self.r.tcx.sess.is_nightly_build() && !self.r.features.gca(),
4449 is_gca_const_items: self.r.features.gca_const_items(),
4450 help_gca: self.r.features.gca_const_items(),
4451 help_suggest_gca: self.r.tcx.sess.is_nightly_build()
4452 && !self.r.features.gca_const_items(),
4453 })
4454 }
4455 }
4456 }
4457
4458 pub(crate) fn report_missing_lifetime_specifiers<'a>(
4459 &mut self,
4460 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4461 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4462 ) -> ErrorGuaranteed {
4463 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4464 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4465
4466 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!(
4467 self.r.dcx(),
4468 spans,
4469 E0106,
4470 "missing lifetime specifier{}",
4471 pluralize!(num_lifetimes)
4472 );
4473 self.add_missing_lifetime_specifiers_label(
4474 &mut err,
4475 lifetime_refs,
4476 function_param_lifetimes,
4477 );
4478 err.emit_err()
4479 }
4480
4481 fn add_missing_lifetime_specifiers_label<'a>(
4482 &mut self,
4483 err: &mut Diag<'_>,
4484 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4485 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4486 ) {
4487 for < in lifetime_refs.clone() {
4488 err.span_label(
4489 lt.span,
4490 ::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!(
4491 "expected {} lifetime parameter{}",
4492 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4493 pluralize!(lt.count),
4494 ),
4495 );
4496 }
4497
4498 let mut in_scope_lifetimes: Vec<_> = self
4499 .lifetime_ribs
4500 .iter()
4501 .rev()
4502 .take_while(|rib| {
4503 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4504 })
4505 .flat_map(|rib| rib.bindings.iter())
4506 .map(|(&ident, &res)| (ident, res))
4507 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4508 .collect();
4509 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4509",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4509u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("in_scope_lifetimes")
}> =
::tracing::__macro_support::FieldName::new("in_scope_lifetimes");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&in_scope_lifetimes)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?in_scope_lifetimes);
4510
4511 let mut maybe_static = false;
4512 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4512",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4512u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("function_param_lifetimes")
}> =
::tracing::__macro_support::FieldName::new("function_param_lifetimes");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&function_param_lifetimes)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?function_param_lifetimes);
4513 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4514 let elided_len = param_lifetimes.len();
4515 let num_params = params.len();
4516
4517 let mut m = String::new();
4518
4519 for (i, info) in params.iter().enumerate() {
4520 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4521 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);
4522
4523 err.span_label(span, "");
4524
4525 if i != 0 {
4526 if i + 1 < num_params {
4527 m.push_str(", ");
4528 } else if num_params == 2 {
4529 m.push_str(" or ");
4530 } else {
4531 m.push_str(", or ");
4532 }
4533 }
4534
4535 let help_name = if let Some(ident) = ident {
4536 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
4537 } else {
4538 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
4539 };
4540
4541 if lifetime_count == 1 {
4542 m.push_str(&help_name[..])
4543 } else {
4544 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")[..])
4545 }
4546 }
4547
4548 if num_params == 0 {
4549 err.help(
4550 "this function's return type contains a borrowed value, but there is no value \
4551 for it to be borrowed from",
4552 );
4553 if in_scope_lifetimes.is_empty() {
4554 maybe_static = true;
4555 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![(
4556 Ident::with_dummy_span(kw::StaticLifetime),
4557 (DUMMY_NODE_ID, LifetimeRes::Static),
4558 )];
4559 }
4560 } else if elided_len == 0 {
4561 err.help(
4562 "this function's return type contains a borrowed value with an elided \
4563 lifetime, but the lifetime cannot be derived from the arguments",
4564 );
4565 if in_scope_lifetimes.is_empty() {
4566 maybe_static = true;
4567 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![(
4568 Ident::with_dummy_span(kw::StaticLifetime),
4569 (DUMMY_NODE_ID, LifetimeRes::Static),
4570 )];
4571 }
4572 } else if num_params == 1 {
4573 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!(
4574 "this function's return type contains a borrowed value, but the signature does \
4575 not say which {m} it is borrowed from",
4576 ));
4577 } else {
4578 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!(
4579 "this function's return type contains a borrowed value, but the signature does \
4580 not say whether it is borrowed from {m}",
4581 ));
4582 }
4583 }
4584
4585 #[allow(rustc::symbol_intern_string_literal)]
4586 let existing_name = match &in_scope_lifetimes[..] {
4587 [] => Symbol::intern("'a"),
4588 [(existing, _)] => existing.name,
4589 _ => Symbol::intern("'lifetime"),
4590 };
4591
4592 let mut spans_suggs: Vec<_> = Vec::new();
4593 let source_map = self.r.tcx.sess.source_map();
4594 let build_sugg = |lt: MissingLifetime| match lt.kind {
4595 MissingLifetimeKind::Underscore => {
4596 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);
4597 (lt.span, existing_name.to_string())
4598 }
4599 MissingLifetimeKind::Ampersand => {
4600 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);
4601 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
4602 }
4603 MissingLifetimeKind::Comma => {
4604 let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4605 .intersperse(", ")
4606 .collect();
4607 let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4608 let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", sugg))
})format!("{sugg}, ") };
4609 (lt.span.shrink_to_hi(), sugg)
4610 }
4611 MissingLifetimeKind::Brackets => {
4612 let sugg: String = std::iter::once("<")
4613 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4614 .chain([">"])
4615 .collect();
4616 (lt.span.shrink_to_hi(), sugg)
4617 }
4618 };
4619 for < in lifetime_refs.clone() {
4620 spans_suggs.push(build_sugg(lt));
4621 }
4622 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs:4622",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4622u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("spans_suggs")
}> =
::tracing::__macro_support::FieldName::new("spans_suggs");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&spans_suggs)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?spans_suggs);
4623 match in_scope_lifetimes.len() {
4624 0 => {
4625 if let Some((param_lifetimes, _)) = function_param_lifetimes {
4626 for lt in param_lifetimes {
4627 spans_suggs.push(build_sugg(lt))
4628 }
4629 }
4630 self.suggest_introducing_lifetime(
4631 err,
4632 None,
4633 |err, higher_ranked, span, message, intro_sugg, _| {
4634 err.multipart_suggestion(
4635 message,
4636 std::iter::once((span, intro_sugg))
4637 .chain(spans_suggs.clone())
4638 .collect(),
4639 Applicability::MaybeIncorrect,
4640 );
4641 higher_ranked
4642 },
4643 );
4644 }
4645 1 => {
4646 let post = if maybe_static {
4647 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4648 let owned = if let Some(lt) = lifetime_refs.next()
4649 && lifetime_refs.next().is_none()
4650 && lt.kind != MissingLifetimeKind::Ampersand
4651 {
4652 ", or if you will only have owned values"
4653 } else {
4654 ""
4655 };
4656 ::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!(
4657 ", but this is uncommon unless you're returning a borrowed value from a \
4658 `const` or a `static`{owned}",
4659 )
4660 } else {
4661 String::new()
4662 };
4663 err.multipart_suggestion(
4664 ::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}"),
4665 spans_suggs,
4666 Applicability::MaybeIncorrect,
4667 );
4668 if maybe_static {
4669 let mut lifetime_refs = lifetime_refs.into_iter();
4675 if let Some(lt) = lifetime_refs.next()
4676 && lifetime_refs.next().is_none()
4677 && (lt.kind == MissingLifetimeKind::Ampersand
4678 || lt.kind == MissingLifetimeKind::Underscore)
4679 {
4680 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4681 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4682 && !sig.decl.inputs.is_empty()
4683 && let sugg = sig
4684 .decl
4685 .inputs
4686 .iter()
4687 .filter_map(|param| {
4688 if param.ty.span.contains(lt.span) {
4689 None
4692 } else if let TyKind::CVarArgs = param.ty.kind {
4693 None
4695 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
4696 None
4698 } else {
4699 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4700 }
4701 })
4702 .collect::<Vec<_>>()
4703 && !sugg.is_empty()
4704 {
4705 let (the, s) = if sig.decl.inputs.len() == 1 {
4706 ("the", "")
4707 } else {
4708 ("one of the", "s")
4709 };
4710 let dotdotdot =
4711 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4712 err.multipart_suggestion(
4713 ::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!(
4714 "instead, you are more likely to want to change {the} \
4715 argument{s} to be borrowed{dotdotdot}",
4716 ),
4717 sugg,
4718 Applicability::MaybeIncorrect,
4719 );
4720 "...or alternatively, you might want"
4721 } else if (lt.kind == MissingLifetimeKind::Ampersand
4722 || lt.kind == MissingLifetimeKind::Underscore)
4723 && let Some((kind, _span)) = self.diag_metadata.current_function
4724 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4725 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4726 && !sig.decl.inputs.is_empty()
4727 && let arg_refs = sig
4728 .decl
4729 .inputs
4730 .iter()
4731 .filter_map(|param| match ¶m.ty.kind {
4732 TyKind::ImplTrait(_, bounds) => Some(bounds),
4733 _ => None,
4734 })
4735 .flat_map(|bounds| bounds.into_iter())
4736 .collect::<Vec<_>>()
4737 && !arg_refs.is_empty()
4738 {
4739 let mut lt_finder =
4745 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4746 for bound in arg_refs {
4747 if let ast::GenericBound::Trait(trait_ref) = bound {
4748 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4749 }
4750 }
4751 lt_finder.visit_ty(ret_ty);
4752 let spans_suggs: Vec<_> = lt_finder
4753 .seen
4754 .iter()
4755 .filter_map(|ty| match &ty.kind {
4756 TyKind::Ref(_, inner_ty, _) => {
4757 let span = ty.span.with_hi(inner_ty.span.lo());
4758 Some((span, "&'a ".to_string()))
4759 }
4760 _ => None,
4761 })
4762 .collect();
4763 self.suggest_introducing_lifetime(
4764 err,
4765 None,
4766 |err, higher_ranked, span, message, intro_sugg, _| {
4767 err.multipart_suggestion(
4768 message,
4769 std::iter::once((span, intro_sugg))
4770 .chain(spans_suggs.clone())
4771 .collect(),
4772 Applicability::MaybeIncorrect,
4773 );
4774 higher_ranked
4775 },
4776 );
4777 "alternatively, you might want"
4778 } else {
4779 "instead, you are more likely to want"
4780 };
4781 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4782 let mut sugg_slice_to_vec_or_string = false;
4783 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())];
4784 if let Some((kind, _span)) = self.diag_metadata.current_function
4785 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4786 {
4787 let mut lt_finder =
4788 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4789 for param in &sig.decl.inputs {
4790 lt_finder.visit_ty(¶m.ty);
4791 }
4792 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4793 lt_finder.visit_ty(ret_ty);
4794 let mut ret_lt_finder =
4795 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4796 ret_lt_finder.visit_ty(ret_ty);
4797 if let [Ty { span, kind: TyKind::Ref(_, inner_ty, _), .. }] =
4798 &ret_lt_finder.seen[..]
4799 {
4800 sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.with_hi(inner_ty.span.lo()), String::new())]))vec![(span.with_hi(inner_ty.span.lo()), String::new())];
4806 owned_sugg = true;
4807 }
4808 }
4809 if let Some(ty) = lt_finder.found {
4810 if let TyKind::Path(None, path) = &ty.kind {
4811 let path: Vec<_> = Segment::from_path(path);
4813 match self.resolve_path(
4814 &path,
4815 Some(TypeNS),
4816 None,
4817 PathSource::Type,
4818 ) {
4819 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4820 match module.res() {
4821 Some(Res::PrimTy(PrimTy::Str)) => {
4822 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![(
4824 lt.span.with_hi(ty.span.hi()),
4825 "String".to_string(),
4826 )];
4827 sugg_slice_to_vec_or_string = true;
4828 }
4829 Some(Res::PrimTy(..)) => {}
4830 Some(Res::Def(
4831 DefKind::Struct
4832 | DefKind::Union
4833 | DefKind::Enum
4834 | DefKind::ForeignTy
4835 | DefKind::AssocTy
4836 | DefKind::OpaqueTy
4837 | DefKind::TyParam,
4838 _,
4839 )) => {}
4840 _ => {
4841 owned_sugg = false;
4843 }
4844 }
4845 }
4846 PathResult::NonModule(res) => {
4847 match res.base_res() {
4848 Res::PrimTy(PrimTy::Str) => {
4849 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![(
4851 lt.span.with_hi(ty.span.hi()),
4852 "String".to_string(),
4853 )];
4854 sugg_slice_to_vec_or_string = true;
4855 }
4856 Res::PrimTy(..) => {}
4857 Res::Def(
4858 DefKind::Struct
4859 | DefKind::Union
4860 | DefKind::Enum
4861 | DefKind::ForeignTy
4862 | DefKind::AssocTy
4863 | DefKind::OpaqueTy
4864 | DefKind::TyParam,
4865 _,
4866 ) => {}
4867 _ => {
4868 owned_sugg = false;
4870 }
4871 }
4872 }
4873 _ => {
4874 owned_sugg = false;
4876 }
4877 }
4878 }
4879 if let TyKind::Slice(inner_ty) = &ty.kind {
4880 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![
4882 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4883 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4884 ];
4885 sugg_slice_to_vec_or_string = true;
4886 }
4887 }
4888 }
4889 if owned_sugg {
4890 if let Some(span) =
4892 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4893 && !sugg_slice_to_vec_or_string
4894 {
4895 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())];
4896 }
4897 err.multipart_suggestion(
4898 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4899 sugg,
4900 Applicability::MaybeIncorrect,
4901 );
4902 }
4903 }
4904 }
4905 }
4906 _ => {
4907 let lifetime_spans: Vec<_> =
4908 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4909 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4910
4911 if spans_suggs.len() > 0 {
4912 err.multipart_suggestion(
4915 "consider using one of the available lifetimes here",
4916 spans_suggs,
4917 Applicability::HasPlaceholders,
4918 );
4919 }
4920 }
4921 }
4922 }
4923
4924 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4925 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4926 if let Some(item) = self.diag_metadata.current_item {
4927 finder.visit_item(item);
4928 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4929 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4930 {
4931 for param in &sig.decl.inputs {
4932 finder.visit_ty(¶m.ty);
4933 }
4934 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4935 finder.visit_ty(ret_ty);
4936 }
4937 }
4938 finder.span
4939 }
4940}
4941
4942fn mk_where_bound_predicate(
4943 path: &Path,
4944 poly_trait_ref: &ast::PolyTraitRef,
4945 ty: &Ty,
4946) -> Option<ast::WhereBoundPredicate> {
4947 let modified_segments = {
4948 let mut segments = path.segments.clone();
4949 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
4950 return None;
4951 };
4952 let mut segments = ThinVec::from(preceding);
4953
4954 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
4955 id: DUMMY_NODE_ID,
4956 ident: last.ident,
4957 gen_args: None,
4958 kind: ast::AssocItemConstraintKind::Equality {
4959 term: ast::Term::Ty(Box::new(ast::Ty {
4960 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
4961 id: DUMMY_NODE_ID,
4962 span: DUMMY_SP,
4963 })),
4964 },
4965 span: DUMMY_SP,
4966 });
4967
4968 match second_last.args.as_deref_mut() {
4969 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
4970 args.push(added_constraint);
4971 }
4972 Some(_) => return None,
4973 None => {
4974 second_last.args =
4975 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
4976 args: ThinVec::from([added_constraint]),
4977 span: DUMMY_SP,
4978 })));
4979 }
4980 }
4981
4982 segments.push(second_last.clone());
4983 segments
4984 };
4985
4986 let new_where_bound_predicate = ast::WhereBoundPredicate {
4987 bound_generic_params: ThinVec::new(),
4988 bounded_ty: Box::new(ty.clone()),
4989 bounds: {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(ast::GenericBound::Trait(ast::PolyTraitRef {
bound_generic_params: ThinVec::new(),
modifiers: ast::TraitBoundModifiers::NONE,
trait_ref: ast::TraitRef {
path: ast::Path {
segments: modified_segments,
span: DUMMY_SP,
},
ref_id: DUMMY_NODE_ID,
},
span: DUMMY_SP,
parens: ast::Parens::No,
}));
vec
}thin_vec![ast::GenericBound::Trait(ast::PolyTraitRef {
4990 bound_generic_params: ThinVec::new(),
4991 modifiers: ast::TraitBoundModifiers::NONE,
4992 trait_ref: ast::TraitRef {
4993 path: ast::Path { segments: modified_segments, span: DUMMY_SP },
4994 ref_id: DUMMY_NODE_ID,
4995 },
4996 span: DUMMY_SP,
4997 parens: ast::Parens::No,
4998 })],
4999 };
5000
5001 Some(new_where_bound_predicate)
5002}
5003
5004pub(super) fn signal_lifetime_shadowing(
5006 sess: &Session,
5007 orig: Ident,
5008 shadower: Ident,
5009) -> ErrorGuaranteed {
5010 {
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!(
5011 sess.dcx(),
5012 shadower.span,
5013 E0496,
5014 "lifetime name `{}` shadows a lifetime name that is already in scope",
5015 orig.name,
5016 )
5017 .with_span_label(orig.span, "first declared here")
5018 .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))
5019 .emit_err()
5020}
5021
5022struct LifetimeFinder<'ast> {
5023 lifetime: Span,
5024 found: Option<&'ast Ty>,
5025 seen: Vec<&'ast Ty>,
5026}
5027
5028impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
5029 fn visit_ty(&mut self, t: &'ast Ty) {
5030 if let TyKind::Ref(_, ty, _) | TyKind::PinnedRef(_, ty, _) = &t.kind {
5031 self.seen.push(t);
5032 if t.span.lo() == self.lifetime.lo() {
5033 self.found = Some(ty);
5034 }
5035 }
5036 walk_ty(self, t)
5037 }
5038}
5039
5040struct RefPrefixSpanFinder {
5041 lifetime: Span,
5042 span: Option<Span>,
5043}
5044
5045impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
5046 fn visit_ty(&mut self, t: &'ast Ty) {
5047 if self.span.is_some() {
5048 return;
5049 }
5050 if let TyKind::Ref(_, inner_ty, _) | TyKind::PinnedRef(_, inner_ty, _) = &t.kind
5051 && t.span.lo() == self.lifetime.lo()
5052 {
5053 self.span = Some(t.span.with_hi(inner_ty.span.lo()));
5054 return;
5055 }
5056 walk_ty(self, t);
5057 }
5058}
5059
5060pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
5063 let name = shadower.name;
5064 let shadower = shadower.span;
5065 sess.dcx()
5066 .struct_span_warn(
5067 shadower,
5068 ::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"),
5069 )
5070 .with_span_label(orig, "first declared here")
5071 .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"))
5072 .emit();
5073}
5074
5075struct ParentPathVisitor<'a> {
5076 target: Ident,
5077 parent: Option<&'a PathSegment>,
5078 stack: Vec<&'a Ty>,
5079}
5080
5081impl<'a> ParentPathVisitor<'a> {
5082 fn new(self_ty: &'a Ty, target: Ident) -> Self {
5083 let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
5084
5085 v.visit_ty(self_ty);
5086 v
5087 }
5088}
5089
5090impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
5091 fn visit_ty(&mut self, ty: &'a Ty) {
5092 if self.parent.is_some() {
5093 return;
5094 }
5095
5096 self.stack.push(ty);
5098
5099 if let TyKind::Path(_, path) = &ty.kind
5100 && let [segment] = path.segments.as_slice()
5102 && segment.ident == self.target
5103 && let [.., parent_ty, _ty] = self.stack.as_slice()
5105 && let TyKind::Path(_, parent_path) = &parent_ty.kind
5106 {
5107 self.parent = parent_path.segments.first();
5108 }
5109
5110 walk_ty(self, ty);
5111
5112 self.stack.pop();
5113 }
5114}