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, DiagnosticBuilder};
8 use rustc_hir::def_id::DefId;
9 use rustc_span::symbol::{sym, Symbol};
10 use rustc_span::{BytePos, MultiSpan, 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 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
38 AbiMismatch(ExpectedFound<abi::Abi>),
40 ArgumentMutability(usize),
41 TupleSize(ExpectedFound<usize>),
42 FixedArraySize(ExpectedFound<u64>),
45 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
46 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
47 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
48 RegionsPlaceholderMismatch,
50 Sorts(ExpectedFound<Ty<'tcx>>),
51 ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
52 IntMismatch(ExpectedFound<ty::IntVarValue>),
53 FloatMismatch(ExpectedFound<ty::FloatTy>),
54 Traits(ExpectedFound<DefId>),
55 VariadicMismatch(ExpectedFound<bool>),
57 /// Instantiating a type variable with the given type would have
58 /// created a cycle (because it appears somewhere within that
61 CyclicConst(&'tcx ty::Const<'tcx>),
62 ProjectionMismatched(ExpectedFound<DefId>),
64 ExpectedFound<&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>>,
66 ObjectUnsafeCoercion(DefId),
67 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
70 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
71 TargetFeatureCast(DefId),
74 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
75 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
76 /// afterwards to present additional details, particularly when it comes to lifetime-related
78 impl<'tcx> fmt::Display for TypeError<'tcx> {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 use self::TypeError::*;
81 fn report_maybe_different(
82 f: &mut fmt::Formatter<'_>,
86 // A naive approach to making sure that we're not reporting silly errors such as:
87 // (expected closure, found closure).
88 if expected == found {
89 write!(f, "expected {}, found a different {}", expected, found)
91 write!(f, "expected {}, found {}", expected, found)
95 let br_string = |br: ty::BoundRegionKind| match br {
96 ty::BrNamed(_, name) => format!(" {}", name),
101 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
102 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
103 Mismatch => write!(f, "types differ"),
104 ConstnessMismatch(values) => {
105 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
107 UnsafetyMismatch(values) => {
108 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
110 AbiMismatch(values) => {
111 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
113 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
114 TupleSize(values) => write!(
116 "expected a tuple with {} element{}, \
117 found one with {} element{}",
119 pluralize!(values.expected),
121 pluralize!(values.found)
123 FixedArraySize(values) => write!(
125 "expected an array with a fixed size of {} element{}, \
126 found one with {} element{}",
128 pluralize!(values.expected),
130 pluralize!(values.found)
132 ArgCount => write!(f, "incorrect number of function parameters"),
133 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
134 RegionsInsufficientlyPolymorphic(br, _) => write!(
136 "expected bound lifetime parameter{}, found concrete lifetime",
139 RegionsOverlyPolymorphic(br, _) => write!(
141 "expected concrete lifetime, found bound lifetime parameter{}",
144 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
145 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
146 report_maybe_different(
148 &values.expected.sort_string(tcx),
149 &values.found.sort_string(tcx),
152 Traits(values) => ty::tls::with(|tcx| {
153 report_maybe_different(
155 &format!("trait `{}`", tcx.def_path_str(values.expected)),
156 &format!("trait `{}`", tcx.def_path_str(values.found)),
159 IntMismatch(ref values) => {
160 let expected = match values.expected {
161 ty::IntVarValue::IntType(ty) => ty.name_str(),
162 ty::IntVarValue::UintType(ty) => ty.name_str(),
164 let found = match values.found {
165 ty::IntVarValue::IntType(ty) => ty.name_str(),
166 ty::IntVarValue::UintType(ty) => ty.name_str(),
168 write!(f, "expected `{}`, found `{}`", expected, found)
170 FloatMismatch(ref values) => {
173 "expected `{}`, found `{}`",
174 values.expected.name_str(),
175 values.found.name_str()
178 VariadicMismatch(ref values) => write!(
180 "expected {} fn, found {} function",
181 if values.expected { "variadic" } else { "non-variadic" },
182 if values.found { "variadic" } else { "non-variadic" }
184 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
187 "expected {}, found {}",
188 tcx.def_path_str(values.expected),
189 tcx.def_path_str(values.found)
192 ExistentialMismatch(ref values) => report_maybe_different(
194 &format!("trait `{}`", values.expected),
195 &format!("trait `{}`", values.found),
197 ConstMismatch(ref values) => {
198 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
200 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
201 TargetFeatureCast(_) => write!(
203 "cannot coerce functions with `#[target_feature]` to safe function pointers"
205 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
210 impl<'tcx> TypeError<'tcx> {
211 pub fn must_include_note(&self) -> bool {
212 use self::TypeError::*;
214 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
215 | Mismatch | AbiMismatch(_) | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_)
216 | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) | TargetFeatureCast(_) => {
221 | ArgumentMutability(_)
224 | RegionsDoesNotOutlive(..)
225 | RegionsInsufficientlyPolymorphic(..)
226 | RegionsOverlyPolymorphic(..)
227 | RegionsPlaceholderMismatch
229 | ProjectionMismatched(_)
230 | ExistentialMismatch(_)
233 | ObjectUnsafeCoercion(_) => true,
238 impl<'tcx> ty::TyS<'tcx> {
239 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
241 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
242 format!("`{}`", self).into()
244 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
246 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
247 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
249 if t.is_simple_ty() {
250 return format!("array `{}`", self).into();
253 let n = tcx.lift(n).unwrap();
254 if let ty::ConstKind::Value(v) = n.val {
255 if let Some(n) = v.try_to_machine_usize(tcx) {
256 return format!("array of {} element{}", n, pluralize!(n)).into();
261 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
262 ty::Slice(_) => "slice".into(),
263 ty::RawPtr(_) => "*-ptr".into(),
264 ty::Ref(_, ty, mutbl) => {
265 let tymut = ty::TypeAndMut { ty, mutbl };
266 let tymut_string = tymut.to_string();
267 if tymut_string != "_"
268 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
270 format!("`&{}`", tymut_string).into()
272 // Unknown type name, it's long or has type arguments
274 hir::Mutability::Mut => "mutable reference",
280 ty::FnDef(..) => "fn item".into(),
281 ty::FnPtr(_) => "fn pointer".into(),
282 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
283 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
285 ty::Dynamic(..) => "trait object".into(),
286 ty::Closure(..) => "closure".into(),
287 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
288 ty::GeneratorWitness(..) => "generator witness".into(),
289 ty::Tuple(..) => "tuple".into(),
290 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
291 ty::Infer(ty::IntVar(_)) => "integer".into(),
292 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
293 ty::Placeholder(..) => "placeholder type".into(),
294 ty::Bound(..) => "bound type".into(),
295 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
296 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
297 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
298 ty::Projection(_) => "associated type".into(),
299 ty::Param(p) => format!("type parameter `{}`", p).into(),
300 ty::Opaque(..) => "opaque type".into(),
301 ty::Error(_) => "type error".into(),
305 pub fn prefix_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
315 | ty::Never => "type".into(),
316 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
317 ty::Adt(def, _) => def.descr().into(),
318 ty::Foreign(_) => "extern type".into(),
319 ty::Array(..) => "array".into(),
320 ty::Slice(_) => "slice".into(),
321 ty::RawPtr(_) => "raw pointer".into(),
322 ty::Ref(.., mutbl) => match mutbl {
323 hir::Mutability::Mut => "mutable reference",
327 ty::FnDef(..) => "fn item".into(),
328 ty::FnPtr(_) => "fn pointer".into(),
329 ty::Dynamic(..) => "trait object".into(),
330 ty::Closure(..) => "closure".into(),
331 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
332 ty::GeneratorWitness(..) => "generator witness".into(),
333 ty::Tuple(..) => "tuple".into(),
334 ty::Placeholder(..) => "higher-ranked type".into(),
335 ty::Bound(..) => "bound type variable".into(),
336 ty::Projection(_) => "associated type".into(),
337 ty::Param(_) => "type parameter".into(),
338 ty::Opaque(..) => "opaque type".into(),
343 impl<'tcx> TyCtxt<'tcx> {
344 pub fn note_and_explain_type_err(
346 db: &mut DiagnosticBuilder<'_>,
347 err: &TypeError<'tcx>,
348 cause: &ObligationCause<'tcx>,
350 body_owner_def_id: DefId,
352 use self::TypeError::*;
353 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
355 ArgumentSorts(values, _) | Sorts(values) => {
356 match (values.expected.kind(), values.found.kind()) {
357 (ty::Closure(..), ty::Closure(..)) => {
358 db.note("no two closures, even if identical, have the same type");
359 db.help("consider boxing your closure and/or using it as a trait object");
361 (ty::Opaque(..), ty::Opaque(..)) => {
363 db.note("distinct uses of `impl Trait` result in different opaque types");
365 (ty::Float(_), ty::Infer(ty::IntVar(_)))
369 ) = self.sess.source_map().span_to_snippet(sp) =>
371 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
374 "use a float literal",
375 format!("{}.0", snippet),
380 (ty::Param(expected), ty::Param(found)) => {
381 let generics = self.generics_of(body_owner_def_id);
382 let e_span = self.def_span(generics.type_param(expected, self).def_id);
383 if !sp.contains(e_span) {
384 db.span_label(e_span, "expected type parameter");
386 let f_span = self.def_span(generics.type_param(found, self).def_id);
387 if !sp.contains(f_span) {
388 db.span_label(f_span, "found type parameter");
391 "a type parameter was expected, but a different one was found; \
392 you might be missing a type parameter or trait bound",
395 "for more information, visit \
396 https://doc.rust-lang.org/book/ch10-02-traits.html\
397 #traits-as-parameters",
400 (ty::Projection(_), ty::Projection(_)) => {
401 db.note("an associated type was expected, but a different one was found");
403 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
404 let generics = self.generics_of(body_owner_def_id);
405 let p_span = self.def_span(generics.type_param(p, self).def_id);
406 if !sp.contains(p_span) {
407 db.span_label(p_span, "this type parameter");
409 let hir = self.hir();
411 if let Some(generics) = generics
415 .map(|id| hir.local_def_id_to_hir_id(id))
416 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
418 .and_then(|node| node.generics())
420 // Synthesize the associated type restriction `Add<Output = Expected>`.
421 // FIXME: extract this logic for use in other diagnostics.
422 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
424 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
425 let item_name = self.item_name(proj.item_def_id);
426 let item_args = self.format_generic_args(assoc_substs);
428 let path = if path.ends_with('>') {
431 &path[..path.len() - 1],
437 format!("{}<{}{} = {}>", path, item_name, item_args, p)
439 note = !suggest_constraining_type_param(
443 &format!("{}", proj.self_ty()),
449 db.note("you might be missing a type parameter or trait bound");
452 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
453 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
454 let generics = self.generics_of(body_owner_def_id);
455 let p_span = self.def_span(generics.type_param(p, self).def_id);
456 if !sp.contains(p_span) {
457 db.span_label(p_span, "this type parameter");
459 db.help("type parameters must be constrained to match other types");
460 if self.sess.teach(&db.get_code().unwrap()) {
462 "given a type parameter `T` and a method `foo`:
464 trait Trait<T> { fn foo(&self) -> T; }
466 the only ways to implement method `foo` are:
467 - constrain `T` with an explicit type:
469 impl Trait<String> for X {
470 fn foo(&self) -> String { String::new() }
473 - add a trait bound to `T` and call a method on that trait that returns `Self`:
475 impl<T: std::default::Default> Trait<T> for X {
476 fn foo(&self) -> T { <T as std::default::Default>::default() }
479 - change `foo` to return an argument of type `T`:
481 impl<T> Trait<T> for X {
482 fn foo(&self, x: T) -> T { x }
488 "for more information, visit \
489 https://doc.rust-lang.org/book/ch10-02-traits.html\
490 #traits-as-parameters",
493 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
494 let generics = self.generics_of(body_owner_def_id);
495 let p_span = self.def_span(generics.type_param(p, self).def_id);
496 if !sp.contains(p_span) {
497 db.span_label(p_span, "this type parameter");
500 "every closure has a distinct type and so could not always match the \
501 caller-chosen type of parameter `{}`",
505 (ty::Param(p), _) | (_, 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 db.span_label(p_span, "this type parameter");
512 (ty::Projection(proj_ty), _) => {
513 self.expected_projection(
521 (_, ty::Projection(proj_ty)) => {
523 "consider constraining the associated type `{}` to `{}`",
524 values.found, values.expected,
526 if !(self.suggest_constraining_opaque_associated_type(
531 ) || self.suggest_constraint(
540 "for more information, visit \
541 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
548 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
550 values.expected.kind(),
556 // Watch out for various cases of cyclic types and try to explain.
557 if ty.is_closure() || ty.is_generator() {
559 "closures cannot capture themselves or take themselves as argument;\n\
560 this error may be the result of a recent compiler bug-fix,\n\
561 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
562 for more information",
566 TargetFeatureCast(def_id) => {
567 let attrs = self.get_attrs(*def_id);
568 let target_spans = attrs
570 .filter(|attr| attr.has_name(sym::target_feature))
571 .map(|attr| attr.span);
573 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
575 db.span_labels(target_spans, "`#[target_feature]` added here");
581 fn suggest_constraint(
583 db: &mut DiagnosticBuilder<'_>,
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
602 // First look in the `where` clause, as this might be
603 // `fn foo<T>(x: T) where T: Trait`.
604 for predicate in hir_generics.where_clause.predicates {
605 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
606 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
609 if path.res.opt_def_id() == Some(def_id) {
610 // This predicate is binding type param `A` in `<A as T>::Foo` to
611 // something, potentially `T`.
619 if self.constrain_generic_bound_associated_type_structured_suggestion(
633 for param in hir_generics.params {
634 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
637 // This is type param `A` in `<A as T>::Foo`.
638 return self.constrain_generic_bound_associated_type_structured_suggestion(
655 /// An associated type was expected and a different type was found.
657 /// We perform a few different checks to see what we can suggest:
659 /// - In the current item, look for associated functions that return the expected type and
660 /// suggest calling them. (Not a structured suggestion.)
661 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
662 /// associated type to the found type.
663 /// - If the associated type has a default type and was expected inside of a `trait`, we
664 /// mention that this is disallowed.
665 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
666 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
667 /// fn that returns the type.
668 fn expected_projection(
670 db: &mut DiagnosticBuilder<'_>,
671 proj_ty: &ty::ProjectionTy<'tcx>,
672 values: &ExpectedFound<Ty<'tcx>>,
673 body_owner_def_id: DefId,
674 cause_code: &ObligationCauseCode<'_>,
677 "consider constraining the associated type `{}` to `{}`",
678 values.expected, values.found
680 let body_owner = self.hir().get_if_local(body_owner_def_id);
681 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
683 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
684 let callable_scope = matches!(
687 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
688 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
689 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
692 let impl_comparison = matches!(
694 ObligationCauseCode::CompareImplMethodObligation { .. }
695 | ObligationCauseCode::CompareImplTypeObligation { .. }
696 | ObligationCauseCode::CompareImplConstObligation
698 let assoc = self.associated_item(proj_ty.item_def_id);
699 if !callable_scope || impl_comparison {
700 // We do not want to suggest calling functions when the reason of the
701 // type error is a comparison of an `impl` with its `trait` or when the
702 // scope is outside of a `Body`.
704 // If we find a suitable associated function that returns the expected type, we don't
705 // want the more general suggestion later in this method about "consider constraining
706 // the associated type or calling a method that returns the associated type".
707 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
709 assoc.container.id(),
710 current_method_ident,
714 // Possibly suggest constraining the associated type to conform to the
716 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
723 self.suggest_constraining_opaque_associated_type(db, &msg, proj_ty, values.found);
725 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
729 if !impl_comparison {
730 // Generic suggestion when we can't be more specific.
732 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
737 "for more information, visit \
738 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
741 if self.sess.teach(&db.get_code().unwrap()) {
743 "given an associated type `T` and a method `foo`:
747 fn foo(&self) -> Self::T;
750 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
754 fn foo(&self) -> Self::T { String::new() }
761 /// When the expected `impl Trait` is not defined in the current item, it will come from
762 /// a return type. This can occur when dealing with `TryStream` (#71035).
763 fn suggest_constraining_opaque_associated_type(
765 db: &mut DiagnosticBuilder<'_>,
767 proj_ty: &ty::ProjectionTy<'tcx>,
770 let assoc = self.associated_item(proj_ty.item_def_id);
771 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
772 let opaque_local_def_id = def_id.as_local();
773 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
774 let hir = self.hir();
775 let opaque_hir_id = hir.local_def_id_to_hir_id(opaque_local_def_id);
776 match &hir.expect_item(opaque_hir_id).kind {
777 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
778 _ => bug!("The HirId comes from a `ty::Opaque`"),
784 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
786 self.constrain_generic_bound_associated_type_structured_suggestion(
789 opaque_hir_ty.bounds,
801 fn point_at_methods_that_satisfy_associated_type(
803 db: &mut DiagnosticBuilder<'_>,
804 assoc_container_id: DefId,
805 current_method_ident: Option<Symbol>,
806 proj_ty_item_def_id: DefId,
809 let items = self.associated_items(assoc_container_id);
810 // Find all the methods in the trait that could be called to construct the
811 // expected associated type.
812 // FIXME: consider suggesting the use of associated `const`s.
813 let methods: Vec<(Span, String)> = items
816 .filter(|(name, item)| {
817 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
819 .filter_map(|(_, item)| {
820 let method = self.fn_sig(item.def_id);
821 match *method.output().skip_binder().kind() {
822 ty::Projection(ty::ProjectionTy { item_def_id, .. })
823 if item_def_id == proj_ty_item_def_id =>
826 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
827 format!("consider calling `{}`", self.def_path_str(item.def_id)),
834 if !methods.is_empty() {
835 // Use a single `help:` to show all the methods in the trait that can
836 // be used to construct the expected associated type.
837 let mut span: MultiSpan =
838 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
840 "{some} method{s} {are} available that return{r} `{ty}`",
841 some = if methods.len() == 1 { "a" } else { "some" },
842 s = pluralize!(methods.len()),
843 are = if methods.len() == 1 { "is" } else { "are" },
844 r = if methods.len() == 1 { "s" } else { "" },
847 for (sp, label) in methods.into_iter() {
848 span.push_span_label(sp, label);
850 db.span_help(span, &msg);
856 fn point_at_associated_type(
858 db: &mut DiagnosticBuilder<'_>,
859 body_owner_def_id: DefId,
863 match body_owner_def_id.as_local().map(|id| self.hir().local_def_id_to_hir_id(id)) {
864 Some(hir_id) => hir_id,
865 None => return false,
867 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
868 // `expected` and point at it.
869 let parent_id = self.hir().get_parent_item(hir_id);
870 let item = self.hir().find(parent_id);
871 debug!("expected_projection parent item {:?}", item);
873 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
874 // FIXME: account for `#![feature(specialization)]`
875 for item in &items[..] {
877 hir::AssocItemKind::Type => {
878 // FIXME: account for returning some type in a trait fn impl that has
879 // an assoc type as a return type (#72076).
880 if let hir::Defaultness::Default { has_value: true } = item.defaultness
882 if self.type_of(item.id.def_id) == found {
885 "associated type defaults can't be assumed inside the \
886 trait defining them",
896 Some(hir::Node::Item(hir::Item {
897 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
900 for item in &items[..] {
901 if let hir::AssocItemKind::Type = item.kind {
902 if self.type_of(item.id.def_id) == found {
903 db.span_label(item.span, "expected this associated type");
914 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
915 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
917 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
918 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
919 /// trait bound as the one we're looking for. This can help in cases where the associated
920 /// type is defined on a supertrait of the one present in the bounds.
921 fn constrain_generic_bound_associated_type_structured_suggestion(
923 db: &mut DiagnosticBuilder<'_>,
924 trait_ref: &ty::TraitRef<'tcx>,
925 bounds: hir::GenericBounds<'_>,
926 assoc: &ty::AssocItem,
927 assoc_substs: &[ty::GenericArg<'tcx>],
930 is_bound_surely_present: bool,
932 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
934 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
935 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
939 let matching_trait_bounds = trait_bounds
941 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
942 .collect::<Vec<_>>();
944 let span = match &matching_trait_bounds[..] {
946 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
953 self.constrain_associated_type_structured_suggestion(db, span, assoc, assoc_substs, ty, msg)
956 /// Given a span corresponding to a bound, provide a structured suggestion to set an
957 /// associated type to a given type `ty`.
958 fn constrain_associated_type_structured_suggestion(
960 db: &mut DiagnosticBuilder<'_>,
962 assoc: &ty::AssocItem,
963 assoc_substs: &[ty::GenericArg<'tcx>],
967 if let Ok(has_params) =
968 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
970 let (span, sugg) = if has_params {
971 let pos = span.hi() - BytePos(1);
972 let span = Span::new(pos, pos, span.ctxt(), span.parent());
973 (span, format!(", {} = {}", assoc.ident, ty))
975 let item_args = self.format_generic_args(assoc_substs);
976 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident, item_args, ty))
978 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
984 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
985 let mut item_args = String::new();
986 FmtPrinter::new(self, &mut item_args, hir::def::Namespace::TypeNS)
987 .path_generic_args(Ok, args)
988 .expect("could not write to `String`.");