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, TypeVisitable)]
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, TypeVisitable)]
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 // Actually naming the region here is a bit confusing because context is lacking
139 RegionsInsufficientlyPolymorphic(..) => {
140 write!(f, "one type is more general than the other")
142 RegionsOverlyPolymorphic(br, _) => write!(
144 "expected concrete lifetime, found bound lifetime parameter{}",
147 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
148 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
149 report_maybe_different(
151 &values.expected.sort_string(tcx),
152 &values.found.sort_string(tcx),
155 Traits(values) => ty::tls::with(|tcx| {
156 report_maybe_different(
158 &format!("trait `{}`", tcx.def_path_str(values.expected)),
159 &format!("trait `{}`", tcx.def_path_str(values.found)),
162 IntMismatch(ref values) => {
163 let expected = match values.expected {
164 ty::IntVarValue::IntType(ty) => ty.name_str(),
165 ty::IntVarValue::UintType(ty) => ty.name_str(),
167 let found = match values.found {
168 ty::IntVarValue::IntType(ty) => ty.name_str(),
169 ty::IntVarValue::UintType(ty) => ty.name_str(),
171 write!(f, "expected `{}`, found `{}`", expected, found)
173 FloatMismatch(ref values) => {
176 "expected `{}`, found `{}`",
177 values.expected.name_str(),
178 values.found.name_str()
181 VariadicMismatch(ref values) => write!(
183 "expected {} fn, found {} function",
184 if values.expected { "variadic" } else { "non-variadic" },
185 if values.found { "variadic" } else { "non-variadic" }
187 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
190 "expected {}, found {}",
191 tcx.def_path_str(values.expected),
192 tcx.def_path_str(values.found)
195 ExistentialMismatch(ref values) => report_maybe_different(
197 &format!("trait `{}`", values.expected),
198 &format!("trait `{}`", values.found),
200 ConstMismatch(ref values) => {
201 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
203 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
204 TargetFeatureCast(_) => write!(
206 "cannot coerce functions with `#[target_feature]` to safe function pointers"
208 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
213 impl<'tcx> TypeError<'tcx> {
214 pub fn must_include_note(&self) -> bool {
215 use self::TypeError::*;
217 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
218 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
219 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
220 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
223 | ArgumentMutability(_)
227 | RegionsDoesNotOutlive(..)
228 | RegionsInsufficientlyPolymorphic(..)
229 | RegionsOverlyPolymorphic(..)
230 | RegionsPlaceholderMismatch
232 | ProjectionMismatched(_)
233 | ExistentialMismatch(_)
236 | ObjectUnsafeCoercion(_) => true,
241 impl<'tcx> Ty<'tcx> {
242 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
244 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
245 format!("`{}`", self).into()
247 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
249 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
250 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
252 if t.is_simple_ty() {
253 return format!("array `{}`", self).into();
256 let n = tcx.lift(n).unwrap();
257 if let ty::ConstKind::Value(v) = n.kind() {
258 if let Some(n) = v.try_to_machine_usize(tcx) {
259 return format!("array of {} element{}", n, pluralize!(n)).into();
264 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
265 ty::Slice(_) => "slice".into(),
266 ty::RawPtr(_) => "*-ptr".into(),
267 ty::Ref(_, ty, mutbl) => {
268 let tymut = ty::TypeAndMut { ty, mutbl };
269 let tymut_string = tymut.to_string();
270 if tymut_string != "_"
271 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
273 format!("`&{}`", tymut_string).into()
275 // Unknown type name, it's long or has type arguments
277 hir::Mutability::Mut => "mutable reference",
283 ty::FnDef(..) => "fn item".into(),
284 ty::FnPtr(_) => "fn pointer".into(),
285 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
286 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
288 ty::Dynamic(..) => "trait object".into(),
289 ty::Closure(..) => "closure".into(),
290 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
291 ty::GeneratorWitness(..) => "generator witness".into(),
292 ty::Tuple(..) => "tuple".into(),
293 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
294 ty::Infer(ty::IntVar(_)) => "integer".into(),
295 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
296 ty::Placeholder(..) => "placeholder type".into(),
297 ty::Bound(..) => "bound type".into(),
298 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
299 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
300 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
301 ty::Projection(_) => "associated type".into(),
302 ty::Param(p) => format!("type parameter `{}`", p).into(),
303 ty::Opaque(..) => "opaque type".into(),
304 ty::Error(_) => "type error".into(),
308 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
318 | ty::Never => "type".into(),
319 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
320 ty::Adt(def, _) => def.descr().into(),
321 ty::Foreign(_) => "extern type".into(),
322 ty::Array(..) => "array".into(),
323 ty::Slice(_) => "slice".into(),
324 ty::RawPtr(_) => "raw pointer".into(),
325 ty::Ref(.., mutbl) => match mutbl {
326 hir::Mutability::Mut => "mutable reference",
330 ty::FnDef(..) => "fn item".into(),
331 ty::FnPtr(_) => "fn pointer".into(),
332 ty::Dynamic(..) => "trait object".into(),
333 ty::Closure(..) => "closure".into(),
334 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
335 ty::GeneratorWitness(..) => "generator witness".into(),
336 ty::Tuple(..) => "tuple".into(),
337 ty::Placeholder(..) => "higher-ranked type".into(),
338 ty::Bound(..) => "bound type variable".into(),
339 ty::Projection(_) => "associated type".into(),
340 ty::Param(_) => "type parameter".into(),
341 ty::Opaque(..) => "opaque type".into(),
346 impl<'tcx> TyCtxt<'tcx> {
347 pub fn note_and_explain_type_err(
349 diag: &mut Diagnostic,
350 err: &TypeError<'tcx>,
351 cause: &ObligationCause<'tcx>,
353 body_owner_def_id: DefId,
355 use self::TypeError::*;
356 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
358 ArgumentSorts(values, _) | Sorts(values) => {
359 match (values.expected.kind(), values.found.kind()) {
360 (ty::Closure(..), ty::Closure(..)) => {
361 diag.note("no two closures, even if identical, have the same type");
362 diag.help("consider boxing your closure and/or using it as a trait object");
364 (ty::Opaque(..), ty::Opaque(..)) => {
366 diag.note("distinct uses of `impl Trait` result in different opaque types");
368 (ty::Float(_), ty::Infer(ty::IntVar(_)))
372 ) = self.sess.source_map().span_to_snippet(sp) =>
374 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
375 diag.span_suggestion(
377 "use a float literal",
378 format!("{}.0", snippet),
383 (ty::Param(expected), ty::Param(found)) => {
384 let generics = self.generics_of(body_owner_def_id);
385 let e_span = self.def_span(generics.type_param(expected, self).def_id);
386 if !sp.contains(e_span) {
387 diag.span_label(e_span, "expected type parameter");
389 let f_span = self.def_span(generics.type_param(found, self).def_id);
390 if !sp.contains(f_span) {
391 diag.span_label(f_span, "found type parameter");
394 "a type parameter was expected, but a different one was found; \
395 you might be missing a type parameter or trait bound",
398 "for more information, visit \
399 https://doc.rust-lang.org/book/ch10-02-traits.html\
400 #traits-as-parameters",
403 (ty::Projection(_), ty::Projection(_)) => {
404 diag.note("an associated type was expected, but a different one was found");
406 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
407 let generics = self.generics_of(body_owner_def_id);
408 let p_span = self.def_span(generics.type_param(p, self).def_id);
409 if !sp.contains(p_span) {
410 diag.span_label(p_span, "this type parameter");
412 let hir = self.hir();
414 if let Some(generics) = generics
418 .map(|id| hir.local_def_id_to_hir_id(id))
419 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
421 .and_then(|node| node.generics())
423 // Synthesize the associated type restriction `Add<Output = Expected>`.
424 // FIXME: extract this logic for use in other diagnostics.
425 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
427 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
428 let item_name = self.item_name(proj.item_def_id);
429 let item_args = self.format_generic_args(assoc_substs);
431 let path = if path.ends_with('>') {
434 &path[..path.len() - 1],
440 format!("{}<{}{} = {}>", path, item_name, item_args, p)
442 note = !suggest_constraining_type_param(
446 &format!("{}", proj.self_ty()),
452 diag.note("you might be missing a type parameter or trait bound");
455 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
456 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
457 let generics = self.generics_of(body_owner_def_id);
458 let p_span = self.def_span(generics.type_param(p, self).def_id);
459 if !sp.contains(p_span) {
460 diag.span_label(p_span, "this type parameter");
462 diag.help("type parameters must be constrained to match other types");
463 if self.sess.teach(&diag.get_code().unwrap()) {
465 "given a type parameter `T` and a method `foo`:
467 trait Trait<T> { fn foo(&self) -> T; }
469 the only ways to implement method `foo` are:
470 - constrain `T` with an explicit type:
472 impl Trait<String> for X {
473 fn foo(&self) -> String { String::new() }
476 - add a trait bound to `T` and call a method on that trait that returns `Self`:
478 impl<T: std::default::Default> Trait<T> for X {
479 fn foo(&self) -> T { <T as std::default::Default>::default() }
482 - change `foo` to return an argument of type `T`:
484 impl<T> Trait<T> for X {
485 fn foo(&self, x: T) -> T { x }
491 "for more information, visit \
492 https://doc.rust-lang.org/book/ch10-02-traits.html\
493 #traits-as-parameters",
496 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
497 let generics = self.generics_of(body_owner_def_id);
498 let p_span = self.def_span(generics.type_param(p, self).def_id);
499 if !sp.contains(p_span) {
500 diag.span_label(p_span, "this type parameter");
503 "every closure has a distinct type and so could not always match the \
504 caller-chosen type of parameter `{}`",
508 (ty::Param(p), _) | (_, ty::Param(p)) => {
509 let generics = self.generics_of(body_owner_def_id);
510 let p_span = self.def_span(generics.type_param(p, self).def_id);
511 if !sp.contains(p_span) {
512 diag.span_label(p_span, "this type parameter");
515 (ty::Projection(proj_ty), _) => {
516 self.expected_projection(
524 (_, ty::Projection(proj_ty)) => {
526 "consider constraining the associated type `{}` to `{}`",
527 values.found, values.expected,
529 if !(self.suggest_constraining_opaque_associated_type(
534 ) || self.suggest_constraint(
543 "for more information, visit \
544 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
551 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
553 values.expected.kind(),
559 // Watch out for various cases of cyclic types and try to explain.
560 if ty.is_closure() || ty.is_generator() {
562 "closures cannot capture themselves or take themselves as argument;\n\
563 this error may be the result of a recent compiler bug-fix,\n\
564 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
565 for more information",
569 TargetFeatureCast(def_id) => {
571 self.get_attrs(*def_id, sym::target_feature).map(|attr| attr.span);
573 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
575 diag.span_labels(target_spans, "`#[target_feature]` added here");
581 fn suggest_constraint(
583 diag: &mut Diagnostic,
585 body_owner_def_id: DefId,
586 proj_ty: &ty::ProjectionTy<'tcx>,
589 let assoc = self.associated_item(proj_ty.item_def_id);
590 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
591 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
592 if let Some(hir_generics) = item.generics() {
593 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
594 // This will also work for `impl Trait`.
595 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
596 let generics = self.generics_of(body_owner_def_id);
597 generics.type_param(param_ty, self).def_id
601 let Some(def_id) = def_id.as_local() else {
605 // First look in the `where` clause, as this might be
606 // `fn foo<T>(x: T) where T: Trait`.
607 for pred in hir_generics.bounds_for_param(def_id) {
608 if self.constrain_generic_bound_associated_type_structured_suggestion(
626 /// An associated type was expected and a different type was found.
628 /// We perform a few different checks to see what we can suggest:
630 /// - In the current item, look for associated functions that return the expected type and
631 /// suggest calling them. (Not a structured suggestion.)
632 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
633 /// associated type to the found type.
634 /// - If the associated type has a default type and was expected inside of a `trait`, we
635 /// mention that this is disallowed.
636 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
637 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
638 /// fn that returns the type.
639 fn expected_projection(
641 diag: &mut Diagnostic,
642 proj_ty: &ty::ProjectionTy<'tcx>,
643 values: &ExpectedFound<Ty<'tcx>>,
644 body_owner_def_id: DefId,
645 cause_code: &ObligationCauseCode<'_>,
648 "consider constraining the associated type `{}` to `{}`",
649 values.expected, values.found
651 let body_owner = self.hir().get_if_local(body_owner_def_id);
652 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
654 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
655 let callable_scope = matches!(
658 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
659 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
660 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
663 let impl_comparison = matches!(
665 ObligationCauseCode::CompareImplMethodObligation { .. }
666 | ObligationCauseCode::CompareImplTypeObligation { .. }
667 | ObligationCauseCode::CompareImplConstObligation
669 let assoc = self.associated_item(proj_ty.item_def_id);
670 if !callable_scope || impl_comparison {
671 // We do not want to suggest calling functions when the reason of the
672 // type error is a comparison of an `impl` with its `trait` or when the
673 // scope is outside of a `Body`.
675 // If we find a suitable associated function that returns the expected type, we don't
676 // want the more general suggestion later in this method about "consider constraining
677 // the associated type or calling a method that returns the associated type".
678 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
680 assoc.container.id(),
681 current_method_ident,
685 // Possibly suggest constraining the associated type to conform to the
687 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
694 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
696 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
700 if !impl_comparison {
701 // Generic suggestion when we can't be more specific.
704 "{} or calling a method that returns `{}`",
711 "for more information, visit \
712 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
715 if self.sess.teach(&diag.get_code().unwrap()) {
717 "given an associated type `T` and a method `foo`:
721 fn foo(&self) -> Self::T;
724 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
728 fn foo(&self) -> Self::T { String::new() }
735 /// When the expected `impl Trait` is not defined in the current item, it will come from
736 /// a return type. This can occur when dealing with `TryStream` (#71035).
737 fn suggest_constraining_opaque_associated_type(
739 diag: &mut Diagnostic,
741 proj_ty: &ty::ProjectionTy<'tcx>,
744 let assoc = self.associated_item(proj_ty.item_def_id);
745 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
746 let opaque_local_def_id = def_id.as_local();
747 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
748 match &self.hir().expect_item(opaque_local_def_id).kind {
749 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
750 _ => bug!("The HirId comes from a `ty::Opaque`"),
756 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
758 self.constrain_generic_bound_associated_type_structured_suggestion(
761 opaque_hir_ty.bounds,
773 fn point_at_methods_that_satisfy_associated_type(
775 diag: &mut Diagnostic,
776 assoc_container_id: DefId,
777 current_method_ident: Option<Symbol>,
778 proj_ty_item_def_id: DefId,
781 let items = self.associated_items(assoc_container_id);
782 // Find all the methods in the trait that could be called to construct the
783 // expected associated type.
784 // FIXME: consider suggesting the use of associated `const`s.
785 let methods: Vec<(Span, String)> = items
788 .filter(|(name, item)| {
789 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
791 .filter_map(|(_, item)| {
792 let method = self.fn_sig(item.def_id);
793 match *method.output().skip_binder().kind() {
794 ty::Projection(ty::ProjectionTy { item_def_id, .. })
795 if item_def_id == proj_ty_item_def_id =>
798 self.def_span(item.def_id),
799 format!("consider calling `{}`", self.def_path_str(item.def_id)),
806 if !methods.is_empty() {
807 // Use a single `help:` to show all the methods in the trait that can
808 // be used to construct the expected associated type.
809 let mut span: MultiSpan =
810 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
812 "{some} method{s} {are} available that return{r} `{ty}`",
813 some = if methods.len() == 1 { "a" } else { "some" },
814 s = pluralize!(methods.len()),
815 are = pluralize!("is", methods.len()),
816 r = if methods.len() == 1 { "s" } else { "" },
819 for (sp, label) in methods.into_iter() {
820 span.push_span_label(sp, label);
822 diag.span_help(span, &msg);
828 fn point_at_associated_type(
830 diag: &mut Diagnostic,
831 body_owner_def_id: DefId,
834 let Some(hir_id) = body_owner_def_id.as_local() else {
837 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
838 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
839 // `expected` and point at it.
840 let parent_id = self.hir().get_parent_item(hir_id);
841 let item = self.hir().find_by_def_id(parent_id);
842 debug!("expected_projection parent item {:?}", item);
844 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
845 // FIXME: account for `#![feature(specialization)]`
846 for item in &items[..] {
848 hir::AssocItemKind::Type => {
849 // FIXME: account for returning some type in a trait fn impl that has
850 // an assoc type as a return type (#72076).
851 if let hir::Defaultness::Default { has_value: true } = item.defaultness
853 if self.type_of(item.id.def_id) == found {
856 "associated type defaults can't be assumed inside the \
857 trait defining them",
867 Some(hir::Node::Item(hir::Item {
868 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
871 for item in &items[..] {
872 if let hir::AssocItemKind::Type = item.kind {
873 if self.type_of(item.id.def_id) == found {
874 diag.span_label(item.span, "expected this associated type");
885 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
886 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
888 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
889 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
890 /// trait bound as the one we're looking for. This can help in cases where the associated
891 /// type is defined on a supertrait of the one present in the bounds.
892 fn constrain_generic_bound_associated_type_structured_suggestion(
894 diag: &mut Diagnostic,
895 trait_ref: &ty::TraitRef<'tcx>,
896 bounds: hir::GenericBounds<'_>,
897 assoc: &ty::AssocItem,
898 assoc_substs: &[ty::GenericArg<'tcx>],
901 is_bound_surely_present: bool,
903 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
905 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
906 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
910 let matching_trait_bounds = trait_bounds
912 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
913 .collect::<Vec<_>>();
915 let span = match &matching_trait_bounds[..] {
917 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
924 self.constrain_associated_type_structured_suggestion(
934 /// Given a span corresponding to a bound, provide a structured suggestion to set an
935 /// associated type to a given type `ty`.
936 fn constrain_associated_type_structured_suggestion(
938 diag: &mut Diagnostic,
940 assoc: &ty::AssocItem,
941 assoc_substs: &[ty::GenericArg<'tcx>],
945 if let Ok(has_params) =
946 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
948 let (span, sugg) = if has_params {
949 let pos = span.hi() - BytePos(1);
950 let span = Span::new(pos, pos, span.ctxt(), span.parent());
951 (span, format!(", {} = {}", assoc.ident(self), ty))
953 let item_args = self.format_generic_args(assoc_substs);
954 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
956 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
962 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
963 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
964 .path_generic_args(Ok, args)
965 .expect("could not write to `String`.")