1 use super::TypeErrCtxt;
2 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
3 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
4 use rustc_hir::{self as hir, def::DefKind};
5 use rustc_middle::traits::ObligationCauseCode;
6 use rustc_middle::ty::error::ExpectedFound;
7 use rustc_middle::ty::print::Printer;
9 traits::ObligationCause,
10 ty::{self, error::TypeError, print::FmtPrinter, suggest_constraining_type_param, Ty},
12 use rustc_span::{def_id::DefId, sym, BytePos, Span, Symbol};
14 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
15 pub fn note_and_explain_type_err(
17 diag: &mut Diagnostic,
19 cause: &ObligationCause<'tcx>,
21 body_owner_def_id: DefId,
23 use ty::error::TypeError::*;
24 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
29 ArgumentSorts(values, _) | Sorts(values) => {
30 match (values.expected.kind(), values.found.kind()) {
31 (ty::Closure(..), ty::Closure(..)) => {
32 diag.note("no two closures, even if identical, have the same type");
33 diag.help("consider boxing your closure and/or using it as a trait object");
35 (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
37 diag.note("distinct uses of `impl Trait` result in different opaque types");
39 (ty::Float(_), ty::Infer(ty::IntVar(_)))
43 ) = tcx.sess.source_map().span_to_snippet(sp) =>
45 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
48 "use a float literal",
49 format!("{}.0", snippet),
54 (ty::Param(expected), ty::Param(found)) => {
55 let generics = tcx.generics_of(body_owner_def_id);
56 let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id);
57 if !sp.contains(e_span) {
58 diag.span_label(e_span, "expected type parameter");
60 let f_span = tcx.def_span(generics.type_param(found, tcx).def_id);
61 if !sp.contains(f_span) {
62 diag.span_label(f_span, "found type parameter");
65 "a type parameter was expected, but a different one was found; \
66 you might be missing a type parameter or trait bound",
69 "for more information, visit \
70 https://doc.rust-lang.org/book/ch10-02-traits.html\
71 #traits-as-parameters",
74 (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => {
75 diag.note("an associated type was expected, but a different one was found");
77 (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p))
78 if tcx.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder =>
80 let generics = tcx.generics_of(body_owner_def_id);
81 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
82 if !sp.contains(p_span) {
83 diag.span_label(p_span, "this type parameter");
87 if let Some(generics) = generics
91 .map(|id| hir.local_def_id_to_hir_id(id))
92 .and_then(|id| tcx.hir().find_parent(id))
94 .and_then(|node| node.generics())
96 // Synthesize the associated type restriction `Add<Output = Expected>`.
97 // FIXME: extract this logic for use in other diagnostics.
98 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(tcx);
100 tcx.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
101 let item_name = tcx.item_name(proj.def_id);
102 let item_args = self.format_generic_args(assoc_substs);
104 let path = if path.ends_with('>') {
107 &path[..path.len() - 1],
113 format!("{}<{}{} = {}>", path, item_name, item_args, p)
115 note = !suggest_constraining_type_param(
119 &format!("{}", proj.self_ty()),
125 diag.note("you might be missing a type parameter or trait bound");
128 (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
129 | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => {
130 let generics = tcx.generics_of(body_owner_def_id);
131 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
132 if !sp.contains(p_span) {
133 diag.span_label(p_span, "this type parameter");
135 diag.help("type parameters must be constrained to match other types");
136 if tcx.sess.teach(&diag.get_code().unwrap()) {
138 "given a type parameter `T` and a method `foo`:
140 trait Trait<T> { fn foo(&tcx) -> T; }
142 the only ways to implement method `foo` are:
143 - constrain `T` with an explicit type:
145 impl Trait<String> for X {
146 fn foo(&tcx) -> String { String::new() }
149 - add a trait bound to `T` and call a method on that trait that returns `Self`:
151 impl<T: std::default::Default> Trait<T> for X {
152 fn foo(&tcx) -> T { <T as std::default::Default>::default() }
155 - change `foo` to return an argument of type `T`:
157 impl<T> Trait<T> for X {
158 fn foo(&tcx, x: T) -> T { x }
164 "for more information, visit \
165 https://doc.rust-lang.org/book/ch10-02-traits.html\
166 #traits-as-parameters",
169 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
170 let generics = tcx.generics_of(body_owner_def_id);
171 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
172 if !sp.contains(p_span) {
173 diag.span_label(p_span, "this type parameter");
176 "every closure has a distinct type and so could not always match the \
177 caller-chosen type of parameter `{}`",
181 (ty::Param(p), _) | (_, ty::Param(p)) => {
182 let generics = tcx.generics_of(body_owner_def_id);
183 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
184 if !sp.contains(p_span) {
185 diag.span_label(p_span, "this type parameter");
188 (ty::Alias(ty::Projection, proj_ty), _) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
189 self.expected_projection(
197 (_, ty::Alias(ty::Projection, proj_ty)) if tcx.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
199 "consider constraining the associated type `{}` to `{}`",
200 values.found, values.expected,
202 if !(self.suggest_constraining_opaque_associated_type(
207 ) || self.suggest_constraint(
216 "for more information, visit \
217 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
224 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
226 values.expected.kind(),
232 // Watch out for various cases of cyclic types and try to explain.
233 if ty.is_closure() || ty.is_generator() {
235 "closures cannot capture themselves or take themselves as argument;\n\
236 this error may be the result of a recent compiler bug-fix,\n\
237 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
238 for more information",
242 TargetFeatureCast(def_id) => {
243 let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
245 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
247 diag.span_labels(target_spans, "`#[target_feature]` added here");
253 fn suggest_constraint(
255 diag: &mut Diagnostic,
257 body_owner_def_id: DefId,
258 proj_ty: &ty::AliasTy<'tcx>,
262 let assoc = tcx.associated_item(proj_ty.def_id);
263 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
264 if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) {
265 if let Some(hir_generics) = item.generics() {
266 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
267 // This will also work for `impl Trait`.
268 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
269 let generics = tcx.generics_of(body_owner_def_id);
270 generics.type_param(param_ty, tcx).def_id
274 let Some(def_id) = def_id.as_local() else {
278 // First look in the `where` clause, as this might be
279 // `fn foo<T>(x: T) where T: Trait`.
280 for pred in hir_generics.bounds_for_param(def_id) {
281 if self.constrain_generic_bound_associated_type_structured_suggestion(
299 /// An associated type was expected and a different type was found.
301 /// We perform a few different checks to see what we can suggest:
303 /// - In the current item, look for associated functions that return the expected type and
304 /// suggest calling them. (Not a structured suggestion.)
305 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
306 /// associated type to the found type.
307 /// - If the associated type has a default type and was expected inside of a `trait`, we
308 /// mention that this is disallowed.
309 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
310 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
311 /// fn that returns the type.
312 fn expected_projection(
314 diag: &mut Diagnostic,
315 proj_ty: &ty::AliasTy<'tcx>,
316 values: ExpectedFound<Ty<'tcx>>,
317 body_owner_def_id: DefId,
318 cause_code: &ObligationCauseCode<'_>,
323 "consider constraining the associated type `{}` to `{}`",
324 values.expected, values.found
326 let body_owner = tcx.hir().get_if_local(body_owner_def_id);
327 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
329 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
330 let callable_scope = matches!(
333 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
334 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
335 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
338 let impl_comparison =
339 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
340 let assoc = tcx.associated_item(proj_ty.def_id);
341 if !callable_scope || impl_comparison {
342 // We do not want to suggest calling functions when the reason of the
343 // type error is a comparison of an `impl` with its `trait` or when the
344 // scope is outside of a `Body`.
346 // If we find a suitable associated function that returns the expected type, we don't
347 // want the more general suggestion later in this method about "consider constraining
348 // the associated type or calling a method that returns the associated type".
349 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
351 assoc.container_id(tcx),
352 current_method_ident,
356 // Possibly suggest constraining the associated type to conform to the
358 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
365 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
367 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
371 if !impl_comparison {
372 // Generic suggestion when we can't be more specific.
375 "{} or calling a method that returns `{}`",
382 "for more information, visit \
383 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
386 if tcx.sess.teach(&diag.get_code().unwrap()) {
388 "given an associated type `T` and a method `foo`:
392 fn foo(&tcx) -> Self::T;
395 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
399 fn foo(&tcx) -> Self::T { String::new() }
406 /// When the expected `impl Trait` is not defined in the current item, it will come from
407 /// a return type. This can occur when dealing with `TryStream` (#71035).
408 fn suggest_constraining_opaque_associated_type(
410 diag: &mut Diagnostic,
412 proj_ty: &ty::AliasTy<'tcx>,
417 let assoc = tcx.associated_item(proj_ty.def_id);
418 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
419 let opaque_local_def_id = def_id.as_local();
420 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
421 match &tcx.hir().expect_item(opaque_local_def_id).kind {
422 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
423 _ => bug!("The HirId comes from a `ty::Opaque`"),
429 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
431 self.constrain_generic_bound_associated_type_structured_suggestion(
434 opaque_hir_ty.bounds,
446 fn point_at_methods_that_satisfy_associated_type(
448 diag: &mut Diagnostic,
449 assoc_container_id: DefId,
450 current_method_ident: Option<Symbol>,
451 proj_ty_item_def_id: DefId,
456 let items = tcx.associated_items(assoc_container_id);
457 // Find all the methods in the trait that could be called to construct the
458 // expected associated type.
459 // FIXME: consider suggesting the use of associated `const`s.
460 let methods: Vec<(Span, String)> = items
461 .in_definition_order()
463 ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident
466 let method = tcx.fn_sig(item.def_id);
467 match *method.output().skip_binder().kind() {
468 ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
469 if item_def_id == proj_ty_item_def_id =>
472 tcx.def_span(item.def_id),
473 format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
480 if !methods.is_empty() {
481 // Use a single `help:` to show all the methods in the trait that can
482 // be used to construct the expected associated type.
483 let mut span: MultiSpan =
484 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
486 "{some} method{s} {are} available that return{r} `{ty}`",
487 some = if methods.len() == 1 { "a" } else { "some" },
488 s = pluralize!(methods.len()),
489 are = pluralize!("is", methods.len()),
490 r = if methods.len() == 1 { "s" } else { "" },
493 for (sp, label) in methods.into_iter() {
494 span.push_span_label(sp, label);
496 diag.span_help(span, &msg);
502 fn point_at_associated_type(
504 diag: &mut Diagnostic,
505 body_owner_def_id: DefId,
510 let Some(hir_id) = body_owner_def_id.as_local() else {
513 let hir_id = tcx.hir().local_def_id_to_hir_id(hir_id);
514 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
515 // `expected` and point at it.
516 let parent_id = tcx.hir().get_parent_item(hir_id);
517 let item = tcx.hir().find_by_def_id(parent_id.def_id);
519 debug!("expected_projection parent item {:?}", item);
521 let param_env = tcx.param_env(body_owner_def_id);
524 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
525 // FIXME: account for `#![feature(specialization)]`
526 for item in &items[..] {
528 hir::AssocItemKind::Type => {
529 // FIXME: account for returning some type in a trait fn impl that has
530 // an assoc type as a return type (#72076).
531 if let hir::Defaultness::Default { has_value: true } =
532 tcx.impl_defaultness(item.id.owner_id)
534 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
535 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
538 "associated type defaults can't be assumed inside the \
539 trait defining them",
549 Some(hir::Node::Item(hir::Item {
550 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
553 for item in &items[..] {
554 if let hir::AssocItemKind::Type = item.kind {
555 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
557 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
558 diag.span_label(item.span, "expected this associated type");
569 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
570 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
572 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
573 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
574 /// trait bound as the one we're looking for. This can help in cases where the associated
575 /// type is defined on a supertrait of the one present in the bounds.
576 fn constrain_generic_bound_associated_type_structured_suggestion(
578 diag: &mut Diagnostic,
579 trait_ref: &ty::TraitRef<'tcx>,
580 bounds: hir::GenericBounds<'_>,
581 assoc: &ty::AssocItem,
582 assoc_substs: &[ty::GenericArg<'tcx>],
585 is_bound_surely_present: bool,
587 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
589 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
590 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
594 let matching_trait_bounds = trait_bounds
596 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
597 .collect::<Vec<_>>();
599 let span = match &matching_trait_bounds[..] {
601 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
608 self.constrain_associated_type_structured_suggestion(
618 /// Given a span corresponding to a bound, provide a structured suggestion to set an
619 /// associated type to a given type `ty`.
620 fn constrain_associated_type_structured_suggestion(
622 diag: &mut Diagnostic,
624 assoc: &ty::AssocItem,
625 assoc_substs: &[ty::GenericArg<'tcx>],
631 if let Ok(has_params) =
632 tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
634 let (span, sugg) = if has_params {
635 let pos = span.hi() - BytePos(1);
636 let span = Span::new(pos, pos, span.ctxt(), span.parent());
637 (span, format!(", {} = {}", assoc.ident(tcx), ty))
639 let item_args = self.format_generic_args(assoc_substs);
640 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
642 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
648 pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
649 FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS)
650 .path_generic_args(Ok, args)
651 .expect("could not write to `String`.")