]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_typeck/src/check/method/suggest.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / 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
9fa01778 4use crate::check::FnCtxt;
74b04a01 5use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5e7ed085
FG
6use rustc_errors::{
7 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
04454e1e 8 MultiSpan,
5e7ed085 9};
dfeec247 10use rustc_hir as hir;
04454e1e
FG
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::DefId;
3dfed10e 13use rustc_hir::lang_items::LangItem;
dfeec247 14use rustc_hir::{ExprKind, Node, QPath};
74b04a01 15use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
5099ac24 16use rustc_middle::traits::util::supertraits;
5e7ed085 17use rustc_middle::ty::fast_reject::{simplify_type, TreatParams};
ba9703b0 18use rustc_middle::ty::print::with_crate_prefix;
5099ac24 19use rustc_middle::ty::ToPolyTraitRef;
a2a8927a 20use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
3dfed10e 21use rustc_span::symbol::{kw, sym, Ident};
04454e1e 22use rustc_span::{lev_distance, source_map, ExpnKind, FileName, MacroKind, Span};
5e7ed085
FG
23use rustc_trait_selection::traits::error_reporting::on_unimplemented::InferCtxtExt as _;
24use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
3c0e092e 25use rustc_trait_selection::traits::{
5e7ed085 26 FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, OnUnimplementedNote,
3c0e092e 27};
85aaf69f 28
85aaf69f 29use std::cmp::Ordering;
6a06907d 30use std::iter;
85aaf69f 31
04454e1e
FG
32use super::probe::{Mode, ProbeScope};
33use super::{super::suggest_call_constructor, CandidateSource, MethodError, NoMatchData};
85aaf69f 34
dc9dc135 35impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
48663c56 36 fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
a7813a04 37 let tcx = self.tcx;
1b1a35ee 38 match ty.kind() {
0731742a
XL
39 // Not all of these (e.g., unsafe fns) implement `FnOnce`,
40 // so we look for these beforehand.
dfeec247 41 ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
0731742a 42 // If it's not a simple function, look for things which implement `FnOnce`.
a7813a04 43 _ => {
5e7ed085
FG
44 let Some(fn_once) = tcx.lang_items().fn_once_trait() else {
45 return false;
3157f602 46 };
a7813a04 47
5099ac24
FG
48 // This conditional prevents us from asking to call errors and unresolved types.
49 // It might seem that we can use `predicate_must_hold_modulo_regions`,
50 // but since a Dummy binder is used to fill in the FnOnce trait's arguments,
51 // type resolution always gives a "maybe" here.
52 if self.autoderef(span, ty).any(|(ty, _)| {
53 info!("check deref {:?} error", ty);
54 matches!(ty.kind(), ty::Error(_) | ty::Infer(_))
55 }) {
56 return false;
57 }
58
c30ab7b3 59 self.autoderef(span, ty).any(|(ty, _)| {
5099ac24 60 info!("check deref {:?} impl FnOnce", ty);
c30ab7b3 61 self.probe(|_| {
dfeec247
XL
62 let fn_once_substs = tcx.mk_substs_trait(
63 ty,
64 &[self
65 .next_ty_var(TypeVariableOrigin {
66 kind: TypeVariableOriginKind::MiscVariable,
67 span,
68 })
69 .into()],
70 );
c30ab7b3 71 let trait_ref = ty::TraitRef::new(fn_once, fn_once_substs);
c295e0f8 72 let poly_trait_ref = ty::Binder::dummy(trait_ref);
dfeec247
XL
73 let obligation = Obligation::misc(
74 span,
75 self.body_id,
76 self.param_env,
f9f354fc 77 poly_trait_ref.without_const().to_predicate(tcx),
dfeec247 78 );
83c7162d 79 self.predicate_may_hold(&obligation)
c30ab7b3
SL
80 })
81 })
54a0048b
SL
82 }
83 }
84 }
3157f602 85
a2a8927a
XL
86 fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool {
87 self.autoderef(span, ty).any(|(ty, _)| matches!(ty.kind(), ty::Slice(..) | ty::Array(..)))
88 }
89
cdc7bbd5 90 pub fn report_method_error(
532ac7d7 91 &self,
94222f64 92 mut span: Span,
532ac7d7 93 rcvr_ty: Ty<'tcx>,
f9f354fc 94 item_name: Ident,
cdc7bbd5 95 source: SelfSource<'tcx>,
532ac7d7 96 error: MethodError<'tcx>,
dfeec247 97 args: Option<&'tcx [hir::Expr<'tcx>]>,
5e7ed085 98 ) -> Option<DiagnosticBuilder<'_, ErrorGuaranteed>> {
0731742a 99 // Avoid suggestions when we don't know what's going on.
a7813a04 100 if rcvr_ty.references_error() {
e1599b0c 101 return None;
a7813a04 102 }
85aaf69f 103
dfeec247 104 let report_candidates = |span: Span,
5e7ed085 105 err: &mut Diagnostic,
dfeec247
XL
106 mut sources: Vec<CandidateSource>,
107 sugg_span: Span| {
a7813a04
XL
108 sources.sort();
109 sources.dedup();
110 // Dynamic limit to avoid hiding just one candidate, which is silly.
111 let limit = if sources.len() == 5 { 5 } else { 4 };
112
113 for (idx, source) in sources.iter().take(limit).enumerate() {
114 match *source {
04454e1e 115 CandidateSource::Impl(impl_did) => {
a7813a04
XL
116 // Provide the best span we can. Use the item, if local to crate, else
117 // the impl, if local to crate (item may be defaulted), else nothing.
5e7ed085 118 let Some(item) = self.associated_value(impl_did, item_name).or_else(|| {
5099ac24
FG
119 let impl_trait_ref = self.tcx.impl_trait_ref(impl_did)?;
120 self.associated_value(impl_trait_ref.def_id, item_name)
5e7ed085
FG
121 }) else {
122 continue;
48663c56 123 };
dfeec247
XL
124 let note_span = self
125 .tcx
126 .hir()
127 .span_if_local(item.def_id)
128 .or_else(|| self.tcx.hir().span_if_local(impl_did));
a7813a04 129
ba9703b0 130 let impl_ty = self.tcx.at(span).type_of(impl_did);
a7813a04
XL
131
132 let insertion = match self.tcx.impl_trait_ref(impl_did) {
8faf50e0 133 None => String::new(),
dfeec247
XL
134 Some(trait_ref) => format!(
135 " of the trait `{}`",
136 self.tcx.def_path_str(trait_ref.def_id)
137 ),
a7813a04
XL
138 };
139
dfeec247
XL
140 let (note_str, idx) = if sources.len() > 1 {
141 (
142 format!(
143 "candidate #{} is defined in an impl{} for the type `{}`",
94b46f34
XL
144 idx + 1,
145 insertion,
dfeec247
XL
146 impl_ty,
147 ),
148 Some(idx + 1),
149 )
94b46f34 150 } else {
dfeec247
XL
151 (
152 format!(
153 "the candidate is defined in an impl{} for the type `{}`",
154 insertion, impl_ty,
155 ),
156 None,
157 )
94b46f34 158 };
a7813a04
XL
159 if let Some(note_span) = note_span {
160 // We have a span pointing to the method. Show note with snippet.
dfeec247 161 err.span_note(
ba9703b0 162 self.tcx.sess.source_map().guess_head_span(note_span),
dfeec247
XL
163 &note_str,
164 );
a7813a04
XL
165 } else {
166 err.note(&note_str);
167 }
416331ca 168 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_did) {
dfeec247
XL
169 let path = self.tcx.def_path_str(trait_ref.def_id);
170
171 let ty = match item.kind {
f035d41b 172 ty::AssocKind::Const | ty::AssocKind::Type => rcvr_ty,
ba9703b0 173 ty::AssocKind::Fn => self
dfeec247
XL
174 .tcx
175 .fn_sig(item.def_id)
176 .inputs()
177 .skip_binder()
178 .get(0)
179 .filter(|ty| ty.is_region_ptr() && !rcvr_ty.is_region_ptr())
74b04a01 180 .copied()
dfeec247
XL
181 .unwrap_or(rcvr_ty),
182 };
183 print_disambiguation_help(
184 item_name,
185 args,
186 err,
187 path,
188 ty,
189 item.kind,
ba9703b0 190 item.def_id,
dfeec247
XL
191 sugg_span,
192 idx,
193 self.tcx.sess.source_map(),
c295e0f8 194 item.fn_has_self_parameter,
dfeec247 195 );
416331ca 196 }
a7813a04 197 }
04454e1e 198 CandidateSource::Trait(trait_did) => {
5e7ed085 199 let Some(item) = self.associated_value(trait_did, item_name) else { continue };
ba9703b0
XL
200 let item_span = self
201 .tcx
202 .sess
203 .source_map()
204 .guess_head_span(self.tcx.def_span(item.def_id));
dfeec247
XL
205 let idx = if sources.len() > 1 {
206 let msg = &format!(
207 "candidate #{} is defined in the trait `{}`",
208 idx + 1,
209 self.tcx.def_path_str(trait_did)
210 );
211 err.span_note(item_span, msg);
212 Some(idx + 1)
94b46f34 213 } else {
dfeec247
XL
214 let msg = &format!(
215 "the candidate is defined in the trait `{}`",
216 self.tcx.def_path_str(trait_did)
217 );
218 err.span_note(item_span, msg);
219 None
220 };
221 let path = self.tcx.def_path_str(trait_did);
222 print_disambiguation_help(
223 item_name,
224 args,
225 err,
226 path,
227 rcvr_ty,
228 item.kind,
ba9703b0 229 item.def_id,
dfeec247
XL
230 sugg_span,
231 idx,
232 self.tcx.sess.source_map(),
c295e0f8 233 item.fn_has_self_parameter,
dfeec247 234 );
9cc50fc6 235 }
54a0048b
SL
236 }
237 }
a7813a04
XL
238 if sources.len() > limit {
239 err.note(&format!("and {} others", sources.len() - limit));
240 }
241 };
62682a34 242
dfeec247
XL
243 let sugg_span = if let SelfSource::MethodCall(expr) = source {
244 // Given `foo.bar(baz)`, `expr` is `bar`, but we want to point to the whole thing.
245 self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id)).span
246 } else {
247 span
248 };
249
a7813a04 250 match error {
ff7c6d11
XL
251 MethodError::NoMatch(NoMatchData {
252 static_candidates: static_sources,
253 unsatisfied_predicates,
254 out_of_scope_traits,
255 lev_candidate,
256 mode,
ff7c6d11 257 }) => {
a7813a04
XL
258 let tcx = self.tcx;
259
fc512014 260 let actual = self.resolve_vars_if_possible(rcvr_ty);
0731742a 261 let ty_str = self.ty_to_string(actual);
ff7c6d11 262 let is_method = mode == Mode::MethodCall;
94b46f34 263 let item_kind = if is_method {
ff7c6d11
XL
264 "method"
265 } else if actual.is_enum() {
48663c56 266 "variant or associated item"
ff7c6d11
XL
267 } else {
268 match (item_name.as_str().chars().next(), actual.is_fresh_ty()) {
dfeec247 269 (Some(name), false) if name.is_lowercase() => "function or associated item",
ff7c6d11 270 (Some(_), false) => "associated item",
dfeec247 271 (Some(_), true) | (None, false) => "variant or associated item",
ff7c6d11
XL
272 (None, true) => "variant",
273 }
274 };
3c0e092e 275
04454e1e
FG
276 if self.suggest_constraining_numerical_ty(
277 tcx, actual, source, span, item_kind, item_name, &ty_str,
278 ) {
279 return None;
280 }
281
282 span = item_name.span;
283
284 // Don't show generic arguments when the method can't be found in any implementation (#81576).
285 let mut ty_str_reported = ty_str.clone();
286 if let ty::Adt(_, generics) = actual.kind() {
287 if generics.len() > 0 {
288 let mut autoderef = self.autoderef(span, actual);
289 let candidate_found = autoderef.any(|(ty, _)| {
290 if let ty::Adt(adt_deref, _) = ty.kind() {
291 self.tcx
292 .inherent_impls(adt_deref.did())
293 .iter()
294 .filter_map(|def_id| self.associated_value(*def_id, item_name))
295 .count()
296 >= 1
297 } else {
298 false
2c00a5a8 299 }
04454e1e
FG
300 });
301 let has_deref = autoderef.step_count() > 0;
302 if !candidate_found && !has_deref && unsatisfied_predicates.is_empty() {
303 if let Some((path_string, _)) = ty_str.split_once('<') {
304 ty_str_reported = path_string.to_string();
17df50a5
XL
305 }
306 }
04454e1e
FG
307 }
308 }
17df50a5 309
04454e1e
FG
310 let mut err = struct_span_err!(
311 tcx.sess,
312 span,
313 E0599,
314 "no {} named `{}` found for {} `{}` in the current scope",
315 item_kind,
316 item_name,
317 actual.prefix_string(self.tcx),
318 ty_str_reported,
319 );
320 if actual.references_error() {
321 err.downgrade_to_delayed_bug();
322 }
323
324 if let Mode::MethodCall = mode && let SelfSource::MethodCall(cal) = source {
325 self.suggest_await_before_method(
326 &mut err, item_name, actual, cal, span,
327 );
328 }
329 if let Some(span) = tcx.resolutions(()).confused_type_with_std_module.get(&span) {
923072b8
FG
330 err.span_suggestion(
331 span.shrink_to_lo(),
332 "you are looking for the module in `std`, not the primitive type",
333 "std::",
334 Applicability::MachineApplicable,
335 );
04454e1e
FG
336 }
337 if let ty::RawPtr(_) = &actual.kind() {
338 err.note(
339 "try using `<*const T>::as_ref()` to get a reference to the \
923072b8
FG
340 type behind the pointer: https://doc.rust-lang.org/std/\
341 primitive.pointer.html#method.as_ref",
04454e1e
FG
342 );
343 err.note(
923072b8
FG
344 "using `<*const T>::as_ref()` on a pointer which is unaligned or points \
345 to invalid or uninitialized memory is undefined behavior",
04454e1e 346 );
5e7ed085
FG
347 }
348
94b46f34 349 if let Some(def) = actual.ty_adt_def() {
5e7ed085 350 if let Some(full_sp) = tcx.hir().span_if_local(def.did()) {
ba9703b0 351 let def_sp = tcx.sess.source_map().guess_head_span(full_sp);
dfeec247
XL
352 err.span_label(
353 def_sp,
354 format!(
355 "{} `{}` not found {}",
356 item_kind,
357 item_name,
358 if def.is_enum() && !is_method { "here" } else { "for this" }
359 ),
360 );
ff7c6d11
XL
361 }
362 }
363
c295e0f8 364 if self.is_fn_ty(rcvr_ty, span) {
0731742a 365 if let SelfSource::MethodCall(expr) = source {
04454e1e
FG
366 let suggest = if let ty::FnDef(def_id, _) = rcvr_ty.kind() {
367 if let Some(local_id) = def_id.as_local() {
368 let hir_id = tcx.hir().local_def_id_to_hir_id(local_id);
369 let node = tcx.hir().get(hir_id);
370 let fields = node.tuple_fields();
371 if let Some(fields) = fields
372 && let Some(DefKind::Ctor(of, _)) = self.tcx.opt_def_kind(local_id) {
373 Some((fields.len(), of))
374 } else {
375 None
376 }
377 } else {
378 // The logic here isn't smart but `associated_item_def_ids`
379 // doesn't work nicely on local.
380 if let DefKind::Ctor(of, _) = tcx.def_kind(def_id) {
381 let parent_def_id = tcx.parent(*def_id);
382 Some((tcx.associated_item_def_ids(parent_def_id).len(), of))
383 } else {
384 None
385 }
a7813a04 386 }
04454e1e
FG
387 } else {
388 None
389 };
390
391 // If the function is a tuple constructor, we recommend that they call it
392 if let Some((fields, kind)) = suggest {
393 suggest_call_constructor(expr.span, kind, fields, &mut err);
394 } else {
395 // General case
396 err.span_label(
397 expr.span,
398 "this is a function, perhaps you wish to call it",
399 );
62682a34
SL
400 }
401 }
c34b1796 402 }
85aaf69f 403
5e7ed085
FG
404 let mut custom_span_label = false;
405
a7813a04 406 if !static_sources.is_empty() {
dfeec247
XL
407 err.note(
408 "found the following associated functions; to be used as methods, \
74b04a01 409 functions must have a `self` parameter",
dfeec247 410 );
94b46f34 411 err.span_label(span, "this is an associated function, not a method");
5e7ed085 412 custom_span_label = true;
94b46f34
XL
413 }
414 if static_sources.len() == 1 {
04454e1e
FG
415 let ty_str =
416 if let Some(CandidateSource::Impl(impl_did)) = static_sources.get(0) {
417 // When the "method" is resolved through dereferencing, we really want the
418 // original type that has the associated function for accurate suggestions.
419 // (#61411)
420 let ty = tcx.at(span).type_of(*impl_did);
421 match (&ty.peel_refs().kind(), &actual.peel_refs().kind()) {
422 (ty::Adt(def, _), ty::Adt(def_actual, _)) if def == def_actual => {
423 // Use `actual` as it will have more `substs` filled in.
424 self.ty_to_value_string(actual.peel_refs())
425 }
426 _ => self.ty_to_value_string(ty.peel_refs()),
e74abb32 427 }
04454e1e
FG
428 } else {
429 self.ty_to_value_string(actual.peel_refs())
430 };
0731742a 431 if let SelfSource::MethodCall(expr) = source {
e74abb32
XL
432 err.span_suggestion(
433 expr.span.to(span),
434 "use associated function syntax instead",
435 format!("{}::{}", ty_str, item_name),
436 Applicability::MachineApplicable,
437 );
94b46f34 438 } else {
dfeec247 439 err.help(&format!("try with `{}::{}`", ty_str, item_name,));
94b46f34
XL
440 }
441
dfeec247 442 report_candidates(span, &mut err, static_sources, sugg_span);
94b46f34 443 } else if static_sources.len() > 1 {
dfeec247 444 report_candidates(span, &mut err, static_sources, sugg_span);
a7813a04 445 }
85aaf69f 446
5e7ed085 447 let mut bound_spans = vec![];
74b04a01 448 let mut restrict_type_params = false;
cdc7bbd5 449 let mut unsatisfied_bounds = false;
a2a8927a
XL
450 if item_name.name == sym::count && self.is_slice_ty(actual, span) {
451 let msg = "consider using `len` instead";
452 if let SelfSource::MethodCall(_expr) = source {
453 err.span_suggestion_short(
454 span,
455 msg,
923072b8 456 "len",
a2a8927a
XL
457 Applicability::MachineApplicable,
458 );
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!("`count` is defined on `{iterator_trait}`, which `{actual}` does not implement"));
465 }
466 } else if !unsatisfied_predicates.is_empty() {
ba9703b0
XL
467 let def_span = |def_id| {
468 self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id))
469 };
74b04a01 470 let mut type_params = FxHashMap::default();
5e7ed085
FG
471
472 // Pick out the list of unimplemented traits on the receiver.
473 // This is used for custom error messages with the `#[rustc_on_unimplemented]` attribute.
474 let mut unimplemented_traits = FxHashMap::default();
475 let mut unimplemented_traits_only = true;
476 for (predicate, _parent_pred, cause) in &unsatisfied_predicates {
477 if let (ty::PredicateKind::Trait(p), Some(cause)) =
478 (predicate.kind().skip_binder(), cause.as_ref())
479 {
480 if p.trait_ref.self_ty() != rcvr_ty {
481 // This is necessary, not just to keep the errors clean, but also
482 // because our derived obligations can wind up with a trait ref that
483 // requires a different param_env to be correctly compared.
484 continue;
485 }
486 unimplemented_traits.entry(p.trait_ref.def_id).or_insert((
487 predicate.kind().rebind(p.trait_ref),
488 Obligation {
489 cause: cause.clone(),
490 param_env: self.param_env,
923072b8 491 predicate: *predicate,
5e7ed085
FG
492 recursion_depth: 0,
493 },
494 ));
495 }
496 }
497
498 // Make sure that, if any traits other than the found ones were involved,
499 // we don't don't report an unimplemented trait.
500 // We don't want to say that `iter::Cloned` is not an iterator, just
501 // because of some non-Clone item being iterated over.
502 for (predicate, _parent_pred, _cause) in &unsatisfied_predicates {
503 match predicate.kind().skip_binder() {
504 ty::PredicateKind::Trait(p)
505 if unimplemented_traits.contains_key(&p.trait_ref.def_id) => {}
506 _ => {
507 unimplemented_traits_only = false;
508 break;
509 }
510 }
511 }
3dfed10e 512
74b04a01 513 let mut collect_type_param_suggestions =
5099ac24 514 |self_ty: Ty<'tcx>, parent_pred: ty::Predicate<'tcx>, obligation: &str| {
3dfed10e 515 // We don't care about regions here, so it's fine to skip the binder here.
94222f64 516 if let (ty::Param(_), ty::PredicateKind::Trait(p)) =
5869c6ff 517 (self_ty.kind(), parent_pred.kind().skip_binder())
74b04a01 518 {
3c0e092e
XL
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.
523 let did = self.tcx.hir().body_owner_def_id(hir::BodyId {
524 hir_id: self.body_id,
525 });
526 Some(
527 self.tcx
528 .hir()
529 .get(self.tcx.hir().local_def_id_to_hir_id(did)),
530 )
531 }
5e7ed085 532 ty::Adt(def, _) => def.did().as_local().map(|def_id| {
3dfed10e
XL
533 self.tcx
534 .hir()
535 .get(self.tcx.hir().local_def_id_to_hir_id(def_id))
3c0e092e
XL
536 }),
537 _ => None,
538 };
539 if let Some(hir::Node::Item(hir::Item { kind, .. })) = node {
540 if let Some(g) = kind.generics() {
923072b8
FG
541 let key = (
542 g.tail_span_for_predicate_suggestion(),
543 g.add_where_or_trailing_comma(),
544 );
3c0e092e
XL
545 type_params
546 .entry(key)
547 .or_insert_with(FxHashSet::default)
548 .insert(obligation.to_owned());
74b04a01
XL
549 }
550 }
551 }
552 };
553 let mut bound_span_label = |self_ty: Ty<'_>, obligation: &str, quiet: &str| {
554 let msg = format!(
555 "doesn't satisfy `{}`",
556 if obligation.len() > 50 { quiet } else { obligation }
557 );
1b1a35ee 558 match &self_ty.kind() {
74b04a01 559 // Point at the type that couldn't satisfy the bound.
5e7ed085 560 ty::Adt(def, _) => bound_spans.push((def_span(def.did()), msg)),
74b04a01
XL
561 // Point at the trait object that couldn't satisfy the bound.
562 ty::Dynamic(preds, _) => {
fc512014
XL
563 for pred in preds.iter() {
564 match pred.skip_binder() {
74b04a01
XL
565 ty::ExistentialPredicate::Trait(tr) => {
566 bound_spans.push((def_span(tr.def_id), msg.clone()))
567 }
568 ty::ExistentialPredicate::Projection(_)
569 | ty::ExistentialPredicate::AutoTrait(_) => {}
570 }
571 }
572 }
573 // Point at the closure that couldn't satisfy the bound.
574 ty::Closure(def_id, _) => bound_spans
575 .push((def_span(*def_id), format!("doesn't satisfy `{}`", quiet))),
576 _ => {}
577 }
578 };
f9f354fc 579 let mut format_pred = |pred: ty::Predicate<'tcx>| {
5869c6ff 580 let bound_predicate = pred.kind();
29967ef6 581 match bound_predicate.skip_binder() {
5869c6ff 582 ty::PredicateKind::Projection(pred) => {
29967ef6 583 let pred = bound_predicate.rebind(pred);
74b04a01 584 // `<Foo as Iterator>::Item = String`.
6a06907d
XL
585 let projection_ty = pred.skip_binder().projection_ty;
586
587 let substs_with_infer_self = tcx.mk_substs(
c295e0f8 588 iter::once(tcx.mk_ty_var(ty::TyVid::from_u32(0)).into())
6a06907d 589 .chain(projection_ty.substs.iter().skip(1)),
74b04a01 590 );
6a06907d
XL
591
592 let quiet_projection_ty = ty::ProjectionTy {
593 substs: substs_with_infer_self,
594 item_def_id: projection_ty.item_def_id,
595 };
596
5099ac24 597 let term = pred.skip_binder().term;
6a06907d 598
5099ac24
FG
599 let obligation = format!("{} = {}", projection_ty, term);
600 let quiet = format!("{} = {}", quiet_projection_ty, term);
6a06907d
XL
601
602 bound_span_label(projection_ty.self_ty(), &obligation, &quiet);
603 Some((obligation, projection_ty.self_ty()))
74b04a01 604 }
94222f64 605 ty::PredicateKind::Trait(poly_trait_ref) => {
29967ef6 606 let p = poly_trait_ref.trait_ref;
74b04a01
XL
607 let self_ty = p.self_ty();
608 let path = p.print_only_trait_path();
609 let obligation = format!("{}: {}", self_ty, path);
610 let quiet = format!("_: {}", path);
611 bound_span_label(self_ty, &obligation, &quiet);
612 Some((obligation, self_ty))
613 }
614 _ => None,
615 }
616 };
3c0e092e
XL
617
618 // Find all the requirements that come from a local `impl` block.
619 let mut skip_list: FxHashSet<_> = Default::default();
620 let mut spanned_predicates: FxHashMap<MultiSpan, _> = Default::default();
5e7ed085 621 for (data, p, parent_p, impl_def_id, cause_span) in unsatisfied_predicates
3c0e092e
XL
622 .iter()
623 .filter_map(|(p, parent, c)| c.as_ref().map(|c| (p, parent, c)))
a2a8927a 624 .filter_map(|(p, parent, c)| match c.code() {
3c0e092e 625 ObligationCauseCode::ImplDerivedObligation(ref data) => {
5e7ed085 626 Some((&data.derived, p, parent, data.impl_def_id, data.span))
3c0e092e
XL
627 }
628 _ => None,
629 })
630 {
5099ac24 631 let parent_trait_ref = data.parent_trait_pred;
5099ac24 632 let path = parent_trait_ref.print_modifiers_and_trait_path();
3c0e092e 633 let tr_self_ty = parent_trait_ref.skip_binder().self_ty();
5e7ed085
FG
634 let unsatisfied_msg = "unsatisfied trait bound introduced here".to_string();
635 let derive_msg =
636 "unsatisfied trait bound introduced in this `derive` macro";
637 match self.tcx.hir().get_if_local(impl_def_id) {
638 // Unmet obligation comes from a `derive` macro, point at it once to
639 // avoid multiple span labels pointing at the same place.
640 Some(Node::Item(hir::Item {
641 kind: hir::ItemKind::Trait(..),
642 ident,
643 ..
644 })) if matches!(
645 ident.span.ctxt().outer_expn_data().kind,
646 ExpnKind::Macro(MacroKind::Derive, _)
647 ) =>
648 {
649 let span = ident.span.ctxt().outer_expn_data().call_site;
650 let mut spans: MultiSpan = span.into();
651 spans.push_span_label(span, derive_msg.to_string());
652 let entry = spanned_predicates.entry(spans);
653 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
654 }
655
656 Some(Node::Item(hir::Item {
657 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
658 ..
659 })) if matches!(
660 self_ty.span.ctxt().outer_expn_data().kind,
661 ExpnKind::Macro(MacroKind::Derive, _)
662 ) || matches!(
663 of_trait.as_ref().map(|t| t
664 .path
665 .span
666 .ctxt()
667 .outer_expn_data()
668 .kind),
669 Some(ExpnKind::Macro(MacroKind::Derive, _))
670 ) =>
671 {
672 let span = self_ty.span.ctxt().outer_expn_data().call_site;
673 let mut spans: MultiSpan = span.into();
674 spans.push_span_label(span, derive_msg.to_string());
923072b8 675 let entry = spanned_predicates.entry(spans);
5e7ed085
FG
676 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
677 }
678
679 // Unmet obligation coming from a `trait`.
680 Some(Node::Item(hir::Item {
681 kind: hir::ItemKind::Trait(..),
682 ident,
683 span: item_span,
684 ..
685 })) if !matches!(
686 ident.span.ctxt().outer_expn_data().kind,
687 ExpnKind::Macro(MacroKind::Derive, _)
688 ) =>
689 {
690 if let Some(pred) = parent_p {
691 // Done to add the "doesn't satisfy" `span_label`.
692 let _ = format_pred(*pred);
3c0e092e 693 }
5e7ed085
FG
694 skip_list.insert(p);
695 let mut spans = if cause_span != *item_span {
696 let mut spans: MultiSpan = cause_span.into();
697 spans.push_span_label(cause_span, unsatisfied_msg);
698 spans
699 } else {
700 ident.span.into()
701 };
702 spans.push_span_label(ident.span, "in this trait".to_string());
923072b8 703 let entry = spanned_predicates.entry(spans);
5e7ed085
FG
704 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
705 }
706
707 // Unmet obligation coming from an `impl`.
708 Some(Node::Item(hir::Item {
709 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
710 span: item_span,
711 ..
712 })) if !matches!(
713 self_ty.span.ctxt().outer_expn_data().kind,
714 ExpnKind::Macro(MacroKind::Derive, _)
715 ) && !matches!(
716 of_trait.as_ref().map(|t| t
717 .path
718 .span
719 .ctxt()
720 .outer_expn_data()
721 .kind),
722 Some(ExpnKind::Macro(MacroKind::Derive, _))
723 ) =>
724 {
725 if let Some(pred) = parent_p {
726 // Done to add the "doesn't satisfy" `span_label`.
727 let _ = format_pred(*pred);
728 }
729 skip_list.insert(p);
730 let mut spans = if cause_span != *item_span {
731 let mut spans: MultiSpan = cause_span.into();
732 spans.push_span_label(cause_span, unsatisfied_msg);
733 spans
734 } else {
3c0e092e
XL
735 let mut spans = Vec::with_capacity(2);
736 if let Some(trait_ref) = of_trait {
737 spans.push(trait_ref.path.span);
738 }
739 spans.push(self_ty.span);
5e7ed085
FG
740 spans.into()
741 };
742 if let Some(trait_ref) = of_trait {
743 spans.push_span_label(trait_ref.path.span, String::new());
3c0e092e 744 }
5e7ed085
FG
745 spans.push_span_label(self_ty.span, String::new());
746
923072b8 747 let entry = spanned_predicates.entry(spans);
5e7ed085 748 entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p);
3c0e092e 749 }
5e7ed085 750 _ => {}
3c0e092e
XL
751 }
752 }
5e7ed085
FG
753 let mut spanned_predicates: Vec<_> = spanned_predicates.into_iter().collect();
754 spanned_predicates.sort_by_key(|(span, (_, _, _))| span.primary_span());
755 for (span, (_path, _self_ty, preds)) in spanned_predicates {
756 let mut preds: Vec<_> = preds
757 .into_iter()
758 .filter_map(|pred| format_pred(*pred))
759 .map(|(p, _)| format!("`{}`", p))
760 .collect();
761 preds.sort();
762 preds.dedup();
763 let msg = if let [pred] = &preds[..] {
764 format!("trait bound {} was not satisfied", pred)
765 } else {
766 format!(
767 "the following trait bounds were not satisfied:\n{}",
768 preds.join("\n"),
769 )
770 };
771 err.span_note(span, &msg);
772 unsatisfied_bounds = true;
3c0e092e
XL
773 }
774
775 // The requirements that didn't have an `impl` span to show.
dfeec247
XL
776 let mut bound_list = unsatisfied_predicates
777 .iter()
3c0e092e
XL
778 .filter_map(|(pred, parent_pred, _cause)| {
779 format_pred(*pred).map(|(p, self_ty)| {
5099ac24 780 collect_type_param_suggestions(self_ty, *pred, &p);
5e7ed085
FG
781 (
782 match parent_pred {
3c0e092e 783 None => format!("`{}`", &p),
5e7ed085
FG
784 Some(parent_pred) => match format_pred(*parent_pred) {
785 None => format!("`{}`", &p),
786 Some((parent_p, _)) => {
787 collect_type_param_suggestions(
788 self_ty,
789 *parent_pred,
790 &p,
791 );
792 format!(
793 "`{}`\nwhich is required by `{}`",
794 p, parent_p
795 )
796 }
797 },
3c0e092e 798 },
5e7ed085
FG
799 *pred,
800 )
74b04a01
XL
801 })
802 })
5e7ed085
FG
803 .filter(|(_, pred)| !skip_list.contains(&pred))
804 .map(|(t, _)| t)
74b04a01
XL
805 .enumerate()
806 .collect::<Vec<(usize, String)>>();
3c0e092e 807
923072b8 808 for ((span, add_where_or_comma), obligations) in type_params.into_iter() {
74b04a01 809 restrict_type_params = true;
3dfed10e
XL
810 // #74886: Sort here so that the output is always the same.
811 let mut obligations = obligations.into_iter().collect::<Vec<_>>();
812 obligations.sort();
74b04a01
XL
813 err.span_suggestion_verbose(
814 span,
815 &format!(
816 "consider restricting the type parameter{s} to satisfy the \
817 trait bound{s}",
818 s = pluralize!(obligations.len())
819 ),
923072b8 820 format!("{} {}", add_where_or_comma, obligations.join(", ")),
74b04a01
XL
821 Applicability::MaybeIncorrect,
822 );
823 }
824
c295e0f8 825 bound_list.sort_by(|(_, a), (_, b)| a.cmp(b)); // Sort alphabetically.
74b04a01
XL
826 bound_list.dedup_by(|(_, a), (_, b)| a == b); // #35677
827 bound_list.sort_by_key(|(pos, _)| *pos); // Keep the original predicate order.
5e7ed085 828
3c0e092e 829 if !bound_list.is_empty() || !skip_list.is_empty() {
74b04a01
XL
830 let bound_list = bound_list
831 .into_iter()
832 .map(|(_, path)| path)
833 .collect::<Vec<_>>()
834 .join("\n");
6a06907d 835 let actual_prefix = actual.prefix_string(self.tcx);
5e7ed085
FG
836 info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
837 let (primary_message, label) = if unimplemented_traits.len() == 1
838 && unimplemented_traits_only
839 {
840 unimplemented_traits
841 .into_iter()
842 .next()
843 .map(|(_, (trait_ref, obligation))| {
844 if trait_ref.self_ty().references_error()
845 || actual.references_error()
846 {
847 // Avoid crashing.
848 return (None, None);
849 }
850 let OnUnimplementedNote { message, label, .. } =
851 self.infcx.on_unimplemented_note(trait_ref, &obligation);
852 (message, label)
853 })
854 .unwrap_or((None, None))
855 } else {
856 (None, None)
857 };
858 let primary_message = primary_message.unwrap_or_else(|| format!(
5869c6ff
XL
859 "the {item_kind} `{item_name}` exists for {actual_prefix} `{ty_str}`, but its trait bounds were not satisfied"
860 ));
5e7ed085
FG
861 err.set_primary_message(&primary_message);
862 if let Some(label) = label {
863 custom_span_label = true;
864 err.span_label(span, label);
865 }
3c0e092e
XL
866 if !bound_list.is_empty() {
867 err.note(&format!(
868 "the following trait bounds were not satisfied:\n{bound_list}"
869 ));
870 }
c295e0f8
XL
871 self.suggest_derive(&mut err, &unsatisfied_predicates);
872
cdc7bbd5 873 unsatisfied_bounds = true;
74b04a01 874 }
a7813a04 875 }
62682a34 876
04454e1e 877 let label_span_not_found = |err: &mut DiagnosticBuilder<'_, _>| {
5e7ed085
FG
878 if unsatisfied_predicates.is_empty() {
879 err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
880 let is_string_or_ref_str = match actual.kind() {
881 ty::Ref(_, ty, _) => {
882 ty.is_str()
883 || matches!(
884 ty.kind(),
885 ty::Adt(adt, _) if self.tcx.is_diagnostic_item(sym::String, adt.did())
886 )
887 }
888 ty::Adt(adt, _) => self.tcx.is_diagnostic_item(sym::String, adt.did()),
889 _ => false,
890 };
891 if is_string_or_ref_str && item_name.name == sym::iter {
892 err.span_suggestion_verbose(
893 item_name.span,
894 "because of the in-memory representation of `&str`, to obtain \
895 an `Iterator` over each of its codepoint use method `chars`",
923072b8 896 "chars",
5e7ed085
FG
897 Applicability::MachineApplicable,
898 );
899 }
900 if let ty::Adt(adt, _) = rcvr_ty.kind() {
901 let mut inherent_impls_candidate = self
902 .tcx
903 .inherent_impls(adt.did())
904 .iter()
905 .copied()
906 .filter(|def_id| {
907 if let Some(assoc) = self.associated_value(*def_id, item_name) {
908 // Check for both mode is the same so we avoid suggesting
909 // incorrect associated item.
910 match (mode, assoc.fn_has_self_parameter, source) {
911 (Mode::MethodCall, true, SelfSource::MethodCall(_)) => {
912 // We check that the suggest type is actually
913 // different from the received one
914 // So we avoid suggestion method with Box<Self>
915 // for instance
916 self.tcx.at(span).type_of(*def_id) != actual
917 && self.tcx.at(span).type_of(*def_id) != rcvr_ty
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| {
937 format!("- `{}`", self.tcx.at(span).type_of(*impl_item))
938 })
939 .collect::<Vec<_>>()
940 .join("\n");
941 let additional_types = if inherent_impls_candidate.len() > limit {
942 format!(
943 "\nand {} more types",
944 inherent_impls_candidate.len() - limit
945 )
946 } else {
947 "".to_string()
948 };
949 err.note(&format!(
950 "the {item_kind} was found for\n{}{}",
951 type_candidates, additional_types
952 ));
953 }
954 }
955 } else {
956 err.span_label(span, format!("{item_kind} cannot be called on `{ty_str}` due to unsatisfied trait bounds"));
957 }
958 };
959
960 // If the method name is the name of a field with a function or closure type,
961 // give a helping note that it has to be called as `(x.f)(...)`.
962 if let SelfSource::MethodCall(expr) = source {
04454e1e
FG
963 if !self.suggest_field_call(span, rcvr_ty, expr, item_name, &mut err)
964 && lev_candidate.is_none()
965 && !custom_span_label
966 {
967 label_span_not_found(&mut err);
968 }
969 } else if !custom_span_label {
970 label_span_not_found(&mut err);
971 }
5e7ed085 972
923072b8 973 self.check_for_field_method(&mut err, source, span, actual, item_name);
5e7ed085 974
923072b8 975 self.check_for_unwrap_self(&mut err, source, span, actual, item_name);
5e7ed085
FG
976
977 bound_spans.sort();
978 bound_spans.dedup();
979 for (span, msg) in bound_spans.into_iter() {
980 err.span_label(span, &msg);
981 }
982
74b04a01 983 if actual.is_numeric() && actual.is_fresh() || restrict_type_params {
2c00a5a8 984 } else {
dfeec247
XL
985 self.suggest_traits_to_import(
986 &mut err,
987 span,
988 rcvr_ty,
989 item_name,
990 source,
991 out_of_scope_traits,
74b04a01 992 &unsatisfied_predicates,
cdc7bbd5 993 unsatisfied_bounds,
dfeec247 994 );
2c00a5a8 995 }
ea8adc8c 996
5869c6ff
XL
997 // Don't emit a suggestion if we found an actual method
998 // that had unsatisfied trait bounds
999 if unsatisfied_predicates.is_empty() && actual.is_enum() {
48663c56
XL
1000 let adt_def = actual.ty_adt_def().expect("enum is not an ADT");
1001 if let Some(suggestion) = lev_distance::find_best_match_for_name(
5e7ed085 1002 &adt_def.variants().iter().map(|s| s.name).collect::<Vec<_>>(),
3dfed10e 1003 item_name.name,
48663c56
XL
1004 None,
1005 ) {
1006 err.span_suggestion(
1007 span,
1008 "there is a variant with a similar name",
923072b8 1009 suggestion,
48663c56
XL
1010 Applicability::MaybeIncorrect,
1011 );
1012 }
1013 }
1014
3dfed10e 1015 if item_name.name == sym::as_str && actual.peel_refs().is_str() {
a2a8927a
XL
1016 let msg = "remove this method call";
1017 let mut fallback_span = true;
e74abb32 1018 if let SelfSource::MethodCall(expr) = source {
dfeec247
XL
1019 let call_expr =
1020 self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
e74abb32 1021 if let Some(span) = call_expr.span.trim_start(expr.span) {
923072b8 1022 err.span_suggestion(span, msg, "", Applicability::MachineApplicable);
e74abb32
XL
1023 fallback_span = false;
1024 }
1025 }
1026 if fallback_span {
1027 err.span_label(span, msg);
1028 }
1029 } else if let Some(lev_candidate) = lev_candidate {
5869c6ff
XL
1030 // Don't emit a suggestion if we found an actual method
1031 // that had unsatisfied trait bounds
1032 if unsatisfied_predicates.is_empty() {
1033 let def_kind = lev_candidate.kind.as_def_kind();
1034 err.span_suggestion(
1035 span,
1036 &format!(
1037 "there is {} {} with a similar name",
1038 def_kind.article(),
1039 def_kind.descr(lev_candidate.def_id),
1040 ),
923072b8 1041 lev_candidate.name,
5869c6ff
XL
1042 Applicability::MaybeIncorrect,
1043 );
1044 }
ea8adc8c 1045 }
48663c56 1046
e1599b0c 1047 return Some(err);
a7813a04 1048 }
85aaf69f 1049
a7813a04 1050 MethodError::Ambiguity(sources) => {
dfeec247
XL
1051 let mut err = struct_span_err!(
1052 self.sess(),
ba9703b0 1053 item_name.span,
dfeec247
XL
1054 E0034,
1055 "multiple applicable items in scope"
1056 );
ba9703b0 1057 err.span_label(item_name.span, format!("multiple `{}` found", item_name));
85aaf69f 1058
dfeec247 1059 report_candidates(span, &mut err, sources, sugg_span);
a7813a04
XL
1060 err.emit();
1061 }
85aaf69f 1062
416331ca 1063 MethodError::PrivateMatch(kind, def_id, out_of_scope_traits) => {
ba9703b0 1064 let kind = kind.descr(def_id);
dfeec247
XL
1065 let mut err = struct_span_err!(
1066 self.tcx.sess,
ba9703b0 1067 item_name.span,
dfeec247
XL
1068 E0624,
1069 "{} `{}` is private",
ba9703b0 1070 kind,
dfeec247
XL
1071 item_name
1072 );
ba9703b0 1073 err.span_label(item_name.span, &format!("private {}", kind));
136023e0
XL
1074 let sp = self
1075 .tcx
1076 .hir()
1077 .span_if_local(def_id)
1078 .unwrap_or_else(|| self.tcx.def_span(def_id));
1079 err.span_label(sp, &format!("private {} defined here", kind));
3b2f2976
XL
1080 self.suggest_valid_traits(&mut err, out_of_scope_traits);
1081 err.emit();
a7813a04 1082 }
3b2f2976 1083
74b04a01 1084 MethodError::IllegalSizedBound(candidates, needs_mut, bound_span) => {
3b2f2976
XL
1085 let msg = format!("the `{}` method cannot be invoked on a trait object", item_name);
1086 let mut err = self.sess().struct_span_err(span, &msg);
74b04a01 1087 err.span_label(bound_span, "this has a `Sized` requirement");
3b2f2976 1088 if !candidates.is_empty() {
e74abb32
XL
1089 let help = format!(
1090 "{an}other candidate{s} {were} found in the following trait{s}, perhaps \
1091 add a `use` for {one_of_them}:",
dfeec247 1092 an = if candidates.len() == 1 { "an" } else { "" },
60c5eb7d 1093 s = pluralize!(candidates.len()),
e74abb32 1094 were = if candidates.len() == 1 { "was" } else { "were" },
dfeec247 1095 one_of_them = if candidates.len() == 1 { "it" } else { "one_of_them" },
e74abb32 1096 );
3b2f2976
XL
1097 self.suggest_use_candidates(&mut err, help, candidates);
1098 }
1b1a35ee 1099 if let ty::Ref(region, t_type, mutability) = rcvr_ty.kind() {
e74abb32 1100 if needs_mut {
dfeec247 1101 let trait_type = self.tcx.mk_ref(
5099ac24
FG
1102 *region,
1103 ty::TypeAndMut { ty: *t_type, mutbl: mutability.invert() },
dfeec247 1104 );
e74abb32
XL
1105 err.note(&format!("you need `{}` instead of `{}`", trait_type, rcvr_ty));
1106 }
1107 }
3b2f2976
XL
1108 err.emit();
1109 }
ea8adc8c 1110
dfeec247 1111 MethodError::BadReturnType => bug!("no return type expectations but got BadReturnType"),
3b2f2976 1112 }
e1599b0c 1113 None
3b2f2976
XL
1114 }
1115
04454e1e
FG
1116 fn suggest_field_call(
1117 &self,
1118 span: Span,
1119 rcvr_ty: Ty<'tcx>,
1120 expr: &hir::Expr<'_>,
1121 item_name: Ident,
1122 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1123 ) -> bool {
1124 let tcx = self.tcx;
1125 let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
1126 ty::Adt(def, substs) if !def.is_enum() => {
1127 let variant = &def.non_enum_variant();
1128 tcx.find_field_index(item_name, variant).map(|index| {
1129 let field = &variant.fields[index];
1130 let field_ty = field.ty(tcx, substs);
1131 (field, field_ty)
1132 })
1133 }
1134 _ => None,
1135 });
1136 if let Some((field, field_ty)) = field_receiver {
1137 let scope = tcx.parent_module(self.body_id).to_def_id();
1138 let is_accessible = field.vis.is_accessible_from(scope, tcx);
1139
1140 if is_accessible {
1141 if self.is_fn_ty(field_ty, span) {
1142 let expr_span = expr.span.to(item_name.span);
1143 err.multipart_suggestion(
1144 &format!(
1145 "to call the function stored in `{}`, \
1146 surround the field access with parentheses",
1147 item_name,
1148 ),
1149 vec![
1150 (expr_span.shrink_to_lo(), '('.to_string()),
1151 (expr_span.shrink_to_hi(), ')'.to_string()),
1152 ],
1153 Applicability::MachineApplicable,
1154 );
1155 } else {
1156 let call_expr = tcx.hir().expect_expr(tcx.hir().get_parent_node(expr.hir_id));
1157
1158 if let Some(span) = call_expr.span.trim_start(item_name.span) {
1159 err.span_suggestion(
1160 span,
1161 "remove the arguments",
923072b8 1162 "",
04454e1e
FG
1163 Applicability::MaybeIncorrect,
1164 );
1165 }
1166 }
1167 }
1168
1169 let field_kind = if is_accessible { "field" } else { "private field" };
1170 err.span_label(item_name.span, format!("{}, not a method", field_kind));
1171 return true;
1172 }
1173 false
1174 }
1175
1176 fn suggest_constraining_numerical_ty(
1177 &self,
1178 tcx: TyCtxt<'tcx>,
1179 actual: Ty<'tcx>,
1180 source: SelfSource<'_>,
1181 span: Span,
1182 item_kind: &str,
1183 item_name: Ident,
1184 ty_str: &str,
1185 ) -> bool {
1186 let found_candidate = all_traits(self.tcx)
1187 .into_iter()
1188 .any(|info| self.associated_value(info.def_id, item_name).is_some());
1189 let found_assoc = |ty: Ty<'tcx>| {
923072b8 1190 simplify_type(tcx, ty, TreatParams::AsInfer)
04454e1e
FG
1191 .and_then(|simp| {
1192 tcx.incoherent_impls(simp)
1193 .iter()
1194 .find_map(|&id| self.associated_value(id, item_name))
1195 })
1196 .is_some()
1197 };
1198 let found_candidate = found_candidate
1199 || found_assoc(tcx.types.i8)
1200 || found_assoc(tcx.types.i16)
1201 || found_assoc(tcx.types.i32)
1202 || found_assoc(tcx.types.i64)
1203 || found_assoc(tcx.types.i128)
1204 || found_assoc(tcx.types.u8)
1205 || found_assoc(tcx.types.u16)
1206 || found_assoc(tcx.types.u32)
1207 || found_assoc(tcx.types.u64)
1208 || found_assoc(tcx.types.u128)
1209 || found_assoc(tcx.types.f32)
1210 || found_assoc(tcx.types.f32);
1211 if found_candidate
1212 && actual.is_numeric()
1213 && !actual.has_concrete_skeleton()
1214 && let SelfSource::MethodCall(expr) = source
1215 {
1216 let mut err = struct_span_err!(
1217 tcx.sess,
1218 span,
1219 E0689,
1220 "can't call {} `{}` on ambiguous numeric type `{}`",
1221 item_kind,
1222 item_name,
1223 ty_str
1224 );
1225 let concrete_type = if actual.is_integral() { "i32" } else { "f32" };
1226 match expr.kind {
1227 ExprKind::Lit(ref lit) => {
1228 // numeric literal
1229 let snippet = tcx
1230 .sess
1231 .source_map()
1232 .span_to_snippet(lit.span)
1233 .unwrap_or_else(|_| "<numeric literal>".to_owned());
1234
1235 // If this is a floating point literal that ends with '.',
1236 // get rid of it to stop this from becoming a member access.
1237 let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);
1238
1239 err.span_suggestion(
1240 lit.span,
1241 &format!(
1242 "you must specify a concrete type for this numeric value, \
1243 like `{}`",
1244 concrete_type
1245 ),
1246 format!("{snippet}_{concrete_type}"),
1247 Applicability::MaybeIncorrect,
1248 );
1249 }
1250 ExprKind::Path(QPath::Resolved(_, path)) => {
1251 // local binding
1252 if let hir::def::Res::Local(hir_id) = path.res {
1253 let span = tcx.hir().span(hir_id);
1254 let snippet = tcx.sess.source_map().span_to_snippet(span);
1255 let filename = tcx.sess.source_map().span_to_filename(span);
1256
1257 let parent_node =
1258 self.tcx.hir().get(self.tcx.hir().get_parent_node(hir_id));
1259 let msg = format!(
1260 "you must specify a type for this binding, like `{}`",
1261 concrete_type,
1262 );
1263
1264 match (filename, parent_node, snippet) {
1265 (
1266 FileName::Real(_),
1267 Node::Local(hir::Local {
1268 source: hir::LocalSource::Normal,
1269 ty,
1270 ..
1271 }),
1272 Ok(ref snippet),
1273 ) => {
1274 err.span_suggestion(
1275 // account for `let x: _ = 42;`
1276 // ^^^^
1277 span.to(ty.as_ref().map(|ty| ty.span).unwrap_or(span)),
1278 &msg,
1279 format!("{}: {}", snippet, concrete_type),
1280 Applicability::MaybeIncorrect,
1281 );
1282 }
1283 _ => {
1284 err.span_label(span, msg);
1285 }
1286 }
1287 }
1288 }
1289 _ => {}
1290 }
1291 err.emit();
1292 return true;
1293 }
1294 false
1295 }
1296
923072b8
FG
1297 fn check_for_field_method(
1298 &self,
1299 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1300 source: SelfSource<'tcx>,
1301 span: Span,
1302 actual: Ty<'tcx>,
1303 item_name: Ident,
1304 ) {
1305 if let SelfSource::MethodCall(expr) = source
1306 && let Some((fields, substs)) = self.get_field_candidates(span, actual)
1307 {
1308 let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().get_parent_node(expr.hir_id));
1309 for candidate_field in fields.iter() {
1310 if let Some(field_path) = self.check_for_nested_field_satisfying(
1311 span,
1312 &|_, field_ty| {
1313 self.lookup_probe(
1314 span,
1315 item_name,
1316 field_ty,
1317 call_expr,
1318 ProbeScope::AllTraits,
1319 )
1320 .is_ok()
1321 },
1322 candidate_field,
1323 substs,
1324 vec![],
1325 self.tcx.parent_module(expr.hir_id).to_def_id(),
1326 ) {
1327 let field_path_str = field_path
1328 .iter()
1329 .map(|id| id.name.to_ident_string())
1330 .collect::<Vec<String>>()
1331 .join(".");
1332 debug!("field_path_str: {:?}", field_path_str);
1333
1334 err.span_suggestion_verbose(
1335 item_name.span.shrink_to_lo(),
1336 "one of the expressions' fields has a method of the same name",
1337 format!("{field_path_str}."),
1338 Applicability::MaybeIncorrect,
1339 );
1340 }
1341 }
1342 }
1343 }
1344
1345 fn check_for_unwrap_self(
1346 &self,
1347 err: &mut DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1348 source: SelfSource<'tcx>,
1349 span: Span,
1350 actual: Ty<'tcx>,
1351 item_name: Ident,
1352 ) {
1353 let tcx = self.tcx;
1354 let SelfSource::MethodCall(expr) = source else { return; };
1355 let call_expr = tcx.hir().expect_expr(tcx.hir().get_parent_node(expr.hir_id));
1356
1357 let ty::Adt(kind, substs) = actual.kind() else { return; };
1358 if !kind.is_enum() {
1359 return;
1360 }
1361
1362 let matching_variants: Vec<_> = kind
1363 .variants()
1364 .iter()
1365 .flat_map(|variant| {
1366 let [field] = &variant.fields[..] else { return None; };
1367 let field_ty = field.ty(tcx, substs);
1368
1369 // Skip `_`, since that'll just lead to ambiguity.
1370 if self.resolve_vars_if_possible(field_ty).is_ty_var() {
1371 return None;
1372 }
1373
1374 self.lookup_probe(span, item_name, field_ty, call_expr, ProbeScope::AllTraits)
1375 .ok()
1376 .map(|pick| (variant, field, pick))
1377 })
1378 .collect();
1379
1380 let ret_ty_matches = |diagnostic_item| {
1381 if let Some(ret_ty) = self
1382 .ret_coercion
1383 .as_ref()
1384 .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty()))
1385 && let ty::Adt(kind, _) = ret_ty.kind()
1386 && tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did())
1387 {
1388 true
1389 } else {
1390 false
1391 }
1392 };
1393
1394 match &matching_variants[..] {
1395 [(_, field, pick)] => {
1396 let self_ty = field.ty(tcx, substs);
1397 err.span_note(
1398 tcx.def_span(pick.item.def_id),
1399 &format!("the method `{item_name}` exists on the type `{self_ty}`"),
1400 );
1401 let (article, kind, variant, question) =
1402 if Some(kind.did()) == tcx.get_diagnostic_item(sym::Result) {
1403 ("a", "Result", "Err", ret_ty_matches(sym::Result))
1404 } else if Some(kind.did()) == tcx.get_diagnostic_item(sym::Option) {
1405 ("an", "Option", "None", ret_ty_matches(sym::Option))
1406 } else {
1407 return;
1408 };
1409 if question {
1410 err.span_suggestion_verbose(
1411 expr.span.shrink_to_hi(),
1412 format!(
1413 "use the `?` operator to extract the `{self_ty}` value, propagating \
1414 {article} `{kind}::{variant}` value to the caller"
1415 ),
1416 "?",
1417 Applicability::MachineApplicable,
1418 );
1419 } else {
1420 err.span_suggestion_verbose(
1421 expr.span.shrink_to_hi(),
1422 format!(
1423 "consider using `{kind}::expect` to unwrap the `{self_ty}` value, \
1424 panicking if the value is {article} `{kind}::{variant}`"
1425 ),
1426 ".expect(\"REASON\")",
1427 Applicability::HasPlaceholders,
1428 );
1429 }
1430 }
1431 // FIXME(compiler-errors): Support suggestions for other matching enum variants
1432 _ => {}
1433 }
1434 }
1435
1436 pub(crate) fn note_unmet_impls_on_type(
c295e0f8 1437 &self,
5e7ed085 1438 err: &mut Diagnostic,
c295e0f8
XL
1439 errors: Vec<FulfillmentError<'tcx>>,
1440 ) {
1441 let all_local_types_needing_impls =
1442 errors.iter().all(|e| match e.obligation.predicate.kind().skip_binder() {
1443 ty::PredicateKind::Trait(pred) => match pred.self_ty().kind() {
5e7ed085 1444 ty::Adt(def, _) => def.did().is_local(),
c295e0f8
XL
1445 _ => false,
1446 },
1447 _ => false,
1448 });
1449 let mut preds: Vec<_> = errors
1450 .iter()
1451 .filter_map(|e| match e.obligation.predicate.kind().skip_binder() {
1452 ty::PredicateKind::Trait(pred) => Some(pred),
1453 _ => None,
1454 })
1455 .collect();
1456 preds.sort_by_key(|pred| (pred.def_id(), pred.self_ty()));
1457 let def_ids = preds
1458 .iter()
1459 .filter_map(|pred| match pred.self_ty().kind() {
5e7ed085 1460 ty::Adt(def, _) => Some(def.did()),
c295e0f8
XL
1461 _ => None,
1462 })
1463 .collect::<FxHashSet<_>>();
1464 let sm = self.tcx.sess.source_map();
1465 let mut spans: MultiSpan = def_ids
1466 .iter()
1467 .filter_map(|def_id| {
1468 let span = self.tcx.def_span(*def_id);
1469 if span.is_dummy() { None } else { Some(sm.guess_head_span(span)) }
1470 })
1471 .collect::<Vec<_>>()
1472 .into();
1473
1474 for pred in &preds {
1475 match pred.self_ty().kind() {
1476 ty::Adt(def, _) => {
1477 spans.push_span_label(
5e7ed085 1478 sm.guess_head_span(self.tcx.def_span(def.did())),
c295e0f8
XL
1479 format!("must implement `{}`", pred.trait_ref.print_only_trait_path()),
1480 );
1481 }
1482 _ => {}
1483 }
1484 }
1485
1486 if all_local_types_needing_impls && spans.primary_span().is_some() {
1487 let msg = if preds.len() == 1 {
1488 format!(
1489 "an implementation of `{}` might be missing for `{}`",
1490 preds[0].trait_ref.print_only_trait_path(),
1491 preds[0].self_ty()
1492 )
1493 } else {
1494 format!(
1495 "the following type{} would have to `impl` {} required trait{} for this \
1496 operation to be valid",
1497 pluralize!(def_ids.len()),
1498 if def_ids.len() == 1 { "its" } else { "their" },
1499 pluralize!(preds.len()),
1500 )
1501 };
1502 err.span_note(spans, &msg);
1503 }
1504
3c0e092e
XL
1505 let preds: Vec<_> = errors
1506 .iter()
1507 .map(|e| (e.obligation.predicate, None, Some(e.obligation.cause.clone())))
1508 .collect();
c295e0f8
XL
1509 self.suggest_derive(err, &preds);
1510 }
1511
1512 fn suggest_derive(
1513 &self,
5e7ed085 1514 err: &mut Diagnostic,
a2a8927a 1515 unsatisfied_predicates: &[(
3c0e092e
XL
1516 ty::Predicate<'tcx>,
1517 Option<ty::Predicate<'tcx>>,
1518 Option<ObligationCause<'tcx>>,
a2a8927a 1519 )],
c295e0f8
XL
1520 ) {
1521 let mut derives = Vec::<(String, Span, String)>::new();
1522 let mut traits = Vec::<Span>::new();
3c0e092e 1523 for (pred, _, _) in unsatisfied_predicates {
5e7ed085 1524 let ty::PredicateKind::Trait(trait_pred) = pred.kind().skip_binder() else { continue };
c295e0f8 1525 let adt = match trait_pred.self_ty().ty_adt_def() {
5e7ed085 1526 Some(adt) if adt.did().is_local() => adt,
c295e0f8
XL
1527 _ => continue,
1528 };
5099ac24
FG
1529 if let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) {
1530 let can_derive = match diagnostic_name {
1531 sym::Default => !adt.is_enum(),
c295e0f8
XL
1532 sym::Eq
1533 | sym::PartialEq
1534 | sym::Ord
1535 | sym::PartialOrd
1536 | sym::Clone
1537 | sym::Copy
1538 | sym::Hash
5099ac24
FG
1539 | sym::Debug => true,
1540 _ => false,
1541 };
1542 if can_derive {
1543 let self_name = trait_pred.self_ty().to_string();
5e7ed085 1544 let self_span = self.tcx.def_span(adt.did());
5099ac24
FG
1545 if let Some(poly_trait_ref) = pred.to_opt_poly_trait_pred() {
1546 for super_trait in supertraits(self.tcx, poly_trait_ref.to_poly_trait_ref())
1547 {
1548 if let Some(parent_diagnostic_name) =
1549 self.tcx.get_diagnostic_name(super_trait.def_id())
1550 {
1551 derives.push((
1552 self_name.clone(),
923072b8 1553 self_span,
5099ac24
FG
1554 parent_diagnostic_name.to_string(),
1555 ));
1556 }
1557 }
1558 }
1559 derives.push((self_name, self_span, diagnostic_name.to_string()));
1560 } else {
1561 traits.push(self.tcx.def_span(trait_pred.def_id()));
1562 }
c295e0f8
XL
1563 } else {
1564 traits.push(self.tcx.def_span(trait_pred.def_id()));
1565 }
1566 }
c295e0f8
XL
1567 traits.sort();
1568 traits.dedup();
1569
a2a8927a
XL
1570 derives.sort();
1571 derives.dedup();
1572
1573 let mut derives_grouped = Vec::<(String, Span, String)>::new();
1574 for (self_name, self_span, trait_name) in derives.into_iter() {
1575 if let Some((last_self_name, _, ref mut last_trait_names)) = derives_grouped.last_mut()
1576 {
1577 if last_self_name == &self_name {
1578 last_trait_names.push_str(format!(", {}", trait_name).as_str());
1579 continue;
1580 }
1581 }
1582 derives_grouped.push((self_name, self_span, trait_name));
1583 }
1584
c295e0f8
XL
1585 let len = traits.len();
1586 if len > 0 {
1587 let span: MultiSpan = traits.into();
1588 err.span_note(
1589 span,
1590 &format!("the following trait{} must be implemented", pluralize!(len),),
1591 );
1592 }
1593
1594 for (self_name, self_span, traits) in &derives_grouped {
1595 err.span_suggestion_verbose(
1596 self_span.shrink_to_lo(),
1597 &format!("consider annotating `{}` with `#[derive({})]`", self_name, traits),
1598 format!("#[derive({})]\n", traits),
1599 Applicability::MaybeIncorrect,
1600 );
1601 }
1602 }
1603
e74abb32
XL
1604 /// Print out the type for use in value namespace.
1605 fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String {
1b1a35ee 1606 match ty.kind() {
5e7ed085 1607 ty::Adt(def, substs) => format!("{}", ty::Instance::new(def.did(), substs)),
e74abb32
XL
1608 _ => self.ty_to_string(ty),
1609 }
1610 }
1611
1b1a35ee
XL
1612 fn suggest_await_before_method(
1613 &self,
5e7ed085 1614 err: &mut Diagnostic,
1b1a35ee
XL
1615 item_name: Ident,
1616 ty: Ty<'tcx>,
1617 call: &hir::Expr<'_>,
1618 span: Span,
1619 ) {
29967ef6 1620 let output_ty = match self.infcx.get_impl_future_output_ty(ty) {
5099ac24 1621 Some(output_ty) => self.resolve_vars_if_possible(output_ty).skip_binder(),
29967ef6
XL
1622 _ => return,
1623 };
1624 let method_exists = self.method_exists(item_name, output_ty, call.hir_id, true);
1625 debug!("suggest_await_before_method: is_method_exist={}", method_exists);
1626 if method_exists {
1627 err.span_suggestion_verbose(
1628 span.shrink_to_lo(),
1629 "consider `await`ing on the `Future` and calling the method on its `Output`",
923072b8 1630 "await.",
29967ef6
XL
1631 Applicability::MaybeIncorrect,
1632 );
1b1a35ee
XL
1633 }
1634 }
1635
04454e1e 1636 fn suggest_use_candidates(&self, err: &mut Diagnostic, msg: String, candidates: Vec<DefId>) {
a2a8927a
XL
1637 let parent_map = self.tcx.visible_parent_map(());
1638
1639 // Separate out candidates that must be imported with a glob, because they are named `_`
1640 // and cannot be referred with their identifier.
1641 let (candidates, globs): (Vec<_>, Vec<_>) = candidates.into_iter().partition(|trait_did| {
1642 if let Some(parent_did) = parent_map.get(trait_did) {
1643 // If the item is re-exported as `_`, we should suggest a glob-import instead.
04454e1e 1644 if *parent_did != self.tcx.parent(*trait_did)
a2a8927a
XL
1645 && self
1646 .tcx
5099ac24 1647 .module_children(*parent_did)
a2a8927a
XL
1648 .iter()
1649 .filter(|child| child.res.opt_def_id() == Some(*trait_did))
1650 .all(|child| child.ident.name == kw::Underscore)
1651 {
1652 return false;
1653 }
1654 }
1655
1656 true
1657 });
1658
74b04a01 1659 let module_did = self.tcx.parent_module(self.body_id);
04454e1e
FG
1660 let (module, _, _) = self.tcx.hir().get_module(module_did);
1661 let span = module.spans.inject_use_span;
ff7c6d11 1662
04454e1e
FG
1663 let path_strings = candidates.iter().map(|trait_did| {
1664 format!("use {};\n", with_crate_prefix!(self.tcx.def_path_str(*trait_did)),)
1665 });
a2a8927a 1666
04454e1e
FG
1667 let glob_path_strings = globs.iter().map(|trait_did| {
1668 let parent_did = parent_map.get(trait_did).unwrap();
1669 format!(
1670 "use {}::*; // trait {}\n",
1671 with_crate_prefix!(self.tcx.def_path_str(*parent_did)),
1672 self.tcx.item_name(*trait_did),
1673 )
1674 });
a2a8927a 1675
04454e1e
FG
1676 err.span_suggestions(
1677 span,
1678 &msg,
1679 path_strings.chain(glob_path_strings),
1680 Applicability::MaybeIncorrect,
1681 );
3b2f2976
XL
1682 }
1683
e74abb32
XL
1684 fn suggest_valid_traits(
1685 &self,
5e7ed085 1686 err: &mut Diagnostic,
e74abb32
XL
1687 valid_out_of_scope_traits: Vec<DefId>,
1688 ) -> bool {
3b2f2976
XL
1689 if !valid_out_of_scope_traits.is_empty() {
1690 let mut candidates = valid_out_of_scope_traits;
1691 candidates.sort();
1692 candidates.dedup();
3c0e092e
XL
1693
1694 // `TryFrom` and `FromIterator` have no methods
1695 let edition_fix = candidates
1696 .iter()
1697 .find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
1698 .copied();
1699
3b2f2976 1700 err.help("items from traits can only be used if the trait is in scope");
e74abb32
XL
1701 let msg = format!(
1702 "the following {traits_are} implemented but not in scope; \
1703 perhaps add a `use` for {one_of_them}:",
dfeec247
XL
1704 traits_are = if candidates.len() == 1 { "trait is" } else { "traits are" },
1705 one_of_them = if candidates.len() == 1 { "it" } else { "one of them" },
e74abb32 1706 );
3b2f2976
XL
1707
1708 self.suggest_use_candidates(err, msg, candidates);
3c0e092e
XL
1709 if let Some(did) = edition_fix {
1710 err.note(&format!(
1711 "'{}' is included in the prelude starting in Edition 2021",
5e7ed085 1712 with_crate_prefix!(self.tcx.def_path_str(did))
3c0e092e
XL
1713 ));
1714 }
1715
3b2f2976
XL
1716 true
1717 } else {
1718 false
54a0048b 1719 }
85aaf69f
SL
1720 }
1721
cdc7bbd5 1722 fn suggest_traits_to_import(
416331ca 1723 &self,
5e7ed085 1724 err: &mut Diagnostic,
416331ca
XL
1725 span: Span,
1726 rcvr_ty: Ty<'tcx>,
f9f354fc 1727 item_name: Ident,
cdc7bbd5 1728 source: SelfSource<'tcx>,
416331ca 1729 valid_out_of_scope_traits: Vec<DefId>,
3c0e092e
XL
1730 unsatisfied_predicates: &[(
1731 ty::Predicate<'tcx>,
1732 Option<ty::Predicate<'tcx>>,
1733 Option<ObligationCause<'tcx>>,
1734 )],
cdc7bbd5 1735 unsatisfied_bounds: bool,
416331ca 1736 ) {
cdc7bbd5
XL
1737 let mut alt_rcvr_sugg = false;
1738 if let (SelfSource::MethodCall(rcvr), false) = (source, unsatisfied_bounds) {
1739 debug!(?span, ?item_name, ?rcvr_ty, ?rcvr);
1740 let skippable = [
1741 self.tcx.lang_items().clone_trait(),
1742 self.tcx.lang_items().deref_trait(),
1743 self.tcx.lang_items().deref_mut_trait(),
1744 self.tcx.lang_items().drop_trait(),
3c0e092e 1745 self.tcx.get_diagnostic_item(sym::AsRef),
cdc7bbd5
XL
1746 ];
1747 // Try alternative arbitrary self types that could fulfill this call.
1748 // FIXME: probe for all types that *could* be arbitrary self-types, not
1749 // just this list.
1750 for (rcvr_ty, post) in &[
1751 (rcvr_ty, ""),
5099ac24
FG
1752 (self.tcx.mk_mut_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&mut "),
1753 (self.tcx.mk_imm_ref(self.tcx.lifetimes.re_erased, rcvr_ty), "&"),
cdc7bbd5 1754 ] {
923072b8 1755 match self.lookup_probe(span, item_name, *rcvr_ty, rcvr, ProbeScope::AllTraits) {
5e7ed085
FG
1756 Ok(pick) => {
1757 // If the method is defined for the receiver we have, it likely wasn't `use`d.
1758 // We point at the method, but we just skip the rest of the check for arbitrary
1759 // self types and rely on the suggestion to `use` the trait from
1760 // `suggest_valid_traits`.
1761 let did = Some(pick.item.container.id());
1762 let skip = skippable.contains(&did);
1763 if pick.autoderefs == 0 && !skip {
1764 err.span_label(
1765 pick.item.ident(self.tcx).span,
1766 &format!("the method is available for `{}` here", rcvr_ty),
1767 );
1768 }
1769 break;
cdc7bbd5 1770 }
5e7ed085
FG
1771 Err(MethodError::Ambiguity(_)) => {
1772 // If the method is defined (but ambiguous) for the receiver we have, it is also
1773 // likely we haven't `use`d it. It may be possible that if we `Box`/`Pin`/etc.
1774 // the receiver, then it might disambiguate this method, but I think these
1775 // suggestions are generally misleading (see #94218).
1776 break;
1777 }
1778 _ => {}
cdc7bbd5 1779 }
5e7ed085 1780
cdc7bbd5 1781 for (rcvr_ty, pre) in &[
5099ac24
FG
1782 (self.tcx.mk_lang_item(*rcvr_ty, LangItem::OwnedBox), "Box::new"),
1783 (self.tcx.mk_lang_item(*rcvr_ty, LangItem::Pin), "Pin::new"),
1784 (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Arc), "Arc::new"),
1785 (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Rc), "Rc::new"),
cdc7bbd5 1786 ] {
923072b8
FG
1787 if let Some(new_rcvr_t) = *rcvr_ty
1788 && let Ok(pick) = self.lookup_probe(
1789 span,
1790 item_name,
1791 new_rcvr_t,
1792 rcvr,
1793 ProbeScope::AllTraits,
1794 )
1795 {
5e7ed085
FG
1796 debug!("try_alt_rcvr: pick candidate {:?}", pick);
1797 let did = Some(pick.item.container.id());
1798 // We don't want to suggest a container type when the missing
1799 // method is `.clone()` or `.deref()` otherwise we'd suggest
1800 // `Arc::new(foo).clone()`, which is far from what the user wants.
1801 // Explicitly ignore the `Pin::as_ref()` method as `Pin` does not
1802 // implement the `AsRef` trait.
1803 let skip = skippable.contains(&did)
1804 || (("Pin::new" == *pre) && (sym::as_ref == item_name.name));
1805 // Make sure the method is defined for the *actual* receiver: we don't
1806 // want to treat `Box<Self>` as a receiver if it only works because of
1807 // an autoderef to `&self`
1808 if pick.autoderefs == 0 && !skip {
1809 err.span_label(
1810 pick.item.ident(self.tcx).span,
1811 &format!("the method is available for `{}` here", new_rcvr_t),
1812 );
1813 err.multipart_suggestion(
1814 "consider wrapping the receiver expression with the \
1815 appropriate type",
1816 vec![
1817 (rcvr.span.shrink_to_lo(), format!("{}({}", pre, post)),
1818 (rcvr.span.shrink_to_hi(), ")".to_string()),
1819 ],
1820 Applicability::MaybeIncorrect,
1821 );
1822 // We don't care about the other suggestions.
1823 alt_rcvr_sugg = true;
cdc7bbd5
XL
1824 }
1825 }
1826 }
1827 }
1828 }
3b2f2976 1829 if self.suggest_valid_traits(err, valid_out_of_scope_traits) {
c30ab7b3 1830 return;
85aaf69f 1831 }
85aaf69f 1832
0731742a 1833 let type_is_local = self.type_derefs_to_local(span, rcvr_ty, source);
a7813a04 1834
74b04a01 1835 let mut arbitrary_rcvr = vec![];
0731742a 1836 // There are no traits implemented, so lets suggest some traits to
a7813a04
XL
1837 // implement, by finding ones that have the item name, and are
1838 // legal to implement.
8bb4bdeb 1839 let mut candidates = all_traits(self.tcx)
83c7162d 1840 .into_iter()
3dfed10e
XL
1841 // Don't issue suggestions for unstable traits since they're
1842 // unlikely to be implementable anyway
1843 .filter(|info| match self.tcx.lookup_stability(info.def_id) {
1844 Some(attr) => attr.level.is_stable(),
1845 None => true,
1846 })
a7813a04 1847 .filter(|info| {
0731742a 1848 // We approximate the coherence rules to only suggest
a7813a04 1849 // traits that are legal to implement by requiring that
0731742a 1850 // either the type or trait is local. Multi-dispatch means
a7813a04
XL
1851 // this isn't perfect (that is, there are cases when
1852 // implementing a trait would be legal but is rejected
1853 // here).
3c0e092e 1854 unsatisfied_predicates.iter().all(|(p, _, _)| {
5869c6ff 1855 match p.kind().skip_binder() {
3dfed10e
XL
1856 // Hide traits if they are present in predicates as they can be fixed without
1857 // having to implement them.
94222f64 1858 ty::PredicateKind::Trait(t) => t.def_id() == info.def_id,
5869c6ff 1859 ty::PredicateKind::Projection(p) => {
3dfed10e
XL
1860 p.projection_ty.item_def_id == info.def_id
1861 }
1862 _ => false,
1863 }
74b04a01 1864 }) && (type_is_local || info.def_id.is_local())
dfeec247 1865 && self
5099ac24 1866 .associated_value(info.def_id, item_name)
2c00a5a8 1867 .filter(|item| {
ba9703b0 1868 if let ty::AssocKind::Fn = item.kind {
f9f354fc
XL
1869 let id = item
1870 .def_id
1871 .as_local()
3dfed10e 1872 .map(|def_id| self.tcx.hir().local_def_id_to_hir_id(def_id));
74b04a01 1873 if let Some(hir::Node::TraitItem(hir::TraitItem {
ba9703b0 1874 kind: hir::TraitItemKind::Fn(fn_sig, method),
74b04a01
XL
1875 ..
1876 })) = id.map(|id| self.tcx.hir().get(id))
1877 {
1878 let self_first_arg = match method {
ba9703b0 1879 hir::TraitFn::Required([ident, ..]) => {
74b04a01
XL
1880 ident.name == kw::SelfLower
1881 }
ba9703b0 1882 hir::TraitFn::Provided(body_id) => {
f9f354fc
XL
1883 self.tcx.hir().body(*body_id).params.first().map_or(
1884 false,
1885 |param| {
1886 matches!(
1887 param.pat.kind,
1888 hir::PatKind::Binding(_, _, ident, _)
1889 if ident.name == kw::SelfLower
1890 )
1891 },
1892 )
74b04a01
XL
1893 }
1894 _ => false,
1895 };
1896
1897 if !fn_sig.decl.implicit_self.has_implicit_self()
1898 && self_first_arg
1899 {
1900 if let Some(ty) = fn_sig.decl.inputs.get(0) {
1901 arbitrary_rcvr.push(ty.span);
1902 }
1903 return false;
1904 }
1905 }
1906 }
2c00a5a8 1907 // We only want to suggest public or local traits (#45781).
3c0e092e 1908 item.vis.is_public() || info.def_id.is_local()
2c00a5a8
XL
1909 })
1910 .is_some()
a7813a04
XL
1911 })
1912 .collect::<Vec<_>>();
74b04a01
XL
1913 for span in &arbitrary_rcvr {
1914 err.span_label(
1915 *span,
1916 "the method might not be found because of this arbitrary self type",
1917 );
1918 }
cdc7bbd5
XL
1919 if alt_rcvr_sugg {
1920 return;
1921 }
a7813a04
XL
1922
1923 if !candidates.is_empty() {
0731742a 1924 // Sort from most relevant to least relevant.
a7813a04
XL
1925 candidates.sort_by(|a, b| a.cmp(b).reverse());
1926 candidates.dedup();
1927
1b1a35ee 1928 let param_type = match rcvr_ty.kind() {
416331ca 1929 ty::Param(param) => Some(param),
1b1a35ee 1930 ty::Ref(_, ty, _) => match ty.kind() {
416331ca
XL
1931 ty::Param(param) => Some(param),
1932 _ => None,
dfeec247 1933 },
416331ca
XL
1934 _ => None,
1935 };
1936 err.help(if param_type.is_some() {
1937 "items from traits can only be used if the type parameter is bounded by the trait"
1938 } else {
1939 "items from traits can only be used if the trait is implemented and in scope"
1940 });
fc512014 1941 let candidates_len = candidates.len();
dfeec247
XL
1942 let message = |action| {
1943 format!(
1944 "the following {traits_define} an item `{name}`, perhaps you need to {action} \
74b04a01 1945 {one_of_them}:",
dfeec247 1946 traits_define =
fc512014 1947 if candidates_len == 1 { "trait defines" } else { "traits define" },
dfeec247 1948 action = action,
fc512014 1949 one_of_them = if candidates_len == 1 { "it" } else { "one of them" },
dfeec247
XL
1950 name = item_name,
1951 )
1952 };
416331ca 1953 // Obtain the span for `param` and use it for a structured suggestion.
c295e0f8 1954 if let (Some(param), Some(table)) = (param_type, self.in_progress_typeck_results) {
ba9703b0 1955 let table_owner = table.borrow().hir_owner;
f035d41b
XL
1956 let generics = self.tcx.generics_of(table_owner.to_def_id());
1957 let type_param = generics.type_param(param, self.tcx);
5099ac24 1958 let hir = self.tcx.hir();
f035d41b 1959 if let Some(def_id) = type_param.def_id.as_local() {
3dfed10e 1960 let id = hir.local_def_id_to_hir_id(def_id);
f035d41b
XL
1961 // Get the `hir::Param` to verify whether it already has any bounds.
1962 // We do this to avoid suggesting code that ends up as `T: FooBar`,
1963 // instead we suggest `T: Foo + Bar` in that case.
1964 match hir.get(id) {
c295e0f8 1965 Node::GenericParam(param) => {
04454e1e
FG
1966 enum Introducer {
1967 Plus,
1968 Colon,
1969 Nothing,
1970 }
1971 let ast_generics = hir.get_generics(id.owner).unwrap();
1972 let (sp, mut introducer) = if let Some(span) =
1973 ast_generics.bounds_span_for_suggestions(def_id)
1974 {
1975 (span, Introducer::Plus)
1976 } else if let Some(colon_span) = param.colon_span {
1977 (colon_span.shrink_to_hi(), Introducer::Nothing)
f035d41b 1978 } else {
04454e1e 1979 (param.span.shrink_to_hi(), Introducer::Colon)
f035d41b 1980 };
04454e1e
FG
1981 if matches!(
1982 param.kind,
1983 hir::GenericParamKind::Type { synthetic: true, .. },
1984 ) {
1985 introducer = Introducer::Plus
1986 }
1987 let trait_def_ids: FxHashSet<DefId> = ast_generics
1988 .bounds_for_param(def_id)
1989 .flat_map(|bp| bp.bounds.iter())
6a06907d 1990 .filter_map(|bound| bound.trait_ref()?.trait_def_id())
f035d41b
XL
1991 .collect();
1992 if !candidates.iter().any(|t| trait_def_ids.contains(&t.def_id)) {
e74abb32
XL
1993 err.span_suggestions(
1994 sp,
f035d41b
XL
1995 &message(format!(
1996 "restrict type parameter `{}` with",
1997 param.name.ident(),
1998 )),
dfeec247 1999 candidates.iter().map(|t| {
f035d41b 2000 format!(
04454e1e
FG
2001 "{} {}",
2002 match introducer {
2003 Introducer::Plus => " +",
2004 Introducer::Colon => ":",
2005 Introducer::Nothing => "",
2006 },
f035d41b 2007 self.tcx.def_path_str(t.def_id),
f035d41b 2008 )
dfeec247 2009 }),
e74abb32
XL
2010 Applicability::MaybeIncorrect,
2011 );
e1599b0c 2012 }
fc512014 2013 return;
f035d41b
XL
2014 }
2015 Node::Item(hir::Item {
2016 kind: hir::ItemKind::Trait(.., bounds, _),
2017 ident,
2018 ..
2019 }) => {
2020 let (sp, sep, article) = if bounds.is_empty() {
2021 (ident.span.shrink_to_hi(), ":", "a")
2022 } else {
2023 (bounds.last().unwrap().span().shrink_to_hi(), " +", "another")
2024 };
2025 err.span_suggestions(
2026 sp,
2027 &message(format!("add {} supertrait for", article)),
2028 candidates.iter().map(|t| {
2029 format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
2030 }),
2031 Applicability::MaybeIncorrect,
2032 );
fc512014 2033 return;
416331ca 2034 }
f035d41b 2035 _ => {}
416331ca 2036 }
f035d41b 2037 }
416331ca
XL
2038 }
2039
fc512014
XL
2040 let (potential_candidates, explicitly_negative) = if param_type.is_some() {
2041 // FIXME: Even though negative bounds are not implemented, we could maybe handle
2042 // cases where a positive bound implies a negative impl.
2043 (candidates, Vec::new())
5e7ed085 2044 } else if let Some(simp_rcvr_ty) =
923072b8 2045 simplify_type(self.tcx, rcvr_ty, TreatParams::AsPlaceholder)
a2a8927a 2046 {
fc512014
XL
2047 let mut potential_candidates = Vec::new();
2048 let mut explicitly_negative = Vec::new();
2049 for candidate in candidates {
2050 // Check if there's a negative impl of `candidate` for `rcvr_ty`
2051 if self
2052 .tcx
2053 .all_impls(candidate.def_id)
2054 .filter(|imp_did| {
2055 self.tcx.impl_polarity(*imp_did) == ty::ImplPolarity::Negative
2056 })
2057 .any(|imp_did| {
2058 let imp = self.tcx.impl_trait_ref(imp_did).unwrap();
5099ac24 2059 let imp_simp =
923072b8 2060 simplify_type(self.tcx, imp.self_ty(), TreatParams::AsPlaceholder);
5869c6ff 2061 imp_simp.map_or(false, |s| s == simp_rcvr_ty)
fc512014
XL
2062 })
2063 {
2064 explicitly_negative.push(candidate);
2065 } else {
2066 potential_candidates.push(candidate);
74b04a01
XL
2067 }
2068 }
fc512014
XL
2069 (potential_candidates, explicitly_negative)
2070 } else {
2071 // We don't know enough about `recv_ty` to make proper suggestions.
2072 (candidates, Vec::new())
2073 };
2074
2075 let action = if let Some(param) = param_type {
2076 format!("restrict type parameter `{}` with", param)
2077 } else {
2078 // FIXME: it might only need to be imported into scope, not implemented.
2079 "implement".to_string()
2080 };
2081 match &potential_candidates[..] {
2082 [] => {}
2083 [trait_info] if trait_info.def_id.is_local() => {
2084 let span = self.tcx.hir().span_if_local(trait_info.def_id).unwrap();
2085 err.span_note(
2086 self.tcx.sess.source_map().guess_head_span(span),
2087 &format!(
2088 "`{}` defines an item `{}`, perhaps you need to {} it",
2089 self.tcx.def_path_str(trait_info.def_id),
2090 item_name,
2091 action
2092 ),
2093 );
2094 }
2095 trait_infos => {
74b04a01 2096 let mut msg = message(action);
fc512014 2097 for (i, trait_info) in trait_infos.iter().enumerate() {
74b04a01
XL
2098 msg.push_str(&format!(
2099 "\ncandidate #{}: `{}`",
2100 i + 1,
2101 self.tcx.def_path_str(trait_info.def_id),
2102 ));
2103 }
fc512014
XL
2104 err.note(&msg);
2105 }
2106 }
2107 match &explicitly_negative[..] {
2108 [] => {}
2109 [trait_info] => {
2110 let msg = format!(
5099ac24 2111 "the trait `{}` defines an item `{}`, but is explicitly unimplemented",
fc512014
XL
2112 self.tcx.def_path_str(trait_info.def_id),
2113 item_name
2114 );
2115 err.note(&msg);
2116 }
2117 trait_infos => {
2118 let mut msg = format!(
5099ac24 2119 "the following traits define an item `{}`, but are explicitly unimplemented:",
fc512014
XL
2120 item_name
2121 );
2122 for trait_info in trait_infos {
2123 msg.push_str(&format!("\n{}", self.tcx.def_path_str(trait_info.def_id)));
2124 }
2125 err.note(&msg);
416331ca 2126 }
a7813a04 2127 }
85aaf69f 2128 }
85aaf69f
SL
2129 }
2130
a7813a04
XL
2131 /// Checks whether there is a local type somewhere in the chain of
2132 /// autoderefs of `rcvr_ty`.
cdc7bbd5
XL
2133 fn type_derefs_to_local(
2134 &self,
2135 span: Span,
2136 rcvr_ty: Ty<'tcx>,
2137 source: SelfSource<'tcx>,
2138 ) -> bool {
9fa01778 2139 fn is_local(ty: Ty<'_>) -> bool {
1b1a35ee 2140 match ty.kind() {
5e7ed085 2141 ty::Adt(def, _) => def.did().is_local(),
b7449926 2142 ty::Foreign(did) => did.is_local(),
c295e0f8 2143 ty::Dynamic(tr, ..) => tr.principal().map_or(false, |d| d.def_id().is_local()),
b7449926 2144 ty::Param(_) => true,
a7813a04 2145
0731742a
XL
2146 // Everything else (primitive types, etc.) is effectively
2147 // non-local (there are "edge" cases, e.g., `(LocalType,)`, but
a7813a04
XL
2148 // the noise from these sort of types is usually just really
2149 // annoying, rather than any sort of help).
c30ab7b3 2150 _ => false,
a7813a04 2151 }
85aaf69f 2152 }
85aaf69f 2153
a7813a04
XL
2154 // This occurs for UFCS desugaring of `T::method`, where there is no
2155 // receiver expression for the method call, and thus no autoderef.
0731742a 2156 if let SelfSource::QPath(_) = source {
e74abb32 2157 return is_local(self.resolve_vars_with_obligations(rcvr_ty));
c34b1796 2158 }
c34b1796 2159
3157f602 2160 self.autoderef(span, rcvr_ty).any(|(ty, _)| is_local(ty))
c34b1796 2161 }
85aaf69f
SL
2162}
2163
cdc7bbd5 2164#[derive(Copy, Clone, Debug)]
0731742a 2165pub enum SelfSource<'a> {
dfeec247
XL
2166 QPath(&'a hir::Ty<'a>),
2167 MethodCall(&'a hir::Expr<'a> /* rcvr */),
0731742a
XL
2168}
2169
c34b1796 2170#[derive(Copy, Clone)]
85aaf69f 2171pub struct TraitInfo {
e9174d1e 2172 pub def_id: DefId,
85aaf69f
SL
2173}
2174
85aaf69f
SL
2175impl PartialEq for TraitInfo {
2176 fn eq(&self, other: &TraitInfo) -> bool {
2177 self.cmp(other) == Ordering::Equal
2178 }
2179}
2180impl Eq for TraitInfo {}
2181impl PartialOrd for TraitInfo {
c30ab7b3
SL
2182 fn partial_cmp(&self, other: &TraitInfo) -> Option<Ordering> {
2183 Some(self.cmp(other))
2184 }
85aaf69f
SL
2185}
2186impl Ord for TraitInfo {
2187 fn cmp(&self, other: &TraitInfo) -> Ordering {
0731742a
XL
2188 // Local crates are more important than remote ones (local:
2189 // `cnum == 0`), and otherwise we throw in the defid for totality.
85aaf69f 2190
b039eaaf
SL
2191 let lhs = (other.def_id.krate, other.def_id);
2192 let rhs = (self.def_id.krate, self.def_id);
85aaf69f
SL
2193 lhs.cmp(&rhs)
2194 }
2195}
2196
a2a8927a
XL
2197/// Retrieves all traits in this crate and any dependent crates,
2198/// and wraps them into `TraitInfo` for custom sorting.
416331ca 2199pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
a2a8927a 2200 tcx.all_traits().map(|def_id| TraitInfo { def_id }).collect()
85aaf69f 2201}
ff7c6d11 2202
a2a8927a 2203fn print_disambiguation_help<'tcx>(
f9f354fc 2204 item_name: Ident,
dfeec247 2205 args: Option<&'tcx [hir::Expr<'tcx>]>,
5e7ed085 2206 err: &mut Diagnostic,
dfeec247
XL
2207 trait_name: String,
2208 rcvr_ty: Ty<'_>,
2209 kind: ty::AssocKind,
ba9703b0 2210 def_id: DefId,
dfeec247
XL
2211 span: Span,
2212 candidate: Option<usize>,
2213 source_map: &source_map::SourceMap,
c295e0f8 2214 fn_has_self_parameter: bool,
dfeec247
XL
2215) {
2216 let mut applicability = Applicability::MachineApplicable;
94222f64
XL
2217 let (span, sugg) = if let (ty::AssocKind::Fn, Some(args)) = (kind, args) {
2218 let args = format!(
dfeec247
XL
2219 "({}{})",
2220 if rcvr_ty.is_region_ptr() {
2221 if rcvr_ty.is_mutable_ptr() { "&mut " } else { "&" }
2222 } else {
2223 ""
2224 },
2225 args.iter()
2226 .map(|arg| source_map.span_to_snippet(arg.span).unwrap_or_else(|_| {
2227 applicability = Applicability::HasPlaceholders;
2228 "_".to_owned()
2229 }))
2230 .collect::<Vec<_>>()
2231 .join(", "),
94222f64 2232 );
c295e0f8
XL
2233 let trait_name = if !fn_has_self_parameter {
2234 format!("<{} as {}>", rcvr_ty, trait_name)
2235 } else {
2236 trait_name
2237 };
94222f64 2238 (span, format!("{}::{}{}", trait_name, item_name, args))
dfeec247 2239 } else {
c295e0f8 2240 (span.with_hi(item_name.span.lo()), format!("<{} as {}>::", rcvr_ty, trait_name))
dfeec247 2241 };
94222f64 2242 err.span_suggestion_verbose(
dfeec247
XL
2243 span,
2244 &format!(
2245 "disambiguate the {} for {}",
ba9703b0 2246 kind.as_def_kind().descr(def_id),
dfeec247
XL
2247 if let Some(candidate) = candidate {
2248 format!("candidate #{}", candidate)
2249 } else {
2250 "the candidate".to_string()
2251 },
2252 ),
2253 sugg,
2254 applicability,
2255 );
2256}