1 use crate::traits::{ObligationCause, ObligationCauseCode};
2 use crate::ty::diagnostics::suggest_constraining_type_param;
3 use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, Printer};
4 use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt};
5 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
6 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
8 use rustc_hir::def::{CtorOf, DefKind};
9 use rustc_hir::def_id::DefId;
10 use rustc_span::symbol::{sym, Symbol};
11 use rustc_span::{BytePos, Span};
12 use rustc_target::spec::abi;
15 use std::collections::hash_map::DefaultHasher;
17 use std::hash::{Hash, Hasher};
18 use std::path::PathBuf;
20 use super::print::PrettyPrinter;
22 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable, Lift)]
23 pub struct ExpectedFound<T> {
28 impl<T> ExpectedFound<T> {
29 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
31 ExpectedFound { expected: a, found: b }
33 ExpectedFound { expected: b, found: a }
38 // Data structures used in type unification
39 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
40 #[rustc_pass_by_value]
41 pub enum TypeError<'tcx> {
43 ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
44 PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
45 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
46 AbiMismatch(ExpectedFound<abi::Abi>),
48 ArgumentMutability(usize),
49 TupleSize(ExpectedFound<usize>),
50 FixedArraySize(ExpectedFound<u64>),
52 FieldMisMatch(Symbol, Symbol),
54 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
55 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
56 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
57 RegionsPlaceholderMismatch,
59 Sorts(ExpectedFound<Ty<'tcx>>),
60 ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
61 IntMismatch(ExpectedFound<ty::IntVarValue>),
62 FloatMismatch(ExpectedFound<ty::FloatTy>),
63 Traits(ExpectedFound<DefId>),
64 VariadicMismatch(ExpectedFound<bool>),
66 /// Instantiating a type variable with the given type would have
67 /// created a cycle (because it appears somewhere within that
70 CyclicConst(ty::Const<'tcx>),
71 ProjectionMismatched(ExpectedFound<DefId>),
72 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
73 ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
76 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
77 TargetFeatureCast(DefId),
81 pub fn involves_regions(self) -> bool {
83 TypeError::RegionsDoesNotOutlive(_, _)
84 | TypeError::RegionsInsufficientlyPolymorphic(_, _)
85 | TypeError::RegionsOverlyPolymorphic(_, _)
86 | TypeError::RegionsPlaceholderMismatch => true,
92 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
93 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
94 /// afterwards to present additional details, particularly when it comes to lifetime-related
96 impl<'tcx> fmt::Display for TypeError<'tcx> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 use self::TypeError::*;
99 fn report_maybe_different(
100 f: &mut fmt::Formatter<'_>,
104 // A naive approach to making sure that we're not reporting silly errors such as:
105 // (expected closure, found closure).
106 if expected == found {
107 write!(f, "expected {}, found a different {}", expected, found)
109 write!(f, "expected {}, found {}", expected, found)
113 let br_string = |br: ty::BoundRegionKind| match br {
114 ty::BrNamed(_, name) => format!(" {}", name),
119 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
120 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
121 Mismatch => write!(f, "types differ"),
122 ConstnessMismatch(values) => {
123 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
125 PolarityMismatch(values) => {
126 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
128 UnsafetyMismatch(values) => {
129 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
131 AbiMismatch(values) => {
132 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
134 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
135 TupleSize(values) => write!(
137 "expected a tuple with {} element{}, found one with {} element{}",
139 pluralize!(values.expected),
141 pluralize!(values.found)
143 FixedArraySize(values) => write!(
145 "expected an array with a fixed size of {} element{}, found one with {} element{}",
147 pluralize!(values.expected),
149 pluralize!(values.found)
151 ArgCount => write!(f, "incorrect number of function parameters"),
152 FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
153 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
154 // Actually naming the region here is a bit confusing because context is lacking
155 RegionsInsufficientlyPolymorphic(..) => {
156 write!(f, "one type is more general than the other")
158 RegionsOverlyPolymorphic(br, _) => write!(
160 "expected concrete lifetime, found bound lifetime parameter{}",
163 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
164 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
165 let (mut expected, mut found) = with_forced_trimmed_paths!((
166 values.expected.sort_string(tcx),
167 values.found.sort_string(tcx),
169 if expected == found {
170 expected = values.expected.sort_string(tcx);
171 found = values.found.sort_string(tcx);
173 report_maybe_different(f, &expected, &found)
175 Traits(values) => ty::tls::with(|tcx| {
176 let (mut expected, mut found) = with_forced_trimmed_paths!((
177 tcx.def_path_str(values.expected),
178 tcx.def_path_str(values.found),
180 if expected == found {
181 expected = tcx.def_path_str(values.expected);
182 found = tcx.def_path_str(values.found);
184 report_maybe_different(
186 &format!("trait `{expected}`"),
187 &format!("trait `{found}`"),
190 IntMismatch(ref values) => {
191 let expected = match values.expected {
192 ty::IntVarValue::IntType(ty) => ty.name_str(),
193 ty::IntVarValue::UintType(ty) => ty.name_str(),
195 let found = match values.found {
196 ty::IntVarValue::IntType(ty) => ty.name_str(),
197 ty::IntVarValue::UintType(ty) => ty.name_str(),
199 write!(f, "expected `{}`, found `{}`", expected, found)
201 FloatMismatch(ref values) => {
204 "expected `{}`, found `{}`",
205 values.expected.name_str(),
206 values.found.name_str()
209 VariadicMismatch(ref values) => write!(
211 "expected {} fn, found {} function",
212 if values.expected { "variadic" } else { "non-variadic" },
213 if values.found { "variadic" } else { "non-variadic" }
215 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
218 "expected {}, found {}",
219 tcx.def_path_str(values.expected),
220 tcx.def_path_str(values.found)
223 ExistentialMismatch(ref values) => report_maybe_different(
225 &format!("trait `{}`", values.expected),
226 &format!("trait `{}`", values.found),
228 ConstMismatch(ref values) => {
229 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
231 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
232 TargetFeatureCast(_) => write!(
234 "cannot coerce functions with `#[target_feature]` to safe function pointers"
240 impl<'tcx> TypeError<'tcx> {
241 pub fn must_include_note(self) -> bool {
242 use self::TypeError::*;
244 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
245 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
246 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
247 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
250 | ArgumentMutability(_)
254 | RegionsDoesNotOutlive(..)
255 | RegionsInsufficientlyPolymorphic(..)
256 | RegionsOverlyPolymorphic(..)
257 | RegionsPlaceholderMismatch
259 | ProjectionMismatched(_)
260 | ExistentialMismatch(_)
262 | IntrinsicCast => true,
267 impl<'tcx> Ty<'tcx> {
268 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
270 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
271 format!("`{}`", self).into()
273 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
275 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
276 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
278 if t.is_simple_ty() {
279 return format!("array `{}`", self).into();
282 let n = tcx.lift(n).unwrap();
283 if let ty::ConstKind::Value(v) = n.kind() {
284 if let Some(n) = v.try_to_machine_usize(tcx) {
285 return format!("array of {} element{}", n, pluralize!(n)).into();
290 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
291 ty::Slice(_) => "slice".into(),
292 ty::RawPtr(tymut) => {
293 let tymut_string = match tymut.mutbl {
294 hir::Mutability::Mut => tymut.to_string(),
295 hir::Mutability::Not => format!("const {}", tymut.ty),
298 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
299 format!("`*{}`", tymut_string).into()
301 // Unknown type name, it's long or has type arguments
305 ty::Ref(_, ty, mutbl) => {
306 let tymut = ty::TypeAndMut { ty, mutbl };
307 let tymut_string = tymut.to_string();
309 if tymut_string != "_"
310 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
312 format!("`&{}`", tymut_string).into()
314 // Unknown type name, it's long or has type arguments
316 hir::Mutability::Mut => "mutable reference",
322 ty::FnDef(def_id, ..) => match tcx.def_kind(def_id) {
323 DefKind::Ctor(CtorOf::Struct, _) => "struct constructor".into(),
324 DefKind::Ctor(CtorOf::Variant, _) => "enum constructor".into(),
325 _ => "fn item".into(),
327 ty::FnPtr(_) => "fn pointer".into(),
328 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
329 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
331 ty::Dynamic(..) => "trait object".into(),
332 ty::Closure(..) => "closure".into(),
333 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
334 ty::GeneratorWitness(..) => "generator witness".into(),
335 ty::Tuple(..) => "tuple".into(),
336 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
337 ty::Infer(ty::IntVar(_)) => "integer".into(),
338 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
339 ty::Placeholder(..) => "placeholder type".into(),
340 ty::Bound(..) => "bound type".into(),
341 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
342 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
343 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
344 ty::Alias(ty::Projection, _) => "associated type".into(),
345 ty::Param(p) => format!("type parameter `{}`", p).into(),
346 ty::Alias(ty::Opaque, ..) => "opaque type".into(),
347 ty::Error(_) => "type error".into(),
351 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
361 | ty::Never => "type".into(),
362 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
363 ty::Adt(def, _) => def.descr().into(),
364 ty::Foreign(_) => "extern type".into(),
365 ty::Array(..) => "array".into(),
366 ty::Slice(_) => "slice".into(),
367 ty::RawPtr(_) => "raw pointer".into(),
368 ty::Ref(.., mutbl) => match mutbl {
369 hir::Mutability::Mut => "mutable reference",
373 ty::FnDef(def_id, ..) => match tcx.def_kind(def_id) {
374 DefKind::Ctor(CtorOf::Struct, _) => "struct constructor".into(),
375 DefKind::Ctor(CtorOf::Variant, _) => "enum constructor".into(),
376 _ => "fn item".into(),
378 ty::FnPtr(_) => "fn pointer".into(),
379 ty::Dynamic(..) => "trait object".into(),
380 ty::Closure(..) => "closure".into(),
381 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
382 ty::GeneratorWitness(..) => "generator witness".into(),
383 ty::Tuple(..) => "tuple".into(),
384 ty::Placeholder(..) => "higher-ranked type".into(),
385 ty::Bound(..) => "bound type variable".into(),
386 ty::Alias(ty::Projection, _) => "associated type".into(),
387 ty::Param(_) => "type parameter".into(),
388 ty::Alias(ty::Opaque, ..) => "opaque type".into(),
393 impl<'tcx> TyCtxt<'tcx> {
394 pub fn note_and_explain_type_err(
396 diag: &mut Diagnostic,
397 err: TypeError<'tcx>,
398 cause: &ObligationCause<'tcx>,
400 body_owner_def_id: DefId,
402 use self::TypeError::*;
403 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
405 ArgumentSorts(values, _) | Sorts(values) => {
406 match (values.expected.kind(), values.found.kind()) {
407 (ty::Closure(..), ty::Closure(..)) => {
408 diag.note("no two closures, even if identical, have the same type");
409 diag.help("consider boxing your closure and/or using it as a trait object");
411 (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
413 diag.note("distinct uses of `impl Trait` result in different opaque types");
415 (ty::Float(_), ty::Infer(ty::IntVar(_)))
419 ) = self.sess.source_map().span_to_snippet(sp) =>
421 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
422 diag.span_suggestion(
424 "use a float literal",
425 format!("{}.0", snippet),
430 (ty::Param(expected), ty::Param(found)) => {
431 let generics = self.generics_of(body_owner_def_id);
432 let e_span = self.def_span(generics.type_param(expected, self).def_id);
433 if !sp.contains(e_span) {
434 diag.span_label(e_span, "expected type parameter");
436 let f_span = self.def_span(generics.type_param(found, self).def_id);
437 if !sp.contains(f_span) {
438 diag.span_label(f_span, "found type parameter");
441 "a type parameter was expected, but a different one was found; \
442 you might be missing a type parameter or trait bound",
445 "for more information, visit \
446 https://doc.rust-lang.org/book/ch10-02-traits.html\
447 #traits-as-parameters",
450 (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => {
451 diag.note("an associated type was expected, but a different one was found");
453 (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p))
454 if self.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder =>
456 let generics = self.generics_of(body_owner_def_id);
457 let p_span = self.def_span(generics.type_param(p, self).def_id);
458 if !sp.contains(p_span) {
459 diag.span_label(p_span, "this type parameter");
461 let hir = self.hir();
463 if let Some(generics) = generics
467 .map(|id| hir.local_def_id_to_hir_id(id))
468 .and_then(|id| self.hir().find_parent(id))
470 .and_then(|node| node.generics())
472 // Synthesize the associated type restriction `Add<Output = Expected>`.
473 // FIXME: extract this logic for use in other diagnostics.
474 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
476 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
477 let item_name = self.item_name(proj.def_id);
478 let item_args = self.format_generic_args(assoc_substs);
480 let path = if path.ends_with('>') {
483 &path[..path.len() - 1],
489 format!("{}<{}{} = {}>", path, item_name, item_args, p)
491 note = !suggest_constraining_type_param(
495 &format!("{}", proj.self_ty()),
501 diag.note("you might be missing a type parameter or trait bound");
504 (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
505 | (ty::Dynamic(..) | ty::Alias(ty::Opaque, ..), ty::Param(p)) => {
506 let generics = self.generics_of(body_owner_def_id);
507 let p_span = self.def_span(generics.type_param(p, self).def_id);
508 if !sp.contains(p_span) {
509 diag.span_label(p_span, "this type parameter");
511 diag.help("type parameters must be constrained to match other types");
512 if self.sess.teach(&diag.get_code().unwrap()) {
514 "given a type parameter `T` and a method `foo`:
516 trait Trait<T> { fn foo(&self) -> T; }
518 the only ways to implement method `foo` are:
519 - constrain `T` with an explicit type:
521 impl Trait<String> for X {
522 fn foo(&self) -> String { String::new() }
525 - add a trait bound to `T` and call a method on that trait that returns `Self`:
527 impl<T: std::default::Default> Trait<T> for X {
528 fn foo(&self) -> T { <T as std::default::Default>::default() }
531 - change `foo` to return an argument of type `T`:
533 impl<T> Trait<T> for X {
534 fn foo(&self, x: T) -> T { x }
540 "for more information, visit \
541 https://doc.rust-lang.org/book/ch10-02-traits.html\
542 #traits-as-parameters",
545 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
546 let generics = self.generics_of(body_owner_def_id);
547 let p_span = self.def_span(generics.type_param(p, self).def_id);
548 if !sp.contains(p_span) {
549 diag.span_label(p_span, "this type parameter");
552 "every closure has a distinct type and so could not always match the \
553 caller-chosen type of parameter `{}`",
557 (ty::Param(p), _) | (_, ty::Param(p)) => {
558 let generics = self.generics_of(body_owner_def_id);
559 let p_span = self.def_span(generics.type_param(p, self).def_id);
560 if !sp.contains(p_span) {
561 diag.span_label(p_span, "this type parameter");
564 (ty::Alias(ty::Projection, proj_ty), _) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
565 self.expected_projection(
573 (_, ty::Alias(ty::Projection, proj_ty)) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
575 "consider constraining the associated type `{}` to `{}`",
576 values.found, values.expected,
578 if !(self.suggest_constraining_opaque_associated_type(
583 ) || self.suggest_constraint(
592 "for more information, visit \
593 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
600 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
602 values.expected.kind(),
608 // Watch out for various cases of cyclic types and try to explain.
609 if ty.is_closure() || ty.is_generator() {
611 "closures cannot capture themselves or take themselves as argument;\n\
612 this error may be the result of a recent compiler bug-fix,\n\
613 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
614 for more information",
618 TargetFeatureCast(def_id) => {
620 self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
622 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
624 diag.span_labels(target_spans, "`#[target_feature]` added here");
630 fn suggest_constraint(
632 diag: &mut Diagnostic,
634 body_owner_def_id: DefId,
635 proj_ty: &ty::AliasTy<'tcx>,
638 let assoc = self.associated_item(proj_ty.def_id);
639 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
640 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
641 if let Some(hir_generics) = item.generics() {
642 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
643 // This will also work for `impl Trait`.
644 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
645 let generics = self.generics_of(body_owner_def_id);
646 generics.type_param(param_ty, self).def_id
650 let Some(def_id) = def_id.as_local() else {
654 // First look in the `where` clause, as this might be
655 // `fn foo<T>(x: T) where T: Trait`.
656 for pred in hir_generics.bounds_for_param(def_id) {
657 if self.constrain_generic_bound_associated_type_structured_suggestion(
675 /// An associated type was expected and a different type was found.
677 /// We perform a few different checks to see what we can suggest:
679 /// - In the current item, look for associated functions that return the expected type and
680 /// suggest calling them. (Not a structured suggestion.)
681 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
682 /// associated type to the found type.
683 /// - If the associated type has a default type and was expected inside of a `trait`, we
684 /// mention that this is disallowed.
685 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
686 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
687 /// fn that returns the type.
688 fn expected_projection(
690 diag: &mut Diagnostic,
691 proj_ty: &ty::AliasTy<'tcx>,
692 values: ExpectedFound<Ty<'tcx>>,
693 body_owner_def_id: DefId,
694 cause_code: &ObligationCauseCode<'_>,
697 "consider constraining the associated type `{}` to `{}`",
698 values.expected, values.found
700 let body_owner = self.hir().get_if_local(body_owner_def_id);
701 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
703 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
704 let callable_scope = matches!(
707 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
708 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
709 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
712 let impl_comparison =
713 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
714 let assoc = self.associated_item(proj_ty.def_id);
715 if !callable_scope || impl_comparison {
716 // We do not want to suggest calling functions when the reason of the
717 // type error is a comparison of an `impl` with its `trait` or when the
718 // scope is outside of a `Body`.
720 // If we find a suitable associated function that returns the expected type, we don't
721 // want the more general suggestion later in this method about "consider constraining
722 // the associated type or calling a method that returns the associated type".
723 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
725 assoc.container_id(self),
726 current_method_ident,
730 // Possibly suggest constraining the associated type to conform to the
732 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
739 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
741 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
745 if !impl_comparison {
746 // Generic suggestion when we can't be more specific.
749 "{} or calling a method that returns `{}`",
756 "for more information, visit \
757 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
760 if self.sess.teach(&diag.get_code().unwrap()) {
762 "given an associated type `T` and a method `foo`:
766 fn foo(&self) -> Self::T;
769 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
773 fn foo(&self) -> Self::T { String::new() }
780 /// When the expected `impl Trait` is not defined in the current item, it will come from
781 /// a return type. This can occur when dealing with `TryStream` (#71035).
782 fn suggest_constraining_opaque_associated_type(
784 diag: &mut Diagnostic,
786 proj_ty: &ty::AliasTy<'tcx>,
789 let assoc = self.associated_item(proj_ty.def_id);
790 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() {
791 let opaque_local_def_id = def_id.as_local();
792 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
793 match &self.hir().expect_item(opaque_local_def_id).kind {
794 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
795 _ => bug!("The HirId comes from a `ty::Opaque`"),
801 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
803 self.constrain_generic_bound_associated_type_structured_suggestion(
806 opaque_hir_ty.bounds,
818 fn point_at_methods_that_satisfy_associated_type(
820 diag: &mut Diagnostic,
821 assoc_container_id: DefId,
822 current_method_ident: Option<Symbol>,
823 proj_ty_item_def_id: DefId,
826 let items = self.associated_items(assoc_container_id);
827 // Find all the methods in the trait that could be called to construct the
828 // expected associated type.
829 // FIXME: consider suggesting the use of associated `const`s.
830 let methods: Vec<(Span, String)> = items
833 .filter(|(name, item)| {
834 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
836 .filter_map(|(_, item)| {
837 let method = self.fn_sig(item.def_id);
838 match *method.output().skip_binder().kind() {
839 ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
840 if item_def_id == proj_ty_item_def_id =>
843 self.def_span(item.def_id),
844 format!("consider calling `{}`", self.def_path_str(item.def_id)),
851 if !methods.is_empty() {
852 // Use a single `help:` to show all the methods in the trait that can
853 // be used to construct the expected associated type.
854 let mut span: MultiSpan =
855 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
857 "{some} method{s} {are} available that return{r} `{ty}`",
858 some = if methods.len() == 1 { "a" } else { "some" },
859 s = pluralize!(methods.len()),
860 are = pluralize!("is", methods.len()),
861 r = if methods.len() == 1 { "s" } else { "" },
864 for (sp, label) in methods.into_iter() {
865 span.push_span_label(sp, label);
867 diag.span_help(span, &msg);
873 fn point_at_associated_type(
875 diag: &mut Diagnostic,
876 body_owner_def_id: DefId,
879 let Some(hir_id) = body_owner_def_id.as_local() else {
882 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
883 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
884 // `expected` and point at it.
885 let parent_id = self.hir().get_parent_item(hir_id);
886 let item = self.hir().find_by_def_id(parent_id.def_id);
887 debug!("expected_projection parent item {:?}", item);
889 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
890 // FIXME: account for `#![feature(specialization)]`
891 for item in &items[..] {
893 hir::AssocItemKind::Type => {
894 // FIXME: account for returning some type in a trait fn impl that has
895 // an assoc type as a return type (#72076).
896 if let hir::Defaultness::Default { has_value: true } =
897 self.impl_defaultness(item.id.owner_id)
899 if self.type_of(item.id.owner_id) == found {
902 "associated type defaults can't be assumed inside the \
903 trait defining them",
913 Some(hir::Node::Item(hir::Item {
914 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
917 for item in &items[..] {
918 if let hir::AssocItemKind::Type = item.kind {
919 if self.type_of(item.id.owner_id) == found {
920 diag.span_label(item.span, "expected this associated type");
931 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
932 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
934 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
935 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
936 /// trait bound as the one we're looking for. This can help in cases where the associated
937 /// type is defined on a supertrait of the one present in the bounds.
938 fn constrain_generic_bound_associated_type_structured_suggestion(
940 diag: &mut Diagnostic,
941 trait_ref: &ty::TraitRef<'tcx>,
942 bounds: hir::GenericBounds<'_>,
943 assoc: &ty::AssocItem,
944 assoc_substs: &[ty::GenericArg<'tcx>],
947 is_bound_surely_present: bool,
949 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
951 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
952 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
956 let matching_trait_bounds = trait_bounds
958 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
959 .collect::<Vec<_>>();
961 let span = match &matching_trait_bounds[..] {
963 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
970 self.constrain_associated_type_structured_suggestion(
980 /// Given a span corresponding to a bound, provide a structured suggestion to set an
981 /// associated type to a given type `ty`.
982 fn constrain_associated_type_structured_suggestion(
984 diag: &mut Diagnostic,
986 assoc: &ty::AssocItem,
987 assoc_substs: &[ty::GenericArg<'tcx>],
991 if let Ok(has_params) =
992 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
994 let (span, sugg) = if has_params {
995 let pos = span.hi() - BytePos(1);
996 let span = Span::new(pos, pos, span.ctxt(), span.parent());
997 (span, format!(", {} = {}", assoc.ident(self), ty))
999 let item_args = self.format_generic_args(assoc_substs);
1000 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
1002 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
1008 pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) {
1009 let width = self.sess.diagnostic_width();
1010 let length_limit = width.saturating_sub(30);
1011 let mut type_limit = 50;
1012 let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1013 .pretty_print_type(ty)
1014 .expect("could not write to `String`")
1016 if regular.len() <= width {
1017 return (regular, None);
1021 // Look for the longest properly trimmed path that still fits in length_limit.
1022 short = with_forced_trimmed_paths!(
1023 FmtPrinter::new_with_limit(
1025 hir::def::Namespace::TypeNS,
1026 rustc_session::Limit(type_limit),
1028 .pretty_print_type(ty)
1029 .expect("could not write to `String`")
1032 if short.len() <= length_limit || type_limit == 0 {
1037 if regular == short {
1038 return (regular, None);
1040 // Multiple types might be shortened in a single error, ensure we create a file for each.
1041 let mut s = DefaultHasher::new();
1043 let hash = s.finish();
1044 let path = self.output_filenames(()).temp_path_ext(&format!("long-type-{hash}.txt"), None);
1045 match std::fs::write(&path, ®ular) {
1046 Ok(_) => (short, Some(path)),
1047 Err(_) => (regular, None),
1051 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
1052 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1053 .path_generic_args(Ok, args)
1054 .expect("could not write to `String`.")