1use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
2use rustc_errors::{Diag, MultiSpan, pluralize};
3use rustc_hir as hir;
4use rustc_hir::def::DefKind;
5use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
6use rustc_middle::ty::error::{ExpectedFound, TypeError};
7use rustc_middle::ty::fast_reject::DeepRejectCtxt;
8use rustc_middle::ty::print::{FmtPrinter, Printer};
9use rustc_middle::ty::{self, Ty, suggest_constraining_type_param};
10use rustc_span::def_id::DefId;
11use rustc_span::{BytePos, Span, Symbol, sym};
12use tracing::debug;
13
14use crate::error_reporting::TypeErrCtxt;
15use crate::infer::InferCtxtExt;
16
17impl<'tcx> TypeErrCtxt<'_, 'tcx> {
18 pub fn note_and_explain_type_err(
19 &self,
20 diag: &mut Diag<'_>,
21 err: TypeError<'tcx>,
22 cause: &ObligationCause<'tcx>,
23 sp: Span,
24 body_owner_def_id: DefId,
25 ) {
26 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
27
28 let tcx = self.tcx;
29
30 match err {
31 TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
32 match (*values.expected.kind(), *values.found.kind()) {
33 (ty::Closure(..), ty::Closure(..)) => {
34 diag.note("no two closures, even if identical, have the same type");
35 diag.help("consider boxing your closure and/or using it as a trait object");
36 }
37 (ty::Coroutine(def_id1, ..), ty::Coroutine(def_id2, ..))
38 if self.tcx.coroutine_is_async(def_id1)
39 && self.tcx.coroutine_is_async(def_id2) =>
40 {
41 diag.note("no two async blocks, even if identical, have the same type");
42 diag.help(
43 "consider pinning your async block and casting it to a trait object",
44 );
45 }
46 (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
47 diag.note("distinct uses of `impl Trait` result in different opaque types");
49 }
50 (ty::Float(_), ty::Infer(ty::IntVar(_)))
51 if let Ok(
52 snippet,
54 ) = tcx.sess.source_map().span_to_snippet(sp) =>
55 {
56 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
57 diag.span_suggestion_verbose(
58 sp.shrink_to_hi(),
59 "use a float literal",
60 ".0",
61 MachineApplicable,
62 );
63 }
64 }
65 (ty::Param(expected), ty::Param(found)) => {
66 let generics = tcx.generics_of(body_owner_def_id);
67 let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id);
68 if !sp.contains(e_span) {
69 diag.span_label(e_span, "expected type parameter");
70 }
71 let f_span = tcx.def_span(generics.type_param(found, tcx).def_id);
72 if !sp.contains(f_span) {
73 diag.span_label(f_span, "found type parameter");
74 }
75 diag.note(
76 "a type parameter was expected, but a different one was found; \
77 you might be missing a type parameter or trait bound",
78 );
79 diag.note(
80 "for more information, visit \
81 https://doc.rust-lang.org/book/ch10-02-traits.html\
82 #traits-as-parameters",
83 );
84 }
85 (
86 ty::Alias(ty::Projection | ty::Inherent, _),
87 ty::Alias(ty::Projection | ty::Inherent, _),
88 ) => {
89 diag.note("an associated type was expected, but a different one was found");
90 }
91 (ty::Param(p), ty::Alias(ty::Projection, proj))
93 | (ty::Alias(ty::Projection, proj), ty::Param(p))
94 if !tcx.is_impl_trait_in_trait(proj.def_id) =>
95 {
96 let param = tcx.generics_of(body_owner_def_id).type_param(p, tcx);
97 let p_def_id = param.def_id;
98 let p_span = tcx.def_span(p_def_id);
99 let expected = match (values.expected.kind(), values.found.kind()) {
100 (ty::Param(_), _) => "expected ",
101 (_, ty::Param(_)) => "found ",
102 _ => "",
103 };
104 if !sp.contains(p_span) {
105 diag.span_label(p_span, format!("{expected}this type parameter"));
106 }
107 let parent = p_def_id.as_local().and_then(|id| {
108 let local_id = tcx.local_def_id_to_hir_id(id);
109 let generics = tcx.parent_hir_node(local_id).generics()?;
110 Some((id, generics))
111 });
112 let mut note = true;
113 if let Some((local_id, generics)) = parent {
114 let (trait_ref, assoc_args) = proj.trait_ref_and_own_args(tcx);
117 let item_name = tcx.item_name(proj.def_id);
118 let item_args = self.format_generic_args(assoc_args);
119
120 let mut matching_span = None;
126 let mut matched_end_of_args = false;
127 for bound in generics.bounds_for_param(local_id) {
128 let potential_spans = bound.bounds.iter().find_map(|bound| {
129 let bound_trait_path = bound.trait_ref()?.path;
130 let def_id = bound_trait_path.res.opt_def_id()?;
131 let generic_args = bound_trait_path
132 .segments
133 .iter()
134 .last()
135 .map(|path| path.args());
136 (def_id == trait_ref.def_id)
137 .then_some((bound_trait_path.span, generic_args))
138 });
139
140 if let Some((end_of_trait, end_of_args)) = potential_spans {
141 let args_span = end_of_args.and_then(|args| args.span());
142 matched_end_of_args = args_span.is_some();
143 matching_span = args_span
144 .or_else(|| Some(end_of_trait))
145 .map(|span| span.shrink_to_hi());
146 break;
147 }
148 }
149
150 if matched_end_of_args {
151 let path = format!(", {item_name}{item_args} = {p}");
153 note = !suggest_constraining_type_param(
154 tcx,
155 generics,
156 diag,
157 &proj.self_ty().to_string(),
158 &path,
159 None,
160 matching_span,
161 );
162 } else {
163 let path = format!("<{item_name}{item_args} = {p}>");
167 note = !suggest_constraining_type_param(
168 tcx,
169 generics,
170 diag,
171 &proj.self_ty().to_string(),
172 &path,
173 None,
174 matching_span,
175 );
176 }
177 }
178 if note {
179 diag.note("you might be missing a type parameter or trait bound");
180 }
181 }
182 (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
183 | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => {
184 let generics = tcx.generics_of(body_owner_def_id);
185 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
186 let expected = match (values.expected.kind(), values.found.kind()) {
187 (ty::Param(_), _) => "expected ",
188 (_, ty::Param(_)) => "found ",
189 _ => "",
190 };
191 if !sp.contains(p_span) {
192 diag.span_label(p_span, format!("{expected}this type parameter"));
193 }
194 diag.help("type parameters must be constrained to match other types");
195 if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
196 diag.help(
197 "given a type parameter `T` and a method `foo`:
198```
199trait Trait<T> { fn foo(&self) -> T; }
200```
201the only ways to implement method `foo` are:
202- constrain `T` with an explicit type:
203```
204impl Trait<String> for X {
205 fn foo(&self) -> String { String::new() }
206}
207```
208- add a trait bound to `T` and call a method on that trait that returns `Self`:
209```
210impl<T: std::default::Default> Trait<T> for X {
211 fn foo(&self) -> T { <T as std::default::Default>::default() }
212}
213```
214- change `foo` to return an argument of type `T`:
215```
216impl<T> Trait<T> for X {
217 fn foo(&self, x: T) -> T { x }
218}
219```",
220 );
221 }
222 diag.note(
223 "for more information, visit \
224 https://doc.rust-lang.org/book/ch10-02-traits.html\
225 #traits-as-parameters",
226 );
227 }
228 (
229 ty::Param(p),
230 ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..),
231 ) => {
232 let generics = tcx.generics_of(body_owner_def_id);
233 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
234 if !sp.contains(p_span) {
235 diag.span_label(p_span, "expected this type parameter");
236 }
237 diag.help(format!(
238 "every closure has a distinct type and so could not always match the \
239 caller-chosen type of parameter `{p}`"
240 ));
241 }
242 (ty::Param(p), _) | (_, ty::Param(p)) => {
243 let generics = tcx.generics_of(body_owner_def_id);
244 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
245 let expected = match (values.expected.kind(), values.found.kind()) {
246 (ty::Param(_), _) => "expected ",
247 (_, ty::Param(_)) => "found ",
248 _ => "",
249 };
250 if !sp.contains(p_span) {
251 diag.span_label(p_span, format!("{expected}this type parameter"));
252 }
253 }
254 (ty::Alias(ty::Projection | ty::Inherent, proj_ty), _)
255 if !tcx.is_impl_trait_in_trait(proj_ty.def_id) =>
256 {
257 self.expected_projection(
258 diag,
259 proj_ty,
260 values,
261 body_owner_def_id,
262 cause.code(),
263 );
264 }
265 (_, ty::Alias(ty::Projection | ty::Inherent, proj_ty))
266 if !tcx.is_impl_trait_in_trait(proj_ty.def_id) =>
267 {
268 let msg = || {
269 format!(
270 "consider constraining the associated type `{}` to `{}`",
271 values.found, values.expected,
272 )
273 };
274 if !(self.suggest_constraining_opaque_associated_type(
275 diag,
276 msg,
277 proj_ty,
278 values.expected,
279 ) || self.suggest_constraint(
280 diag,
281 &msg,
282 body_owner_def_id,
283 proj_ty,
284 values.expected,
285 )) {
286 diag.help(msg());
287 diag.note(
288 "for more information, visit \
289 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
290 );
291 }
292 }
293 (ty::Dynamic(t, _, ty::DynKind::Dyn), ty::Alias(ty::Opaque, alias))
294 if let Some(def_id) = t.principal_def_id()
295 && tcx
296 .explicit_item_self_bounds(alias.def_id)
297 .skip_binder()
298 .iter()
299 .any(|(pred, _span)| match pred.kind().skip_binder() {
300 ty::ClauseKind::Trait(trait_predicate)
301 if trait_predicate.polarity
302 == ty::PredicatePolarity::Positive =>
303 {
304 trait_predicate.def_id() == def_id
305 }
306 _ => false,
307 }) =>
308 {
309 diag.help(format!(
310 "you can box the `{}` to coerce it to `Box<{}>`, but you'll have to \
311 change the expected type as well",
312 values.found, values.expected,
313 ));
314 }
315 (ty::Dynamic(t, _, ty::DynKind::Dyn), _)
316 if let Some(def_id) = t.principal_def_id() =>
317 {
318 let mut has_matching_impl = false;
319 tcx.for_each_relevant_impl(def_id, values.found, |did| {
320 if DeepRejectCtxt::relate_rigid_infer(tcx)
321 .types_may_unify(values.found, tcx.type_of(did).skip_binder())
322 {
323 has_matching_impl = true;
324 }
325 });
326 if has_matching_impl {
327 let trait_name = tcx.item_name(def_id);
328 diag.help(format!(
329 "`{}` implements `{trait_name}` so you could box the found value \
330 and coerce it to the trait object `Box<dyn {trait_name}>`, you \
331 will have to change the expected type as well",
332 values.found,
333 ));
334 }
335 }
336 (_, ty::Dynamic(t, _, ty::DynKind::Dyn))
337 if let Some(def_id) = t.principal_def_id() =>
338 {
339 let mut has_matching_impl = false;
340 tcx.for_each_relevant_impl(def_id, values.expected, |did| {
341 if DeepRejectCtxt::relate_rigid_infer(tcx)
342 .types_may_unify(values.expected, tcx.type_of(did).skip_binder())
343 {
344 has_matching_impl = true;
345 }
346 });
347 if has_matching_impl {
348 let trait_name = tcx.item_name(def_id);
349 diag.help(format!(
350 "`{}` implements `{trait_name}` so you could change the expected \
351 type to `Box<dyn {trait_name}>`",
352 values.expected,
353 ));
354 }
355 }
356 (ty::Dynamic(t, _, ty::DynKind::DynStar), _)
357 if let Some(def_id) = t.principal_def_id() =>
358 {
359 let mut has_matching_impl = false;
360 tcx.for_each_relevant_impl(def_id, values.found, |did| {
361 if DeepRejectCtxt::relate_rigid_infer(tcx)
362 .types_may_unify(values.found, tcx.type_of(did).skip_binder())
363 {
364 has_matching_impl = true;
365 }
366 });
367 if has_matching_impl {
368 let trait_name = tcx.item_name(def_id);
369 diag.help(format!(
370 "`{}` implements `{trait_name}`, `#[feature(dyn_star)]` is likely \
371 not enabled; that feature it is currently incomplete",
372 values.found,
373 ));
374 }
375 }
376 (_, ty::Alias(ty::Opaque, opaque_ty))
377 | (ty::Alias(ty::Opaque, opaque_ty), _) => {
378 if opaque_ty.def_id.is_local()
379 && matches!(
380 tcx.def_kind(body_owner_def_id),
381 DefKind::Fn
382 | DefKind::Static { .. }
383 | DefKind::Const
384 | DefKind::AssocFn
385 | DefKind::AssocConst
386 )
387 && matches!(
388 tcx.opaque_ty_origin(opaque_ty.def_id),
389 hir::OpaqueTyOrigin::TyAlias { .. }
390 )
391 && !tcx
392 .opaque_types_defined_by(body_owner_def_id.expect_local())
393 .contains(&opaque_ty.def_id.expect_local())
394 {
395 let sp = tcx
396 .def_ident_span(body_owner_def_id)
397 .unwrap_or_else(|| tcx.def_span(body_owner_def_id));
398 let mut alias_def_id = opaque_ty.def_id;
399 while let DefKind::OpaqueTy = tcx.def_kind(alias_def_id) {
400 alias_def_id = tcx.parent(alias_def_id);
401 }
402 let opaque_path = tcx.def_path_str(alias_def_id);
403 match tcx.opaque_ty_origin(opaque_ty.def_id) {
405 rustc_hir::OpaqueTyOrigin::FnReturn { .. } => {}
406 rustc_hir::OpaqueTyOrigin::AsyncFn { .. } => {}
407 rustc_hir::OpaqueTyOrigin::TyAlias {
408 in_assoc_ty: false, ..
409 } => {
410 diag.span_note(
411 sp,
412 format!("this item must have a `#[define_opaque({opaque_path})]` \
413 attribute to be able to define hidden types"),
414 );
415 }
416 rustc_hir::OpaqueTyOrigin::TyAlias {
417 in_assoc_ty: true, ..
418 } => {}
419 }
420 }
421 let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code() else {
424 return;
425 };
426 let hir::Node::Expr(&hir::Expr {
427 kind:
428 hir::ExprKind::If(
429 _,
430 &hir::Expr {
431 kind:
432 hir::ExprKind::Block(
433 &hir::Block { expr: Some(then), .. },
434 _,
435 ),
436 ..
437 },
438 Some(&hir::Expr {
439 kind:
440 hir::ExprKind::Block(
441 &hir::Block { expr: Some(else_), .. },
442 _,
443 ),
444 ..
445 }),
446 ),
447 ..
448 }) = self.tcx.hir_node(*expr_id)
449 else {
450 return;
451 };
452 let expected = match values.found.kind() {
453 ty::Alias(..) => values.expected,
454 _ => values.found,
455 };
456 let preds = tcx.explicit_item_self_bounds(opaque_ty.def_id);
457 for (pred, _span) in preds.skip_binder() {
458 let ty::ClauseKind::Trait(trait_predicate) = pred.kind().skip_binder()
459 else {
460 continue;
461 };
462 if trait_predicate.polarity != ty::PredicatePolarity::Positive {
463 continue;
464 }
465 let def_id = trait_predicate.def_id();
466 let mut impl_def_ids = vec![];
467 tcx.for_each_relevant_impl(def_id, expected, |did| {
468 impl_def_ids.push(did)
469 });
470 if let [_] = &impl_def_ids[..] {
471 let trait_name = tcx.item_name(def_id);
472 diag.multipart_suggestion(
473 format!(
474 "`{expected}` implements `{trait_name}` so you can box \
475 both arms and coerce to the trait object \
476 `Box<dyn {trait_name}>`",
477 ),
478 vec![
479 (then.span.shrink_to_lo(), "Box::new(".to_string()),
480 (
481 then.span.shrink_to_hi(),
482 format!(") as Box<dyn {}>", tcx.def_path_str(def_id)),
483 ),
484 (else_.span.shrink_to_lo(), "Box::new(".to_string()),
485 (else_.span.shrink_to_hi(), ")".to_string()),
486 ],
487 MachineApplicable,
488 );
489 }
490 }
491 }
492 (ty::FnPtr(_, hdr), ty::FnDef(def_id, _))
493 | (ty::FnDef(def_id, _), ty::FnPtr(_, hdr)) => {
494 if tcx.fn_sig(def_id).skip_binder().safety() < hdr.safety {
495 if !tcx.codegen_fn_attrs(def_id).safe_target_features {
496 diag.note(
497 "unsafe functions cannot be coerced into safe function pointers",
498 );
499 }
500 }
501 }
502 (ty::Adt(_, _), ty::Adt(def, args))
503 if let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code()
504 && let hir::Node::Expr(if_expr) = self.tcx.hir_node(*expr_id)
505 && let hir::ExprKind::If(_, then_expr, _) = if_expr.kind
506 && let hir::ExprKind::Block(blk, _) = then_expr.kind
507 && let Some(then) = blk.expr
508 && def.is_box()
509 && let boxed_ty = args.type_at(0)
510 && let ty::Dynamic(t, _, _) = boxed_ty.kind()
511 && let Some(def_id) = t.principal_def_id()
512 && let mut impl_def_ids = vec![]
513 && let _ =
514 tcx.for_each_relevant_impl(def_id, values.expected, |did| {
515 impl_def_ids.push(did)
516 })
517 && let [_] = &impl_def_ids[..] =>
518 {
519 diag.multipart_suggestion(
522 format!(
523 "`{}` implements `{}` so you can box it to coerce to the trait \
524 object `{}`",
525 values.expected,
526 tcx.item_name(def_id),
527 values.found,
528 ),
529 vec![
530 (then.span.shrink_to_lo(), "Box::new(".to_string()),
531 (then.span.shrink_to_hi(), ")".to_string()),
532 ],
533 MachineApplicable,
534 );
535 }
536 _ => {}
537 }
538 debug!(
539 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
540 values.expected,
541 values.expected.kind(),
542 values.found,
543 values.found.kind(),
544 );
545 }
546 TypeError::CyclicTy(ty) => {
547 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() {
549 diag.note(
550 "closures cannot capture themselves or take themselves as argument;\n\
551 this error may be the result of a recent compiler bug-fix,\n\
552 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
553 for more information",
554 );
555 }
556 }
557 TypeError::TargetFeatureCast(def_id) => {
558 let target_spans =
559 tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span());
560 diag.note(
561 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
562 );
563 diag.span_labels(target_spans, "`#[target_feature]` added here");
564 }
565 _ => {}
566 }
567 }
568
569 fn suggest_constraint(
570 &self,
571 diag: &mut Diag<'_>,
572 msg: impl Fn() -> String,
573 body_owner_def_id: DefId,
574 proj_ty: ty::AliasTy<'tcx>,
575 ty: Ty<'tcx>,
576 ) -> bool {
577 let tcx = self.tcx;
578 let assoc = tcx.associated_item(proj_ty.def_id);
579 let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
580 let Some(item) = tcx.hir_get_if_local(body_owner_def_id) else {
581 return false;
582 };
583 let Some(hir_generics) = item.generics() else {
584 return false;
585 };
586 let ty::Param(param_ty) = *proj_ty.self_ty().kind() else {
589 return false;
590 };
591 let generics = tcx.generics_of(body_owner_def_id);
592 let def_id = generics.type_param(param_ty, tcx).def_id;
593 let Some(def_id) = def_id.as_local() else {
594 return false;
595 };
596
597 for pred in hir_generics.bounds_for_param(def_id) {
600 if self.constrain_generic_bound_associated_type_structured_suggestion(
601 diag,
602 trait_ref,
603 pred.bounds,
604 assoc,
605 assoc_args,
606 ty,
607 &msg,
608 false,
609 ) {
610 return true;
611 }
612 }
613 if (param_ty.index as usize) >= generics.parent_count {
614 return false;
616 }
617 let hir_id = match item {
619 hir::Node::ImplItem(item) => item.hir_id(),
620 hir::Node::TraitItem(item) => item.hir_id(),
621 _ => return false,
622 };
623 let parent = tcx.hir_get_parent_item(hir_id).def_id;
624 self.suggest_constraint(diag, msg, parent.into(), proj_ty, ty)
625 }
626
627 fn expected_projection(
641 &self,
642 diag: &mut Diag<'_>,
643 proj_ty: ty::AliasTy<'tcx>,
644 values: ExpectedFound<Ty<'tcx>>,
645 body_owner_def_id: DefId,
646 cause_code: &ObligationCauseCode<'_>,
647 ) {
648 let tcx = self.tcx;
649
650 if self.tcx.erase_regions(values.found).contains(self.tcx.erase_regions(values.expected)) {
652 return;
653 }
654
655 let msg = || {
656 format!(
657 "consider constraining the associated type `{}` to `{}`",
658 values.expected, values.found
659 )
660 };
661
662 let body_owner = tcx.hir_get_if_local(body_owner_def_id);
663 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
664
665 let callable_scope = matches!(
667 body_owner,
668 Some(
669 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })
670 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
671 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
672 )
673 );
674 let impl_comparison = matches!(cause_code, ObligationCauseCode::CompareImplItem { .. });
675 let assoc = tcx.associated_item(proj_ty.def_id);
676 if impl_comparison {
677 } else {
680 let point_at_assoc_fn = if callable_scope
681 && self.point_at_methods_that_satisfy_associated_type(
682 diag,
683 assoc.container_id(tcx),
684 current_method_ident,
685 proj_ty.def_id,
686 values.expected,
687 ) {
688 true
693 } else {
694 false
695 };
696 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
699 || point_at_assoc_fn
700 {
701 return;
702 }
703 }
704
705 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
706
707 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
708 return;
709 }
710
711 if !impl_comparison {
712 if callable_scope {
714 diag.help(format!(
715 "{} or calling a method that returns `{}`",
716 msg(),
717 values.expected
718 ));
719 } else {
720 diag.help(msg());
721 }
722 diag.note(
723 "for more information, visit \
724 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
725 );
726 }
727 if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
728 diag.help(
729 "given an associated type `T` and a method `foo`:
730```
731trait Trait {
732type T;
733fn foo(&self) -> Self::T;
734}
735```
736the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
737```
738impl Trait for X {
739type T = String;
740fn foo(&self) -> Self::T { String::new() }
741}
742```",
743 );
744 }
745 }
746
747 fn suggest_constraining_opaque_associated_type(
750 &self,
751 diag: &mut Diag<'_>,
752 msg: impl Fn() -> String,
753 proj_ty: ty::AliasTy<'tcx>,
754 ty: Ty<'tcx>,
755 ) -> bool {
756 let tcx = self.tcx;
757
758 let assoc = tcx.associated_item(proj_ty.def_id);
759 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
760 let opaque_local_def_id = def_id.as_local();
761 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
762 tcx.hir_expect_opaque_ty(opaque_local_def_id)
763 } else {
764 return false;
765 };
766
767 let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
768
769 self.constrain_generic_bound_associated_type_structured_suggestion(
770 diag,
771 trait_ref,
772 opaque_hir_ty.bounds,
773 assoc,
774 assoc_args,
775 ty,
776 msg,
777 true,
778 )
779 } else {
780 false
781 }
782 }
783
784 fn point_at_methods_that_satisfy_associated_type(
785 &self,
786 diag: &mut Diag<'_>,
787 assoc_container_id: DefId,
788 current_method_ident: Option<Symbol>,
789 proj_ty_item_def_id: DefId,
790 expected: Ty<'tcx>,
791 ) -> bool {
792 let tcx = self.tcx;
793
794 let items = tcx.associated_items(assoc_container_id);
795 let methods: Vec<(Span, String)> = items
799 .in_definition_order()
800 .filter(|item| {
801 item.is_fn()
802 && Some(item.name()) != current_method_ident
803 && !tcx.is_doc_hidden(item.def_id)
804 })
805 .filter_map(|item| {
806 let method = tcx.fn_sig(item.def_id).instantiate_identity();
807 match *method.output().skip_binder().kind() {
808 ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
809 if item_def_id == proj_ty_item_def_id =>
810 {
811 Some((
812 tcx.def_span(item.def_id),
813 format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
814 ))
815 }
816 _ => None,
817 }
818 })
819 .collect();
820 if !methods.is_empty() {
821 let mut span: MultiSpan =
824 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
825 let msg = format!(
826 "{some} method{s} {are} available that return{r} `{ty}`",
827 some = if methods.len() == 1 { "a" } else { "some" },
828 s = pluralize!(methods.len()),
829 are = pluralize!("is", methods.len()),
830 r = if methods.len() == 1 { "s" } else { "" },
831 ty = expected
832 );
833 for (sp, label) in methods.into_iter() {
834 span.push_span_label(sp, label);
835 }
836 diag.span_help(span, msg);
837 return true;
838 }
839 false
840 }
841
842 fn point_at_associated_type(
843 &self,
844 diag: &mut Diag<'_>,
845 body_owner_def_id: DefId,
846 found: Ty<'tcx>,
847 ) -> bool {
848 let tcx = self.tcx;
849
850 let Some(def_id) = body_owner_def_id.as_local() else {
851 return false;
852 };
853
854 let hir_id = tcx.local_def_id_to_hir_id(def_id);
857 let parent_id = tcx.hir_get_parent_item(hir_id);
858 let item = tcx.hir_node_by_def_id(parent_id.def_id);
859
860 debug!("expected_projection parent item {:?}", item);
861
862 let param_env = tcx.param_env(body_owner_def_id);
863
864 match item {
865 hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. }) => {
866 for item in &items[..] {
868 match item.kind {
869 hir::AssocItemKind::Type => {
870 if let hir::Defaultness::Default { has_value: true } =
873 tcx.defaultness(item.id.owner_id)
874 {
875 let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
876 if self.infcx.can_eq(param_env, assoc_ty, found) {
877 diag.span_label(
878 item.span,
879 "associated type defaults can't be assumed inside the \
880 trait defining them",
881 );
882 return true;
883 }
884 }
885 }
886 _ => {}
887 }
888 }
889 }
890 hir::Node::Item(hir::Item {
891 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
892 ..
893 }) => {
894 for item in &items[..] {
895 if let hir::AssocItemKind::Type = item.kind {
896 let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
897 if let hir::Defaultness::Default { has_value: true } =
898 tcx.defaultness(item.id.owner_id)
899 && self.infcx.can_eq(param_env, assoc_ty, found)
900 {
901 diag.span_label(
902 item.span,
903 "associated type is `default` and may be overridden",
904 );
905 return true;
906 }
907 }
908 }
909 }
910 _ => {}
911 }
912 false
913 }
914
915 fn constrain_generic_bound_associated_type_structured_suggestion(
923 &self,
924 diag: &mut Diag<'_>,
925 trait_ref: ty::TraitRef<'tcx>,
926 bounds: hir::GenericBounds<'_>,
927 assoc: ty::AssocItem,
928 assoc_args: &[ty::GenericArg<'tcx>],
929 ty: Ty<'tcx>,
930 msg: impl Fn() -> String,
931 is_bound_surely_present: bool,
932 ) -> bool {
933 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
936 hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifiers::NONE => {
937 Some(ptr)
938 }
939 _ => None,
940 });
941
942 let matching_trait_bounds = trait_bounds
943 .clone()
944 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
945 .collect::<Vec<_>>();
946
947 let span = match &matching_trait_bounds[..] {
948 &[ptr] => ptr.span,
949 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
950 &[ptr] => ptr.span,
951 _ => return false,
952 },
953 _ => return false,
954 };
955
956 self.constrain_associated_type_structured_suggestion(diag, span, assoc, assoc_args, ty, msg)
957 }
958
959 fn constrain_associated_type_structured_suggestion(
962 &self,
963 diag: &mut Diag<'_>,
964 span: Span,
965 assoc: ty::AssocItem,
966 assoc_args: &[ty::GenericArg<'tcx>],
967 ty: Ty<'tcx>,
968 msg: impl Fn() -> String,
969 ) -> bool {
970 let tcx = self.tcx;
971
972 if let Ok(has_params) =
973 tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
974 {
975 let (span, sugg) = if has_params {
976 let pos = span.hi() - BytePos(1);
977 let span = Span::new(pos, pos, span.ctxt(), span.parent());
978 (span, format!(", {} = {}", assoc.ident(tcx), ty))
979 } else {
980 let item_args = self.format_generic_args(assoc_args);
981 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
982 };
983 diag.span_suggestion_verbose(span, msg(), sugg, MaybeIncorrect);
984 return true;
985 }
986 false
987 }
988
989 pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
990 FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |cx| {
991 cx.path_generic_args(|_| Ok(()), args)
992 })
993 .expect("could not write to `String`.")
994 }
995}