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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
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]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_fields_finish(f,
"BaseError msg fallback_label span span_label could_be_expr suggestion module notes",
&[&self.msg, &self.fallback_label, &self.span, &self.span_label,
&self.could_be_expr, &self.suggestion, &self.module,
&&self.notes])
}
}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]
#[rustc_trivial_field_reads]
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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:422",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:423",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/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/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:1690",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/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 call_span = *span;
2645 let source_map = this.r.tcx.sess.source_map();
2646 let path_span = path.span;
2647
2648 let arg_spans: Option<Vec<_>> = args
2652 .iter()
2653 .map(|arg| arg.span.find_ancestor_inside_same_ctxt(call_span))
2654 .collect();
2655
2656 if !call_span.in_external_macro(source_map)
2657 && call_span.contains(path_span)
2658 && path_span.ctxt() == call_span.ctxt()
2659 && let Some(arg_spans) = arg_spans
2660 {
2661 let first_arg = arg_spans[0];
2662 let last_arg = arg_spans[arg_spans.len() - 1];
2663 let ordered_args =
2664 arg_spans.windows(2).all(|pair| pair[0].hi() <= pair[1].lo());
2665
2666 if !path_span.is_empty()
2671 && arg_spans.iter().all(|arg| !arg.is_empty())
2672 && path_span.hi() < first_arg.lo()
2673 && ordered_args
2674 && last_arg.hi() < call_span.hi()
2675 {
2676 let can_use_shorthand = |field: &rustc_span::Ident,
2677 arg: &rustc_ast::Expr,
2678 span: rustc_span::Span| {
2679 let rustc_ast::ExprKind::Path(None, path) = &arg.kind else {
2680 return false;
2681 };
2682
2683 let Some(ident) = path.as_single_argless_ident() else {
2684 return false;
2685 };
2686
2687 ident.name == field.name
2688 && source_map
2689 .span_to_snippet(span)
2690 .is_ok_and(|snippet| snippet == field.to_string())
2691 };
2692
2693 let mut parts = Vec::new();
2694
2695 let opening =
2696 if can_use_shorthand(&fields[0], &args[0], first_arg) {
2697 " { ".to_owned()
2698 } else {
2699 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0}: ", fields[0]))
})format!(" {{ {}: ", fields[0])
2700 };
2701
2702 parts
2703 .push((path_span.shrink_to_hi().until(first_arg), opening));
2704
2705 for ((field, arg), &arg_span) in
2706 fields.iter().zip(args.iter()).zip(arg_spans.iter()).skip(1)
2707 {
2708 if !can_use_shorthand(field, arg, arg_span) {
2709 parts.push((
2710 arg_span.shrink_to_lo(),
2711 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", field))
})format!("{field}: "),
2712 ));
2713 }
2714 }
2715
2716 parts.push((
2717 last_arg.shrink_to_hi().until(call_span.shrink_to_hi()),
2718 " }".to_owned(),
2719 ));
2720
2721 err.multipart_suggestion(
2722 ::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"),
2723 parts,
2724 applicability,
2725 );
2726 }
2727 }
2728 } else {
2729 let (fields, applicability) = match fields {
2730 Some(fields) => {
2731 let fields = if let Some(old_fields) = old_fields {
2732 fields
2733 .iter()
2734 .enumerate()
2735 .map(|(idx, new)| (new, old_fields.get(idx)))
2736 .map(|(new, old)| {
2737 if let Some(Some(old)) = old
2738 && new.as_str() != old
2739 {
2740 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", new, old))
})format!("{new}: {old}")
2741 } else {
2742 new.to_string()
2743 }
2744 })
2745 .collect::<Vec<String>>()
2746 } else {
2747 fields
2748 .iter()
2749 .map(|f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", f, tail))
})format!("{f}{tail}"))
2750 .collect::<Vec<String>>()
2751 };
2752
2753 (fields.join(", "), applicability)
2754 }
2755 None => {
2756 ("/* fields */".to_string(), Applicability::HasPlaceholders)
2757 }
2758 };
2759 let pad = if has_fields { " " } else { "" };
2760 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}}}");
2761 if !this.suggest_named_format_argument(
2762 err,
2763 source,
2764 path.last().unwrap().ident,
2765 &expression,
2766 applicability,
2767 ) {
2768 err.span_suggestion_verbose(
2769 span,
2770 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use struct {0} syntax instead",
descr))
})format!("use struct {descr} syntax instead"),
2771 expression,
2772 applicability,
2773 );
2774 }
2775 }
2776 }
2777 if let PathSource::Expr(Some(Expr {
2778 kind: ExprKind::Call(path, args),
2779 span: call_span,
2780 ..
2781 })) = source
2782 {
2783 this.suggest_alternative_construction_methods(
2784 def_id,
2785 err,
2786 path.span,
2787 *call_span,
2788 &args[..],
2789 );
2790 }
2791 }
2792 _ => {
2793 err.span_label(span, fallback_label.to_string());
2794 }
2795 }
2796 };
2797
2798 match (res, source) {
2799 (
2800 Res::Def(DefKind::Macro(kinds), def_id),
2801 PathSource::Expr(Some(Expr {
2802 kind: ExprKind::Index(..) | ExprKind::Call(..), ..
2803 }))
2804 | PathSource::Struct(_),
2805 ) if kinds.contains(MacroKinds::BANG) => {
2806 let suggestable = def_id.is_local()
2808 || self.r.tcx.lookup_stability(def_id).is_none_or(|s| s.is_stable());
2809
2810 err.span_label(span, fallback_label.to_string());
2811
2812 if path
2814 .last()
2815 .is_some_and(|segment| !segment.has_generic_args && !segment.has_lifetime_args)
2816 && suggestable
2817 {
2818 err.span_suggestion_verbose(
2819 span.shrink_to_hi(),
2820 "use `!` to invoke the macro",
2821 "!",
2822 Applicability::MaybeIncorrect,
2823 );
2824 }
2825
2826 if path_str == "try" && span.is_rust_2015() {
2827 err.note("if you want the `try` keyword, you need Rust 2018 or later");
2828 }
2829 }
2830 (Res::Def(DefKind::Macro(kinds), _), _) if kinds.contains(MacroKinds::BANG) => {
2831 err.span_label(span, fallback_label.to_string());
2832 }
2833 (Res::Def(DefKind::TyAlias, def_id), PathSource::Trait(_)) => {
2834 err.span_label(span, "type aliases cannot be used as traits");
2835 if self.r.tcx.sess.is_nightly_build() {
2836 let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
2837 `type` alias";
2838 let span = self.r.def_span(def_id);
2839 if let Ok(snip) = self.r.tcx.sess.source_map().span_to_snippet(span) {
2840 let snip = snip.replacen("type", "trait", 1);
2843 err.span_suggestion_verbose(span, msg, snip, Applicability::MaybeIncorrect);
2844 } else {
2845 err.span_help(span, msg);
2846 }
2847 }
2848 }
2849 (
2850 Res::Def(kind @ (DefKind::Mod | DefKind::Trait | DefKind::TyAlias), _),
2851 PathSource::Expr(Some(parent)),
2852 ) if path_sep(self, err, parent, kind) => {
2853 return true;
2854 }
2855 (
2856 Res::Def(DefKind::Enum, def_id),
2857 PathSource::TupleStruct(..) | PathSource::Expr(..),
2858 ) => {
2859 self.suggest_using_enum_variant(err, source, def_id, span);
2860 }
2861 (Res::Def(DefKind::Struct, def_id), source) if ns == ValueNS => {
2862 if let PathSource::Expr(Some(parent)) = source
2863 && let ExprKind::Field(..) | ExprKind::MethodCall(..) = parent.kind
2864 {
2865 bad_struct_syntax_suggestion(self, err, def_id);
2866 return true;
2867 }
2868 let Some(ctor) = self.r.struct_ctor(def_id) else {
2869 bad_struct_syntax_suggestion(self, err, def_id);
2870 return true;
2871 };
2872
2873 let is_accessible = self.r.is_accessible_from(ctor.vis, self.parent_scope.module);
2876 if is_accessible
2877 && let mod_path = &path[..path.len() - 1]
2878 && let PathResult::Module(ModuleOrUniformRoot::Module(import_mod)) =
2879 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Module)
2880 && ctor.has_private_fields(import_mod, self.r)
2881 && let Ok(import_decl) = self.r.cm().maybe_resolve_ident_in_module(
2882 ModuleOrUniformRoot::Module(import_mod),
2883 path.last().unwrap().ident,
2884 TypeNS,
2885 &self.parent_scope,
2886 None,
2887 )
2888 {
2889 err.span_note(
2890 import_decl.span,
2891 "the type is accessed through this re-export, but the type's constructor \
2892 is not visible in this import's scope due to private fields",
2893 );
2894 if !ctor.has_private_fields(self.parent_scope.module, self.r) {
2895 err.span_suggestion_verbose(
2896 span,
2897 "the type can be constructed directly, because its fields are \
2898 available from the current scope",
2899 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
self.r.tcx.def_path(def_id).to_string_no_crate_verbose()))
})format!(
2903 "crate{}", self.r.tcx.def_path(def_id).to_string_no_crate_verbose(),
2905 ),
2906 Applicability::MachineApplicable,
2907 );
2908 }
2909 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2910 }
2911 if !is_expected(ctor.res) || is_accessible {
2912 return true;
2913 }
2914
2915 let field_spans =
2916 self.update_err_for_private_tuple_struct_fields(err, &source, def_id);
2917
2918 if let Some(spans) = field_spans
2919 .filter(|spans| spans.len() > 0 && ctor.field_visibilities.len() == spans.len())
2920 {
2921 let non_visible_spans: Vec<Span> = iter::zip(&ctor.field_visibilities, &spans)
2922 .filter(|(vis, _)| {
2923 !self.r.is_accessible_from(**vis, self.parent_scope.module)
2924 })
2925 .map(|(_, span)| *span)
2926 .collect();
2927
2928 if non_visible_spans.len() > 0 {
2929 if let Some(fields) = self.r.field_visibility_spans.get(&def_id) {
2930 err.multipart_suggestion(
2931 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider making the field{0} publicly accessible",
if fields.len() == 1 { "" } else { "s" }))
})format!(
2932 "consider making the field{} publicly accessible",
2933 pluralize!(fields.len())
2934 ),
2935 fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
2936 Applicability::MaybeIncorrect,
2937 );
2938 }
2939
2940 let mut m: MultiSpan = non_visible_spans.clone().into();
2941 non_visible_spans
2942 .into_iter()
2943 .for_each(|s| m.push_span_label(s, "private field"));
2944 err.span_note(m, "constructor is not visible here due to private fields");
2945 }
2946
2947 return true;
2948 }
2949
2950 err.span_label(span, "constructor is not visible here due to private fields");
2951 }
2952 (Res::Def(DefKind::Union | DefKind::Variant, def_id), _) if ns == ValueNS => {
2953 bad_struct_syntax_suggestion(self, err, def_id);
2954 }
2955 (Res::Def(DefKind::Ctor(of, CtorKind::Const), def_id), _) if ns == ValueNS => {
2956 match source {
2957 PathSource::Expr(_) | PathSource::TupleStruct(..) | PathSource::Pat => {
2958 let span = find_span(&source, err);
2959 err.span_label(
2960 self.r.def_span(def_id),
2961 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", path_str))
})format!("`{path_str}` defined here"),
2962 );
2963 if of == CtorOf::Variant {
2964 err.span_context(
2965 self.r
2966 .def_span(self.r.tcx.parent(self.r.tcx.parent(def_id)))
2967 .shrink_to_lo(),
2968 );
2969 }
2970 err.span_suggestion_verbose(
2971 span,
2972 "use the unit struct syntax instead",
2973 path_str,
2974 Applicability::MaybeIncorrect,
2975 );
2976 }
2977 _ => return false,
2978 }
2979 }
2980 (Res::Def(DefKind::Ctor(of, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
2981 let def_id = self.r.tcx.parent(ctor_def_id);
2982 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"));
2983 if of == CtorOf::Variant {
2984 err.span_context(self.r.def_span(self.r.tcx.parent(def_id)).shrink_to_lo());
2985 }
2986 let fields = self.r.field_idents(def_id).map_or_else(
2987 || "/* fields */".to_string(),
2988 |field_ids| ::alloc::vec::from_elem_global("_", field_ids.len())vec!["_"; field_ids.len()].join(", "),
2989 );
2990 err.span_suggestion_verbose(
2991 span,
2992 "use the tuple variant pattern syntax instead",
2993 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}({1})", path_str, fields))
})format!("{path_str}({fields})"),
2994 Applicability::HasPlaceholders,
2995 );
2996 }
2997 (Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }, _) if ns == ValueNS => {
2998 err.span_label(span, fallback_label.to_string());
2999 err.note("can't use `Self` as a constructor, you must use the implemented struct");
3000 }
3001 (
3002 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
3003 PathSource::TraitItem(ValueNS, PathSource::TupleStruct(whole, args)),
3004 ) => {
3005 err.note("can't use a type alias as tuple pattern");
3006
3007 let mut suggestion = Vec::new();
3008
3009 if let &&[first, ..] = args
3010 && let &&[.., last] = args
3011 {
3012 suggestion.extend([
3013 (span.between(first), " { 0: ".to_owned()),
3019 (last.between(whole.shrink_to_hi()), " }".to_owned()),
3020 ]);
3021
3022 suggestion.extend(
3023 args.iter()
3024 .enumerate()
3025 .skip(1) .map(|(index, &arg)| (arg.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
3027 )
3028 } else {
3029 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
3030 }
3031
3032 err.multipart_suggestion(
3033 "use struct pattern instead",
3034 suggestion,
3035 Applicability::MachineApplicable,
3036 );
3037 }
3038 (
3039 Res::Def(DefKind::TyAlias | DefKind::AssocTy, _),
3040 PathSource::TraitItem(
3041 ValueNS,
3042 PathSource::Expr(Some(ast::Expr {
3043 span: whole,
3044 kind: ast::ExprKind::Call(_, args),
3045 ..
3046 })),
3047 ),
3048 ) => {
3049 err.note("can't use a type alias as a constructor");
3050
3051 let mut suggestion = Vec::new();
3052
3053 if let [first, ..] = &**args
3054 && let [.., last] = &**args
3055 {
3056 suggestion.extend([
3057 (span.between(first.span), " { 0: ".to_owned()),
3063 (last.span.between(whole.shrink_to_hi()), " }".to_owned()),
3064 ]);
3065
3066 suggestion.extend(
3067 args.iter()
3068 .enumerate()
3069 .skip(1) .map(|(index, arg)| (arg.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", index))
})format!("{index}: "))),
3071 )
3072 } else {
3073 suggestion.push((span.between(whole.shrink_to_hi()), " {}".to_owned()));
3074 }
3075
3076 err.multipart_suggestion(
3077 "use struct expression instead",
3078 suggestion,
3079 Applicability::MachineApplicable,
3080 );
3081 }
3082 _ => return false,
3083 }
3084 true
3085 }
3086
3087 fn suggest_alternative_construction_methods(
3088 &self,
3089 def_id: DefId,
3090 err: &mut Diag<'_>,
3091 path_span: Span,
3092 call_span: Span,
3093 args: &[Box<Expr>],
3094 ) {
3095 if def_id.is_local() {
3096 return;
3098 }
3099 let mut items = self
3102 .r
3103 .tcx
3104 .inherent_impls(def_id)
3105 .iter()
3106 .flat_map(|&i| self.r.tcx.associated_items(i).in_definition_order())
3107 .filter(|item| item.is_fn() && !item.is_method())
3109 .filter_map(|item| {
3110 let fn_sig = self.r.tcx.fn_sig(item.def_id).skip_binder();
3112 let ret_ty = fn_sig.output().skip_binder();
3114 let ty::Adt(def, _args) = ret_ty.kind() else {
3115 return None;
3116 };
3117 let input_len = fn_sig.inputs().skip_binder().len();
3118 if def.did() != def_id {
3119 return None;
3120 }
3121 let name = item.name();
3122 let order = !name.as_str().starts_with("new");
3123 Some((order, name, input_len))
3124 })
3125 .collect::<Vec<_>>();
3126 items.sort_by_key(|(order, _, _)| *order);
3127 let suggestion = |name, args| {
3128 ::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(", "))
3129 };
3130 match &items[..] {
3131 [] => {}
3132 [(_, name, len)] if *len == args.len() => {
3133 err.span_suggestion_verbose(
3134 path_span.shrink_to_hi(),
3135 ::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",),
3136 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}", name))
})format!("::{name}"),
3137 Applicability::MaybeIncorrect,
3138 );
3139 }
3140 [(_, name, len)] => {
3141 err.span_suggestion_verbose(
3142 path_span.shrink_to_hi().with_hi(call_span.hi()),
3143 ::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",),
3144 suggestion(name, *len),
3145 Applicability::MaybeIncorrect,
3146 );
3147 }
3148 _ => {
3149 err.span_suggestions_with_style(
3150 path_span.shrink_to_hi().with_hi(call_span.hi()),
3151 "you might have meant to use an associated function to build this type",
3152 items.iter().map(|(_, name, len)| suggestion(name, *len)),
3153 Applicability::MaybeIncorrect,
3154 SuggestionStyle::ShowAlways,
3155 );
3156 }
3157 }
3158 let default_trait = self
3166 .r
3167 .lookup_import_candidates(
3168 Ident::with_dummy_span(sym::Default),
3169 Namespace::TypeNS,
3170 &self.parent_scope,
3171 &|res: Res| #[allow(non_exhaustive_omitted_patterns)] match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
}matches!(res, Res::Def(DefKind::Trait, _)),
3172 )
3173 .iter()
3174 .filter_map(|candidate| candidate.did)
3175 .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)));
3176 let Some(default_trait) = default_trait else {
3177 return;
3178 };
3179 if self
3180 .r
3181 .extern_crate_map
3182 .items()
3183 .flat_map(|(_, crate_)| {
3185 UnordItems::new(
3186 self.r.tcx.implementations_of_trait((*crate_, default_trait)).into_iter(),
3187 )
3188 })
3189 .filter_map(|(_, simplified_self_ty)| *simplified_self_ty)
3190 .filter_map(|simplified_self_ty| match simplified_self_ty {
3191 SimplifiedType::Adt(did) => Some(did),
3192 _ => None,
3193 })
3194 .any(|did| did == def_id)
3195 {
3196 err.multipart_suggestion(
3197 "consider using the `Default` trait",
3198 ::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![
3199 (path_span.shrink_to_lo(), "<".to_string()),
3200 (
3201 path_span.shrink_to_hi().with_hi(call_span.hi()),
3202 " as std::default::Default>::default()".to_string(),
3203 ),
3204 ],
3205 Applicability::MaybeIncorrect,
3206 );
3207 }
3208 }
3209
3210 pub(crate) fn find_similarly_named_assoc_item(
3213 &mut self,
3214 ident: Symbol,
3215 kind: &AssocItemKind,
3216 ) -> Option<Symbol> {
3217 let (module, _) = self.current_trait_ref?;
3218 if ident == kw::Underscore {
3219 return None;
3221 }
3222
3223 let targets = self
3224 .r
3225 .resolutions(module)
3226 .iter()
3227 .filter_map(|(key, res)| {
3228 res.borrow(self.r).best_decl().map(|binding| (key, binding.res()))
3229 })
3230 .filter(|(_, res)| match (kind, res) {
3231 (AssocItemKind::Const(..), Res::Def(DefKind::AssocConst, _)) => true,
3232 (AssocItemKind::Fn(_), Res::Def(DefKind::AssocFn, _)) => true,
3233 (AssocItemKind::Type(..), Res::Def(DefKind::AssocTy, _)) => true,
3234 (AssocItemKind::Delegation(_), Res::Def(DefKind::AssocFn, _)) => true,
3235 _ => false,
3236 })
3237 .map(|(key, _)| key.ident.name)
3238 .collect::<Vec<_>>();
3239
3240 find_best_match_for_name(&targets, ident, None)
3241 }
3242
3243 fn lookup_assoc_candidate<FilterFn>(
3245 &self,
3246 ident: Ident,
3247 ns: Namespace,
3248 filter_fn: FilterFn,
3249 called: bool,
3250 ) -> Option<(AssocSuggestion, Span)>
3251 where
3252 FilterFn: Fn(Res) -> bool,
3253 {
3254 fn extract_node_id(t: &Ty) -> Option<NodeId> {
3255 match t.kind {
3256 TyKind::Path(None, _) => Some(t.id),
3257 TyKind::Ref(_, ref inner_ty, _) => extract_node_id(inner_ty),
3258 _ => None,
3262 }
3263 }
3264 if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
3266 if let Some(node_id) = self.diag_metadata.current_self_type.and_then(extract_node_id)
3267 && let Some(resolution) = self.r.partial_res_map.get(&node_id)
3268 && let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) = resolution.full_res()
3269 && let Some(fields) = self.r.field_idents(did)
3270 && let Some(field) = fields.iter().find(|id| ident.name == id.name)
3271 {
3272 return Some((AssocSuggestion::Field, field.span));
3274 }
3275 }
3276
3277 if let Some(items) = self.diag_metadata.current_trait_assoc_items {
3278 for assoc_item in items {
3279 if let Some(assoc_ident) = assoc_item.kind.ident()
3280 && assoc_ident == ident
3281 {
3282 let from = AssocFrom::Impl;
3283 let candidate = match &assoc_item.kind {
3284 ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
3285 ast::AssocItemKind::Fn(ast::Fn { sig, .. }) if sig.decl.has_self() => {
3286 AssocSuggestion::MethodWithSelf { called, from }
3287 }
3288 ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called, from },
3289 ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType { from },
3290 ast::AssocItemKind::Delegation(..)
3291 if self
3292 .r
3293 .owners
3294 .get(&assoc_item.id)
3295 .and_then(|o| self.r.delegation_fn_sigs.get(&o.def_id))
3296 .is_some_and(|sig| sig.has_self) =>
3297 {
3298 AssocSuggestion::MethodWithSelf { called, from }
3299 }
3300 ast::AssocItemKind::Delegation(..) => {
3301 AssocSuggestion::AssocFn { called, from }
3302 }
3303 ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(..) => {
3304 continue;
3305 }
3306 };
3307 return Some((candidate, assoc_ident.span));
3308 }
3309 }
3310 }
3311
3312 if let Some((module, _)) = self.current_trait_ref
3314 && let Ok(binding) = self.r.cm().maybe_resolve_ident_in_module(
3315 ModuleOrUniformRoot::Module(module),
3316 ident,
3317 ns,
3318 &self.parent_scope,
3319 None,
3320 )
3321 {
3322 let res = binding.res();
3323 if filter_fn(res) {
3324 let from = AssocFrom::Trait;
3325 match res {
3326 Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => {
3327 let has_self = match def_id.as_local() {
3328 Some(def_id) => self
3329 .r
3330 .delegation_fn_sigs
3331 .get(&def_id)
3332 .is_some_and(|sig| sig.has_self),
3333 None => {
3334 self.r.tcx.fn_arg_idents(def_id).first().is_some_and(|&ident| {
3335 #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. }))
3336 })
3337 }
3338 };
3339 if has_self {
3340 return Some((
3341 AssocSuggestion::MethodWithSelf { called, from },
3342 binding.span,
3343 ));
3344 } else {
3345 return Some((AssocSuggestion::AssocFn { called, from }, binding.span));
3346 }
3347 }
3348 Res::Def(DefKind::AssocConst, _) => {
3349 return Some((AssocSuggestion::AssocConst, binding.span));
3350 }
3351 Res::Def(DefKind::AssocTy, _) => {
3352 return Some((AssocSuggestion::AssocType { from }, binding.span));
3353 }
3354 _ => {}
3355 }
3356 }
3357 }
3358
3359 None
3360 }
3361
3362 fn lookup_typo_candidate(
3363 &mut self,
3364 path: &[Segment],
3365 following_seg: Option<&Segment>,
3366 ns: Namespace,
3367 filter_fn: &impl Fn(Res) -> bool,
3368 ) -> TypoCandidate {
3369 let mut names = Vec::new();
3370 if let [segment] = path {
3371 let mut ctxt = segment.ident.span.ctxt();
3372
3373 for rib in self.ribs[ns].iter().rev() {
3376 let rib_ctxt = if rib.kind.contains_params() {
3377 ctxt.normalize_to_macros_2_0()
3378 } else {
3379 ctxt.normalize_to_macro_rules()
3380 };
3381
3382 for (ident, &res) in &rib.bindings {
3384 if filter_fn(res) && ident.span.ctxt() == rib_ctxt {
3385 names.push(TypoSuggestion::new(ident.name, ident.span, res));
3386 }
3387 }
3388
3389 if let RibKind::Block(Some(module)) = rib.kind {
3390 self.r.add_module_candidates(
3391 module.to_module(),
3392 &mut names,
3393 &filter_fn,
3394 Some(ctxt),
3395 );
3396 } else if let RibKind::Module(module) = rib.kind {
3397 let parent_scope =
3399 &ParentScope { module: module.to_module(), ..self.parent_scope };
3400 self.r.add_scope_set_candidates(
3401 &mut names,
3402 ScopeSet::All(ns),
3403 parent_scope,
3404 segment.ident.span.with_ctxt(ctxt),
3405 filter_fn,
3406 );
3407 break;
3408 }
3409
3410 if let RibKind::MacroDefinition(def) = rib.kind
3411 && def == self.r.macro_def(ctxt)
3412 {
3413 ctxt.remove_mark();
3416 }
3417 }
3418 } else {
3419 let mod_path = &path[..path.len() - 1];
3421 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
3422 self.resolve_path(mod_path, Some(TypeNS), None, PathSource::Type)
3423 {
3424 self.r.add_module_candidates(module, &mut names, &filter_fn, None);
3425 }
3426 }
3427
3428 if let Some(following_seg) = following_seg {
3430 names.retain(|suggestion| match suggestion.res {
3431 Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _) => {
3432 suggestion.candidate != following_seg.ident.name
3434 }
3435 Res::Def(DefKind::Mod, def_id) => {
3436 let module = self.r.expect_module(def_id);
3437 self.r
3438 .resolutions(module)
3439 .iter()
3440 .any(|(key, _)| key.ident.name == following_seg.ident.name)
3441 }
3442 _ => true,
3443 });
3444 }
3445 let name = path[path.len() - 1].ident.name;
3446 names.sort_by(|a, b| a.candidate.as_str().cmp(b.candidate.as_str()));
3448
3449 match find_best_match_for_name(
3450 &names.iter().map(|suggestion| suggestion.candidate).collect::<Vec<Symbol>>(),
3451 name,
3452 None,
3453 ) {
3454 Some(found) => {
3455 let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found)
3456 else {
3457 return TypoCandidate::None;
3458 };
3459 if found == name {
3460 TypoCandidate::Shadowed(sugg.res, sugg.span)
3461 } else {
3462 TypoCandidate::Typo(sugg)
3463 }
3464 }
3465 _ => TypoCandidate::None,
3466 }
3467 }
3468
3469 fn likely_rust_type(path: &[Segment]) -> Option<Symbol> {
3472 let name = path[path.len() - 1].ident.as_str();
3473 Some(match name {
3475 "byte" => sym::u8, "short" => sym::i16,
3477 "Bool" => sym::bool,
3478 "Boolean" => sym::bool,
3479 "boolean" => sym::bool,
3480 "int" => sym::i32,
3481 "long" => sym::i64,
3482 "float" => sym::f32,
3483 "double" => sym::f64,
3484 _ => return None,
3485 })
3486 }
3487
3488 fn let_binding_suggestion(&self, err: &mut Diag<'_>, ident_span: Span) -> bool {
3491 if ident_span.from_expansion() {
3492 return false;
3493 }
3494
3495 if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
3497 && let ast::ExprKind::Path(None, ref path) = lhs.kind
3498 && self.r.tcx.sess.source_map().is_line_before_span_empty(ident_span)
3499 {
3500 let (span, text) = match path.segments.first() {
3501 Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
3502 let name = name.trim_prefix('_');
3504 (ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let {0}", name))
})format!("let {name}"))
3505 }
3506 _ => (ident_span.shrink_to_lo(), "let ".to_string()),
3507 };
3508
3509 err.span_suggestion_verbose(
3510 span,
3511 "you might have meant to introduce a new binding",
3512 text,
3513 Applicability::MaybeIncorrect,
3514 );
3515 return true;
3516 }
3517
3518 if err.code == Some(E0423)
3521 && let Some((let_span, None, Some(val_span))) = self.diag_metadata.current_let_binding
3522 && val_span.contains(ident_span)
3523 && val_span.lo() == ident_span.lo()
3524 {
3525 err.span_suggestion_verbose(
3526 let_span.shrink_to_hi().to(val_span.shrink_to_lo()),
3527 "you might have meant to use `:` for type annotation",
3528 ": ",
3529 Applicability::MaybeIncorrect,
3530 );
3531 return true;
3532 }
3533 false
3534 }
3535
3536 fn find_module(&self, def_id: DefId) -> Option<(Module<'ra>, ImportSuggestion)> {
3537 let mut result = None;
3538 let mut seen_modules = FxHashSet::default();
3539 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)];
3540
3541 while let Some((in_module, path_segments, doc_visible)) = worklist.pop() {
3542 if result.is_some() {
3544 break;
3545 }
3546
3547 in_module.for_each_child(self.r, |r, ident, orig_ident_span, _, name_binding| {
3548 if result.is_some() || !name_binding.vis().is_visible_locally() {
3550 return;
3551 }
3552 if let Some(module_def_id) = name_binding.res().module_like_def_id() {
3553 let mut path_segments = path_segments.clone();
3555 path_segments.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3556 let doc_visible = doc_visible
3557 && (module_def_id.is_local() || !r.tcx.is_doc_hidden(module_def_id));
3558 if module_def_id == def_id {
3559 let path = Path { span: name_binding.span, segments: path_segments };
3560 result = Some((
3561 r.expect_module(module_def_id),
3562 ImportSuggestion {
3563 did: Some(def_id),
3564 descr: "module",
3565 path,
3566 accessible: true,
3567 doc_visible,
3568 note: None,
3569 via_import: false,
3570 is_stable: true,
3571 },
3572 ));
3573 } else {
3574 if seen_modules.insert(module_def_id) {
3576 let module = r.expect_module(module_def_id);
3577 worklist.push((module, path_segments, doc_visible));
3578 }
3579 }
3580 }
3581 });
3582 }
3583
3584 result
3585 }
3586
3587 fn collect_enum_ctors(&self, def_id: DefId) -> Option<Vec<(Path, DefId, CtorKind)>> {
3588 self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
3589 let mut variants = Vec::new();
3590 enum_module.for_each_child(self.r, |_, ident, orig_ident_span, _, name_binding| {
3591 if let Res::Def(DefKind::Ctor(CtorOf::Variant, kind), def_id) = name_binding.res() {
3592 let mut segms = enum_import_suggestion.path.segments.clone();
3593 segms.push(ast::PathSegment::from_ident(ident.orig(orig_ident_span)));
3594 let path = Path { span: name_binding.span, segments: segms };
3595 variants.push((path, def_id, kind));
3596 }
3597 });
3598 variants
3599 })
3600 }
3601
3602 fn suggest_using_enum_variant(
3604 &self,
3605 err: &mut Diag<'_>,
3606 source: PathSource<'_, '_, '_>,
3607 def_id: DefId,
3608 span: Span,
3609 ) {
3610 let Some(variant_ctors) = self.collect_enum_ctors(def_id) else {
3611 err.note("you might have meant to use one of the enum's variants");
3612 return;
3613 };
3614
3615 let (suggest_path_sep_dot_span, suggest_only_tuple_variants) = match source {
3620 PathSource::TupleStruct(..) => (None, true),
3622 PathSource::Expr(Some(expr)) => match &expr.kind {
3623 ExprKind::Call(..) => (None, true),
3625 ExprKind::MethodCall(MethodCall {
3628 receiver,
3629 span,
3630 seg: PathSegment { ident, .. },
3631 ..
3632 }) => {
3633 let dot_span = receiver.span.between(*span);
3634 let found_tuple_variant = variant_ctors.iter().any(|(path, _, ctor_kind)| {
3635 *ctor_kind == CtorKind::Fn
3636 && path.segments.last().is_some_and(|seg| seg.ident == *ident)
3637 });
3638 (found_tuple_variant.then_some(dot_span), false)
3639 }
3640 ExprKind::Field(base, ident) => {
3643 let dot_span = base.span.between(ident.span);
3644 let found_tuple_or_unit_variant = variant_ctors.iter().any(|(path, ..)| {
3645 path.segments.last().is_some_and(|seg| seg.ident == *ident)
3646 });
3647 (found_tuple_or_unit_variant.then_some(dot_span), false)
3648 }
3649 _ => (None, false),
3650 },
3651 _ => (None, false),
3652 };
3653
3654 if let Some(dot_span) = suggest_path_sep_dot_span {
3655 err.span_suggestion_verbose(
3656 dot_span,
3657 "use the path separator to refer to a variant",
3658 "::",
3659 Applicability::MaybeIncorrect,
3660 );
3661 } else if suggest_only_tuple_variants {
3662 let mut suggestable_variants = variant_ctors
3665 .iter()
3666 .filter(|(.., kind)| *kind == CtorKind::Fn)
3667 .map(|(variant, ..)| path_names_to_string(variant))
3668 .collect::<Vec<_>>();
3669 suggestable_variants.sort();
3670
3671 let non_suggestable_variant_count = variant_ctors.len() - suggestable_variants.len();
3672
3673 let source_msg = if #[allow(non_exhaustive_omitted_patterns)] match source {
PathSource::TupleStruct(..) => true,
_ => false,
}matches!(source, PathSource::TupleStruct(..)) {
3674 "to match against"
3675 } else {
3676 "to construct"
3677 };
3678
3679 if !suggestable_variants.is_empty() {
3680 let msg = if non_suggestable_variant_count == 0 && suggestable_variants.len() == 1 {
3681 ::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")
3682 } else {
3683 ::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")
3684 };
3685
3686 err.span_suggestions(
3687 span,
3688 msg,
3689 suggestable_variants,
3690 Applicability::MaybeIncorrect,
3691 );
3692 }
3693
3694 if non_suggestable_variant_count == variant_ctors.len() {
3696 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}"));
3697 }
3698
3699 if non_suggestable_variant_count == 1 {
3701 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"));
3702 } else if non_suggestable_variant_count >= 1 {
3703 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!(
3704 "you might have meant {source_msg} one of the enum's non-tuple variants"
3705 ));
3706 }
3707 } else {
3708 let needs_placeholder = |ctor_def_id: DefId, kind: CtorKind| {
3709 let def_id = self.r.tcx.parent(ctor_def_id);
3710 match kind {
3711 CtorKind::Const => false,
3712 CtorKind::Fn => {
3713 !self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
3714 }
3715 }
3716 };
3717
3718 let mut suggestable_variants = variant_ctors
3719 .iter()
3720 .filter(|(_, def_id, kind)| !needs_placeholder(*def_id, *kind))
3721 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3722 .map(|(variant, kind)| match kind {
3723 CtorKind::Const => variant,
3724 CtorKind::Fn => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}())", variant))
})format!("({variant}())"),
3725 })
3726 .collect::<Vec<_>>();
3727 suggestable_variants.sort();
3728 let no_suggestable_variant = suggestable_variants.is_empty();
3729
3730 if !no_suggestable_variant {
3731 let msg = if suggestable_variants.len() == 1 {
3732 "you might have meant to use the following enum variant"
3733 } else {
3734 "you might have meant to use one of the following enum variants"
3735 };
3736
3737 err.span_suggestions(
3738 span,
3739 msg,
3740 suggestable_variants,
3741 Applicability::MaybeIncorrect,
3742 );
3743 }
3744
3745 let mut suggestable_variants_with_placeholders = variant_ctors
3746 .iter()
3747 .filter(|(_, def_id, kind)| needs_placeholder(*def_id, *kind))
3748 .map(|(variant, _, kind)| (path_names_to_string(variant), kind))
3749 .filter_map(|(variant, kind)| match kind {
3750 CtorKind::Fn => Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(/* fields */))", variant))
})format!("({variant}(/* fields */))")),
3751 _ => None,
3752 })
3753 .collect::<Vec<_>>();
3754 suggestable_variants_with_placeholders.sort();
3755
3756 if !suggestable_variants_with_placeholders.is_empty() {
3757 let msg =
3758 match (no_suggestable_variant, suggestable_variants_with_placeholders.len()) {
3759 (true, 1) => "the following enum variant is available",
3760 (true, _) => "the following enum variants are available",
3761 (false, 1) => "alternatively, the following enum variant is available",
3762 (false, _) => {
3763 "alternatively, the following enum variants are also available"
3764 }
3765 };
3766
3767 err.span_suggestions(
3768 span,
3769 msg,
3770 suggestable_variants_with_placeholders,
3771 Applicability::HasPlaceholders,
3772 );
3773 }
3774 };
3775
3776 if def_id.is_local() {
3777 err.span_note(self.r.def_span(def_id), "the enum is defined here");
3778 }
3779 }
3780
3781 pub(crate) fn detect_and_suggest_const_parameter_error(
3812 &mut self,
3813 path: &[Segment],
3814 source: PathSource<'_, 'ast, 'ra>,
3815 ) -> Option<Diag<'tcx>> {
3816 let Some(item) = self.diag_metadata.current_item else { return None };
3817 let ItemKind::Impl(impl_) = &item.kind else { return None };
3818 let self_ty = &impl_.self_ty;
3819
3820 let [current_parameter] = path else {
3822 return None;
3823 };
3824
3825 let target_ident = current_parameter.ident;
3826
3827 let visitor = ParentPathVisitor::new(self_ty, target_ident);
3829
3830 let Some(parent_segment) = visitor.parent else {
3831 return None;
3832 };
3833
3834 let Some(args) = parent_segment.args.as_ref() else {
3835 return None;
3836 };
3837
3838 let GenericArgs::AngleBracketed(angle) = args.as_ref() else {
3839 return None;
3840 };
3841
3842 let usage_to_pos: FxHashMap<NodeId, usize> = angle
3845 .args
3846 .iter()
3847 .enumerate()
3848 .filter_map(|(pos, arg)| {
3849 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3850 && let TyKind::Path(_, path) = &ty.kind
3851 && let [segment] = path.segments.as_slice()
3852 {
3853 Some((segment.id, pos))
3854 } else {
3855 None
3856 }
3857 })
3858 .collect();
3859
3860 let Some(idx) = current_parameter.id.and_then(|id| usage_to_pos.get(&id).copied()) else {
3863 return None;
3864 };
3865
3866 let ns = source.namespace();
3868 let segment = Segment::from(parent_segment);
3869 let segments = [segment];
3870 let finalize = Finalize::new(parent_segment.id, parent_segment.ident.span);
3871
3872 if let Ok(Some(resolve)) = self.resolve_qpath_anywhere(
3873 &None,
3874 &segments,
3875 ns,
3876 source.defer_to_typeck(),
3877 finalize,
3878 source,
3879 ) && let Some(resolve) = resolve.full_res()
3880 && let Res::Def(_, def_id) = resolve
3881 && def_id.is_local()
3882 && let Some(local_def_id) = def_id.as_local()
3883 && let Some(struct_generics) = self.r.struct_generics.get(&local_def_id)
3884 && let Some(target_param) = &struct_generics.params.get(idx)
3885 && let GenericParamKind::Const { ty, .. } = &target_param.kind
3886 && let TyKind::Path(_, path) = &ty.kind
3887 {
3888 let full_type = path
3889 .segments
3890 .iter()
3891 .map(|seg| seg.ident.to_string())
3892 .collect::<Vec<_>>()
3893 .join("::");
3894
3895 let next_impl_param = impl_.generics.params.iter().find(|impl_param| {
3900 angle
3901 .args
3902 .iter()
3903 .find_map(|arg| {
3904 if let AngleBracketedArg::Arg(GenericArg::Type(ty)) = arg
3905 && let TyKind::Path(_, path) = &ty.kind
3906 && let [segment] = path.segments.as_slice()
3907 && segment.ident == impl_param.ident
3908 {
3909 usage_to_pos.get(&segment.id).copied()
3910 } else {
3911 None
3912 }
3913 })
3914 .is_some_and(|pos| pos > idx)
3915 });
3916
3917 let (insert_span, snippet) = match next_impl_param {
3918 Some(next_param) => {
3919 (
3922 next_param.span().shrink_to_lo(),
3923 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: {1}, ", target_ident,
full_type))
})format!("const {}: {}, ", target_ident, full_type),
3924 )
3925 }
3926 None => match impl_.generics.params.last() {
3927 Some(last) => {
3928 (
3931 last.span().shrink_to_hi(),
3932 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", const {0}: {1}", target_ident,
full_type))
})format!(", const {}: {}", target_ident, full_type),
3933 )
3934 }
3935 None => {
3936 (
3939 impl_.generics.span.shrink_to_hi(),
3940 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<const {0}: {1}>", target_ident,
full_type))
})format!("<const {}: {}>", target_ident, full_type),
3941 )
3942 }
3943 },
3944 };
3945
3946 let mut err = self.r.dcx().struct_span_err(
3947 target_ident.span,
3948 ::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),
3949 );
3950
3951 err.code(E0425);
3952
3953 err.span_label(target_ident.span, "not found in this scope");
3954
3955 err.span_label(
3956 target_param.span(),
3957 ::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",),
3958 );
3959
3960 err.subdiagnostic(diagnostics::UnexpectedMissingConstParameter {
3961 span: insert_span,
3962 snippet,
3963 item_name: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", target_ident))
})format!("{}", target_ident),
3964 item_location: String::from("impl"),
3965 });
3966
3967 return Some(err);
3968 }
3969
3970 None
3971 }
3972
3973 pub(crate) fn suggest_adding_generic_parameter(
3974 &mut self,
3975 path: &[Segment],
3976 source: PathSource<'_, 'ast, 'ra>,
3977 ) -> (Option<(Span, &'static str, String, Applicability)>, Option<Diag<'tcx>>) {
3978 let (ident, span) = match path {
3979 [segment]
3980 if !segment.has_generic_args
3981 && segment.ident.name != kw::SelfUpper
3982 && segment.ident.name != kw::Dyn =>
3983 {
3984 (segment.ident.to_string(), segment.ident.span)
3985 }
3986 _ => return (None, None),
3987 };
3988 let mut iter = ident.chars().map(|c| c.is_uppercase());
3989 let single_uppercase_char =
3990 #[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);
3991 if !self.diag_metadata.currently_processing_generic_args && !single_uppercase_char {
3992 return (None, None);
3993 }
3994 match (
3995 self.diag_metadata.current_item,
3996 single_uppercase_char,
3997 self.diag_metadata.currently_processing_generic_args,
3998 ) {
3999 (Some(Item { kind: ItemKind::Fn(fn_), .. }), _, _) if fn_.ident.name == sym::main => {
4000 }
4002 (Some(Item { span, .. }), _, _) if span.in_derive_expansion() => {
4003 return (None, None);
4004 }
4005 (
4006 Some(Item {
4007 kind:
4008 kind @ ItemKind::Fn(..)
4009 | kind @ ItemKind::Enum(..)
4010 | kind @ ItemKind::Struct(..)
4011 | kind @ ItemKind::Union(..),
4012 ..
4013 }),
4014 true,
4015 _,
4016 )
4017 | (Some(Item { kind: kind @ ItemKind::Impl(..), .. }), true, true)
4019 | (Some(Item { kind, .. }), false, _) => {
4020 if let Some(generics) = kind.generics() {
4021 if span.overlaps(generics.span) {
4022 return (None, None);
4031 }
4032
4033 let (msg, sugg) = match source {
4034 PathSource::Type | PathSource::PreciseCapturingArg(TypeNS) => {
4035 if let Some(err) =
4036 self.detect_and_suggest_const_parameter_error(path, source)
4037 {
4038 return (None, Some(err));
4039 }
4040 ("you might be missing a type parameter", ident)
4041 }
4042 PathSource::Expr(_) | PathSource::PreciseCapturingArg(ValueNS) => (
4043 "you might be missing a const parameter",
4044 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("const {0}: /* Type */", ident))
})format!("const {ident}: /* Type */"),
4045 ),
4046 _ => return (None, None),
4047 };
4048 let (span, sugg) = if let [.., param] = &generics.params[..] {
4049 let span = if let [.., bound] = ¶m.bounds[..] {
4050 bound.span()
4051 } else if let GenericParam {
4052 kind: GenericParamKind::Const { ty, span: _, default },
4053 ..
4054 } = param
4055 {
4056 default.as_ref().map(|def| def.value.span).unwrap_or(ty.span)
4057 } else {
4058 param.ident.span
4059 };
4060 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", sugg))
})format!(", {sugg}"))
4061 } else {
4062 (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", sugg))
})format!("<{sugg}>"))
4063 };
4064 if span.can_be_used_for_suggestions() {
4066 return (
4067 Some((span.shrink_to_hi(), msg, sugg, Applicability::MaybeIncorrect)),
4068 None,
4069 );
4070 }
4071 }
4072 }
4073 _ => {}
4074 }
4075 (None, None)
4076 }
4077
4078 pub(crate) fn suggestion_for_label_in_rib(
4081 &self,
4082 rib_index: usize,
4083 label: Ident,
4084 ) -> Option<LabelSuggestion> {
4085 let within_scope = self.is_label_valid_from_rib(rib_index);
4087
4088 let rib = &self.label_ribs[rib_index];
4089 let names = rib
4090 .bindings
4091 .iter()
4092 .filter(|(id, _)| id.span.ctxt() == label.span.ctxt())
4093 .map(|(id, _)| id.name)
4094 .collect::<Vec<Symbol>>();
4095
4096 find_best_match_for_name(&names, label.name, None).map(|symbol| {
4097 let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap();
4101 (*ident, within_scope)
4102 })
4103 }
4104
4105 pub(crate) fn maybe_report_lifetime_uses(
4106 &mut self,
4107 generics_span: Span,
4108 params: &[ast::GenericParam],
4109 ) {
4110 for (param_index, param) in params.iter().enumerate() {
4111 let GenericParamKind::Lifetime = param.kind else { continue };
4112
4113 let def_id = self.r.local_def_id(param.id);
4114
4115 let use_set = self.lifetime_uses.remove(&def_id);
4116 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4116",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4116u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::late::diagnostics"),
::tracing_core::field::FieldSet::new(&["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!(
4117 "Use set for {:?}({:?} at {:?}) is {:?}",
4118 def_id, param.ident, param.ident.span, use_set
4119 );
4120
4121 let deletion_span = || {
4122 if params.len() == 1 {
4123 Some(generics_span)
4125 } else if param_index == 0 {
4126 match (
4129 param.span_with_attributes().find_ancestor_inside(generics_span),
4130 params[param_index + 1]
4131 .span_with_attributes()
4132 .find_ancestor_inside(generics_span),
4133 ) {
4134 (Some(param_span), Some(next_param_span)) => {
4135 Some(param_span.to(next_param_span.shrink_to_lo()))
4136 }
4137 _ => None,
4138 }
4139 } else {
4140 match (
4143 param.span_with_attributes().find_ancestor_inside(generics_span),
4144 params[param_index - 1]
4145 .span_with_attributes()
4146 .find_ancestor_inside(generics_span),
4147 ) {
4148 (Some(param_span), Some(prev_param_span)) => {
4149 Some(prev_param_span.shrink_to_hi().to(param_span))
4150 }
4151 _ => None,
4152 }
4153 }
4154 };
4155 match use_set {
4156 Some(LifetimeUseSet::Many) => {}
4157 Some(LifetimeUseSet::One { .. }) if !param.bounds.is_empty() => {}
4160 Some(LifetimeUseSet::One { use_span, use_ctxt }) => {
4161 let param_ident = param.ident;
4162 let deletion_span =
4163 if param.bounds.is_empty() { deletion_span() } else { None };
4164 self.r.lint_buffer.dyn_buffer_lint_any(
4165 SINGLE_USE_LIFETIMES,
4166 param.id,
4167 param_ident.span,
4168 move |dcx, level, sess| {
4169 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4169",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4169u32),
::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);
4170
4171 let elidable = #[allow(non_exhaustive_omitted_patterns)] match use_ctxt {
LifetimeCtxt::Ref => true,
_ => false,
}matches!(use_ctxt, LifetimeCtxt::Ref);
4172 let suggestion = if let Some(deletion_span) = deletion_span {
4173 let (use_span, replace_lt) = if elidable {
4174 let use_span = sess
4175 .downcast_ref::<Session>()
4176 .expect("expected a `Session`")
4177 .source_map()
4178 .span_extend_while_whitespace(use_span);
4179 (use_span, String::new())
4180 } else {
4181 (use_span, "'_".to_owned())
4182 };
4183 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4183",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4183u32),
::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);
4184
4185 let deletion_span = if deletion_span.is_empty() {
4188 None
4189 } else {
4190 Some(deletion_span)
4191 };
4192 Some(diagnostics::SingleUseLifetimeSugg {
4193 deletion_span,
4194 use_span,
4195 replace_lt,
4196 })
4197 } else {
4198 None
4199 };
4200 diagnostics::SingleUseLifetime {
4201 suggestion,
4202 param_span: param_ident.span,
4203 use_span,
4204 ident: param_ident,
4205 }
4206 .into_diag(dcx, level)
4207 },
4208 );
4209 }
4210 None => {
4211 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4211",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4211u32),
::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);
4212 let deletion_span = deletion_span();
4213
4214 if deletion_span.is_some_and(|sp| !sp.in_derive_expansion()) {
4216 self.r.lint_buffer.buffer_lint(
4217 UNUSED_LIFETIMES,
4218 param.id,
4219 param.ident.span,
4220 diagnostics::UnusedLifetime { deletion_span, ident: param.ident },
4221 );
4222 }
4223 }
4224 }
4225 }
4226 }
4227
4228 pub(crate) fn emit_undeclared_lifetime_error(
4229 &self,
4230 lifetime_ref: &ast::Lifetime,
4231 outer_lifetime_ref: Option<Ident>,
4232 ) -> ErrorGuaranteed {
4233 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);
4234 let mut err = if let Some(outer) = outer_lifetime_ref {
4235 {
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!(
4236 self.r.dcx(),
4237 lifetime_ref.ident.span,
4238 E0401,
4239 "can't use generic parameters from outer item",
4240 )
4241 .with_span_label(lifetime_ref.ident.span, "use of generic parameter from outer item")
4242 .with_span_label(outer.span, "lifetime parameter from outer item")
4243 } else {
4244 {
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!(
4245 self.r.dcx(),
4246 lifetime_ref.ident.span,
4247 E0261,
4248 "use of undeclared lifetime name `{}`",
4249 lifetime_ref.ident
4250 )
4251 .with_span_label(lifetime_ref.ident.span, "undeclared lifetime")
4252 };
4253
4254 if edit_distance(lifetime_ref.ident.name.as_str(), "'static", 2).is_some() {
4256 err.span_suggestion_verbose(
4257 lifetime_ref.ident.span,
4258 "you may have misspelled the `'static` lifetime",
4259 "'static",
4260 Applicability::MachineApplicable,
4261 );
4262 } else {
4263 self.suggest_introducing_lifetime(
4264 &mut err,
4265 Some(lifetime_ref.ident),
4266 |err, _, span, message, suggestion, span_suggs| {
4267 err.multipart_suggestion(
4268 message,
4269 std::iter::once((span, suggestion)).chain(span_suggs).collect(),
4270 Applicability::MaybeIncorrect,
4271 );
4272 true
4273 },
4274 );
4275 }
4276
4277 err.emit_err()
4278 }
4279
4280 fn suggest_introducing_lifetime(
4281 &self,
4282 err: &mut Diag<'_>,
4283 name: Option<Ident>,
4284 suggest: impl Fn(
4285 &mut Diag<'_>,
4286 bool,
4287 Span,
4288 Cow<'static, str>,
4289 String,
4290 Vec<(Span, String)>,
4291 ) -> bool,
4292 ) {
4293 self.suggest_introducing_lifetime_filtered(err, name, |_| true, suggest);
4294 }
4295
4296 pub(crate) fn suggest_introducing_lifetime_for_assoc_ty_binding(
4297 &self,
4298 err: &mut Diag<'_>,
4299 lifetime: Span,
4300 ) {
4301 self.suggest_introducing_lifetime_filtered(
4302 err,
4303 None,
4304 |kind| {
4305 !#[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
4306 kind,
4307 LifetimeBinderKind::FnPtrType
4308 | LifetimeBinderKind::PolyTrait
4309 | LifetimeBinderKind::WhereBound
4310 )
4311 },
4312 |err, _higher_ranked, span, message, intro_sugg, _| {
4313 err.multipart_suggestion(
4314 message,
4315 ::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())],
4316 Applicability::MaybeIncorrect,
4317 );
4318 false
4319 },
4320 );
4321 }
4322
4323 fn suggest_introducing_lifetime_filtered(
4324 &self,
4325 err: &mut Diag<'_>,
4326 name: Option<Ident>,
4327 mut consider: impl FnMut(LifetimeBinderKind) -> bool,
4328 suggest: impl Fn(
4329 &mut Diag<'_>,
4330 bool,
4331 Span,
4332 Cow<'static, str>,
4333 String,
4334 Vec<(Span, String)>,
4335 ) -> bool,
4336 ) {
4337 let mut suggest_note = true;
4338 for rib in self.lifetime_ribs.iter().rev() {
4339 let mut should_continue = true;
4340 match rib.kind {
4341 LifetimeRibKind::Generics { binder, span, kind } => {
4342 if let LifetimeBinderKind::ConstItem = kind
4345 && !self.r.tcx().features().generic_const_items()
4346 {
4347 continue;
4348 }
4349 if #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::ImplAssocType => true,
_ => false,
}matches!(kind, LifetimeBinderKind::ImplAssocType) || !consider(kind) {
4350 continue;
4351 }
4352
4353 if !span.can_be_used_for_suggestions()
4354 && suggest_note
4355 && let Some(name) = name
4356 {
4357 suggest_note = false; err.span_label(
4359 span,
4360 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}` is missing in item created through this procedural macro",
name))
})format!(
4361 "lifetime `{name}` is missing in item created through this procedural macro",
4362 ),
4363 );
4364 continue;
4365 }
4366
4367 let higher_ranked = #[allow(non_exhaustive_omitted_patterns)] match kind {
LifetimeBinderKind::FnPtrType | LifetimeBinderKind::PolyTrait |
LifetimeBinderKind::WhereBound => true,
_ => false,
}matches!(
4368 kind,
4369 LifetimeBinderKind::FnPtrType
4370 | LifetimeBinderKind::PolyTrait
4371 | LifetimeBinderKind::WhereBound
4372 );
4373
4374 let mut rm_inner_binders: FxIndexSet<Span> = Default::default();
4375 let (span, sugg) = if span.is_empty() {
4376 let mut binder_idents: FxIndexSet<Ident> = Default::default();
4377 binder_idents.insert(name.unwrap_or(Ident::from_str("'a")));
4378
4379 if let LifetimeBinderKind::WhereBound = kind
4386 && let Some(predicate) = self.diag_metadata.current_where_predicate
4387 && let ast::WherePredicateKind::BoundPredicate(
4388 ast::WhereBoundPredicate { bounded_ty, bounds, .. },
4389 ) = &predicate.kind
4390 && bounded_ty.id == binder
4391 {
4392 for bound in bounds {
4393 if let ast::GenericBound::Trait(poly_trait_ref) = bound
4394 && let span = poly_trait_ref
4395 .span
4396 .with_hi(poly_trait_ref.trait_ref.path.span.lo())
4397 && !span.is_empty()
4398 {
4399 rm_inner_binders.insert(span);
4400 poly_trait_ref.bound_generic_params.iter().for_each(|v| {
4401 binder_idents.insert(v.ident);
4402 });
4403 }
4404 }
4405 }
4406
4407 let binders_sugg: String = binder_idents
4408 .into_iter()
4409 .map(|ident| ident.to_string())
4410 .intersperse(", ".to_owned())
4411 .collect();
4412 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!(
4413 "{}<{}>{}",
4414 if higher_ranked { "for" } else { "" },
4415 binders_sugg,
4416 if higher_ranked { " " } else { "" },
4417 );
4418 (span, sugg)
4419 } else {
4420 let span = self
4421 .r
4422 .tcx
4423 .sess
4424 .source_map()
4425 .span_through_char(span, '<')
4426 .shrink_to_hi();
4427 let sugg =
4428 ::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"));
4429 (span, sugg)
4430 };
4431
4432 if higher_ranked {
4433 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!(
4434 "consider making the {} lifetime-generic with a new `{}` lifetime",
4435 kind.descr(),
4436 name.map(|i| i.to_string()).as_deref().unwrap_or("'a"),
4437 ));
4438 should_continue = suggest(
4439 err,
4440 true,
4441 span,
4442 message,
4443 sugg,
4444 if !rm_inner_binders.is_empty() {
4445 rm_inner_binders
4446 .into_iter()
4447 .map(|v| (v, "".to_string()))
4448 .collect::<Vec<_>>()
4449 } else {
4450 ::alloc::vec::Vec::new()vec![]
4451 },
4452 );
4453 err.note_once(
4454 "for more information on higher-ranked polymorphism, visit \
4455 https://doc.rust-lang.org/nomicon/hrtb.html",
4456 );
4457 } else if let Some(name) = name {
4458 let message =
4459 Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider introducing lifetime `{0}` here",
name))
})format!("consider introducing lifetime `{name}` here"));
4460 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4461 } else {
4462 let message = Cow::from("consider introducing a named lifetime parameter");
4463 should_continue = suggest(err, false, span, message, sugg, ::alloc::vec::Vec::new()vec![]);
4464 }
4465 }
4466 LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => break,
4467 _ => {}
4468 }
4469 if !should_continue {
4470 break;
4471 }
4472 }
4473 }
4474
4475 pub(crate) fn emit_non_static_lt_in_const_param_ty_error(
4476 &self,
4477 lifetime_ref: &ast::Lifetime,
4478 ) -> ErrorGuaranteed {
4479 self.r.dcx().emit_err(diagnostics::ParamInTyOfConstParam {
4480 span: lifetime_ref.ident.span,
4481 name: lifetime_ref.ident.name,
4482 })
4483 }
4484
4485 pub(crate) fn emit_forbidden_non_static_lifetime_error(
4489 &self,
4490 cause: NoConstantGenericsReason,
4491 lifetime_ref: &ast::Lifetime,
4492 ) -> ErrorGuaranteed {
4493 match cause {
4494 NoConstantGenericsReason::IsEnumDiscriminant => {
4495 self.r.dcx().emit_err(diagnostics::ParamInEnumDiscriminant {
4496 span: lifetime_ref.ident.span,
4497 name: lifetime_ref.ident.name,
4498 param_kind: diagnostics::ParamKindInEnumDiscriminant::Lifetime,
4499 })
4500 }
4501 NoConstantGenericsReason::NonTrivialConstArg => {
4502 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());
4503 self.r.dcx().emit_err(diagnostics::ParamInNonTrivialAnonConst {
4504 span: lifetime_ref.ident.span,
4505 name: lifetime_ref.ident.name,
4506 param_kind: diagnostics::ParamKindInNonTrivialAnonConst::Lifetime,
4507 help: self.r.tcx.sess.is_nightly_build() && !self.r.features.gca(),
4508 is_gca_const_items: self.r.features.gca_const_items(),
4509 help_gca: self.r.features.gca_const_items(),
4510 help_suggest_gca: self.r.tcx.sess.is_nightly_build()
4511 && !self.r.features.gca_const_items(),
4512 })
4513 }
4514 }
4515 }
4516
4517 pub(crate) fn report_missing_lifetime_specifiers<'a>(
4518 &mut self,
4519 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4520 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4521 ) -> ErrorGuaranteed {
4522 let num_lifetimes: usize = lifetime_refs.clone().into_iter().map(|lt| lt.count).sum();
4523 let spans: Vec<_> = lifetime_refs.clone().into_iter().map(|lt| lt.span).collect();
4524
4525 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!(
4526 self.r.dcx(),
4527 spans,
4528 E0106,
4529 "missing lifetime specifier{}",
4530 pluralize!(num_lifetimes)
4531 );
4532 self.add_missing_lifetime_specifiers_label(
4533 &mut err,
4534 lifetime_refs,
4535 function_param_lifetimes,
4536 );
4537 err.emit_err()
4538 }
4539
4540 fn add_missing_lifetime_specifiers_label<'a>(
4541 &mut self,
4542 err: &mut Diag<'_>,
4543 lifetime_refs: impl Clone + IntoIterator<Item = &'a MissingLifetime>,
4544 function_param_lifetimes: Option<(Vec<MissingLifetime>, Vec<ElisionFnParameter>)>,
4545 ) {
4546 for < in lifetime_refs.clone() {
4547 err.span_label(
4548 lt.span,
4549 ::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!(
4550 "expected {} lifetime parameter{}",
4551 if lt.count == 1 { "named".to_string() } else { lt.count.to_string() },
4552 pluralize!(lt.count),
4553 ),
4554 );
4555 }
4556
4557 let mut in_scope_lifetimes: Vec<_> = self
4558 .lifetime_ribs
4559 .iter()
4560 .rev()
4561 .take_while(|rib| {
4562 !#[allow(non_exhaustive_omitted_patterns)] match rib.kind {
LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy => true,
_ => false,
}matches!(rib.kind, LifetimeRibKind::Item | LifetimeRibKind::ConstParamTy)
4563 })
4564 .flat_map(|rib| rib.bindings.iter())
4565 .map(|(&ident, &res)| (ident, res))
4566 .filter(|(ident, _)| ident.name != kw::UnderscoreLifetime)
4567 .collect();
4568 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4568",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4568u32),
::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);
4569
4570 let mut maybe_static = false;
4571 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4571",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4571u32),
::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);
4572 if let Some((param_lifetimes, params)) = &function_param_lifetimes {
4573 let elided_len = param_lifetimes.len();
4574 let num_params = params.len();
4575
4576 let mut m = String::new();
4577
4578 for (i, info) in params.iter().enumerate() {
4579 let ElisionFnParameter { ident, index, lifetime_count, span } = *info;
4580 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);
4581
4582 err.span_label(span, "");
4583
4584 if i != 0 {
4585 if i + 1 < num_params {
4586 m.push_str(", ");
4587 } else if num_params == 2 {
4588 m.push_str(" or ");
4589 } else {
4590 m.push_str(", or ");
4591 }
4592 }
4593
4594 let help_name = if let Some(ident) = ident {
4595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", ident))
})format!("`{ident}`")
4596 } else {
4597 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("argument {0}", index + 1))
})format!("argument {}", index + 1)
4598 };
4599
4600 if lifetime_count == 1 {
4601 m.push_str(&help_name[..])
4602 } else {
4603 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")[..])
4604 }
4605 }
4606
4607 if num_params == 0 {
4608 err.help(
4609 "this function's return type contains a borrowed value, but there is no value \
4610 for it to be borrowed from",
4611 );
4612 if in_scope_lifetimes.is_empty() {
4613 maybe_static = true;
4614 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![(
4615 Ident::with_dummy_span(kw::StaticLifetime),
4616 (DUMMY_NODE_ID, LifetimeRes::Static),
4617 )];
4618 }
4619 } else if elided_len == 0 {
4620 err.help(
4621 "this function's return type contains a borrowed value with an elided \
4622 lifetime, but the lifetime cannot be derived from the arguments",
4623 );
4624 if in_scope_lifetimes.is_empty() {
4625 maybe_static = true;
4626 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![(
4627 Ident::with_dummy_span(kw::StaticLifetime),
4628 (DUMMY_NODE_ID, LifetimeRes::Static),
4629 )];
4630 }
4631 } else if num_params == 1 {
4632 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!(
4633 "this function's return type contains a borrowed value, but the signature does \
4634 not say which {m} it is borrowed from",
4635 ));
4636 } else {
4637 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!(
4638 "this function's return type contains a borrowed value, but the signature does \
4639 not say whether it is borrowed from {m}",
4640 ));
4641 }
4642 }
4643
4644 #[allow(rustc::symbol_intern_string_literal)]
4645 let existing_name = match &in_scope_lifetimes[..] {
4646 [] => Symbol::intern("'a"),
4647 [(existing, _)] => existing.name,
4648 _ => Symbol::intern("'lifetime"),
4649 };
4650
4651 let mut spans_suggs: Vec<_> = Vec::new();
4652 let source_map = self.r.tcx.sess.source_map();
4653 let build_sugg = |lt: MissingLifetime| match lt.kind {
4654 MissingLifetimeKind::Underscore => {
4655 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);
4656 (lt.span, existing_name.to_string())
4657 }
4658 MissingLifetimeKind::Ampersand => {
4659 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);
4660 (lt.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ", existing_name))
})format!("{existing_name} "))
4661 }
4662 MissingLifetimeKind::Comma => {
4663 let sugg: String = std::iter::repeat_n(existing_name.as_str(), lt.count)
4664 .intersperse(", ")
4665 .collect();
4666 let is_empty_brackets = source_map.span_followed_by(lt.span, ">").is_some();
4667 let sugg = if is_empty_brackets { sugg } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", sugg))
})format!("{sugg}, ") };
4668 (lt.span.shrink_to_hi(), sugg)
4669 }
4670 MissingLifetimeKind::Brackets => {
4671 let sugg: String = std::iter::once("<")
4672 .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", "))
4673 .chain([">"])
4674 .collect();
4675 (lt.span.shrink_to_hi(), sugg)
4676 }
4677 };
4678 for < in lifetime_refs.clone() {
4679 spans_suggs.push(build_sugg(lt));
4680 }
4681 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs:4681",
"rustc_resolve::late::diagnostics", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_resolve/src/late/diagnostics.rs"),
::tracing_core::__macro_support::Option::Some(4681u32),
::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);
4682 match in_scope_lifetimes.len() {
4683 0 => {
4684 if let Some((param_lifetimes, _)) = function_param_lifetimes {
4685 for lt in param_lifetimes {
4686 spans_suggs.push(build_sugg(lt))
4687 }
4688 }
4689 self.suggest_introducing_lifetime(
4690 err,
4691 None,
4692 |err, higher_ranked, span, message, intro_sugg, _| {
4693 err.multipart_suggestion(
4694 message,
4695 std::iter::once((span, intro_sugg))
4696 .chain(spans_suggs.clone())
4697 .collect(),
4698 Applicability::MaybeIncorrect,
4699 );
4700 higher_ranked
4701 },
4702 );
4703 }
4704 1 => {
4705 let post = if maybe_static {
4706 let mut lifetime_refs = lifetime_refs.clone().into_iter();
4707 let owned = if let Some(lt) = lifetime_refs.next()
4708 && lifetime_refs.next().is_none()
4709 && lt.kind != MissingLifetimeKind::Ampersand
4710 {
4711 ", or if you will only have owned values"
4712 } else {
4713 ""
4714 };
4715 ::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!(
4716 ", but this is uncommon unless you're returning a borrowed value from a \
4717 `const` or a `static`{owned}",
4718 )
4719 } else {
4720 String::new()
4721 };
4722 err.multipart_suggestion(
4723 ::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}"),
4724 spans_suggs,
4725 Applicability::MaybeIncorrect,
4726 );
4727 if maybe_static {
4728 let mut lifetime_refs = lifetime_refs.into_iter();
4734 if let Some(lt) = lifetime_refs.next()
4735 && lifetime_refs.next().is_none()
4736 && (lt.kind == MissingLifetimeKind::Ampersand
4737 || lt.kind == MissingLifetimeKind::Underscore)
4738 {
4739 let pre = if let Some((kind, _span)) = self.diag_metadata.current_function
4740 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4741 && !sig.decl.inputs.is_empty()
4742 && let sugg = sig
4743 .decl
4744 .inputs
4745 .iter()
4746 .filter_map(|param| {
4747 if param.ty.span.contains(lt.span) {
4748 None
4751 } else if let TyKind::CVarArgs = param.ty.kind {
4752 None
4754 } else if let TyKind::ImplTrait(..) = ¶m.ty.kind {
4755 None
4757 } else {
4758 Some((param.ty.span.shrink_to_lo(), "&".to_string()))
4759 }
4760 })
4761 .collect::<Vec<_>>()
4762 && !sugg.is_empty()
4763 {
4764 let (the, s) = if sig.decl.inputs.len() == 1 {
4765 ("the", "")
4766 } else {
4767 ("one of the", "s")
4768 };
4769 let dotdotdot =
4770 if lt.kind == MissingLifetimeKind::Ampersand { "..." } else { "" };
4771 err.multipart_suggestion(
4772 ::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!(
4773 "instead, you are more likely to want to change {the} \
4774 argument{s} to be borrowed{dotdotdot}",
4775 ),
4776 sugg,
4777 Applicability::MaybeIncorrect,
4778 );
4779 "...or alternatively, you might want"
4780 } else if (lt.kind == MissingLifetimeKind::Ampersand
4781 || lt.kind == MissingLifetimeKind::Underscore)
4782 && let Some((kind, _span)) = self.diag_metadata.current_function
4783 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4784 && let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output
4785 && !sig.decl.inputs.is_empty()
4786 && let arg_refs = sig
4787 .decl
4788 .inputs
4789 .iter()
4790 .filter_map(|param| match ¶m.ty.kind {
4791 TyKind::ImplTrait(_, bounds) => Some(bounds),
4792 _ => None,
4793 })
4794 .flat_map(|bounds| bounds.into_iter())
4795 .collect::<Vec<_>>()
4796 && !arg_refs.is_empty()
4797 {
4798 let mut lt_finder =
4804 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4805 for bound in arg_refs {
4806 if let ast::GenericBound::Trait(trait_ref) = bound {
4807 lt_finder.visit_trait_ref(&trait_ref.trait_ref);
4808 }
4809 }
4810 lt_finder.visit_ty(ret_ty);
4811 let spans_suggs: Vec<_> = lt_finder
4812 .seen
4813 .iter()
4814 .filter_map(|ty| match &ty.kind {
4815 TyKind::Ref(_, inner_ty, _) => {
4816 let span = ty.span.with_hi(inner_ty.span.lo());
4817 Some((span, "&'a ".to_string()))
4818 }
4819 _ => None,
4820 })
4821 .collect();
4822 self.suggest_introducing_lifetime(
4823 err,
4824 None,
4825 |err, higher_ranked, span, message, intro_sugg, _| {
4826 err.multipart_suggestion(
4827 message,
4828 std::iter::once((span, intro_sugg))
4829 .chain(spans_suggs.clone())
4830 .collect(),
4831 Applicability::MaybeIncorrect,
4832 );
4833 higher_ranked
4834 },
4835 );
4836 "alternatively, you might want"
4837 } else {
4838 "instead, you are more likely to want"
4839 };
4840 let mut owned_sugg = lt.kind == MissingLifetimeKind::Ampersand;
4841 let mut sugg_slice_to_vec_or_string = false;
4842 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())];
4843 if let Some((kind, _span)) = self.diag_metadata.current_function
4844 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4845 {
4846 let mut lt_finder =
4847 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4848 for param in &sig.decl.inputs {
4849 lt_finder.visit_ty(¶m.ty);
4850 }
4851 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4852 lt_finder.visit_ty(ret_ty);
4853 let mut ret_lt_finder =
4854 LifetimeFinder { lifetime: lt.span, found: None, seen: ::alloc::vec::Vec::new()vec![] };
4855 ret_lt_finder.visit_ty(ret_ty);
4856 if let [Ty { span, kind: TyKind::Ref(_, inner_ty, _), .. }] =
4857 &ret_lt_finder.seen[..]
4858 {
4859 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())];
4865 owned_sugg = true;
4866 }
4867 }
4868 if let Some(ty) = lt_finder.found {
4869 if let TyKind::Path(None, path) = &ty.kind {
4870 let path: Vec<_> = Segment::from_path(path);
4872 match self.resolve_path(
4873 &path,
4874 Some(TypeNS),
4875 None,
4876 PathSource::Type,
4877 ) {
4878 PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
4879 match module.res() {
4880 Some(Res::PrimTy(PrimTy::Str)) => {
4881 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![(
4883 lt.span.with_hi(ty.span.hi()),
4884 "String".to_string(),
4885 )];
4886 sugg_slice_to_vec_or_string = true;
4887 }
4888 Some(Res::PrimTy(..)) => {}
4889 Some(Res::Def(
4890 DefKind::Struct
4891 | DefKind::Union
4892 | DefKind::Enum
4893 | DefKind::ForeignTy
4894 | DefKind::AssocTy
4895 | DefKind::OpaqueTy
4896 | DefKind::TyParam,
4897 _,
4898 )) => {}
4899 _ => {
4900 owned_sugg = false;
4902 }
4903 }
4904 }
4905 PathResult::NonModule(res) => {
4906 match res.base_res() {
4907 Res::PrimTy(PrimTy::Str) => {
4908 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![(
4910 lt.span.with_hi(ty.span.hi()),
4911 "String".to_string(),
4912 )];
4913 sugg_slice_to_vec_or_string = true;
4914 }
4915 Res::PrimTy(..) => {}
4916 Res::Def(
4917 DefKind::Struct
4918 | DefKind::Union
4919 | DefKind::Enum
4920 | DefKind::ForeignTy
4921 | DefKind::AssocTy
4922 | DefKind::OpaqueTy
4923 | DefKind::TyParam,
4924 _,
4925 ) => {}
4926 _ => {
4927 owned_sugg = false;
4929 }
4930 }
4931 }
4932 _ => {
4933 owned_sugg = false;
4935 }
4936 }
4937 }
4938 if let TyKind::Slice(inner_ty) = &ty.kind {
4939 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![
4941 (lt.span.with_hi(inner_ty.span.lo()), "Vec<".to_string()),
4942 (ty.span.with_lo(inner_ty.span.hi()), ">".to_string()),
4943 ];
4944 sugg_slice_to_vec_or_string = true;
4945 }
4946 }
4947 }
4948 if owned_sugg {
4949 if let Some(span) =
4951 self.find_ref_prefix_span_for_owned_suggestion(lt.span)
4952 && !sugg_slice_to_vec_or_string
4953 {
4954 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())];
4955 }
4956 err.multipart_suggestion(
4957 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} to return an owned value",
pre))
})format!("{pre} to return an owned value"),
4958 sugg,
4959 Applicability::MaybeIncorrect,
4960 );
4961 }
4962 }
4963 }
4964 }
4965 _ => {
4966 let lifetime_spans: Vec<_> =
4967 in_scope_lifetimes.iter().map(|(ident, _)| ident.span).collect();
4968 err.span_note(lifetime_spans, "these named lifetimes are available to use");
4969
4970 if spans_suggs.len() > 0 {
4971 err.multipart_suggestion(
4974 "consider using one of the available lifetimes here",
4975 spans_suggs,
4976 Applicability::HasPlaceholders,
4977 );
4978 }
4979 }
4980 }
4981 }
4982
4983 fn find_ref_prefix_span_for_owned_suggestion(&self, lifetime: Span) -> Option<Span> {
4984 let mut finder = RefPrefixSpanFinder { lifetime, span: None };
4985 if let Some(item) = self.diag_metadata.current_item {
4986 finder.visit_item(item);
4987 } else if let Some((kind, _span)) = self.diag_metadata.current_function
4988 && let FnKind::Fn(_, _, ast::Fn { sig, .. }) = kind
4989 {
4990 for param in &sig.decl.inputs {
4991 finder.visit_ty(¶m.ty);
4992 }
4993 if let ast::FnRetTy::Ty(ret_ty) = &sig.decl.output {
4994 finder.visit_ty(ret_ty);
4995 }
4996 }
4997 finder.span
4998 }
4999}
5000
5001fn mk_where_bound_predicate(
5002 path: &Path,
5003 poly_trait_ref: &ast::PolyTraitRef,
5004 ty: &Ty,
5005) -> Option<ast::WhereBoundPredicate> {
5006 let modified_segments = {
5007 let mut segments = path.segments.clone();
5008 let [preceding @ .., second_last, last] = segments.as_mut_slice() else {
5009 return None;
5010 };
5011 let mut segments = ThinVec::from(preceding);
5012
5013 let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocItemConstraint {
5014 id: DUMMY_NODE_ID,
5015 ident: last.ident,
5016 gen_args: None,
5017 kind: ast::AssocItemConstraintKind::Equality {
5018 term: ast::Term::Ty(Box::new(ast::Ty {
5019 kind: ast::TyKind::Path(None, poly_trait_ref.trait_ref.path.clone()),
5020 id: DUMMY_NODE_ID,
5021 span: DUMMY_SP,
5022 })),
5023 },
5024 span: DUMMY_SP,
5025 });
5026
5027 match second_last.args.as_deref_mut() {
5028 Some(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { args, .. })) => {
5029 args.push(added_constraint);
5030 }
5031 Some(_) => return None,
5032 None => {
5033 second_last.args =
5034 Some(Box::new(ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs {
5035 args: ThinVec::from([added_constraint]),
5036 span: DUMMY_SP,
5037 })));
5038 }
5039 }
5040
5041 segments.push(second_last.clone());
5042 segments
5043 };
5044
5045 let new_where_bound_predicate = ast::WhereBoundPredicate {
5046 bound_generic_params: ThinVec::new(),
5047 bounded_ty: Box::new(ty.clone()),
5048 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 {
5049 bound_generic_params: ThinVec::new(),
5050 modifiers: ast::TraitBoundModifiers::NONE,
5051 trait_ref: ast::TraitRef {
5052 path: ast::Path { segments: modified_segments, span: DUMMY_SP },
5053 ref_id: DUMMY_NODE_ID,
5054 },
5055 span: DUMMY_SP,
5056 parens: ast::Parens::No,
5057 })],
5058 };
5059
5060 Some(new_where_bound_predicate)
5061}
5062
5063pub(super) fn signal_lifetime_shadowing(
5065 sess: &Session,
5066 orig: Ident,
5067 shadower: Ident,
5068) -> ErrorGuaranteed {
5069 {
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!(
5070 sess.dcx(),
5071 shadower.span,
5072 E0496,
5073 "lifetime name `{}` shadows a lifetime name that is already in scope",
5074 orig.name,
5075 )
5076 .with_span_label(orig.span, "first declared here")
5077 .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))
5078 .emit_err()
5079}
5080
5081struct LifetimeFinder<'ast> {
5082 lifetime: Span,
5083 found: Option<&'ast Ty>,
5084 seen: Vec<&'ast Ty>,
5085}
5086
5087impl<'ast> Visitor<'ast> for LifetimeFinder<'ast> {
5088 fn visit_ty(&mut self, t: &'ast Ty) {
5089 if let TyKind::Ref(_, ty, _) | TyKind::PinnedRef(_, ty, _) = &t.kind {
5090 self.seen.push(t);
5091 if t.span.lo() == self.lifetime.lo() {
5092 self.found = Some(ty);
5093 }
5094 }
5095 walk_ty(self, t)
5096 }
5097}
5098
5099struct RefPrefixSpanFinder {
5100 lifetime: Span,
5101 span: Option<Span>,
5102}
5103
5104impl<'ast> Visitor<'ast> for RefPrefixSpanFinder {
5105 fn visit_ty(&mut self, t: &'ast Ty) {
5106 if self.span.is_some() {
5107 return;
5108 }
5109 if let TyKind::Ref(_, inner_ty, _) | TyKind::PinnedRef(_, inner_ty, _) = &t.kind
5110 && t.span.lo() == self.lifetime.lo()
5111 {
5112 self.span = Some(t.span.with_hi(inner_ty.span.lo()));
5113 return;
5114 }
5115 walk_ty(self, t);
5116 }
5117}
5118
5119pub(super) fn signal_label_shadowing(sess: &Session, orig: Span, shadower: Ident) {
5122 let name = shadower.name;
5123 let shadower = shadower.span;
5124 sess.dcx()
5125 .struct_span_warn(
5126 shadower,
5127 ::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"),
5128 )
5129 .with_span_label(orig, "first declared here")
5130 .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"))
5131 .emit();
5132}
5133
5134struct ParentPathVisitor<'a> {
5135 target: Ident,
5136 parent: Option<&'a PathSegment>,
5137 stack: Vec<&'a Ty>,
5138}
5139
5140impl<'a> ParentPathVisitor<'a> {
5141 fn new(self_ty: &'a Ty, target: Ident) -> Self {
5142 let mut v = ParentPathVisitor { target, parent: None, stack: Vec::new() };
5143
5144 v.visit_ty(self_ty);
5145 v
5146 }
5147}
5148
5149impl<'a> Visitor<'a> for ParentPathVisitor<'a> {
5150 fn visit_ty(&mut self, ty: &'a Ty) {
5151 if self.parent.is_some() {
5152 return;
5153 }
5154
5155 self.stack.push(ty);
5157
5158 if let TyKind::Path(_, path) = &ty.kind
5159 && let [segment] = path.segments.as_slice()
5161 && segment.ident == self.target
5162 && let [.., parent_ty, _ty] = self.stack.as_slice()
5164 && let TyKind::Path(_, parent_path) = &parent_ty.kind
5165 {
5166 self.parent = parent_path.segments.first();
5167 }
5168
5169 walk_ty(self, ty);
5170
5171 self.stack.pop();
5172 }
5173}