1 use crate::traits::{ObligationCause, ObligationCauseCode};
2 use crate::ty::diagnostics::suggest_constraining_type_param;
3 use crate::ty::print::{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_id::DefId;
9 use rustc_span::symbol::{sym, Symbol};
10 use rustc_span::{BytePos, Span};
11 use rustc_target::spec::abi;
16 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
17 pub struct ExpectedFound<T> {
22 impl<T> ExpectedFound<T> {
23 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
25 ExpectedFound { expected: a, found: b }
27 ExpectedFound { expected: b, found: a }
32 // Data structures used in type unification
33 #[derive(Clone, Debug, TypeFoldable)]
34 pub enum TypeError<'tcx> {
36 ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
37 PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
38 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
39 AbiMismatch(ExpectedFound<abi::Abi>),
41 ArgumentMutability(usize),
42 TupleSize(ExpectedFound<usize>),
43 FixedArraySize(ExpectedFound<u64>),
45 FieldMisMatch(Symbol, Symbol),
47 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
48 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
49 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
50 RegionsPlaceholderMismatch,
52 Sorts(ExpectedFound<Ty<'tcx>>),
53 ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
54 IntMismatch(ExpectedFound<ty::IntVarValue>),
55 FloatMismatch(ExpectedFound<ty::FloatTy>),
56 Traits(ExpectedFound<DefId>),
57 VariadicMismatch(ExpectedFound<bool>),
59 /// Instantiating a type variable with the given type would have
60 /// created a cycle (because it appears somewhere within that
63 CyclicConst(ty::Const<'tcx>),
64 ProjectionMismatched(ExpectedFound<DefId>),
66 ExpectedFound<&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>>,
68 ObjectUnsafeCoercion(DefId),
69 ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
72 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
73 TargetFeatureCast(DefId),
76 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
77 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
78 /// afterwards to present additional details, particularly when it comes to lifetime-related
80 impl<'tcx> fmt::Display for TypeError<'tcx> {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 use self::TypeError::*;
83 fn report_maybe_different(
84 f: &mut fmt::Formatter<'_>,
88 // A naive approach to making sure that we're not reporting silly errors such as:
89 // (expected closure, found closure).
90 if expected == found {
91 write!(f, "expected {}, found a different {}", expected, found)
93 write!(f, "expected {}, found {}", expected, found)
97 let br_string = |br: ty::BoundRegionKind| match br {
98 ty::BrNamed(_, name) => format!(" {}", name),
103 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
104 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
105 Mismatch => write!(f, "types differ"),
106 ConstnessMismatch(values) => {
107 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
109 PolarityMismatch(values) => {
110 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
112 UnsafetyMismatch(values) => {
113 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
115 AbiMismatch(values) => {
116 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
118 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
119 TupleSize(values) => write!(
121 "expected a tuple with {} element{}, found one with {} element{}",
123 pluralize!(values.expected),
125 pluralize!(values.found)
127 FixedArraySize(values) => write!(
129 "expected an array with a fixed size of {} element{}, found one with {} element{}",
131 pluralize!(values.expected),
133 pluralize!(values.found)
135 ArgCount => write!(f, "incorrect number of function parameters"),
136 FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
137 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
138 RegionsInsufficientlyPolymorphic(br, _) => write!(
140 "expected bound lifetime parameter{}, found concrete lifetime",
143 RegionsOverlyPolymorphic(br, _) => write!(
145 "expected concrete lifetime, found bound lifetime parameter{}",
148 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
149 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
150 report_maybe_different(
152 &values.expected.sort_string(tcx),
153 &values.found.sort_string(tcx),
156 Traits(values) => ty::tls::with(|tcx| {
157 report_maybe_different(
159 &format!("trait `{}`", tcx.def_path_str(values.expected)),
160 &format!("trait `{}`", tcx.def_path_str(values.found)),
163 IntMismatch(ref values) => {
164 let expected = match values.expected {
165 ty::IntVarValue::IntType(ty) => ty.name_str(),
166 ty::IntVarValue::UintType(ty) => ty.name_str(),
168 let found = match values.found {
169 ty::IntVarValue::IntType(ty) => ty.name_str(),
170 ty::IntVarValue::UintType(ty) => ty.name_str(),
172 write!(f, "expected `{}`, found `{}`", expected, found)
174 FloatMismatch(ref values) => {
177 "expected `{}`, found `{}`",
178 values.expected.name_str(),
179 values.found.name_str()
182 VariadicMismatch(ref values) => write!(
184 "expected {} fn, found {} function",
185 if values.expected { "variadic" } else { "non-variadic" },
186 if values.found { "variadic" } else { "non-variadic" }
188 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
191 "expected {}, found {}",
192 tcx.def_path_str(values.expected),
193 tcx.def_path_str(values.found)
196 ExistentialMismatch(ref values) => report_maybe_different(
198 &format!("trait `{}`", values.expected),
199 &format!("trait `{}`", values.found),
201 ConstMismatch(ref values) => {
202 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
204 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
205 TargetFeatureCast(_) => write!(
207 "cannot coerce functions with `#[target_feature]` to safe function pointers"
209 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
214 impl<'tcx> TypeError<'tcx> {
215 pub fn must_include_note(&self) -> bool {
216 use self::TypeError::*;
218 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
219 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
220 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
221 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
224 | ArgumentMutability(_)
228 | RegionsDoesNotOutlive(..)
229 | RegionsInsufficientlyPolymorphic(..)
230 | RegionsOverlyPolymorphic(..)
231 | RegionsPlaceholderMismatch
233 | ProjectionMismatched(_)
234 | ExistentialMismatch(_)
237 | ObjectUnsafeCoercion(_) => true,
242 impl<'tcx> Ty<'tcx> {
243 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
245 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
246 format!("`{}`", self).into()
248 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
250 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
251 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
253 if t.is_simple_ty() {
254 return format!("array `{}`", self).into();
257 let n = tcx.lift(n).unwrap();
258 if let ty::ConstKind::Value(v) = n.val() {
259 if let Some(n) = v.try_to_machine_usize(tcx) {
260 return format!("array of {} element{}", n, pluralize!(n)).into();
265 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
266 ty::Slice(_) => "slice".into(),
267 ty::RawPtr(_) => "*-ptr".into(),
268 ty::Ref(_, ty, mutbl) => {
269 let tymut = ty::TypeAndMut { ty, mutbl };
270 let tymut_string = tymut.to_string();
271 if tymut_string != "_"
272 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
274 format!("`&{}`", tymut_string).into()
276 // Unknown type name, it's long or has type arguments
278 hir::Mutability::Mut => "mutable reference",
284 ty::FnDef(..) => "fn item".into(),
285 ty::FnPtr(_) => "fn pointer".into(),
286 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
287 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
289 ty::Dynamic(..) => "trait object".into(),
290 ty::Closure(..) => "closure".into(),
291 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
292 ty::GeneratorWitness(..) => "generator witness".into(),
293 ty::Tuple(..) => "tuple".into(),
294 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
295 ty::Infer(ty::IntVar(_)) => "integer".into(),
296 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
297 ty::Placeholder(..) => "placeholder type".into(),
298 ty::Bound(..) => "bound type".into(),
299 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
300 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
301 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
302 ty::Projection(_) => "associated type".into(),
303 ty::Param(p) => format!("type parameter `{}`", p).into(),
304 ty::Opaque(..) => "opaque type".into(),
305 ty::Error(_) => "type error".into(),
309 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
319 | ty::Never => "type".into(),
320 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
321 ty::Adt(def, _) => def.descr().into(),
322 ty::Foreign(_) => "extern type".into(),
323 ty::Array(..) => "array".into(),
324 ty::Slice(_) => "slice".into(),
325 ty::RawPtr(_) => "raw pointer".into(),
326 ty::Ref(.., mutbl) => match mutbl {
327 hir::Mutability::Mut => "mutable reference",
331 ty::FnDef(..) => "fn item".into(),
332 ty::FnPtr(_) => "fn pointer".into(),
333 ty::Dynamic(..) => "trait object".into(),
334 ty::Closure(..) => "closure".into(),
335 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
336 ty::GeneratorWitness(..) => "generator witness".into(),
337 ty::Tuple(..) => "tuple".into(),
338 ty::Placeholder(..) => "higher-ranked type".into(),
339 ty::Bound(..) => "bound type variable".into(),
340 ty::Projection(_) => "associated type".into(),
341 ty::Param(_) => "type parameter".into(),
342 ty::Opaque(..) => "opaque type".into(),
347 impl<'tcx> TyCtxt<'tcx> {
348 pub fn note_and_explain_type_err(
350 diag: &mut Diagnostic,
351 err: &TypeError<'tcx>,
352 cause: &ObligationCause<'tcx>,
354 body_owner_def_id: DefId,
356 use self::TypeError::*;
357 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
359 ArgumentSorts(values, _) | Sorts(values) => {
360 match (values.expected.kind(), values.found.kind()) {
361 (ty::Closure(..), ty::Closure(..)) => {
362 diag.note("no two closures, even if identical, have the same type");
363 diag.help("consider boxing your closure and/or using it as a trait object");
365 (ty::Opaque(..), ty::Opaque(..)) => {
367 diag.note("distinct uses of `impl Trait` result in different opaque types");
369 (ty::Float(_), ty::Infer(ty::IntVar(_)))
373 ) = self.sess.source_map().span_to_snippet(sp) =>
375 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
376 diag.span_suggestion(
378 "use a float literal",
379 format!("{}.0", snippet),
384 (ty::Param(expected), ty::Param(found)) => {
385 let generics = self.generics_of(body_owner_def_id);
386 let e_span = self.def_span(generics.type_param(expected, self).def_id);
387 if !sp.contains(e_span) {
388 diag.span_label(e_span, "expected type parameter");
390 let f_span = self.def_span(generics.type_param(found, self).def_id);
391 if !sp.contains(f_span) {
392 diag.span_label(f_span, "found type parameter");
395 "a type parameter was expected, but a different one was found; \
396 you might be missing a type parameter or trait bound",
399 "for more information, visit \
400 https://doc.rust-lang.org/book/ch10-02-traits.html\
401 #traits-as-parameters",
404 (ty::Projection(_), ty::Projection(_)) => {
405 diag.note("an associated type was expected, but a different one was found");
407 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
408 let generics = self.generics_of(body_owner_def_id);
409 let p_span = self.def_span(generics.type_param(p, self).def_id);
410 if !sp.contains(p_span) {
411 diag.span_label(p_span, "this type parameter");
413 let hir = self.hir();
415 if let Some(generics) = generics
419 .map(|id| hir.local_def_id_to_hir_id(id))
420 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
422 .and_then(|node| node.generics())
424 // Synthesize the associated type restriction `Add<Output = Expected>`.
425 // FIXME: extract this logic for use in other diagnostics.
426 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
428 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
429 let item_name = self.item_name(proj.item_def_id);
430 let item_args = self.format_generic_args(assoc_substs);
432 let path = if path.ends_with('>') {
435 &path[..path.len() - 1],
441 format!("{}<{}{} = {}>", path, item_name, item_args, p)
443 note = !suggest_constraining_type_param(
447 &format!("{}", proj.self_ty()),
453 diag.note("you might be missing a type parameter or trait bound");
456 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
457 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
458 let generics = self.generics_of(body_owner_def_id);
459 let p_span = self.def_span(generics.type_param(p, self).def_id);
460 if !sp.contains(p_span) {
461 diag.span_label(p_span, "this type parameter");
463 diag.help("type parameters must be constrained to match other types");
464 if self.sess.teach(&diag.get_code().unwrap()) {
466 "given a type parameter `T` and a method `foo`:
468 trait Trait<T> { fn foo(&self) -> T; }
470 the only ways to implement method `foo` are:
471 - constrain `T` with an explicit type:
473 impl Trait<String> for X {
474 fn foo(&self) -> String { String::new() }
477 - add a trait bound to `T` and call a method on that trait that returns `Self`:
479 impl<T: std::default::Default> Trait<T> for X {
480 fn foo(&self) -> T { <T as std::default::Default>::default() }
483 - change `foo` to return an argument of type `T`:
485 impl<T> Trait<T> for X {
486 fn foo(&self, x: T) -> T { x }
492 "for more information, visit \
493 https://doc.rust-lang.org/book/ch10-02-traits.html\
494 #traits-as-parameters",
497 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
498 let generics = self.generics_of(body_owner_def_id);
499 let p_span = self.def_span(generics.type_param(p, self).def_id);
500 if !sp.contains(p_span) {
501 diag.span_label(p_span, "this type parameter");
504 "every closure has a distinct type and so could not always match the \
505 caller-chosen type of parameter `{}`",
509 (ty::Param(p), _) | (_, ty::Param(p)) => {
510 let generics = self.generics_of(body_owner_def_id);
511 let p_span = self.def_span(generics.type_param(p, self).def_id);
512 if !sp.contains(p_span) {
513 diag.span_label(p_span, "this type parameter");
516 (ty::Projection(proj_ty), _) => {
517 self.expected_projection(
525 (_, ty::Projection(proj_ty)) => {
527 "consider constraining the associated type `{}` to `{}`",
528 values.found, values.expected,
530 if !(self.suggest_constraining_opaque_associated_type(
535 ) || self.suggest_constraint(
544 "for more information, visit \
545 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
552 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
554 values.expected.kind(),
560 // Watch out for various cases of cyclic types and try to explain.
561 if ty.is_closure() || ty.is_generator() {
563 "closures cannot capture themselves or take themselves as argument;\n\
564 this error may be the result of a recent compiler bug-fix,\n\
565 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
566 for more information",
570 TargetFeatureCast(def_id) => {
571 let attrs = self.get_attrs(*def_id);
572 let target_spans = attrs
574 .filter(|attr| attr.has_name(sym::target_feature))
575 .map(|attr| attr.span);
577 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
579 diag.span_labels(target_spans, "`#[target_feature]` added here");
585 fn suggest_constraint(
587 diag: &mut Diagnostic,
589 body_owner_def_id: DefId,
590 proj_ty: &ty::ProjectionTy<'tcx>,
593 let assoc = self.associated_item(proj_ty.item_def_id);
594 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
595 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
596 if let Some(hir_generics) = item.generics() {
597 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
598 // This will also work for `impl Trait`.
599 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
600 let generics = self.generics_of(body_owner_def_id);
601 generics.type_param(param_ty, self).def_id
605 let Some(def_id) = def_id.as_local() else {
609 // First look in the `where` clause, as this might be
610 // `fn foo<T>(x: T) where T: Trait`.
611 for pred in hir_generics.bounds_for_param(def_id) {
612 if self.constrain_generic_bound_associated_type_structured_suggestion(
630 /// An associated type was expected and a different type was found.
632 /// We perform a few different checks to see what we can suggest:
634 /// - In the current item, look for associated functions that return the expected type and
635 /// suggest calling them. (Not a structured suggestion.)
636 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
637 /// associated type to the found type.
638 /// - If the associated type has a default type and was expected inside of a `trait`, we
639 /// mention that this is disallowed.
640 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
641 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
642 /// fn that returns the type.
643 fn expected_projection(
645 diag: &mut Diagnostic,
646 proj_ty: &ty::ProjectionTy<'tcx>,
647 values: &ExpectedFound<Ty<'tcx>>,
648 body_owner_def_id: DefId,
649 cause_code: &ObligationCauseCode<'_>,
652 "consider constraining the associated type `{}` to `{}`",
653 values.expected, values.found
655 let body_owner = self.hir().get_if_local(body_owner_def_id);
656 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
658 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
659 let callable_scope = matches!(
662 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
663 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
664 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
667 let impl_comparison = matches!(
669 ObligationCauseCode::CompareImplMethodObligation { .. }
670 | ObligationCauseCode::CompareImplTypeObligation { .. }
671 | ObligationCauseCode::CompareImplConstObligation
673 let assoc = self.associated_item(proj_ty.item_def_id);
674 if !callable_scope || impl_comparison {
675 // We do not want to suggest calling functions when the reason of the
676 // type error is a comparison of an `impl` with its `trait` or when the
677 // scope is outside of a `Body`.
679 // If we find a suitable associated function that returns the expected type, we don't
680 // want the more general suggestion later in this method about "consider constraining
681 // the associated type or calling a method that returns the associated type".
682 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
684 assoc.container.id(),
685 current_method_ident,
689 // Possibly suggest constraining the associated type to conform to the
691 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
698 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
700 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
704 if !impl_comparison {
705 // Generic suggestion when we can't be more specific.
708 "{} or calling a method that returns `{}`",
715 "for more information, visit \
716 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
719 if self.sess.teach(&diag.get_code().unwrap()) {
721 "given an associated type `T` and a method `foo`:
725 fn foo(&self) -> Self::T;
728 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
732 fn foo(&self) -> Self::T { String::new() }
739 /// When the expected `impl Trait` is not defined in the current item, it will come from
740 /// a return type. This can occur when dealing with `TryStream` (#71035).
741 fn suggest_constraining_opaque_associated_type(
743 diag: &mut Diagnostic,
745 proj_ty: &ty::ProjectionTy<'tcx>,
748 let assoc = self.associated_item(proj_ty.item_def_id);
749 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
750 let opaque_local_def_id = def_id.as_local();
751 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
752 match &self.hir().expect_item(opaque_local_def_id).kind {
753 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
754 _ => bug!("The HirId comes from a `ty::Opaque`"),
760 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
762 self.constrain_generic_bound_associated_type_structured_suggestion(
765 opaque_hir_ty.bounds,
777 fn point_at_methods_that_satisfy_associated_type(
779 diag: &mut Diagnostic,
780 assoc_container_id: DefId,
781 current_method_ident: Option<Symbol>,
782 proj_ty_item_def_id: DefId,
785 let items = self.associated_items(assoc_container_id);
786 // Find all the methods in the trait that could be called to construct the
787 // expected associated type.
788 // FIXME: consider suggesting the use of associated `const`s.
789 let methods: Vec<(Span, String)> = items
792 .filter(|(name, item)| {
793 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
795 .filter_map(|(_, item)| {
796 let method = self.fn_sig(item.def_id);
797 match *method.output().skip_binder().kind() {
798 ty::Projection(ty::ProjectionTy { item_def_id, .. })
799 if item_def_id == proj_ty_item_def_id =>
802 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
803 format!("consider calling `{}`", self.def_path_str(item.def_id)),
810 if !methods.is_empty() {
811 // Use a single `help:` to show all the methods in the trait that can
812 // be used to construct the expected associated type.
813 let mut span: MultiSpan =
814 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
816 "{some} method{s} {are} available that return{r} `{ty}`",
817 some = if methods.len() == 1 { "a" } else { "some" },
818 s = pluralize!(methods.len()),
819 are = pluralize!("is", methods.len()),
820 r = if methods.len() == 1 { "s" } else { "" },
823 for (sp, label) in methods.into_iter() {
824 span.push_span_label(sp, label);
826 diag.span_help(span, &msg);
832 fn point_at_associated_type(
834 diag: &mut Diagnostic,
835 body_owner_def_id: DefId,
838 let Some(hir_id) = body_owner_def_id.as_local() else {
841 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
842 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
843 // `expected` and point at it.
844 let parent_id = self.hir().get_parent_item(hir_id);
845 let item = self.hir().find_by_def_id(parent_id);
846 debug!("expected_projection parent item {:?}", item);
848 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
849 // FIXME: account for `#![feature(specialization)]`
850 for item in &items[..] {
852 hir::AssocItemKind::Type => {
853 // FIXME: account for returning some type in a trait fn impl that has
854 // an assoc type as a return type (#72076).
855 if let hir::Defaultness::Default { has_value: true } = item.defaultness
857 if self.type_of(item.id.def_id) == found {
860 "associated type defaults can't be assumed inside the \
861 trait defining them",
871 Some(hir::Node::Item(hir::Item {
872 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
875 for item in &items[..] {
876 if let hir::AssocItemKind::Type = item.kind {
877 if self.type_of(item.id.def_id) == found {
878 diag.span_label(item.span, "expected this associated type");
889 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
890 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
892 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
893 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
894 /// trait bound as the one we're looking for. This can help in cases where the associated
895 /// type is defined on a supertrait of the one present in the bounds.
896 fn constrain_generic_bound_associated_type_structured_suggestion(
898 diag: &mut Diagnostic,
899 trait_ref: &ty::TraitRef<'tcx>,
900 bounds: hir::GenericBounds<'_>,
901 assoc: &ty::AssocItem,
902 assoc_substs: &[ty::GenericArg<'tcx>],
905 is_bound_surely_present: bool,
907 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
909 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
910 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
914 let matching_trait_bounds = trait_bounds
916 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
917 .collect::<Vec<_>>();
919 let span = match &matching_trait_bounds[..] {
921 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
928 self.constrain_associated_type_structured_suggestion(
938 /// Given a span corresponding to a bound, provide a structured suggestion to set an
939 /// associated type to a given type `ty`.
940 fn constrain_associated_type_structured_suggestion(
942 diag: &mut Diagnostic,
944 assoc: &ty::AssocItem,
945 assoc_substs: &[ty::GenericArg<'tcx>],
949 if let Ok(has_params) =
950 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
952 let (span, sugg) = if has_params {
953 let pos = span.hi() - BytePos(1);
954 let span = Span::new(pos, pos, span.ctxt(), span.parent());
955 (span, format!(", {} = {}", assoc.ident(self), ty))
957 let item_args = self.format_generic_args(assoc_substs);
958 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
960 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
966 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
967 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
968 .path_generic_args(Ok, args)
969 .expect("could not write to `String`.")