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(&self) -> 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(&self) -> 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(&self) -> 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(&self, 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",
221 (ty::FnPtr(_), ty::FnDef(def, _))
222 if let hir::def::DefKind::Fn = tcx.def_kind(def) => {
224 "when the arguments and return types match, functions can be coerced \
225 to function pointers",
231 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
233 values.expected.kind(),
239 // Watch out for various cases of cyclic types and try to explain.
240 if ty.is_closure() || ty.is_generator() {
242 "closures cannot capture themselves or take themselves as argument;\n\
243 this error may be the result of a recent compiler bug-fix,\n\
244 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
245 for more information",
249 TargetFeatureCast(def_id) => {
250 let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
252 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
254 diag.span_labels(target_spans, "`#[target_feature]` added here");
260 fn suggest_constraint(
262 diag: &mut Diagnostic,
264 body_owner_def_id: DefId,
265 proj_ty: &ty::AliasTy<'tcx>,
269 let assoc = tcx.associated_item(proj_ty.def_id);
270 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
271 if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) {
272 if let Some(hir_generics) = item.generics() {
273 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
274 // This will also work for `impl Trait`.
275 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
276 let generics = tcx.generics_of(body_owner_def_id);
277 generics.type_param(param_ty, tcx).def_id
281 let Some(def_id) = def_id.as_local() else {
285 // First look in the `where` clause, as this might be
286 // `fn foo<T>(x: T) where T: Trait`.
287 for pred in hir_generics.bounds_for_param(def_id) {
288 if self.constrain_generic_bound_associated_type_structured_suggestion(
306 /// An associated type was expected and a different type was found.
308 /// We perform a few different checks to see what we can suggest:
310 /// - In the current item, look for associated functions that return the expected type and
311 /// suggest calling them. (Not a structured suggestion.)
312 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
313 /// associated type to the found type.
314 /// - If the associated type has a default type and was expected inside of a `trait`, we
315 /// mention that this is disallowed.
316 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
317 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
318 /// fn that returns the type.
319 fn expected_projection(
321 diag: &mut Diagnostic,
322 proj_ty: &ty::AliasTy<'tcx>,
323 values: ExpectedFound<Ty<'tcx>>,
324 body_owner_def_id: DefId,
325 cause_code: &ObligationCauseCode<'_>,
330 "consider constraining the associated type `{}` to `{}`",
331 values.expected, values.found
333 let body_owner = tcx.hir().get_if_local(body_owner_def_id);
334 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
336 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
337 let callable_scope = matches!(
340 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
341 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
342 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
345 let impl_comparison =
346 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
347 let assoc = tcx.associated_item(proj_ty.def_id);
348 if !callable_scope || impl_comparison {
349 // We do not want to suggest calling functions when the reason of the
350 // type error is a comparison of an `impl` with its `trait` or when the
351 // scope is outside of a `Body`.
353 // If we find a suitable associated function that returns the expected type, we don't
354 // want the more general suggestion later in this method about "consider constraining
355 // the associated type or calling a method that returns the associated type".
356 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
358 assoc.container_id(tcx),
359 current_method_ident,
363 // Possibly suggest constraining the associated type to conform to the
365 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
372 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
374 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
378 if !impl_comparison {
379 // Generic suggestion when we can't be more specific.
382 "{} or calling a method that returns `{}`",
389 "for more information, visit \
390 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
393 if tcx.sess.teach(&diag.get_code().unwrap()) {
395 "given an associated type `T` and a method `foo`:
399 fn foo(&self) -> Self::T;
402 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
406 fn foo(&self) -> Self::T { String::new() }
413 /// When the expected `impl Trait` is not defined in the current item, it will come from
414 /// a return type. This can occur when dealing with `TryStream` (#71035).
415 fn suggest_constraining_opaque_associated_type(
417 diag: &mut Diagnostic,
419 proj_ty: &ty::AliasTy<'tcx>,
424 let assoc = tcx.associated_item(proj_ty.def_id);
425 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
426 let opaque_local_def_id = def_id.as_local();
427 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
428 match &tcx.hir().expect_item(opaque_local_def_id).kind {
429 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
430 _ => bug!("The HirId comes from a `ty::Opaque`"),
436 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx);
438 self.constrain_generic_bound_associated_type_structured_suggestion(
441 opaque_hir_ty.bounds,
453 fn point_at_methods_that_satisfy_associated_type(
455 diag: &mut Diagnostic,
456 assoc_container_id: DefId,
457 current_method_ident: Option<Symbol>,
458 proj_ty_item_def_id: DefId,
463 let items = tcx.associated_items(assoc_container_id);
464 // Find all the methods in the trait that could be called to construct the
465 // expected associated type.
466 // FIXME: consider suggesting the use of associated `const`s.
467 let methods: Vec<(Span, String)> = items
468 .in_definition_order()
470 ty::AssocKind::Fn == item.kind && Some(item.name) != current_method_ident
473 let method = tcx.fn_sig(item.def_id).subst_identity();
474 match *method.output().skip_binder().kind() {
475 ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
476 if item_def_id == proj_ty_item_def_id =>
479 tcx.def_span(item.def_id),
480 format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
487 if !methods.is_empty() {
488 // Use a single `help:` to show all the methods in the trait that can
489 // be used to construct the expected associated type.
490 let mut span: MultiSpan =
491 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
493 "{some} method{s} {are} available that return{r} `{ty}`",
494 some = if methods.len() == 1 { "a" } else { "some" },
495 s = pluralize!(methods.len()),
496 are = pluralize!("is", methods.len()),
497 r = if methods.len() == 1 { "s" } else { "" },
500 for (sp, label) in methods.into_iter() {
501 span.push_span_label(sp, label);
503 diag.span_help(span, &msg);
509 fn point_at_associated_type(
511 diag: &mut Diagnostic,
512 body_owner_def_id: DefId,
517 let Some(hir_id) = body_owner_def_id.as_local() else {
520 let hir_id = tcx.hir().local_def_id_to_hir_id(hir_id);
521 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
522 // `expected` and point at it.
523 let parent_id = tcx.hir().get_parent_item(hir_id);
524 let item = tcx.hir().find_by_def_id(parent_id.def_id);
526 debug!("expected_projection parent item {:?}", item);
528 let param_env = tcx.param_env(body_owner_def_id);
531 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
532 // FIXME: account for `#![feature(specialization)]`
533 for item in &items[..] {
535 hir::AssocItemKind::Type => {
536 // FIXME: account for returning some type in a trait fn impl that has
537 // an assoc type as a return type (#72076).
538 if let hir::Defaultness::Default { has_value: true } =
539 tcx.impl_defaultness(item.id.owner_id)
541 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
542 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
545 "associated type defaults can't be assumed inside the \
546 trait defining them",
556 Some(hir::Node::Item(hir::Item {
557 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
560 for item in &items[..] {
561 if let hir::AssocItemKind::Type = item.kind {
562 let assoc_ty = tcx.bound_type_of(item.id.owner_id).subst_identity();
564 if self.infcx.can_eq(param_env, assoc_ty, found).is_ok() {
565 diag.span_label(item.span, "expected this associated type");
576 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
577 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
579 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
580 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
581 /// trait bound as the one we're looking for. This can help in cases where the associated
582 /// type is defined on a supertrait of the one present in the bounds.
583 fn constrain_generic_bound_associated_type_structured_suggestion(
585 diag: &mut Diagnostic,
586 trait_ref: &ty::TraitRef<'tcx>,
587 bounds: hir::GenericBounds<'_>,
588 assoc: &ty::AssocItem,
589 assoc_substs: &[ty::GenericArg<'tcx>],
592 is_bound_surely_present: bool,
594 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
596 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
597 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
601 let matching_trait_bounds = trait_bounds
603 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
604 .collect::<Vec<_>>();
606 let span = match &matching_trait_bounds[..] {
608 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
615 self.constrain_associated_type_structured_suggestion(
625 /// Given a span corresponding to a bound, provide a structured suggestion to set an
626 /// associated type to a given type `ty`.
627 fn constrain_associated_type_structured_suggestion(
629 diag: &mut Diagnostic,
631 assoc: &ty::AssocItem,
632 assoc_substs: &[ty::GenericArg<'tcx>],
638 if let Ok(has_params) =
639 tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
641 let (span, sugg) = if has_params {
642 let pos = span.hi() - BytePos(1);
643 let span = Span::new(pos, pos, span.ctxt(), span.parent());
644 (span, format!(", {} = {}", assoc.ident(tcx), ty))
646 let item_args = self.format_generic_args(assoc_substs);
647 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
649 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
655 pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
656 FmtPrinter::new(self.tcx, hir::def::Namespace::TypeNS)
657 .path_generic_args(Ok, args)
658 .expect("could not write to `String`.")