]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_typeck/src/method/suggest.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / compiler / rustc_hir_typeck / src / method / suggest.rs
CommitLineData
d9579d0f 1//! Give useful errors and suggestions to users when an item can't be
85aaf69f
SL
2//! found or is otherwise invalid.
3
2b03887a 4use crate::errors;
9c376795 5use crate::Expectation;
2b03887a
FG
6use crate::FnCtxt;
7use rustc_ast::ast::Mutability;
74b04a01 8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
487cf647 9use rustc_errors::StashKey;
5e7ed085
FG
10use rustc_errors::{
11 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
04454e1e 12 MultiSpan,
5e7ed085 13};
dfeec247 14use rustc_hir as hir;
04454e1e
FG
15use rustc_hir::def::DefKind;
16use rustc_hir::def_id::DefId;
3dfed10e 17use rustc_hir::lang_items::LangItem;
487cf647
FG
18use rustc_hir::PatKind::Binding;
19use rustc_hir::PathSegment;
dfeec247 20use rustc_hir::{ExprKind, Node, QPath};
487cf647
FG
21use rustc_infer::infer::{
22 type_variable::{TypeVariableOrigin, TypeVariableOriginKind},
23 RegionVariableOrigin,
24};
25use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
5099ac24 26use rustc_middle::traits::util::supertraits;
487cf647 27use rustc_middle::ty::fast_reject::DeepRejectCtxt;
5e7ed085 28use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
9c376795 29use rustc_middle::ty::print::{with_crate_prefix, with_forced_trimmed_paths};
9ffffee4 30use rustc_middle::ty::{self, DefIdTree, GenericArgKind, Ty, TyCtxt, TypeVisitableExt};
f2b60f7d 31use rustc_middle::ty::{IsSuggestable, ToPolyTraitRef};
3dfed10e 32use rustc_span::symbol::{kw, sym, Ident};
064997fb 33use rustc_span::Symbol;
9ffffee4 34use rustc_span::{edit_distance, source_map, ExpnKind, FileName, MacroKind, Span};
487cf647 35use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedNote;
2b03887a 36use rustc_trait_selection::traits::error_reporting::on_unimplemented::TypeErrCtxtExt as _;
5e7ed085 37use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
3c0e092e 38use rustc_trait_selection::traits::{
487cf647 39 FulfillmentError, Obligation, ObligationCause, ObligationCauseCode,
3c0e092e 40};
85aaf69f 41
2b03887a 42use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope};
f2b60f7d 43use super::{CandidateSource, MethodError, NoMatchData};
487cf647
FG
44use rustc_hir::intravisit::Visitor;
45use std::cmp::Ordering;
46use std::iter;
85aaf69f 47
dc9dc135 48impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48663c56 49 fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
a7813a04 50 let tcx = self.tcx;
1b1a35ee 51 match ty.kind() {
0731742a
XL
52 // Not all of these (e.g., unsafe fns) implement `FnOnce`,
53 // so we look for these beforehand.
dfeec247 54 ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
0731742a 55 // If it's not a simple function, look for things which implement `FnOnce`.
a7813a04 56 _ => {
5e7ed085
FG
57 let Some(fn_once) = tcx.lang_items().fn_once_trait() else {
58 return false;
3157f602 59 };
a7813a04 60
5099ac24
FG
61 // This conditional prevents us from asking to call errors and unresolved types.
62 // It might seem that we can use `predicate_must_hold_modulo_regions`,
63 // but since a Dummy binder is used to fill in the FnOnce trait's arguments,
64 // type resolution always gives a "maybe" here.
65 if self.autoderef(span, ty).any(|(ty, _)| {
66 info!("check deref {:?} error", ty);
67 matches!(ty.kind(), ty::Error(_) | ty::Infer(_))
68 }) {
69 return false;
70 }
71
c30ab7b3 72 self.autoderef(span, ty).any(|(ty, _)| {
5099ac24 73 info!("check deref {:?} impl FnOnce", ty);
c30ab7b3 74 self.probe(|_| {
487cf647
FG
75 let trait_ref = tcx.mk_trait_ref(
76 fn_once,
77 [
78 ty,
79 self.next_ty_var(TypeVariableOrigin {
dfeec247
XL
80 kind: TypeVariableOriginKind::MiscVariable,
81 span,
487cf647
FG
82 }),
83 ],
dfeec247 84 );
c295e0f8 85 let poly_trait_ref = ty::Binder::dummy(trait_ref);
dfeec247 86 let obligation = Obligation::misc(
487cf647 87 tcx,
dfeec247
XL
88 span,
89 self.body_id,
90 self.param_env,
487cf647 91 poly_trait_ref.without_const(),
dfeec247 92 );
83c7162d 93 self.predicate_may_hold(&obligation)
c30ab7b3
SL
94 })
95 })
54a0048b
SL
96 }
97 }
98 }
3157f602 99
a2a8927a
XL
100 fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
101 self.autoderef(span, ty).any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
102 }
103
9c376795 104 #[instrument(level = "debug", skip(self))]
cdc7bbd5 105 pub fn report_method_error(
532ac7d7 106 &self,
9c376795 107 span: Span,
532ac7d7 108 rcvr_ty: Ty<'tcx>,
f9f354fc 109 item_name: Ident,
cdc7bbd5 110 source: SelfSource<'tcx>,
532ac7d7 111 error: MethodError<'tcx>,
f2b60f7d 112 args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
9c376795 113 expected: Expectation<'tcx>,
5e7ed085 114 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
0731742a 115 // Avoid suggestions when we don't know what's going on.
a7813a04 116 if rcvr_ty.references_error() {
e1599b0c 117 return None;
a7813a04 118 }
85aaf69f 119
9c376795
FG
120 let sugg_span = if let SelfSource::MethodCall(expr) = source {
121 // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing.
122 self.tcx.hir().expect_expr(self.tcx.hir().parent_id(expr.hir_id)).span
123 } else {
124 span
125 };
064997fb 126
9c376795
FG
127 match error {
128 MethodError::NoMatch(mut no_match_data) => {
129 return self.report_no_match_method_error(
130 span,
131 rcvr_ty,
132 item_name,
133 source,
134 args,
135 sugg_span,
136 &mut no_match_data,
137 expected,
138 );
139 }
a7813a04 140
9c376795
FG
141 MethodError::Ambiguity(mut sources) => {
142 let mut err = struct_span_err!(
143 self.sess(),
144 item_name.span,
145 E0034,
146 "multiple applicable items in scope"
147 );
148 err.span_label(item_name.span, format!("multiple `{}` found", item_name));
a7813a04 149
9c376795
FG
150 self.note_candidates_on_method_error(
151 rcvr_ty,
152 item_name,
153 args,
154 span,
155 &mut err,
156 &mut sources,
157 Some(sugg_span),
158 );
159 err.emit();
160 }
a7813a04 161
9c376795 162 MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
9ffffee4 163 let kind = self.tcx.def_kind_descr(kind, def_id);
9c376795
FG
164 let mut err = struct_span_err!(
165 self.tcx.sess,
166 item_name.span,
167 E0624,
168 "{} `{}` is private",
169 kind,
170 item_name
171 );
172 err.span_label(item_name.span, &format!("private {}", kind));
173 let sp = self
174 .tcx
175 .hir()
176 .span_if_local(def_id)
177 .unwrap_or_else(|| self.tcx.def_span(def_id));
178 err.span_label(sp, &format!("private {} defined here", kind));
179 self.suggest_valid_traits(&mut err, out_of_scope_traits);
180 err.emit();
181 }
182
183 MethodError::IllegalSizedBound { candidates, needs_mut, bound_span, self_expr } => {
184 let msg = if needs_mut {
185 with_forced_trimmed_paths!(format!(
186 "the `{item_name}` method cannot be invoked on `{rcvr_ty}`"
187 ))
188 } else {
189 format!("the `{item_name}` method cannot be invoked on a trait object")
190 };
191 let mut err = self.sess().struct_span_err(span, &msg);
192 if !needs_mut {
193 err.span_label(bound_span, "this has a `Sized` requirement");
194 }
195 if !candidates.is_empty() {
196 let help = format!(
197 "{an}other candidate{s} {were} found in the following trait{s}, perhaps \
198 add a `use` for {one_of_them}:",
199 an = if candidates.len() == 1 { "an" } else { "" },
200 s = pluralize!(candidates.len()),
201 were = pluralize!("was", candidates.len()),
202 one_of_them = if candidates.len() == 1 { "it" } else { "one_of_them" },
203 );
204 self.suggest_use_candidates(&mut err, help, candidates);
205 }
206 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
207 if needs_mut {
208 let trait_type = self.tcx.mk_ref(
209 *region,
210 ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() },
211 );
212 let msg = format!("you need `{}` instead of `{}`", trait_type, rcvr_ty);
213 let mut kind = &self_expr.kind;
214 while let hir::ExprKind::AddrOf(_, _, expr)
215 | hir::ExprKind::Unary(hir::UnOp::Deref, expr) = kind
216 {
217 kind = &expr.kind;
416331ca 218 }
9c376795
FG
219 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = kind
220 && let hir::def::Res::Local(hir_id) = path.res
221 && let Some(hir::Node::Pat(b)) = self.tcx.hir().find(hir_id)
222 && let Some(hir::Node::Param(p)) = self.tcx.hir().find_parent(b.hir_id)
223 && let Some(node) = self.tcx.hir().find_parent(p.hir_id)
224 && let Some(decl) = node.fn_decl()
225 && let Some(ty) = decl.inputs.iter().find(|ty| ty.span == p.ty_span)
226 && let hir::TyKind::Ref(_, mut_ty) = &ty.kind
227 && let hir::Mutability::Not = mut_ty.mutbl
228 {
229 err.span_suggestion_verbose(
230 mut_ty.ty.span.shrink_to_lo(),
231 &msg,
232 "mut ",
233 Applicability::MachineApplicable,
dfeec247 234 );
94b46f34 235 } else {
9c376795 236 err.help(&msg);
487cf647 237 }
9cc50fc6 238 }
54a0048b 239 }
9c376795 240 err.emit();
54a0048b 241 }
62682a34 242
9c376795
FG
243 MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
244 }
245 None
246 }
247
248 pub fn report_no_match_method_error(
249 &self,
250 mut span: Span,
251 rcvr_ty: Ty<'tcx>,
252 item_name: Ident,
253 source: SelfSource<'tcx>,
254 args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
255 sugg_span: Span,
256 no_match_data: &mut NoMatchData<'tcx>,
257 expected: Expectation<'tcx>,
258 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
259 let mode = no_match_data.mode;
260 let tcx = self.tcx;
261 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
9ffffee4
FG
262 let (ty_str, ty_file) = tcx.short_ty_string(rcvr_ty);
263 let short_ty_str = with_forced_trimmed_paths!(rcvr_ty.to_string());
9c376795
FG
264 let is_method = mode == Mode::MethodCall;
265 let unsatisfied_predicates = &no_match_data.unsatisfied_predicates;
9ffffee4 266 let similar_candidate = no_match_data.similar_candidate;
9c376795
FG
267 let item_kind = if is_method {
268 "method"
269 } else if rcvr_ty.is_enum() {
270 "variant or associated item"
dfeec247 271 } else {
9c376795
FG
272 match (item_name.as_str().chars().next(), rcvr_ty.is_fresh_ty()) {
273 (Some(name), false) if name.is_lowercase() => "function or associated item",
274 (Some(_), false) => "associated item",
275 (Some(_), true) | (None, false) => "variant or associated item",
276 (None, true) => "variant",
277 }
dfeec247
XL
278 };
279
9ffffee4
FG
280 // We could pass the file for long types into these two, but it isn't strictly necessary
281 // given how targetted they are.
282 if self.suggest_wrapping_range_with_parens(
283 tcx,
284 rcvr_ty,
285 source,
286 span,
287 item_name,
288 &short_ty_str,
289 ) || self.suggest_constraining_numerical_ty(
290 tcx,
291 rcvr_ty,
292 source,
293 span,
294 item_kind,
295 item_name,
296 &short_ty_str,
297 ) {
9c376795
FG
298 return None;
299 }
300 span = item_name.span;
301
302 // Don't show generic arguments when the method can't be found in any implementation (#81576).
303 let mut ty_str_reported = ty_str.clone();
304 if let ty::Adt(_, generics) = rcvr_ty.kind() {
305 if generics.len() > 0 {
306 let mut autoderef = self.autoderef(span, rcvr_ty);
307 let candidate_found = autoderef.any(|(ty, _)| {
308 if let ty::Adt(adt_def, _) = ty.kind() {
309 self.tcx
310 .inherent_impls(adt_def.did())
311 .iter()
312 .any(|def_id| self.associated_value(*def_id, item_name).is_some())
313 } else {
314 false
ff7c6d11 315 }
9c376795
FG
316 });
317 let has_deref = autoderef.step_count() > 0;
318 if !candidate_found && !has_deref && unsatisfied_predicates.is_empty() {
319 if let Some((path_string, _)) = ty_str.split_once('<') {
320 ty_str_reported = path_string.to_string();
04454e1e
FG
321 }
322 }
9c376795
FG
323 }
324 }
17df50a5 325
9c376795
FG
326 let mut err = struct_span_err!(
327 tcx.sess,
328 span,
329 E0599,
330 "no {} named `{}` found for {} `{}` in the current scope",
331 item_kind,
332 item_name,
333 rcvr_ty.prefix_string(self.tcx),
334 ty_str_reported,
335 );
9ffffee4
FG
336 if tcx.sess.source_map().is_multiline(sugg_span) {
337 err.span_label(sugg_span.with_hi(span.lo()), "");
338 }
339 let ty_str = if short_ty_str.len() < ty_str.len() && ty_str.len() > 10 {
340 short_ty_str
341 } else {
342 ty_str
343 };
344 if let Some(file) = ty_file {
345 err.note(&format!("the full type name has been written to '{}'", file.display(),));
346 }
9c376795
FG
347 if rcvr_ty.references_error() {
348 err.downgrade_to_delayed_bug();
349 }
04454e1e 350
9c376795
FG
351 if let Mode::MethodCall = mode && let SelfSource::MethodCall(cal) = source {
352 self.suggest_await_before_method(
353 &mut err, item_name, rcvr_ty, cal, span, expected.only_has_type(self),
354 );
355 }
356 if let Some(span) =
357 tcx.resolutions(()).confused_type_with_std_module.get(&span.with_parent(None))
358 {
359 err.span_suggestion(
360 span.shrink_to_lo(),
361 "you are looking for the module in `std`, not the primitive type",
362 "std::",
363 Applicability::MachineApplicable,
364 );
365 }
366 if let ty::RawPtr(_) = &rcvr_ty.kind() {
367 err.note(
368 "try using `<*const T>::as_ref()` to get a reference to the \
369 type behind the pointer: https://doc.rust-lang.org/std/\
370 primitive.pointer.html#method.as_ref",
371 );
372 err.note(
373 "using `<*const T>::as_ref()` on a pointer which is unaligned or points \
374 to invalid or uninitialized memory is undefined behavior",
375 );
376 }
5e7ed085 377
9c376795
FG
378 let ty_span = match rcvr_ty.kind() {
379 ty::Param(param_type) => {
9ffffee4 380 Some(param_type.span_from_generics(self.tcx, self.body_id.to_def_id()))
9c376795
FG
381 }
382 ty::Adt(def, _) if def.did().is_local() => Some(tcx.def_span(def.did())),
383 _ => None,
384 };
385 if let Some(span) = ty_span {
386 err.span_label(
387 span,
388 format!(
389 "{item_kind} `{item_name}` not found for this {}",
390 rcvr_ty.prefix_string(self.tcx)
391 ),
392 );
393 }
ff7c6d11 394
9c376795
FG
395 if let SelfSource::MethodCall(rcvr_expr) = source {
396 self.suggest_fn_call(&mut err, rcvr_expr, rcvr_ty, |output_ty| {
397 let call_expr =
398 self.tcx.hir().expect_expr(self.tcx.hir().parent_id(rcvr_expr.hir_id));
399 let probe = self.lookup_probe_for_diagnostic(
400 item_name,
401 output_ty,
402 call_expr,
403 ProbeScope::AllTraits,
404 expected.only_has_type(self),
405 );
406 probe.is_ok()
407 });
408 }
85aaf69f 409
9c376795 410 let mut custom_span_label = false;
5e7ed085 411
9c376795
FG
412 let static_candidates = &mut no_match_data.static_candidates;
413 if !static_candidates.is_empty() {
414 err.note(
415 "found the following associated functions; to be used as methods, \
416 functions must have a `self` parameter",
417 );
418 err.span_label(span, "this is an associated function, not a method");
419 custom_span_label = true;
420 }
421 if static_candidates.len() == 1 {
422 self.suggest_associated_call_syntax(
423 &mut err,
424 &static_candidates,
425 rcvr_ty,
426 source,
427 item_name,
428 args,
429 sugg_span,
430 );
9c376795
FG
431 self.note_candidates_on_method_error(
432 rcvr_ty,
433 item_name,
434 args,
435 span,
436 &mut err,
437 static_candidates,
438 None,
439 );
440 } else if static_candidates.len() > 1 {
441 self.note_candidates_on_method_error(
442 rcvr_ty,
443 item_name,
444 args,
445 span,
446 &mut err,
447 static_candidates,
448 Some(sugg_span),
449 );
450 }
85aaf69f 451
9c376795
FG
452 let mut bound_spans = vec![];
453 let mut restrict_type_params = false;
454 let mut unsatisfied_bounds = false;
455 if item_name.name == sym::count && self.is_slice_ty(rcvr_ty, span) {
456 let msg = "consider using `len` instead";
457 if let SelfSource::MethodCall(_expr) = source {
458 err.span_suggestion_short(span, msg, "len", Applicability::MachineApplicable);
459 } else {
460 err.span_label(span, msg);
461 }
462 if let Some(iterator_trait) = self.tcx.get_diagnostic_item(sym::Iterator) {
463 let iterator_trait = self.tcx.def_path_str(iterator_trait);
464 err.note(&format!(
465 "`count` is defined on `{iterator_trait}`, which `{rcvr_ty}` does not implement"
466 ));
467 }
468 } else if !unsatisfied_predicates.is_empty() {
469 let mut type_params = FxHashMap::default();
470
471 // Pick out the list of unimplemented traits on the receiver.
472 // This is used for custom error messages with the `#[rustc_on_unimplemented]` attribute.
473 let mut unimplemented_traits = FxHashMap::default();
474 let mut unimplemented_traits_only = true;
475 for (predicate, _parent_pred, cause) in unsatisfied_predicates {
476 if let (ty::PredicateKind::Clause(ty::Clause::Trait(p)), Some(cause)) =
477 (predicate.kind().skip_binder(), cause.as_ref())
478 {
479 if p.trait_ref.self_ty() != rcvr_ty {
480 // This is necessary, not just to keep the errors clean, but also
481 // because our derived obligations can wind up with a trait ref that
482 // requires a different param_env to be correctly compared.
483 continue;
5e7ed085 484 }
9c376795
FG
485 unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
486 predicate.kind().rebind(p.trait_ref),
487 Obligation {
488 cause: cause.clone(),
489 param_env: self.param_env,
490 predicate: *predicate,
491 recursion_depth: 0,
492 },
493 ));
494 }
495 }
5e7ed085 496
9c376795
FG
497 // Make sure that, if any traits other than the found ones were involved,
498 // we don't don't report an unimplemented trait.
499 // We don't want to say that `iter::Cloned` is not an iterator, just
500 // because of some non-Clone item being iterated over.
501 for (predicate, _parent_pred, _cause) in unsatisfied_predicates {
502 match predicate.kind().skip_binder() {
503 ty::PredicateKind::Clause(ty::Clause::Trait(p))
504 if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
505 _ => {
506 unimplemented_traits_only = false;
507 break;
5e7ed085 508 }
9c376795
FG
509 }
510 }
3dfed10e 511
9c376795
FG
512 let mut collect_type_param_suggestions =
513 |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
514 // We don't care about regions here, so it's fine to skip the binder here.
515 if let (ty::Param(_), ty::PredicateKind::Clause(ty::Clause::Trait(p))) =
516 (self_ty.kind(), parent_pred.kind().skip_binder())
517 {
518 let hir = self.tcx.hir();
519 let node = match p.trait_ref.self_ty().kind() {
520 ty::Param(_) => {
521 // Account for `fn` items like in `issue-35677.rs` to
522 // suggest restricting its type params.
9ffffee4 523 Some(hir.get_by_def_id(self.body_id))
74b04a01 524 }
064997fb 525 ty::Adt(def, _) => {
9c376795 526 def.did().as_local().map(|def_id| hir.get_by_def_id(def_id))
064997fb 527 }
9c376795
FG
528 _ => None,
529 };
530 if let Some(hir::Node::Item(hir::Item { kind, .. })) = node
531 && let Some(g) = kind.generics()
532 {
533 let key = (
534 g.tail_span_for_predicate_suggestion(),
535 g.add_where_or_trailing_comma(),
536 );
537 type_params
538 .entry(key)
539 .or_insert_with(FxHashSet::default)
540 .insert(obligation.to_owned());
541 return true;
542 }
543 }
544 false
545 };
546 let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
547 let msg = format!(
548 "doesn't satisfy `{}`",
549 if obligation.len() > 50 { quiet } else { obligation }
550 );
551 match &self_ty.kind() {
552 // Point at the type that couldn't satisfy the bound.
553 ty::Adt(def, _) => bound_spans.push((self.tcx.def_span(def.did()), msg)),
554 // Point at the trait object that couldn't satisfy the bound.
555 ty::Dynamic(preds, _, _) => {
556 for pred in preds.iter() {
557 match pred.skip_binder() {
558 ty::ExistentialPredicate::Trait(tr) => {
559 bound_spans.push((self.tcx.def_span(tr.def_id), msg.clone()))
74b04a01 560 }
9c376795
FG
561 ty::ExistentialPredicate::Projection(_)
562 | ty::ExistentialPredicate::AutoTrait(_) => {}
74b04a01 563 }
74b04a01 564 }
9c376795
FG
565 }
566 // Point at the closure that couldn't satisfy the bound.
567 ty::Closure(def_id, _) => bound_spans
568 .push((tcx.def_span(*def_id), format!("doesn't satisfy `{}`", quiet))),
569 _ => {}
570 }
571 };
572 let mut format_pred = |pred: ty::Predicate<'tcx>| {
573 let bound_predicate = pred.kind();
574 match bound_predicate.skip_binder() {
575 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
576 let pred = bound_predicate.rebind(pred);
577 // `<Foo as Iterator>::Item = String`.
578 let projection_ty = pred.skip_binder().projection_ty;
579
9ffffee4 580 let substs_with_infer_self = tcx.mk_substs_from_iter(
9c376795
FG
581 iter::once(tcx.mk_ty_var(ty::TyVid::from_u32(0)).into())
582 .chain(projection_ty.substs.iter().skip(1)),
583 );
6a06907d 584
9c376795
FG
585 let quiet_projection_ty =
586 tcx.mk_alias_ty(projection_ty.def_id, substs_with_infer_self);
3c0e092e 587
9c376795 588 let term = pred.skip_binder().term;
5e7ed085 589
9c376795
FG
590 let obligation = format!("{} = {}", projection_ty, term);
591 let quiet = with_forced_trimmed_paths!(format!(
592 "{} = {}",
593 quiet_projection_ty, term
594 ));
5e7ed085 595
9c376795
FG
596 bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
597 Some((obligation, projection_ty.self_ty()))
3c0e092e 598 }
9c376795
FG
599 ty::PredicateKind::Clause(ty::Clause::Trait(poly_trait_ref)) => {
600 let p = poly_trait_ref.trait_ref;
601 let self_ty = p.self_ty();
602 let path = p.print_only_trait_path();
603 let obligation = format!("{}: {}", self_ty, path);
604 let quiet = with_forced_trimmed_paths!(format!("_: {}", path));
605 bound_span_label(self_ty, &obligation, &quiet);
606 Some((obligation, self_ty))
3c0e092e 607 }
9c376795
FG
608 _ => None,
609 }
610 };
3c0e092e 611
9c376795
FG
612 // Find all the requirements that come from a local `impl` block.
613 let mut skip_list: FxHashSet<_> = Default::default();
614 let mut spanned_predicates = FxHashMap::default();
615 for (p, parent_p, impl_def_id, cause) in unsatisfied_predicates
616 .iter()
617 .filter_map(|(p, parent, c)| c.as_ref().map(|c| (p, parent, c)))
618 .filter_map(|(p, parent, c)| match c.code() {
619 ObligationCauseCode::ImplDerivedObligation(data)
620 if matches!(p.kind().skip_binder(), ty::PredicateKind::Clause(_)) =>
621 {
9ffffee4 622 Some((p, parent, data.impl_or_alias_def_id, data))
74b04a01 623 }
9c376795
FG
624 _ => None,
625 })
626 {
627 match self.tcx.hir().get_if_local(impl_def_id) {
628 // Unmet obligation comes from a `derive` macro, point at it once to
629 // avoid multiple span labels pointing at the same place.
630 Some(Node::Item(hir::Item {
631 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
632 ..
633 })) if matches!(
634 self_ty.span.ctxt().outer_expn_data().kind,
635 ExpnKind::Macro(MacroKind::Derive, _)
636 ) || matches!(
637 of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
638 Some(ExpnKind::Macro(MacroKind::Derive, _))
639 ) =>
640 {
641 let span = self_ty.span.ctxt().outer_expn_data().call_site;
642 let entry = spanned_predicates.entry(span);
643 let entry = entry.or_insert_with(|| {
644 (FxHashSet::default(), FxHashSet::default(), Vec::new())
645 });
646 entry.0.insert(span);
647 entry.1.insert((
648 span,
649 "unsatisfied trait bound introduced in this `derive` macro",
5869c6ff 650 ));
9c376795
FG
651 entry.2.push(p);
652 skip_list.insert(p);
653 }
654
655 // Unmet obligation coming from an `impl`.
656 Some(Node::Item(hir::Item {
657 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
658 span: item_span,
659 ..
660 })) => {
661 let sized_pred =
662 unsatisfied_predicates.iter().any(|(pred, _, _)| {
663 match pred.kind().skip_binder() {
664 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
665 Some(pred.def_id()) == self.tcx.lang_items().sized_trait()
666 && pred.polarity == ty::ImplPolarity::Positive
667 }
668 _ => false,
669 }
670 });
671 for param in generics.params {
672 if param.span == cause.span && sized_pred {
673 let (sp, sugg) = match param.colon_span {
674 Some(sp) => (sp.shrink_to_hi(), " ?Sized +"),
675 None => (param.span.shrink_to_hi(), ": ?Sized"),
676 };
677 err.span_suggestion_verbose(
678 sp,
679 "consider relaxing the type parameter's implicit `Sized` bound",
680 sugg,
681 Applicability::MachineApplicable,
682 );
683 }
5e7ed085 684 }
9c376795
FG
685 if let Some(pred) = parent_p {
686 // Done to add the "doesn't satisfy" `span_label`.
687 let _ = format_pred(*pred);
3c0e092e 688 }
9c376795
FG
689 skip_list.insert(p);
690 let entry = spanned_predicates.entry(self_ty.span);
691 let entry = entry.or_insert_with(|| {
692 (FxHashSet::default(), FxHashSet::default(), Vec::new())
693 });
694 entry.2.push(p);
695 if cause.span != *item_span {
696 entry.0.insert(cause.span);
697 entry.1.insert((cause.span, "unsatisfied trait bound introduced here"));
698 } else {
699 if let Some(trait_ref) = of_trait {
700 entry.0.insert(trait_ref.path.span);
701 }
702 entry.0.insert(self_ty.span);
703 };
704 if let Some(trait_ref) = of_trait {
705 entry.1.insert((trait_ref.path.span, ""));
706 }
707 entry.1.insert((self_ty.span, ""));
708 }
709 Some(Node::Item(hir::Item {
710 kind: hir::ItemKind::Trait(rustc_ast::ast::IsAuto::Yes, ..),
711 span: item_span,
712 ..
713 })) => {
714 tcx.sess.delay_span_bug(
715 *item_span,
716 "auto trait is invoked with no method error, but no error reported?",
717 );
718 }
719 Some(Node::Item(hir::Item {
9ffffee4
FG
720 ident,
721 kind: hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..),
722 ..
9c376795
FG
723 })) => {
724 skip_list.insert(p);
725 let entry = spanned_predicates.entry(ident.span);
726 let entry = entry.or_insert_with(|| {
727 (FxHashSet::default(), FxHashSet::default(), Vec::new())
728 });
729 entry.0.insert(cause.span);
730 entry.1.insert((ident.span, ""));
731 entry.1.insert((cause.span, "unsatisfied trait bound introduced here"));
732 entry.2.push(p);
74b04a01 733 }
9c376795
FG
734 Some(node) => unreachable!("encountered `{node:?}`"),
735 None => (),
736 }
737 }
738 let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
739 spanned_predicates.sort_by_key(|(span, _)| *span);
740 for (_, (primary_spans, span_labels, predicates)) in spanned_predicates {
741 let mut preds: Vec<_> = predicates
742 .iter()
743 .filter_map(|pred| format_pred(**pred))
744 .map(|(p, _)| format!("`{}`", p))
745 .collect();
746 preds.sort();
747 preds.dedup();
748 let msg = if let [pred] = &preds[..] {
749 format!("trait bound {} was not satisfied", pred)
750 } else {
751 format!("the following trait bounds were not satisfied:\n{}", preds.join("\n"),)
752 };
753 let mut span: MultiSpan = primary_spans.into_iter().collect::<Vec<_>>().into();
754 for (sp, label) in span_labels {
755 span.push_span_label(sp, label);
a7813a04 756 }
9c376795
FG
757 err.span_note(span, &msg);
758 unsatisfied_bounds = true;
759 }
62682a34 760
9c376795
FG
761 let mut suggested_bounds = FxHashSet::default();
762 // The requirements that didn't have an `impl` span to show.
763 let mut bound_list = unsatisfied_predicates
764 .iter()
765 .filter_map(|(pred, parent_pred, _cause)| {
766 let mut suggested = false;
767 format_pred(*pred).map(|(p, self_ty)| {
768 if let Some(parent) = parent_pred && suggested_bounds.contains(parent) {
769 // We don't suggest `PartialEq` when we already suggest `Eq`.
770 } else if !suggested_bounds.contains(pred) {
771 if collect_type_param_suggestions(self_ty, *pred, &p) {
772 suggested = true;
773 suggested_bounds.insert(pred);
5e7ed085 774 }
5e7ed085 775 }
9c376795
FG
776 (
777 match parent_pred {
778 None => format!("`{}`", &p),
779 Some(parent_pred) => match format_pred(*parent_pred) {
780 None => format!("`{}`", &p),
781 Some((parent_p, _)) => {
782 if !suggested
783 && !suggested_bounds.contains(pred)
784 && !suggested_bounds.contains(parent_pred)
785 {
786 if collect_type_param_suggestions(
787 self_ty,
788 *parent_pred,
789 &p,
790 ) {
791 suggested_bounds.insert(pred);
5e7ed085 792 }
5e7ed085 793 }
9c376795 794 format!("`{}`\nwhich is required by `{}`", p, parent_p)
5e7ed085 795 }
9c376795
FG
796 },
797 },
798 *pred,
799 )
800 })
801 })
802 .filter(|(_, pred)| !skip_list.contains(&pred))
803 .map(|(t, _)| t)
804 .enumerate()
805 .collect::<Vec<(usize, String)>>();
806
807 for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
808 restrict_type_params = true;
809 // #74886: Sort here so that the output is always the same.
810 let mut obligations = obligations.into_iter().collect::<Vec<_>>();
811 obligations.sort();
812 err.span_suggestion_verbose(
813 span,
814 &format!(
815 "consider restricting the type parameter{s} to satisfy the \
816 trait bound{s}",
817 s = pluralize!(obligations.len())
818 ),
819 format!("{} {}", add_where_or_comma, obligations.join(", ")),
820 Applicability::MaybeIncorrect,
821 );
822 }
823
824 bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); // Sort alphabetically.
825 bound_list.dedup_by(|(_, a), (_, b)| a == b); // #35677
826 bound_list.sort_by_key(|(pos, _)| *pos); // Keep the original predicate order.
827
828 if !bound_list.is_empty() || !skip_list.is_empty() {
829 let bound_list =
830 bound_list.into_iter().map(|(_, path)| path).collect::<Vec<_>>().join("\n");
831 let actual_prefix = rcvr_ty.prefix_string(self.tcx);
832 info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
833 let (primary_message, label) = if unimplemented_traits.len() == 1
834 && unimplemented_traits_only
835 {
836 unimplemented_traits
837 .into_iter()
838 .next()
839 .map(|(_, (trait_ref, obligation))| {
840 if trait_ref.self_ty().references_error() || rcvr_ty.references_error()
841 {
842 // Avoid crashing.
843 return (None, None);
5e7ed085 844 }
9c376795
FG
845 let OnUnimplementedNote { message, label, .. } =
846 self.err_ctxt().on_unimplemented_note(trait_ref, &obligation);
847 (message, label)
848 })
849 .unwrap()
850 } else {
851 (None, None)
5e7ed085 852 };
9c376795
FG
853 let primary_message = primary_message.unwrap_or_else(|| {
854 format!(
855 "the {item_kind} `{item_name}` exists for {actual_prefix} `{ty_str}`, \
9ffffee4 856 but its trait bounds were not satisfied"
9c376795
FG
857 )
858 });
859 err.set_primary_message(&primary_message);
860 if let Some(label) = label {
861 custom_span_label = true;
862 err.span_label(span, label);
f2b60f7d 863 }
9c376795
FG
864 if !bound_list.is_empty() {
865 err.note(&format!(
866 "the following trait bounds were not satisfied:\n{bound_list}"
867 ));
5e7ed085 868 }
9c376795 869 self.suggest_derive(&mut err, &unsatisfied_predicates);
5e7ed085 870
9c376795
FG
871 unsatisfied_bounds = true;
872 }
873 }
ea8adc8c 874
9c376795
FG
875 let label_span_not_found = |err: &mut Diagnostic| {
876 if unsatisfied_predicates.is_empty() {
877 err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
878 let is_string_or_ref_str = match rcvr_ty.kind() {
879 ty::Ref(_, ty, _) => {
880 ty.is_str()
881 || matches!(
882 ty.kind(),
883 ty::Adt(adt, _) if Some(adt.did()) == self.tcx.lang_items().string()
884 )
48663c56 885 }
9c376795
FG
886 ty::Adt(adt, _) => Some(adt.did()) == self.tcx.lang_items().string(),
887 _ => false,
888 };
889 if is_string_or_ref_str && item_name.name == sym::iter {
890 err.span_suggestion_verbose(
891 item_name.span,
892 "because of the in-memory representation of `&str`, to obtain \
893 an `Iterator` over each of its codepoint use method `chars`",
894 "chars",
895 Applicability::MachineApplicable,
896 );
48663c56 897 }
9c376795
FG
898 if let ty::Adt(adt, _) = rcvr_ty.kind() {
899 let mut inherent_impls_candidate = self
900 .tcx
901 .inherent_impls(adt.did())
902 .iter()
903 .copied()
904 .filter(|def_id| {
905 if let Some(assoc) = self.associated_value(*def_id, item_name) {
906 // Check for both mode is the same so we avoid suggesting
907 // incorrect associated item.
908 match (mode, assoc.fn_has_self_parameter, source) {
909 (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
910 // We check that the suggest type is actually
911 // different from the received one
912 // So we avoid suggestion method with Box<Self>
913 // for instance
9ffffee4
FG
914 self.tcx.at(span).type_of(*def_id).subst_identity()
915 != rcvr_ty
916 && self.tcx.at(span).type_of(*def_id).subst_identity()
917 != rcvr_ty
9c376795
FG
918 }
919 (Mode::Path, false, _) => true,
920 _ => false,
921 }
922 } else {
923 false
924 }
925 })
926 .collect::<Vec<_>>();
927 if !inherent_impls_candidate.is_empty() {
928 inherent_impls_candidate.sort();
929 inherent_impls_candidate.dedup();
930
931 // number of type to shows at most.
932 let limit = if inherent_impls_candidate.len() == 5 { 5 } else { 4 };
933 let type_candidates = inherent_impls_candidate
934 .iter()
935 .take(limit)
936 .map(|impl_item| {
9ffffee4
FG
937 format!(
938 "- `{}`",
939 self.tcx.at(span).type_of(*impl_item).subst_identity()
940 )
9c376795
FG
941 })
942 .collect::<Vec<_>>()
943 .join("\n");
944 let additional_types = if inherent_impls_candidate.len() > limit {
945 format!("\nand {} more types", inherent_impls_candidate.len() - limit)
f2b60f7d 946 } else {
9c376795
FG
947 "".to_string()
948 };
949 err.note(&format!(
950 "the {item_kind} was found for\n{}{}",
951 type_candidates, additional_types
952 ));
5869c6ff 953 }
ea8adc8c 954 }
9c376795
FG
955 } else {
956 let ty_str =
957 if ty_str.len() > 50 { String::new() } else { format!("on `{ty_str}` ") };
958 err.span_label(
959 span,
960 format!("{item_kind} cannot be called {ty_str}due to unsatisfied trait bounds"),
961 );
962 }
963 };
48663c56 964
9c376795
FG
965 // If the method name is the name of a field with a function or closure type,
966 // give a helping note that it has to be called as `(x.f)(...)`.
967 if let SelfSource::MethodCall(expr) = source {
968 if !self.suggest_calling_field_as_fn(span, rcvr_ty, expr, item_name, &mut err)
9ffffee4 969 && similar_candidate.is_none()
9c376795
FG
970 && !custom_span_label
971 {
972 label_span_not_found(&mut err);
a7813a04 973 }
9c376795
FG
974 } else if !custom_span_label {
975 label_span_not_found(&mut err);
976 }
85aaf69f 977
9c376795
FG
978 // Don't suggest (for example) `expr.field.clone()` if `expr.clone()`
979 // can't be called due to `typeof(expr): Clone` not holding.
980 if unsatisfied_predicates.is_empty() {
981 self.suggest_calling_method_on_field(
982 &mut err,
983 source,
984 span,
985 rcvr_ty,
986 item_name,
987 expected.only_has_type(self),
988 );
989 }
85aaf69f 990
9c376795 991 self.check_for_inner_self(&mut err, source, rcvr_ty, item_name);
85aaf69f 992
9c376795
FG
993 bound_spans.sort();
994 bound_spans.dedup();
995 for (span, msg) in bound_spans.into_iter() {
996 err.span_label(span, &msg);
997 }
998
999 if rcvr_ty.is_numeric() && rcvr_ty.is_fresh() || restrict_type_params {
1000 } else {
1001 self.suggest_traits_to_import(
1002 &mut err,
1003 span,
1004 rcvr_ty,
1005 item_name,
1006 args.map(|(_, args)| args.len() + 1),
1007 source,
1008 no_match_data.out_of_scope_traits.clone(),
1009 &unsatisfied_predicates,
1010 &static_candidates,
1011 unsatisfied_bounds,
1012 expected.only_has_type(self),
1013 );
1014 }
1015
1016 // Don't emit a suggestion if we found an actual method
1017 // that had unsatisfied trait bounds
1018 if unsatisfied_predicates.is_empty() && rcvr_ty.is_enum() {
1019 let adt_def = rcvr_ty.ty_adt_def().expect("enum is not an ADT");
9ffffee4 1020 if let Some(suggestion) = edit_distance::find_best_match_for_name(
9c376795
FG
1021 &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
1022 item_name.name,
1023 None,
1024 ) {
1025 err.span_suggestion(
1026 span,
1027 "there is a variant with a similar name",
1028 suggestion,
1029 Applicability::MaybeIncorrect,
dfeec247 1030 );
a7813a04 1031 }
9c376795 1032 }
3b2f2976 1033
9c376795
FG
1034 if item_name.name == sym::as_str && rcvr_ty.peel_refs().is_str() {
1035 let msg = "remove this method call";
1036 let mut fallback_span = true;
1037 if let SelfSource::MethodCall(expr) = source {
1038 let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().parent_id(expr.hir_id));
1039 if let Some(span) = call_expr.span.trim_start(expr.span) {
1040 err.span_suggestion(span, msg, "", Applicability::MachineApplicable);
1041 fallback_span = false;
1042 }
1043 }
1044 if fallback_span {
1045 err.span_label(span, msg);
1046 }
9ffffee4 1047 } else if let Some(similar_candidate) = similar_candidate {
9c376795
FG
1048 // Don't emit a suggestion if we found an actual method
1049 // that had unsatisfied trait bounds
1050 if unsatisfied_predicates.is_empty() {
9ffffee4 1051 let def_kind = similar_candidate.kind.as_def_kind();
9c376795
FG
1052 // Methods are defined within the context of a struct and their first parameter is always self,
1053 // which represents the instance of the struct the method is being called on
1054 // Associated functions don’t take self as a parameter and
1055 // they are not methods because they don’t have an instance of the struct to work with.
9ffffee4 1056 if def_kind == DefKind::AssocFn && similar_candidate.fn_has_self_parameter {
9c376795
FG
1057 err.span_suggestion(
1058 span,
1059 "there is a method with a similar name",
9ffffee4 1060 similar_candidate.name,
9c376795
FG
1061 Applicability::MaybeIncorrect,
1062 );
1063 } else {
1064 err.span_suggestion(
1065 span,
1066 &format!(
1067 "there is {} {} with a similar name",
9ffffee4
FG
1068 self.tcx.def_kind_descr_article(def_kind, similar_candidate.def_id),
1069 self.tcx.def_kind_descr(def_kind, similar_candidate.def_id)
9c376795 1070 ),
9ffffee4 1071 similar_candidate.name,
9c376795 1072 Applicability::MaybeIncorrect,
e74abb32 1073 );
3b2f2976 1074 }
9c376795
FG
1075 }
1076 }
1077
1078 self.check_for_deref_method(&mut err, source, rcvr_ty, item_name, expected);
1079 return Some(err);
1080 }
1081
1082 fn note_candidates_on_method_error(
1083 &self,
1084 rcvr_ty: Ty<'tcx>,
1085 item_name: Ident,
1086 args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
1087 span: Span,
1088 err: &mut Diagnostic,
1089 sources: &mut Vec<CandidateSource>,
1090 sugg_span: Option<Span>,
1091 ) {
1092 sources.sort();
1093 sources.dedup();
1094 // Dynamic limit to avoid hiding just one candidate, which is silly.
1095 let limit = if sources.len() == 5 { 5 } else { 4 };
1096
1097 for (idx, source) in sources.iter().take(limit).enumerate() {
1098 match *source {
1099 CandidateSource::Impl(impl_did) => {
1100 // Provide the best span we can. Use the item, if local to crate, else
1101 // the impl, if local to crate (item may be defaulted), else nothing.
1102 let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
1103 let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
1104 self.associated_value(impl_trait_ref.skip_binder().def_id, item_name)
1105 }) else {
1106 continue;
1107 };
1108
1109 let note_span = if item.def_id.is_local() {
1110 Some(self.tcx.def_span(item.def_id))
1111 } else if impl_did.is_local() {
1112 Some(self.tcx.def_span(impl_did))
1113 } else {
1114 None
1115 };
1116
9ffffee4 1117 let impl_ty = self.tcx.at(span).type_of(impl_did).subst_identity();
9c376795
FG
1118
1119 let insertion = match self.tcx.impl_trait_ref(impl_did) {
1120 None => String::new(),
1121 Some(trait_ref) => {
1122 format!(
1123 " of the trait `{}`",
1124 self.tcx.def_path_str(trait_ref.skip_binder().def_id)
1125 )
1126 }
1127 };
1128
1129 let (note_str, idx) = if sources.len() > 1 {
1130 (
1131 format!(
1132 "candidate #{} is defined in an impl{} for the type `{}`",
1133 idx + 1,
1134 insertion,
1135 impl_ty,
1136 ),
1137 Some(idx + 1),
1138 )
1139 } else {
1140 (
1141 format!(
1142 "the candidate is defined in an impl{} for the type `{}`",
1143 insertion, impl_ty,
1144 ),
1145 None,
1146 )
1147 };
1148 if let Some(note_span) = note_span {
1149 // We have a span pointing to the method. Show note with snippet.
1150 err.span_note(note_span, &note_str);
1151 } else {
1152 err.note(&note_str);
1153 }
1154 if let Some(sugg_span) = sugg_span
1155 && let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
1156 let path = self.tcx.def_path_str(trait_ref.skip_binder().def_id);
1157
1158 let ty = match item.kind {
1159 ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty,
1160 ty::AssocKind::Fn => self
1161 .tcx
1162 .fn_sig(item.def_id)
9ffffee4 1163 .subst_identity()
9c376795
FG
1164 .inputs()
1165 .skip_binder()
1166 .get(0)
1167 .filter(|ty| ty.is_region_ptr() && !rcvr_ty.is_region_ptr())
1168 .copied()
1169 .unwrap_or(rcvr_ty),
1170 };
1171 print_disambiguation_help(
1172 item_name,
1173 args,
1174 err,
1175 path,
1176 ty,
1177 item.kind,
9ffffee4 1178 self.tcx.def_kind_descr(item.kind.as_def_kind(), item.def_id),
9c376795
FG
1179 sugg_span,
1180 idx,
1181 self.tcx.sess.source_map(),
1182 item.fn_has_self_parameter,
1183 );
1184 }
1185 }
1186 CandidateSource::Trait(trait_did) => {
1187 let Some(item) = self.associated_value(trait_did, item_name) else { continue };
1188 let item_span = self.tcx.def_span(item.def_id);
1189 let idx = if sources.len() > 1 {
1190 let msg = &format!(
1191 "candidate #{} is defined in the trait `{}`",
1192 idx + 1,
1193 self.tcx.def_path_str(trait_did)
1194 );
1195 err.span_note(item_span, msg);
1196 Some(idx + 1)
1197 } else {
1198 let msg = &format!(
1199 "the candidate is defined in the trait `{}`",
1200 self.tcx.def_path_str(trait_did)
1201 );
1202 err.span_note(item_span, msg);
1203 None
1204 };
1205 if let Some(sugg_span) = sugg_span {
1206 let path = self.tcx.def_path_str(trait_did);
1207 print_disambiguation_help(
1208 item_name,
1209 args,
1210 err,
1211 path,
1212 rcvr_ty,
1213 item.kind,
9ffffee4 1214 self.tcx.def_kind_descr(item.kind.as_def_kind(), item.def_id),
9c376795
FG
1215 sugg_span,
1216 idx,
1217 self.tcx.sess.source_map(),
1218 item.fn_has_self_parameter,
dfeec247 1219 );
e74abb32
XL
1220 }
1221 }
3b2f2976
XL
1222 }
1223 }
9c376795
FG
1224 if sources.len() > limit {
1225 err.note(&format!("and {} others", sources.len() - limit));
1226 }
3b2f2976
XL
1227 }
1228
487cf647
FG
1229 /// Suggest calling `Ty::method` if `.method()` isn't found because the method
1230 /// doesn't take a `self` receiver.
1231 fn suggest_associated_call_syntax(
1232 &self,
1233 err: &mut Diagnostic,
1234 static_candidates: &Vec<CandidateSource>,
1235 rcvr_ty: Ty<'tcx>,
1236 source: SelfSource<'tcx>,
1237 item_name: Ident,
1238 args: Option<(&hir::Expr<'tcx>, &[hir::Expr<'tcx>])>,
1239 sugg_span: Span,
1240 ) {
1241 let mut has_unsuggestable_args = false;
1242 let ty_str = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0) {
1243 // When the "method" is resolved through dereferencing, we really want the
1244 // original type that has the associated function for accurate suggestions.
1245 // (#61411)
9ffffee4 1246 let impl_ty = self.tcx.type_of(*impl_did).subst_identity();
487cf647
FG
1247 let target_ty = self
1248 .autoderef(sugg_span, rcvr_ty)
1249 .find(|(rcvr_ty, _)| {
1250 DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer }
1251 .types_may_unify(*rcvr_ty, impl_ty)
1252 })
1253 .map_or(impl_ty, |(ty, _)| ty)
1254 .peel_refs();
1255 if let ty::Adt(def, substs) = target_ty.kind() {
1256 // If there are any inferred arguments, (`{integer}`), we should replace
1257 // them with underscores to allow the compiler to infer them
9ffffee4 1258 let infer_substs = self.tcx.mk_substs_from_iter(substs.into_iter().map(|arg| {
487cf647
FG
1259 if !arg.is_suggestable(self.tcx, true) {
1260 has_unsuggestable_args = true;
1261 match arg.unpack() {
1262 GenericArgKind::Lifetime(_) => self
1263 .next_region_var(RegionVariableOrigin::MiscVariable(
1264 rustc_span::DUMMY_SP,
1265 ))
1266 .into(),
1267 GenericArgKind::Type(_) => self
1268 .next_ty_var(TypeVariableOrigin {
1269 span: rustc_span::DUMMY_SP,
1270 kind: TypeVariableOriginKind::MiscVariable,
1271 })
1272 .into(),
1273 GenericArgKind::Const(arg) => self
1274 .next_const_var(
1275 arg.ty(),
1276 ConstVariableOrigin {
1277 span: rustc_span::DUMMY_SP,
1278 kind: ConstVariableOriginKind::MiscVariable,
1279 },
1280 )
1281 .into(),
1282 }
1283 } else {
1284 arg
1285 }
1286 }));
1287
1288 self.tcx.value_path_str_with_substs(def.did(), infer_substs)
1289 } else {
1290 self.ty_to_value_string(target_ty)
1291 }
1292 } else {
1293 self.ty_to_value_string(rcvr_ty.peel_refs())
1294 };
1295 if let SelfSource::MethodCall(_) = source {
1296 let first_arg = if let Some(CandidateSource::Impl(impl_did)) = static_candidates.get(0)
1297 && let Some(assoc) = self.associated_value(*impl_did, item_name)
1298 && assoc.kind == ty::AssocKind::Fn
1299 {
9ffffee4 1300 let sig = self.tcx.fn_sig(assoc.def_id).subst_identity();
487cf647
FG
1301 sig.inputs().skip_binder().get(0).and_then(|first| if first.peel_refs() == rcvr_ty.peel_refs() {
1302 None
1303 } else {
1304 Some(first.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()))
1305 })
1306 } else {
1307 None
1308 };
1309 let mut applicability = Applicability::MachineApplicable;
1310 let args = if let Some((receiver, args)) = args {
1311 // The first arg is the same kind as the receiver
1312 let explicit_args = if first_arg.is_some() {
1313 std::iter::once(receiver).chain(args.iter()).collect::<Vec<_>>()
1314 } else {
1315 // There is no `Self` kind to infer the arguments from
1316 if has_unsuggestable_args {
1317 applicability = Applicability::HasPlaceholders;
1318 }
1319 args.iter().collect()
1320 };
1321 format!(
1322 "({}{})",
1323 first_arg.unwrap_or(""),
1324 explicit_args
1325 .iter()
1326 .map(|arg| self
1327 .tcx
1328 .sess
1329 .source_map()
1330 .span_to_snippet(arg.span)
1331 .unwrap_or_else(|_| {
1332 applicability = Applicability::HasPlaceholders;
1333 "_".to_owned()
1334 }))
1335 .collect::<Vec<_>>()
1336 .join(", "),
1337 )
1338 } else {
1339 applicability = Applicability::HasPlaceholders;
1340 "(...)".to_owned()
1341 };
1342 err.span_suggestion(
1343 sugg_span,
1344 "use associated function syntax instead",
1345 format!("{}::{}{}", ty_str, item_name, args),
1346 applicability,
1347 );
1348 } else {
1349 err.help(&format!("try with `{}::{}`", ty_str, item_name,));
1350 }
1351 }
1352
1353 /// Suggest calling a field with a type that implements the `Fn*` traits instead of a method with
1354 /// the same name as the field i.e. `(a.my_fn_ptr)(10)` instead of `a.my_fn_ptr(10)`.
1355 fn suggest_calling_field_as_fn(
04454e1e
FG
1356 &self,
1357 span: Span,
1358 rcvr_ty: Ty<'tcx>,
1359 expr: &hir::Expr<'_>,
1360 item_name: Ident,
f2b60f7d 1361 err: &mut Diagnostic,
04454e1e
FG
1362 ) -> bool {
1363 let tcx = self.tcx;
1364 let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
1365 ty::Adt(def, substs) if !def.is_enum() => {
1366 let variant = &def.non_enum_variant();
1367 tcx.find_field_index(item_name, variant).map(|index| {
1368 let field = &variant.fields[index];
1369 let field_ty = field.ty(tcx, substs);
1370 (field, field_ty)
1371 })
1372 }
1373 _ => None,
1374 });
1375 if let Some((field, field_ty)) = field_receiver {
9ffffee4 1376 let scope = tcx.parent_module_from_def_id(self.body_id);
04454e1e
FG
1377 let is_accessible = field.vis.is_accessible_from(scope, tcx);
1378
1379 if is_accessible {
1380 if self.is_fn_ty(field_ty, span) {
1381 let expr_span = expr.span.to(item_name.span);
1382 err.multipart_suggestion(
1383 &format!(
1384 "to call the function stored in `{}`, \
1385 surround the field access with parentheses",
1386 item_name,
1387 ),
1388 vec![
1389 (expr_span.shrink_to_lo(), '('.to_string()),
1390 (expr_span.shrink_to_hi(), ')'.to_string()),
1391 ],
1392 Applicability::MachineApplicable,
1393 );
1394 } else {
9c376795 1395 let call_expr = tcx.hir().expect_expr(tcx.hir().parent_id(expr.hir_id));
04454e1e
FG
1396
1397 if let Some(span) = call_expr.span.trim_start(item_name.span) {
1398 err.span_suggestion(
1399 span,
1400 "remove the arguments",
923072b8 1401 "",
04454e1e
FG
1402 Applicability::MaybeIncorrect,
1403 );
1404 }
1405 }
1406 }
1407
1408 let field_kind = if is_accessible { "field" } else { "private field" };
1409 err.span_label(item_name.span, format!("{}, not a method", field_kind));
1410 return true;
1411 }
1412 false
1413 }
1414
2b03887a
FG
1415 /// Suggest possible range with adding parentheses, for example:
1416 /// when encountering `0..1.map(|i| i + 1)` suggest `(0..1).map(|i| i + 1)`.
1417 fn suggest_wrapping_range_with_parens(
1418 &self,
1419 tcx: TyCtxt<'tcx>,
1420 actual: Ty<'tcx>,
1421 source: SelfSource<'tcx>,
1422 span: Span,
1423 item_name: Ident,
1424 ty_str: &str,
1425 ) -> bool {
1426 if let SelfSource::MethodCall(expr) = source {
1427 for (_, parent) in tcx.hir().parent_iter(expr.hir_id).take(5) {
1428 if let Node::Expr(parent_expr) = parent {
1429 let lang_item = match parent_expr.kind {
1430 ExprKind::Struct(ref qpath, _, _) => match **qpath {
1431 QPath::LangItem(LangItem::Range, ..) => Some(LangItem::Range),
1432 QPath::LangItem(LangItem::RangeTo, ..) => Some(LangItem::RangeTo),
1433 QPath::LangItem(LangItem::RangeToInclusive, ..) => {
1434 Some(LangItem::RangeToInclusive)
1435 }
1436 _ => None,
1437 },
1438 ExprKind::Call(ref func, _) => match func.kind {
1439 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1440 ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, ..)) => {
1441 Some(LangItem::RangeInclusiveStruct)
1442 }
1443 _ => None,
1444 },
1445 _ => None,
1446 };
1447
1448 if lang_item.is_none() {
1449 continue;
1450 }
1451
1452 let span_included = match parent_expr.kind {
1453 hir::ExprKind::Struct(_, eps, _) => {
1454 eps.len() > 0 && eps.last().map_or(false, |ep| ep.span.contains(span))
1455 }
1456 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1457 hir::ExprKind::Call(ref func, ..) => func.span.contains(span),
1458 _ => false,
1459 };
1460
1461 if !span_included {
1462 continue;
1463 }
1464
1465 let range_def_id = self.tcx.require_lang_item(lang_item.unwrap(), None);
9ffffee4 1466 let range_ty = self.tcx.type_of(range_def_id).subst(self.tcx, &[actual.into()]);
2b03887a 1467
9c376795 1468 let pick = self.lookup_probe_for_diagnostic(
2b03887a 1469 item_name,
2b03887a 1470 range_ty,
9c376795 1471 expr,
2b03887a 1472 ProbeScope::AllTraits,
9c376795 1473 None,
2b03887a
FG
1474 );
1475 if pick.is_ok() {
1476 let range_span = parent_expr.span.with_hi(expr.span.hi());
1477 tcx.sess.emit_err(errors::MissingParentheseInRange {
1478 span,
1479 ty_str: ty_str.to_string(),
1480 method_name: item_name.as_str().to_string(),
1481 add_missing_parentheses: Some(errors::AddMissingParenthesesInRange {
1482 func_name: item_name.name.as_str().to_string(),
1483 left: range_span.shrink_to_lo(),
1484 right: range_span.shrink_to_hi(),
1485 }),
1486 });
1487 return true;
1488 }
1489 }
1490 }
1491 }
1492 false
1493 }
1494
04454e1e
FG
1495 fn suggest_constraining_numerical_ty(
1496 &self,
1497 tcx: TyCtxt<'tcx>,
1498 actual: Ty<'tcx>,
1499 source: SelfSource<'_>,
1500 span: Span,
1501 item_kind: &str,
1502 item_name: Ident,
1503 ty_str: &str,
1504 ) -> bool {
1505 let found_candidate = all_traits(self.tcx)
1506 .into_iter()
1507 .any(|info| self.associated_value(info.def_id, item_name).is_some());
1508 let found_assoc = |ty: Ty<'tcx>| {
923072b8 1509 simplify_type(tcx, ty, TreatParams::AsInfer)
04454e1e
FG
1510 .and_then(|simp| {
1511 tcx.incoherent_impls(simp)
1512 .iter()
1513 .find_map(|&id| self.associated_value(id, item_name))
1514 })
1515 .is_some()
1516 };
1517 let found_candidate = found_candidate
1518 || found_assoc(tcx.types.i8)
1519 || found_assoc(tcx.types.i16)
1520 || found_assoc(tcx.types.i32)
1521 || found_assoc(tcx.types.i64)
1522 || found_assoc(tcx.types.i128)
1523 || found_assoc(tcx.types.u8)
1524 || found_assoc(tcx.types.u16)
1525 || found_assoc(tcx.types.u32)
1526 || found_assoc(tcx.types.u64)
1527 || found_assoc(tcx.types.u128)
1528 || found_assoc(tcx.types.f32)
1529 || found_assoc(tcx.types.f32);
1530 if found_candidate
1531 && actual.is_numeric()
1532 && !actual.has_concrete_skeleton()
1533 && let SelfSource::MethodCall(expr) = source
1534 {
1535 let mut err = struct_span_err!(
1536 tcx.sess,
1537 span,
1538 E0689,
1539 "can't call {} `{}` on ambiguous numeric type `{}`",
1540 item_kind,
1541 item_name,
1542 ty_str
1543 );
1544 let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
1545 match expr.kind {
1546 ExprKind::Lit(ref lit) => {
1547 // numeric literal
1548 let snippet = tcx
1549 .sess
1550 .source_map()
1551 .span_to_snippet(lit.span)
1552 .unwrap_or_else(|_| "<numeric literal>".to_owned());
1553
1554 // If this is a floating point literal that ends with '.',
1555 // get rid of it to stop this from becoming a member access.
1556 let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);
04454e1e
FG
1557 err.span_suggestion(
1558 lit.span,
1559 &format!(
1560 "you must specify a concrete type for this numeric value, \
1561 like `{}`",
1562 concrete_type
1563 ),
1564 format!("{snippet}_{concrete_type}"),
1565 Applicability::MaybeIncorrect,
1566 );
1567 }
1568 ExprKind::Path(QPath::Resolved(_, path)) => {
1569 // local binding
1570 if let hir::def::Res::Local(hir_id) = path.res {
1571 let span = tcx.hir().span(hir_id);
04454e1e
FG
1572 let filename = tcx.sess.source_map().span_to_filename(span);
1573
1574 let parent_node =
9c376795 1575 self.tcx.hir().get_parent(hir_id);
04454e1e
FG
1576 let msg = format!(
1577 "you must specify a type for this binding, like `{}`",
1578 concrete_type,
1579 );
1580
f2b60f7d 1581 match (filename, parent_node) {
04454e1e
FG
1582 (
1583 FileName::Real(_),
1584 Node::Local(hir::Local {
1585 source: hir::LocalSource::Normal,
1586 ty,
1587 ..
1588 }),
04454e1e 1589 ) => {
f2b60f7d 1590 let type_span = ty.map(|ty| ty.span.with_lo(span.hi())).unwrap_or(span.shrink_to_hi());
04454e1e
FG
1591 err.span_suggestion(
1592 // account for `let x: _ = 42;`
f2b60f7d
FG
1593 // ^^^
1594 type_span,
04454e1e 1595 &msg,
f2b60f7d 1596 format!(": {concrete_type}"),
04454e1e
FG
1597 Applicability::MaybeIncorrect,
1598 );
1599 }
1600 _ => {
1601 err.span_label(span, msg);
1602 }
1603 }
1604 }
1605 }
1606 _ => {}
1607 }
1608 err.emit();
1609 return true;
1610 }
1611 false
1612 }
1613
487cf647
FG
1614 /// For code `rect::area(...)`,
1615 /// if `rect` is a local variable and `area` is a valid assoc method for it,
1616 /// we try to suggest `rect.area()`
1617 pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) {
1618 debug!("suggest_assoc_method_call segs: {:?}", segs);
1619 let [seg1, seg2] = segs else { return; };
1620 let Some(mut diag) =
1621 self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod)
1622 else { return };
1623
1624 let map = self.infcx.tcx.hir();
9ffffee4
FG
1625 let body_id = self.tcx.hir().body_owned_by(self.body_id);
1626 let body = map.body(body_id);
487cf647
FG
1627 struct LetVisitor<'a> {
1628 result: Option<&'a hir::Expr<'a>>,
1629 ident_name: Symbol,
1630 }
1631
1632 // FIXME: This really should be taking scoping, etc into account.
1633 impl<'v> Visitor<'v> for LetVisitor<'v> {
1634 fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) {
1635 if let hir::StmtKind::Local(hir::Local { pat, init, .. }) = &ex.kind
1636 && let Binding(_, _, ident, ..) = pat.kind
1637 && ident.name == self.ident_name
1638 {
1639 self.result = *init;
1640 } else {
1641 hir::intravisit::walk_stmt(self, ex);
1642 }
1643 }
1644 }
1645
1646 let mut visitor = LetVisitor { result: None, ident_name: seg1.ident.name };
1647 visitor.visit_body(&body);
1648
9c376795 1649 let parent = self.tcx.hir().parent_id(seg1.hir_id);
487cf647
FG
1650 if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent)
1651 && let Some(expr) = visitor.result
1652 && let Some(self_ty) = self.node_ty_opt(expr.hir_id)
1653 {
9c376795 1654 let probe = self.lookup_probe_for_diagnostic(
487cf647
FG
1655 seg2.ident,
1656 self_ty,
1657 call_expr,
1658 ProbeScope::TraitsInScope,
9c376795 1659 None,
487cf647
FG
1660 );
1661 if probe.is_ok() {
1662 let sm = self.infcx.tcx.sess.source_map();
1663 diag.span_suggestion_verbose(
1664 sm.span_extend_while(seg1.ident.span.shrink_to_hi(), |c| c == ':').unwrap(),
1665 "you may have meant to call an instance method",
1666 ".".to_string(),
1667 Applicability::MaybeIncorrect,
1668 );
1669 }
1670 }
1671 diag.emit();
1672 }
1673
1674 /// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
1675 fn suggest_calling_method_on_field(
923072b8 1676 &self,
f2b60f7d 1677 err: &mut Diagnostic,
923072b8
FG
1678 source: SelfSource<'tcx>,
1679 span: Span,
1680 actual: Ty<'tcx>,
1681 item_name: Ident,
9c376795 1682 return_type: Option<Ty<'tcx>>,
923072b8
FG
1683 ) {
1684 if let SelfSource::MethodCall(expr) = source
f2b60f7d
FG
1685 && let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id()
1686 && let Some((fields, substs)) =
1687 self.get_field_candidates_considering_privacy(span, actual, mod_id)
923072b8 1688 {
9c376795 1689 let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().parent_id(expr.hir_id));
f2b60f7d
FG
1690
1691 let lang_items = self.tcx.lang_items();
1692 let never_mention_traits = [
1693 lang_items.clone_trait(),
1694 lang_items.deref_trait(),
1695 lang_items.deref_mut_trait(),
1696 self.tcx.get_diagnostic_item(sym::AsRef),
1697 self.tcx.get_diagnostic_item(sym::AsMut),
1698 self.tcx.get_diagnostic_item(sym::Borrow),
1699 self.tcx.get_diagnostic_item(sym::BorrowMut),
1700 ];
1701 let candidate_fields: Vec<_> = fields
1702 .filter_map(|candidate_field| {
1703 self.check_for_nested_field_satisfying(
1704 span,
1705 &|_, field_ty| {
9c376795 1706 self.lookup_probe_for_diagnostic(
f2b60f7d
FG
1707 item_name,
1708 field_ty,
1709 call_expr,
1710 ProbeScope::TraitsInScope,
9c376795 1711 return_type,
f2b60f7d
FG
1712 )
1713 .map_or(false, |pick| {
1714 !never_mention_traits
1715 .iter()
1716 .flatten()
1717 .any(|def_id| self.tcx.parent(pick.item.def_id) == *def_id)
1718 })
1719 },
1720 candidate_field,
1721 substs,
1722 vec![],
1723 mod_id,
1724 )
1725 })
1726 .map(|field_path| {
1727 field_path
923072b8
FG
1728 .iter()
1729 .map(|id| id.name.to_ident_string())
1730 .collect::<Vec<String>>()
f2b60f7d
FG
1731 .join(".")
1732 })
1733 .collect();
1734
1735 let len = candidate_fields.len();
1736 if len > 0 {
1737 err.span_suggestions(
1738 item_name.span.shrink_to_lo(),
1739 format!(
1740 "{} of the expressions' fields {} a method of the same name",
1741 if len > 1 { "some" } else { "one" },
1742 if len > 1 { "have" } else { "has" },
1743 ),
1744 candidate_fields.iter().map(|path| format!("{path}.")),
1745 Applicability::MaybeIncorrect,
1746 );
923072b8
FG
1747 }
1748 }
1749 }
1750
2b03887a 1751 fn check_for_inner_self(
923072b8 1752 &self,
f2b60f7d 1753 err: &mut Diagnostic,
923072b8 1754 source: SelfSource<'tcx>,
923072b8
FG
1755 actual: Ty<'tcx>,
1756 item_name: Ident,
1757 ) {
1758 let tcx = self.tcx;
1759 let SelfSource::MethodCall(expr) = source else { return; };
9c376795 1760 let call_expr = tcx.hir().expect_expr(tcx.hir().parent_id(expr.hir_id));
923072b8
FG
1761
1762 let ty::Adt(kind, substs) = actual.kind() else { return; };
2b03887a
FG
1763 match kind.adt_kind() {
1764 ty::AdtKind::Enum => {
1765 let matching_variants: Vec<_> = kind
1766 .variants()
1767 .iter()
1768 .flat_map(|variant| {
1769 let [field] = &variant.fields[..] else { return None; };
1770 let field_ty = field.ty(tcx, substs);
1771
1772 // Skip `_`, since that'll just lead to ambiguity.
1773 if self.resolve_vars_if_possible(field_ty).is_ty_var() {
1774 return None;
1775 }
923072b8 1776
9c376795
FG
1777 self.lookup_probe_for_diagnostic(
1778 item_name,
1779 field_ty,
1780 call_expr,
1781 ProbeScope::TraitsInScope,
1782 None,
1783 )
1784 .ok()
1785 .map(|pick| (variant, field, pick))
2b03887a
FG
1786 })
1787 .collect();
1788
1789 let ret_ty_matches = |diagnostic_item| {
1790 if let Some(ret_ty) = self
1791 .ret_coercion
1792 .as_ref()
1793 .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
1794 && let ty::Adt(kind, _) = ret_ty.kind()
1795 && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
1796 {
1797 true
1798 } else {
1799 false
1800 }
1801 };
923072b8 1802
2b03887a
FG
1803 match &matching_variants[..] {
1804 [(_, field, pick)] => {
1805 let self_ty = field.ty(tcx, substs);
1806 err.span_note(
1807 tcx.def_span(pick.item.def_id),
1808 &format!("the method `{item_name}` exists on the type `{self_ty}`"),
1809 );
1810 let (article, kind, variant, question) =
1811 if tcx.is_diagnostic_item(sym::Result, kind.did()) {
1812 ("a", "Result", "Err", ret_ty_matches(sym::Result))
1813 } else if tcx.is_diagnostic_item(sym::Option, kind.did()) {
1814 ("an", "Option", "None", ret_ty_matches(sym::Option))
1815 } else {
1816 return;
1817 };
1818 if question {
1819 err.span_suggestion_verbose(
1820 expr.span.shrink_to_hi(),
1821 format!(
1822 "use the `?` operator to extract the `{self_ty}` value, propagating \
1823 {article} `{kind}::{variant}` value to the caller"
1824 ),
1825 "?",
1826 Applicability::MachineApplicable,
1827 );
1828 } else {
1829 err.span_suggestion_verbose(
1830 expr.span.shrink_to_hi(),
1831 format!(
1832 "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
1833 panicking if the value is {article} `{kind}::{variant}`"
1834 ),
1835 ".expect(\"REASON\")",
1836 Applicability::HasPlaceholders,
1837 );
1838 }
1839 }
1840 // FIXME(compiler-errors): Support suggestions for other matching enum variants
1841 _ => {}
923072b8 1842 }
923072b8 1843 }
2b03887a
FG
1844 // Target wrapper types - types that wrap or pretend to wrap another type,
1845 // perhaps this inner type is meant to be called?
1846 ty::AdtKind::Struct | ty::AdtKind::Union => {
1847 let [first] = ***substs else { return; };
1848 let ty::GenericArgKind::Type(ty) = first.unpack() else { return; };
9c376795 1849 let Ok(pick) = self.lookup_probe_for_diagnostic(
487cf647
FG
1850 item_name,
1851 ty,
1852 call_expr,
1853 ProbeScope::TraitsInScope,
9c376795 1854 None,
487cf647 1855 ) else { return; };
923072b8 1856
2b03887a
FG
1857 let name = self.ty_to_value_string(actual);
1858 let inner_id = kind.did();
1859 let mutable = if let Some(AutorefOrPtrAdjustment::Autoref { mutbl, .. }) =
1860 pick.autoref_or_ptr_adjustment
1861 {
1862 Some(mutbl)
1863 } else {
1864 None
1865 };
1866
1867 if tcx.is_diagnostic_item(sym::LocalKey, inner_id) {
1868 err.help("use `with` or `try_with` to access thread local storage");
1869 } else if Some(kind.did()) == tcx.lang_items().maybe_uninit() {
1870 err.help(format!(
1871 "if this `{name}` has been initialized, \
1872 use one of the `assume_init` methods to access the inner value"
1873 ));
1874 } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) {
1875 let (suggestion, borrow_kind, panic_if) = match mutable {
1876 Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"),
1877 Some(Mutability::Mut) => {
1878 (".borrow_mut()", "mutably borrow", "any borrows exist")
1879 }
1880 None => return,
923072b8 1881 };
923072b8
FG
1882 err.span_suggestion_verbose(
1883 expr.span.shrink_to_hi(),
1884 format!(
2b03887a
FG
1885 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
1886 panicking if {panic_if}"
923072b8 1887 ),
2b03887a
FG
1888 suggestion,
1889 Applicability::MaybeIncorrect,
923072b8 1890 );
2b03887a 1891 } else if tcx.is_diagnostic_item(sym::Mutex, inner_id) {
923072b8
FG
1892 err.span_suggestion_verbose(
1893 expr.span.shrink_to_hi(),
1894 format!(
2b03887a
FG
1895 "use `.lock().unwrap()` to borrow the `{ty}`, \
1896 blocking the current thread until it can be acquired"
923072b8 1897 ),
2b03887a
FG
1898 ".lock().unwrap()",
1899 Applicability::MaybeIncorrect,
923072b8 1900 );
2b03887a
FG
1901 } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) {
1902 let (suggestion, borrow_kind) = match mutable {
1903 Some(Mutability::Not) => (".read().unwrap()", "borrow"),
1904 Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"),
1905 None => return,
1906 };
1907 err.span_suggestion_verbose(
1908 expr.span.shrink_to_hi(),
1909 format!(
1910 "use `{suggestion}` to {borrow_kind} the `{ty}`, \
1911 blocking the current thread until it can be acquired"
1912 ),
1913 suggestion,
1914 Applicability::MaybeIncorrect,
1915 );
1916 } else {
1917 return;
1918 };
1919
1920 err.span_note(
1921 tcx.def_span(pick.item.def_id),
1922 &format!("the method `{item_name}` exists on the type `{ty}`"),
1923 );
923072b8 1924 }
923072b8
FG
1925 }
1926 }
1927
1928 pub(crate) fn note_unmet_impls_on_type(
c295e0f8 1929 &self,
5e7ed085 1930 err: &mut Diagnostic,
c295e0f8
XL
1931 errors: Vec<FulfillmentError<'tcx>>,
1932 ) {
1933 let all_local_types_needing_impls =
1934 errors.iter().all(|e| match e.obligation.predicate.kind().skip_binder() {
487cf647 1935 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => match pred.self_ty().kind() {
5e7ed085 1936 ty::Adt(def, _) => def.did().is_local(),
c295e0f8
XL
1937 _ => false,
1938 },
1939 _ => false,
1940 });
1941 let mut preds: Vec<_> = errors
1942 .iter()
1943 .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
487cf647 1944 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => Some(pred),
c295e0f8
XL
1945 _ => None,
1946 })
1947 .collect();
1948 preds.sort_by_key(|pred| (pred.def_id(), pred.self_ty()));
1949 let def_ids = preds
1950 .iter()
1951 .filter_map(|pred| match pred.self_ty().kind() {
5e7ed085 1952 ty::Adt(def, _) => Some(def.did()),
c295e0f8
XL
1953 _ => None,
1954 })
1955 .collect::<FxHashSet<_>>();
c295e0f8
XL
1956 let mut spans: MultiSpan = def_ids
1957 .iter()
1958 .filter_map(|def_id| {
1959 let span = self.tcx.def_span(*def_id);
064997fb 1960 if span.is_dummy() { None } else { Some(span) }
c295e0f8
XL
1961 })
1962 .collect::<Vec<_>>()
1963 .into();
1964
1965 for pred in &preds {
1966 match pred.self_ty().kind() {
064997fb 1967 ty::Adt(def, _) if def.did().is_local() => {
c295e0f8 1968 spans.push_span_label(
064997fb 1969 self.tcx.def_span(def.did()),
c295e0f8
XL
1970 format!("must implement `{}`", pred.trait_ref.print_only_trait_path()),
1971 );
1972 }
1973 _ => {}
1974 }
1975 }
1976
1977 if all_local_types_needing_impls && spans.primary_span().is_some() {
1978 let msg = if preds.len() == 1 {
1979 format!(
1980 "an implementation of `{}` might be missing for `{}`",
1981 preds[0].trait_ref.print_only_trait_path(),
1982 preds[0].self_ty()
1983 )
1984 } else {
1985 format!(
1986 "the following type{} would have to `impl` {} required trait{} for this \
1987 operation to be valid",
1988 pluralize!(def_ids.len()),
1989 if def_ids.len() == 1 { "its" } else { "their" },
1990 pluralize!(preds.len()),
1991 )
1992 };
1993 err.span_note(spans, &msg);
1994 }
1995
3c0e092e
XL
1996 let preds: Vec<_> = errors
1997 .iter()
1998 .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
1999 .collect();
c295e0f8
XL
2000 self.suggest_derive(err, &preds);
2001 }
2002
9c376795 2003 pub fn suggest_derive(
c295e0f8 2004 &self,
5e7ed085 2005 err: &mut Diagnostic,
a2a8927a 2006 unsatisfied_predicates: &[(
3c0e092e
XL
2007 ty::Predicate<'tcx>,
2008 Option<ty::Predicate<'tcx>>,
2009 Option<ObligationCause<'tcx>>,
a2a8927a 2010 )],
c295e0f8 2011 ) {
064997fb 2012 let mut derives = Vec::<(String, Span, Symbol)>::new();
9c376795 2013 let mut traits = Vec::new();
3c0e092e 2014 for (pred, _, _) in unsatisfied_predicates {
487cf647 2015 let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder() else { continue };
c295e0f8 2016 let adt = match trait_pred.self_ty().ty_adt_def() {
5e7ed085 2017 Some(adt) if adt.did().is_local() => adt,
c295e0f8
XL
2018 _ => continue,
2019 };
5099ac24
FG
2020 if let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) {
2021 let can_derive = match diagnostic_name {
2022 sym::Default => !adt.is_enum(),
c295e0f8
XL
2023 sym::Eq
2024 | sym::PartialEq
2025 | sym::Ord
2026 | sym::PartialOrd
2027 | sym::Clone
2028 | sym::Copy
2029 | sym::Hash
5099ac24
FG
2030 | sym::Debug => true,
2031 _ => false,
2032 };
2033 if can_derive {
2034 let self_name = trait_pred.self_ty().to_string();
5e7ed085 2035 let self_span = self.tcx.def_span(adt.did());
5099ac24
FG
2036 if let Some(poly_trait_ref) = pred.to_opt_poly_trait_pred() {
2037 for super_trait in supertraits(self.tcx, poly_trait_ref.to_poly_trait_ref())
2038 {
2039 if let Some(parent_diagnostic_name) =
2040 self.tcx.get_diagnostic_name(super_trait.def_id())
2041 {
2042 derives.push((
2043 self_name.clone(),
923072b8 2044 self_span,
064997fb 2045 parent_diagnostic_name,
5099ac24
FG
2046 ));
2047 }
2048 }
2049 }
064997fb 2050 derives.push((self_name, self_span, diagnostic_name));
5099ac24 2051 } else {
9c376795 2052 traits.push(trait_pred.def_id());
5099ac24 2053 }
c295e0f8 2054 } else {
9c376795 2055 traits.push(trait_pred.def_id());
c295e0f8
XL
2056 }
2057 }
c295e0f8
XL
2058 traits.sort();
2059 traits.dedup();
2060
a2a8927a
XL
2061 derives.sort();
2062 derives.dedup();
2063
2064 let mut derives_grouped = Vec::<(String, Span, String)>::new();
2065 for (self_name, self_span, trait_name) in derives.into_iter() {
2066 if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut()
2067 {
2068 if last_self_name == &self_name {
2069 last_trait_names.push_str(format!(", {}", trait_name).as_str());
2070 continue;
2071 }
2072 }
064997fb 2073 derives_grouped.push((self_name, self_span, trait_name.to_string()));
a2a8927a
XL
2074 }
2075
c295e0f8
XL
2076 let len = traits.len();
2077 if len > 0 {
9c376795
FG
2078 let span =
2079 MultiSpan::from_spans(traits.iter().map(|&did| self.tcx.def_span(did)).collect());
2080 let mut names = format!("`{}`", self.tcx.def_path_str(traits[0]));
2081 for (i, &did) in traits.iter().enumerate().skip(1) {
2082 if len > 2 {
2083 names.push_str(", ");
2084 }
2085 if i == len - 1 {
2086 names.push_str(" and ");
2087 }
2088 names.push('`');
2089 names.push_str(&self.tcx.def_path_str(did));
2090 names.push('`');
2091 }
c295e0f8
XL
2092 err.span_note(
2093 span,
9c376795 2094 &format!("the trait{} {} must be implemented", pluralize!(len), names),
c295e0f8
XL
2095 );
2096 }
2097
2098 for (self_name, self_span, traits) in &derives_grouped {
2099 err.span_suggestion_verbose(
2100 self_span.shrink_to_lo(),
2101 &format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
2102 format!("#[derive({})]\n", traits),
2103 Applicability::MaybeIncorrect,
2104 );
2105 }
2106 }
2107
f2b60f7d
FG
2108 fn check_for_deref_method(
2109 &self,
2110 err: &mut Diagnostic,
2111 self_source: SelfSource<'tcx>,
2112 rcvr_ty: Ty<'tcx>,
2113 item_name: Ident,
9c376795 2114 expected: Expectation<'tcx>,
f2b60f7d
FG
2115 ) {
2116 let SelfSource::QPath(ty) = self_source else { return; };
2117 for (deref_ty, _) in self.autoderef(rustc_span::DUMMY_SP, rcvr_ty).skip(1) {
2118 if let Ok(pick) = self.probe_for_name(
f2b60f7d
FG
2119 Mode::Path,
2120 item_name,
9c376795 2121 expected.only_has_type(self),
f2b60f7d
FG
2122 IsSuggestion(true),
2123 deref_ty,
2124 ty.hir_id,
2125 ProbeScope::TraitsInScope,
2126 ) {
2127 if deref_ty.is_suggestable(self.tcx, true)
2128 // If this method receives `&self`, then the provided
2129 // argument _should_ coerce, so it's valid to suggest
2130 // just changing the path.
2131 && pick.item.fn_has_self_parameter
2132 && let Some(self_ty) =
9ffffee4 2133 self.tcx.fn_sig(pick.item.def_id).subst_identity().inputs().skip_binder().get(0)
f2b60f7d
FG
2134 && self_ty.is_ref()
2135 {
2136 let suggested_path = match deref_ty.kind() {
2137 ty::Bool
2138 | ty::Char
2139 | ty::Int(_)
2140 | ty::Uint(_)
2141 | ty::Float(_)
2142 | ty::Adt(_, _)
2143 | ty::Str
9c376795 2144 | ty::Alias(ty::Projection, _)
f2b60f7d 2145 | ty::Param(_) => format!("{deref_ty}"),
487cf647
FG
2146 // we need to test something like <&[_]>::len or <(&[u32])>::len
2147 // and Vec::function();
2148 // <&[_]>::len or <&[u32]>::len doesn't need an extra "<>" between
2149 // but for Adt type like Vec::function()
2150 // we would suggest <[_]>::function();
2151 _ if self.tcx.sess.source_map().span_wrapped_by_angle_or_parentheses(ty.span) => format!("{deref_ty}"),
f2b60f7d
FG
2152 _ => format!("<{deref_ty}>"),
2153 };
2154 err.span_suggestion_verbose(
2155 ty.span,
2156 format!("the function `{item_name}` is implemented on `{deref_ty}`"),
2157 suggested_path,
2158 Applicability::MaybeIncorrect,
2159 );
2160 } else {
2161 err.span_note(
2162 ty.span,
2163 format!("the function `{item_name}` is implemented on `{deref_ty}`"),
2164 );
2165 }
2166 return;
2167 }
2168 }
2169 }
2170
e74abb32
XL
2171 /// Print out the type for use in value namespace.
2172 fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
1b1a35ee 2173 match ty.kind() {
487cf647 2174 ty::Adt(def, substs) => self.tcx.def_path_str_with_substs(def.did(), substs),
e74abb32
XL
2175 _ => self.ty_to_string(ty),
2176 }
2177 }
2178
1b1a35ee
XL
2179 fn suggest_await_before_method(
2180 &self,
5e7ed085 2181 err: &mut Diagnostic,
1b1a35ee
XL
2182 item_name: Ident,
2183 ty: Ty<'tcx>,
2184 call: &hir::Expr<'_>,
2185 span: Span,
9c376795 2186 return_type: Option<Ty<'tcx>>,
1b1a35ee 2187 ) {
064997fb 2188 let output_ty = match self.get_impl_future_output_ty(ty) {
487cf647 2189 Some(output_ty) => self.resolve_vars_if_possible(output_ty),
29967ef6
XL
2190 _ => return,
2191 };
9c376795
FG
2192 let method_exists =
2193 self.method_exists(item_name, output_ty, call.hir_id, true, return_type);
29967ef6
XL
2194 debug!("suggest_await_before_method: is_method_exist={}", method_exists);
2195 if method_exists {
2196 err.span_suggestion_verbose(
2197 span.shrink_to_lo(),
2198 "consider `await`ing on the `Future` and calling the method on its `Output`",
923072b8 2199 "await.",
29967ef6
XL
2200 Applicability::MaybeIncorrect,
2201 );
1b1a35ee
XL
2202 }
2203 }
2204
04454e1e 2205 fn suggest_use_candidates(&self, err: &mut Diagnostic, msg: String, candidates: Vec<DefId>) {
a2a8927a
XL
2206 let parent_map = self.tcx.visible_parent_map(());
2207
2208 // Separate out candidates that must be imported with a glob, because they are named `_`
2209 // and cannot be referred with their identifier.
2210 let (candidates, globs): (Vec<_>, Vec<_>) = candidates.into_iter().partition(|trait_did| {
2211 if let Some(parent_did) = parent_map.get(trait_did) {
2212 // If the item is re-exported as `_`, we should suggest a glob-import instead.
04454e1e 2213 if *parent_did != self.tcx.parent(*trait_did)
a2a8927a
XL
2214 && self
2215 .tcx
5099ac24 2216 .module_children(*parent_did)
a2a8927a
XL
2217 .iter()
2218 .filter(|child| child.res.opt_def_id() == Some(*trait_did))
2219 .all(|child| child.ident.name == kw::Underscore)
2220 {
2221 return false;
2222 }
2223 }
2224
2225 true
2226 });
2227
9ffffee4 2228 let module_did = self.tcx.parent_module_from_def_id(self.body_id);
04454e1e
FG
2229 let (module, _, _) = self.tcx.hir().get_module(module_did);
2230 let span = module.spans.inject_use_span;
ff7c6d11 2231
04454e1e
FG
2232 let path_strings = candidates.iter().map(|trait_did| {
2233 format!("use {};\n", with_crate_prefix!(self.tcx.def_path_str(*trait_did)),)
2234 });
a2a8927a 2235
04454e1e
FG
2236 let glob_path_strings = globs.iter().map(|trait_did| {
2237 let parent_did = parent_map.get(trait_did).unwrap();
2238 format!(
2239 "use {}::*; // trait {}\n",
2240 with_crate_prefix!(self.tcx.def_path_str(*parent_did)),
2241 self.tcx.item_name(*trait_did),
2242 )
2243 });
a2a8927a 2244
04454e1e
FG
2245 err.span_suggestions(
2246 span,
2247 &msg,
2248 path_strings.chain(glob_path_strings),
2249 Applicability::MaybeIncorrect,
2250 );
3b2f2976
XL
2251 }
2252
e74abb32
XL
2253 fn suggest_valid_traits(
2254 &self,
5e7ed085 2255 err: &mut Diagnostic,
e74abb32
XL
2256 valid_out_of_scope_traits: Vec<DefId>,
2257 ) -> bool {
3b2f2976
XL
2258 if !valid_out_of_scope_traits.is_empty() {
2259 let mut candidates = valid_out_of_scope_traits;
2260 candidates.sort();
2261 candidates.dedup();
3c0e092e
XL
2262
2263 // `TryFrom` and `FromIterator` have no methods
2264 let edition_fix = candidates
2265 .iter()
2266 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
2267 .copied();
2268
3b2f2976 2269 err.help("items from traits can only be used if the trait is in scope");
e74abb32
XL
2270 let msg = format!(
2271 "the following {traits_are} implemented but not in scope; \
2272 perhaps add a `use` for {one_of_them}:",
dfeec247
XL
2273 traits_are = if candidates.len() == 1 { "trait is" } else { "traits are" },
2274 one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
e74abb32 2275 );
3b2f2976
XL
2276
2277 self.suggest_use_candidates(err, msg, candidates);
3c0e092e
XL
2278 if let Some(did) = edition_fix {
2279 err.note(&format!(
2280 "'{}' is included in the prelude starting in Edition 2021",
5e7ed085 2281 with_crate_prefix!(self.tcx.def_path_str(did))
3c0e092e
XL
2282 ));
2283 }
2284
3b2f2976
XL
2285 true
2286 } else {
2287 false
54a0048b 2288 }
85aaf69f
SL
2289 }
2290
cdc7bbd5 2291 fn suggest_traits_to_import(
416331ca 2292 &self,
5e7ed085 2293 err: &mut Diagnostic,
416331ca
XL
2294 span: Span,
2295 rcvr_ty: Ty<'tcx>,
f9f354fc 2296 item_name: Ident,
064997fb 2297 inputs_len: Option<usize>,
cdc7bbd5 2298 source: SelfSource<'tcx>,
416331ca 2299 valid_out_of_scope_traits: Vec<DefId>,
3c0e092e
XL
2300 unsatisfied_predicates: &[(
2301 ty::Predicate<'tcx>,
2302 Option<ty::Predicate<'tcx>>,
2303 Option<ObligationCause<'tcx>>,
2304 )],
2b03887a 2305 static_candidates: &[CandidateSource],
cdc7bbd5 2306 unsatisfied_bounds: bool,
9c376795 2307 return_type: Option<Ty<'tcx>>,
416331ca 2308 ) {
cdc7bbd5
XL
2309 let mut alt_rcvr_sugg = false;
2310 if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
487cf647
FG
2311 debug!(
2312 "suggest_traits_to_import: span={:?}, item_name={:?}, rcvr_ty={:?}, rcvr={:?}",
2313 span, item_name, rcvr_ty, rcvr
2314 );
cdc7bbd5
XL
2315 let skippable = [
2316 self.tcx.lang_items().clone_trait(),
2317 self.tcx.lang_items().deref_trait(),
2318 self.tcx.lang_items().deref_mut_trait(),
2319 self.tcx.lang_items().drop_trait(),
3c0e092e 2320 self.tcx.get_diagnostic_item(sym::AsRef),
cdc7bbd5
XL
2321 ];
2322 // Try alternative arbitrary self types that could fulfill this call.
2323 // FIXME: probe for all types that *could* be arbitrary self-types, not
2324 // just this list.
2325 for (rcvr_ty, post) in &[
2326 (rcvr_ty, ""),
5099ac24
FG
2327 (self.tcx.mk_mut_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&mut "),
2328 (self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&"),
cdc7bbd5 2329 ] {
9c376795
FG
2330 match self.lookup_probe_for_diagnostic(
2331 item_name,
2332 *rcvr_ty,
2333 rcvr,
2334 ProbeScope::AllTraits,
2335 return_type,
2336 ) {
5e7ed085
FG
2337 Ok(pick) => {
2338 // If the method is defined for the receiver we have, it likely wasn't `use`d.
2339 // We point at the method, but we just skip the rest of the check for arbitrary
2340 // self types and rely on the suggestion to `use` the trait from
2341 // `suggest_valid_traits`.
064997fb 2342 let did = Some(pick.item.container_id(self.tcx));
5e7ed085
FG
2343 let skip = skippable.contains(&did);
2344 if pick.autoderefs == 0 && !skip {
2345 err.span_label(
2346 pick.item.ident(self.tcx).span,
2347 &format!("the method is available for `{}` here", rcvr_ty),
2348 );
2349 }
2350 break;
cdc7bbd5 2351 }
5e7ed085
FG
2352 Err(MethodError::Ambiguity(_)) => {
2353 // If the method is defined (but ambiguous) for the receiver we have, it is also
2354 // likely we haven't `use`d it. It may be possible that if we `Box`/`Pin`/etc.
2355 // the receiver, then it might disambiguate this method, but I think these
2356 // suggestions are generally misleading (see #94218).
2357 break;
2358 }
487cf647 2359 Err(_) => (),
cdc7bbd5 2360 }
5e7ed085 2361
cdc7bbd5 2362 for (rcvr_ty, pre) in &[
5099ac24
FG
2363 (self.tcx.mk_lang_item(*rcvr_ty, LangItem::OwnedBox), "Box::new"),
2364 (self.tcx.mk_lang_item(*rcvr_ty, LangItem::Pin), "Pin::new"),
2365 (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Arc), "Arc::new"),
2366 (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Rc), "Rc::new"),
cdc7bbd5 2367 ] {
923072b8 2368 if let Some(new_rcvr_t) = *rcvr_ty
9c376795 2369 && let Ok(pick) = self.lookup_probe_for_diagnostic(
923072b8
FG
2370 item_name,
2371 new_rcvr_t,
2372 rcvr,
2373 ProbeScope::AllTraits,
9c376795 2374 return_type,
923072b8
FG
2375 )
2376 {
5e7ed085 2377 debug!("try_alt_rcvr: pick candidate {:?}", pick);
064997fb 2378 let did = Some(pick.item.container_id(self.tcx));
5e7ed085
FG
2379 // We don't want to suggest a container type when the missing
2380 // method is `.clone()` or `.deref()` otherwise we'd suggest
2381 // `Arc::new(foo).clone()`, which is far from what the user wants.
2382 // Explicitly ignore the `Pin::as_ref()` method as `Pin` does not
2383 // implement the `AsRef` trait.
2384 let skip = skippable.contains(&did)
064997fb 2385 || (("Pin::new" == *pre) && (sym::as_ref == item_name.name))
9ffffee4 2386 || inputs_len.map_or(false, |inputs_len| pick.item.kind == ty::AssocKind::Fn && self.tcx.fn_sig(pick.item.def_id).skip_binder().skip_binder().inputs().len() != inputs_len);
5e7ed085
FG
2387 // Make sure the method is defined for the *actual* receiver: we don't
2388 // want to treat `Box<Self>` as a receiver if it only works because of
2389 // an autoderef to `&self`
2390 if pick.autoderefs == 0 && !skip {
2391 err.span_label(
2392 pick.item.ident(self.tcx).span,
2393 &format!("the method is available for `{}` here", new_rcvr_t),
2394 );
2395 err.multipart_suggestion(
2396 "consider wrapping the receiver expression with the \
2397 appropriate type",
2398 vec![
2399 (rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)),
2400 (rcvr.span.shrink_to_hi(), ")".to_string()),
2401 ],
2402 Applicability::MaybeIncorrect,
2403 );
2404 // We don't care about the other suggestions.
2405 alt_rcvr_sugg = true;
cdc7bbd5
XL
2406 }
2407 }
2408 }
2409 }
2410 }
3b2f2976 2411 if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
c30ab7b3 2412 return;
85aaf69f 2413 }
85aaf69f 2414
0731742a 2415 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
a7813a04 2416
74b04a01 2417 let mut arbitrary_rcvr = vec![];
0731742a 2418 // There are no traits implemented, so lets suggest some traits to
a7813a04
XL
2419 // implement, by finding ones that have the item name, and are
2420 // legal to implement.
8bb4bdeb 2421 let mut candidates = all_traits(self.tcx)
83c7162d 2422 .into_iter()
3dfed10e
XL
2423 // Don't issue suggestions for unstable traits since they're
2424 // unlikely to be implementable anyway
2425 .filter(|info| match self.tcx.lookup_stability(info.def_id) {
2426 Some(attr) => attr.level.is_stable(),
2427 None => true,
2428 })
2b03887a
FG
2429 .filter(|info| {
2430 // Static candidates are already implemented, and known not to work
2431 // Do not suggest them again
2432 static_candidates.iter().all(|sc| match *sc {
2433 CandidateSource::Trait(def_id) => def_id != info.def_id,
2434 CandidateSource::Impl(def_id) => {
2435 self.tcx.trait_id_of_impl(def_id) != Some(info.def_id)
2436 }
2437 })
2438 })
a7813a04 2439 .filter(|info| {
0731742a 2440 // We approximate the coherence rules to only suggest
a7813a04 2441 // traits that are legal to implement by requiring that
0731742a 2442 // either the type or trait is local. Multi-dispatch means
a7813a04
XL
2443 // this isn't perfect (that is, there are cases when
2444 // implementing a trait would be legal but is rejected
2445 // here).
3c0e092e 2446 unsatisfied_predicates.iter().all(|(p, _, _)| {
5869c6ff 2447 match p.kind().skip_binder() {
3dfed10e
XL
2448 // Hide traits if they are present in predicates as they can be fixed without
2449 // having to implement them.
487cf647
FG
2450 ty::PredicateKind::Clause(ty::Clause::Trait(t)) => {
2451 t.def_id() == info.def_id
2452 }
2453 ty::PredicateKind::Clause(ty::Clause::Projection(p)) => {
9c376795 2454 p.projection_ty.def_id == info.def_id
3dfed10e
XL
2455 }
2456 _ => false,
2457 }
74b04a01 2458 }) && (type_is_local || info.def_id.is_local())
9c376795 2459 && !self.tcx.trait_is_auto(info.def_id)
dfeec247 2460 && self
5099ac24 2461 .associated_value(info.def_id, item_name)
2c00a5a8 2462 .filter(|item| {
ba9703b0 2463 if let ty::AssocKind::Fn = item.kind {
f9f354fc
XL
2464 let id = item
2465 .def_id
2466 .as_local()
3dfed10e 2467 .map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id));
74b04a01 2468 if let Some(hir::Node::TraitItem(hir::TraitItem {
ba9703b0 2469 kind: hir::TraitItemKind::Fn(fn_sig, method),
74b04a01
XL
2470 ..
2471 })) = id.map(|id| self.tcx.hir().get(id))
2472 {
2473 let self_first_arg = match method {
ba9703b0 2474 hir::TraitFn::Required([ident, ..]) => {
74b04a01
XL
2475 ident.name == kw::SelfLower
2476 }
ba9703b0 2477 hir::TraitFn::Provided(body_id) => {
f9f354fc
XL
2478 self.tcx.hir().body(*body_id).params.first().map_or(
2479 false,
2480 |param| {
2481 matches!(
2482 param.pat.kind,
2483 hir::PatKind::Binding(_, _, ident, _)
2484 if ident.name == kw::SelfLower
2485 )
2486 },
2487 )
74b04a01
XL
2488 }
2489 _ => false,
2490 };
2491
2492 if !fn_sig.decl.implicit_self.has_implicit_self()
2493 && self_first_arg
2494 {
2495 if let Some(ty) = fn_sig.decl.inputs.get(0) {
2496 arbitrary_rcvr.push(ty.span);
2497 }
2498 return false;
2499 }
2500 }
2501 }
2c00a5a8 2502 // We only want to suggest public or local traits (#45781).
064997fb 2503 item.visibility(self.tcx).is_public() || info.def_id.is_local()
2c00a5a8
XL
2504 })
2505 .is_some()
a7813a04
XL
2506 })
2507 .collect::<Vec<_>>();
74b04a01
XL
2508 for span in &arbitrary_rcvr {
2509 err.span_label(
2510 *span,
2511 "the method might not be found because of this arbitrary self type",
2512 );
2513 }
cdc7bbd5
XL
2514 if alt_rcvr_sugg {
2515 return;
2516 }
a7813a04
XL
2517
2518 if !candidates.is_empty() {
0731742a 2519 // Sort from most relevant to least relevant.
a7813a04
XL
2520 candidates.sort_by(|a, b| a.cmp(b).reverse());
2521 candidates.dedup();
2522
1b1a35ee 2523 let param_type = match rcvr_ty.kind() {
416331ca 2524 ty::Param(param) => Some(param),
1b1a35ee 2525 ty::Ref(_, ty, _) => match ty.kind() {
416331ca
XL
2526 ty::Param(param) => Some(param),
2527 _ => None,
dfeec247 2528 },
416331ca
XL
2529 _ => None,
2530 };
2531 err.help(if param_type.is_some() {
2532 "items from traits can only be used if the type parameter is bounded by the trait"
2533 } else {
2534 "items from traits can only be used if the trait is implemented and in scope"
2535 });
fc512014 2536 let candidates_len = candidates.len();
dfeec247
XL
2537 let message = |action| {
2538 format!(
2539 "the following {traits_define} an item `{name}`, perhaps you need to {action} \
74b04a01 2540 {one_of_them}:",
dfeec247 2541 traits_define =
fc512014 2542 if candidates_len == 1 { "trait defines" } else { "traits define" },
dfeec247 2543 action = action,
fc512014 2544 one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
dfeec247
XL
2545 name = item_name,
2546 )
2547 };
416331ca 2548 // Obtain the span for `param` and use it for a structured suggestion.
064997fb 2549 if let Some(param) = param_type {
9ffffee4 2550 let generics = self.tcx.generics_of(self.body_id.to_def_id());
f035d41b 2551 let type_param = generics.type_param(param, self.tcx);
5099ac24 2552 let hir = self.tcx.hir();
f035d41b 2553 if let Some(def_id) = type_param.def_id.as_local() {
3dfed10e 2554 let id = hir.local_def_id_to_hir_id(def_id);
f035d41b
XL
2555 // Get the `hir::Param` to verify whether it already has any bounds.
2556 // We do this to avoid suggesting code that ends up as `T: FooBar`,
2557 // instead we suggest `T: Foo + Bar` in that case.
2558 match hir.get(id) {
c295e0f8 2559 Node::GenericParam(param) => {
04454e1e
FG
2560 enum Introducer {
2561 Plus,
2562 Colon,
2563 Nothing,
2564 }
2b03887a 2565 let ast_generics = hir.get_generics(id.owner.def_id).unwrap();
04454e1e
FG
2566 let (sp, mut introducer) = if let Some(span) =
2567 ast_generics.bounds_span_for_suggestions(def_id)
2568 {
2569 (span, Introducer::Plus)
2570 } else if let Some(colon_span) = param.colon_span {
2571 (colon_span.shrink_to_hi(), Introducer::Nothing)
f035d41b 2572 } else {
04454e1e 2573 (param.span.shrink_to_hi(), Introducer::Colon)
f035d41b 2574 };
04454e1e
FG
2575 if matches!(
2576 param.kind,
2577 hir::GenericParamKind::Type { synthetic: true, .. },
2578 ) {
2579 introducer = Introducer::Plus
2580 }
2581 let trait_def_ids: FxHashSet<DefId> = ast_generics
2582 .bounds_for_param(def_id)
2583 .flat_map(|bp| bp.bounds.iter())
6a06907d 2584 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
f035d41b
XL
2585 .collect();
2586 if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
e74abb32
XL
2587 err.span_suggestions(
2588 sp,
f035d41b
XL
2589 &message(format!(
2590 "restrict type parameter `{}` with",
2591 param.name.ident(),
2592 )),
dfeec247 2593 candidates.iter().map(|t| {
f035d41b 2594 format!(
04454e1e
FG
2595 "{} {}",
2596 match introducer {
2597 Introducer::Plus => " +",
2598 Introducer::Colon => ":",
2599 Introducer::Nothing => "",
2600 },
f035d41b 2601 self.tcx.def_path_str(t.def_id),
f035d41b 2602 )
dfeec247 2603 }),
e74abb32
XL
2604 Applicability::MaybeIncorrect,
2605 );
e1599b0c 2606 }
fc512014 2607 return;
f035d41b
XL
2608 }
2609 Node::Item(hir::Item {
2610 kind: hir::ItemKind::Trait(.., bounds, _),
2611 ident,
2612 ..
2613 }) => {
2614 let (sp, sep, article) = if bounds.is_empty() {
2615 (ident.span.shrink_to_hi(), ":", "a")
2616 } else {
2617 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
2618 };
2619 err.span_suggestions(
2620 sp,
2621 &message(format!("add {} supertrait for", article)),
2622 candidates.iter().map(|t| {
2623 format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
2624 }),
2625 Applicability::MaybeIncorrect,
2626 );
fc512014 2627 return;
416331ca 2628 }
f035d41b 2629 _ => {}
416331ca 2630 }
f035d41b 2631 }
416331ca
XL
2632 }
2633
fc512014
XL
2634 let (potential_candidates, explicitly_negative) = if param_type.is_some() {
2635 // FIXME: Even though negative bounds are not implemented, we could maybe handle
2636 // cases where a positive bound implies a negative impl.
2637 (candidates, Vec::new())
5e7ed085 2638 } else if let Some(simp_rcvr_ty) =
923072b8 2639 simplify_type(self.tcx, rcvr_ty, TreatParams::AsPlaceholder)
a2a8927a 2640 {
fc512014
XL
2641 let mut potential_candidates = Vec::new();
2642 let mut explicitly_negative = Vec::new();
2643 for candidate in candidates {
2644 // Check if there's a negative impl of `candidate` for `rcvr_ty`
2645 if self
2646 .tcx
2647 .all_impls(candidate.def_id)
2648 .filter(|imp_did| {
2649 self.tcx.impl_polarity(*imp_did) == ty::ImplPolarity::Negative
2650 })
2651 .any(|imp_did| {
9c376795 2652 let imp = self.tcx.impl_trait_ref(imp_did).unwrap().subst_identity();
5099ac24 2653 let imp_simp =
923072b8 2654 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsPlaceholder);
5869c6ff 2655 imp_simp.map_or(false, |s| s == simp_rcvr_ty)
fc512014
XL
2656 })
2657 {
2658 explicitly_negative.push(candidate);
2659 } else {
2660 potential_candidates.push(candidate);
74b04a01
XL
2661 }
2662 }
fc512014
XL
2663 (potential_candidates, explicitly_negative)
2664 } else {
2665 // We don't know enough about `recv_ty` to make proper suggestions.
2666 (candidates, Vec::new())
2667 };
2668
2669 let action = if let Some(param) = param_type {
2670 format!("restrict type parameter `{}` with", param)
2671 } else {
2672 // FIXME: it might only need to be imported into scope, not implemented.
2673 "implement".to_string()
2674 };
2675 match &potential_candidates[..] {
2676 [] => {}
2677 [trait_info] if trait_info.def_id.is_local() => {
fc512014 2678 err.span_note(
064997fb 2679 self.tcx.def_span(trait_info.def_id),
fc512014
XL
2680 &format!(
2681 "`{}` defines an item `{}`, perhaps you need to {} it",
2682 self.tcx.def_path_str(trait_info.def_id),
2683 item_name,
2684 action
2685 ),
2686 );
2687 }
2688 trait_infos => {
74b04a01 2689 let mut msg = message(action);
fc512014 2690 for (i, trait_info) in trait_infos.iter().enumerate() {
74b04a01
XL
2691 msg.push_str(&format!(
2692 "\ncandidate #{}: `{}`",
2693 i + 1,
2694 self.tcx.def_path_str(trait_info.def_id),
2695 ));
2696 }
fc512014
XL
2697 err.note(&msg);
2698 }
2699 }
2700 match &explicitly_negative[..] {
2701 [] => {}
2702 [trait_info] => {
2703 let msg = format!(
5099ac24 2704 "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
fc512014
XL
2705 self.tcx.def_path_str(trait_info.def_id),
2706 item_name
2707 );
2708 err.note(&msg);
2709 }
2710 trait_infos => {
2711 let mut msg = format!(
5099ac24 2712 "the following traits define an item `{}`, but are explicitly unimplemented:",
fc512014
XL
2713 item_name
2714 );
2715 for trait_info in trait_infos {
2716 msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
2717 }
2718 err.note(&msg);
416331ca 2719 }
a7813a04 2720 }
85aaf69f 2721 }
85aaf69f
SL
2722 }
2723
2b03887a
FG
2724 /// issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else`
2725 /// FIXME: currently not working for suggesting `map_or_else`, see #102408
2726 pub(crate) fn suggest_else_fn_with_closure(
2727 &self,
2728 err: &mut Diagnostic,
2729 expr: &hir::Expr<'_>,
2730 found: Ty<'tcx>,
2731 expected: Ty<'tcx>,
2732 ) -> bool {
9c376795
FG
2733 let Some((_def_id_or_name, output, _inputs)) =
2734 self.extract_callable_info(found) else {
2735 return false;
2736 };
2b03887a
FG
2737
2738 if !self.can_coerce(output, expected) {
2739 return false;
2740 }
2741
9c376795 2742 let parent = self.tcx.hir().parent_id(expr.hir_id);
2b03887a
FG
2743 if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) &&
2744 let hir::ExprKind::MethodCall(
2745 hir::PathSegment { ident: method_name, .. },
2746 self_expr,
2747 args,
2748 ..,
2749 ) = call_expr.kind &&
2750 let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr) {
2751 let new_name = Ident {
2752 name: Symbol::intern(&format!("{}_else", method_name.as_str())),
2753 span: method_name.span,
2754 };
9c376795 2755 let probe = self.lookup_probe_for_diagnostic(
2b03887a
FG
2756 new_name,
2757 self_ty,
2758 self_expr,
2759 ProbeScope::TraitsInScope,
9c376795 2760 Some(expected),
2b03887a
FG
2761 );
2762
2763 // check the method arguments number
2764 if let Ok(pick) = probe &&
2765 let fn_sig = self.tcx.fn_sig(pick.item.def_id) &&
9ffffee4 2766 let fn_args = fn_sig.skip_binder().skip_binder().inputs() &&
2b03887a
FG
2767 fn_args.len() == args.len() + 1 {
2768 err.span_suggestion_verbose(
2769 method_name.span.shrink_to_hi(),
2770 &format!("try calling `{}` instead", new_name.name.as_str()),
2771 "_else",
2772 Applicability::MaybeIncorrect,
2773 );
2774 return true;
2775 }
2776 }
2777 false
2778 }
2779
a7813a04
XL
2780 /// Checks whether there is a local type somewhere in the chain of
2781 /// autoderefs of `rcvr_ty`.
cdc7bbd5
XL
2782 fn type_derefs_to_local(
2783 &self,
2784 span: Span,
2785 rcvr_ty: Ty<'tcx>,
2786 source: SelfSource<'tcx>,
2787 ) -> bool {
9fa01778 2788 fn is_local(ty: Ty<'_>) -> bool {
1b1a35ee 2789 match ty.kind() {
5e7ed085 2790 ty::Adt(def, _) => def.did().is_local(),
b7449926 2791 ty::Foreign(did) => did.is_local(),
c295e0f8 2792 ty::Dynamic(tr, ..) => tr.principal().map_or(false, |d| d.def_id().is_local()),
b7449926 2793 ty::Param(_) => true,
a7813a04 2794
0731742a
XL
2795 // Everything else (primitive types, etc.) is effectively
2796 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
a7813a04
XL
2797 // the noise from these sort of types is usually just really
2798 // annoying, rather than any sort of help).
c30ab7b3 2799 _ => false,
a7813a04 2800 }
85aaf69f 2801 }
85aaf69f 2802
a7813a04
XL
2803 // This occurs for UFCS desugaring of `T::method`, where there is no
2804 // receiver expression for the method call, and thus no autoderef.
0731742a 2805 if let SelfSource::QPath(_) = source {
e74abb32 2806 return is_local(self.resolve_vars_with_obligations(rcvr_ty));
c34b1796 2807 }
c34b1796 2808
3157f602 2809 self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
c34b1796 2810 }
85aaf69f
SL
2811}
2812
cdc7bbd5 2813#[derive(Copy, Clone, Debug)]
0731742a 2814pub enum SelfSource<'a> {
dfeec247
XL
2815 QPath(&'a hir::Ty<'a>),
2816 MethodCall(&'a hir::Expr<'a> /* rcvr */),
0731742a
XL
2817}
2818
c34b1796 2819#[derive(Copy, Clone)]
85aaf69f 2820pub struct TraitInfo {
e9174d1e 2821 pub def_id: DefId,
85aaf69f
SL
2822}
2823
85aaf69f
SL
2824impl PartialEq for TraitInfo {
2825 fn eq(&self, other: &TraitInfo) -> bool {
2826 self.cmp(other) == Ordering::Equal
2827 }
2828}
2829impl Eq for TraitInfo {}
2830impl PartialOrd for TraitInfo {
c30ab7b3
SL
2831 fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
2832 Some(self.cmp(other))
2833 }
85aaf69f
SL
2834}
2835impl Ord for TraitInfo {
2836 fn cmp(&self, other: &TraitInfo) -> Ordering {
0731742a
XL
2837 // Local crates are more important than remote ones (local:
2838 // `cnum == 0`), and otherwise we throw in the defid for totality.
85aaf69f 2839
b039eaaf
SL
2840 let lhs = (other.def_id.krate, other.def_id);
2841 let rhs = (self.def_id.krate, self.def_id);
85aaf69f
SL
2842 lhs.cmp(&rhs)
2843 }
2844}
2845
a2a8927a
XL
2846/// Retrieves all traits in this crate and any dependent crates,
2847/// and wraps them into `TraitInfo` for custom sorting.
416331ca 2848pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
a2a8927a 2849 tcx.all_traits().map(|def_id| TraitInfo { def_id }).collect()
85aaf69f 2850}
ff7c6d11 2851
a2a8927a 2852fn print_disambiguation_help<'tcx>(
f9f354fc 2853 item_name: Ident,
f2b60f7d 2854 args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
5e7ed085 2855 err: &mut Diagnostic,
dfeec247
XL
2856 trait_name: String,
2857 rcvr_ty: Ty<'_>,
2858 kind: ty::AssocKind,
9ffffee4 2859 def_kind_descr: &'static str,
dfeec247
XL
2860 span: Span,
2861 candidate: Option<usize>,
2862 source_map: &source_map::SourceMap,
c295e0f8 2863 fn_has_self_parameter: bool,
dfeec247
XL
2864) {
2865 let mut applicability = Applicability::MachineApplicable;
f2b60f7d 2866 let (span, sugg) = if let (ty::AssocKind::Fn, Some((receiver, args))) = (kind, args) {
94222f64 2867 let args = format!(
dfeec247 2868 "({}{})",
487cf647 2869 rcvr_ty.ref_mutability().map_or("", |mutbl| mutbl.ref_prefix_str()),
f2b60f7d
FG
2870 std::iter::once(receiver)
2871 .chain(args.iter())
dfeec247
XL
2872 .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| {
2873 applicability = Applicability::HasPlaceholders;
2874 "_".to_owned()
2875 }))
2876 .collect::<Vec<_>>()
2877 .join(", "),
94222f64 2878 );
c295e0f8
XL
2879 let trait_name = if !fn_has_self_parameter {
2880 format!("<{} as {}>", rcvr_ty, trait_name)
2881 } else {
2882 trait_name
2883 };
94222f64 2884 (span, format!("{}::{}{}", trait_name, item_name, args))
dfeec247 2885 } else {
c295e0f8 2886 (span.with_hi(item_name.span.lo()), format!("<{} as {}>::", rcvr_ty, trait_name))
dfeec247 2887 };
94222f64 2888 err.span_suggestion_verbose(
dfeec247
XL
2889 span,
2890 &format!(
2891 "disambiguate the {} for {}",
9ffffee4 2892 def_kind_descr,
dfeec247
XL
2893 if let Some(candidate) = candidate {
2894 format!("candidate #{}", candidate)
2895 } else {
2896 "the candidate".to_string()
2897 },
2898 ),
2899 sugg,
2900 applicability,
2901 );
2902}