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 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>),
46 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
47 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
48 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
49 RegionsPlaceholderMismatch,
51 Sorts(ExpectedFound<Ty<'tcx>>),
52 ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
53 IntMismatch(ExpectedFound<ty::IntVarValue>),
54 FloatMismatch(ExpectedFound<ty::FloatTy>),
55 Traits(ExpectedFound<DefId>),
56 VariadicMismatch(ExpectedFound<bool>),
58 /// Instantiating a type variable with the given type would have
59 /// created a cycle (because it appears somewhere within that
62 CyclicConst(&'tcx ty::Const<'tcx>),
63 ProjectionMismatched(ExpectedFound<DefId>),
65 ExpectedFound<&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>>,
67 ObjectUnsafeCoercion(DefId),
68 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
71 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
72 TargetFeatureCast(DefId),
75 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
76 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
77 /// afterwards to present additional details, particularly when it comes to lifetime-related
79 impl<'tcx> fmt::Display for TypeError<'tcx> {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 use self::TypeError::*;
82 fn report_maybe_different(
83 f: &mut fmt::Formatter<'_>,
87 // A naive approach to making sure that we're not reporting silly errors such as:
88 // (expected closure, found closure).
89 if expected == found {
90 write!(f, "expected {}, found a different {}", expected, found)
92 write!(f, "expected {}, found {}", expected, found)
96 let br_string = |br: ty::BoundRegionKind| match br {
97 ty::BrNamed(_, name) => format!(" {}", name),
102 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
103 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
104 Mismatch => write!(f, "types differ"),
105 ConstnessMismatch(values) => {
106 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
108 PolarityMismatch(values) => {
109 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
111 UnsafetyMismatch(values) => {
112 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
114 AbiMismatch(values) => {
115 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
117 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
118 TupleSize(values) => write!(
120 "expected a tuple with {} element{}, \
121 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{}, \
130 found one with {} element{}",
132 pluralize!(values.expected),
134 pluralize!(values.found)
136 ArgCount => write!(f, "incorrect number of function parameters"),
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(_)
227 | RegionsDoesNotOutlive(..)
228 | RegionsInsufficientlyPolymorphic(..)
229 | RegionsOverlyPolymorphic(..)
230 | RegionsPlaceholderMismatch
232 | ProjectionMismatched(_)
233 | ExistentialMismatch(_)
236 | ObjectUnsafeCoercion(_) => true,
241 impl<'tcx> ty::TyS<'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.val {
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 db: &mut DiagnosticBuilder<'_>,
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 db.note("no two closures, even if identical, have the same type");
362 db.help("consider boxing your closure and/or using it as a trait object");
364 (ty::Opaque(..), ty::Opaque(..)) => {
366 db.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 == '_') {
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 db.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 db.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 db.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 db.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 db.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 db.span_label(p_span, "this type parameter");
462 db.help("type parameters must be constrained to match other types");
463 if self.sess.teach(&db.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 db.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 db.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) => {
570 let attrs = self.get_attrs(*def_id);
571 let target_spans = attrs
573 .filter(|attr| attr.has_name(sym::target_feature))
574 .map(|attr| attr.span);
576 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
578 db.span_labels(target_spans, "`#[target_feature]` added here");
584 fn suggest_constraint(
586 db: &mut DiagnosticBuilder<'_>,
588 body_owner_def_id: DefId,
589 proj_ty: &ty::ProjectionTy<'tcx>,
592 let assoc = self.associated_item(proj_ty.item_def_id);
593 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
594 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
595 if let Some(hir_generics) = item.generics() {
596 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
597 // This will also work for `impl Trait`.
598 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
599 let generics = self.generics_of(body_owner_def_id);
600 generics.type_param(param_ty, self).def_id
605 // First look in the `where` clause, as this might be
606 // `fn foo<T>(x: T) where T: Trait`.
607 for predicate in hir_generics.where_clause.predicates {
608 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
609 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
612 if path.res.opt_def_id() == Some(def_id) {
613 // This predicate is binding type param `A` in `<A as T>::Foo` to
614 // something, potentially `T`.
622 if self.constrain_generic_bound_associated_type_structured_suggestion(
636 for param in hir_generics.params {
637 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
640 // This is type param `A` in `<A as T>::Foo`.
641 return self.constrain_generic_bound_associated_type_structured_suggestion(
658 /// An associated type was expected and a different type was found.
660 /// We perform a few different checks to see what we can suggest:
662 /// - In the current item, look for associated functions that return the expected type and
663 /// suggest calling them. (Not a structured suggestion.)
664 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
665 /// associated type to the found type.
666 /// - If the associated type has a default type and was expected inside of a `trait`, we
667 /// mention that this is disallowed.
668 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
669 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
670 /// fn that returns the type.
671 fn expected_projection(
673 db: &mut DiagnosticBuilder<'_>,
674 proj_ty: &ty::ProjectionTy<'tcx>,
675 values: &ExpectedFound<Ty<'tcx>>,
676 body_owner_def_id: DefId,
677 cause_code: &ObligationCauseCode<'_>,
680 "consider constraining the associated type `{}` to `{}`",
681 values.expected, values.found
683 let body_owner = self.hir().get_if_local(body_owner_def_id);
684 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
686 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
687 let callable_scope = matches!(
690 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
691 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
692 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
695 let impl_comparison = matches!(
697 ObligationCauseCode::CompareImplMethodObligation { .. }
698 | ObligationCauseCode::CompareImplTypeObligation { .. }
699 | ObligationCauseCode::CompareImplConstObligation
701 let assoc = self.associated_item(proj_ty.item_def_id);
702 if !callable_scope || impl_comparison {
703 // We do not want to suggest calling functions when the reason of the
704 // type error is a comparison of an `impl` with its `trait` or when the
705 // scope is outside of a `Body`.
707 // If we find a suitable associated function that returns the expected type, we don't
708 // want the more general suggestion later in this method about "consider constraining
709 // the associated type or calling a method that returns the associated type".
710 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
712 assoc.container.id(),
713 current_method_ident,
717 // Possibly suggest constraining the associated type to conform to the
719 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
726 self.suggest_constraining_opaque_associated_type(db, &msg, proj_ty, values.found);
728 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
732 if !impl_comparison {
733 // Generic suggestion when we can't be more specific.
735 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
740 "for more information, visit \
741 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
744 if self.sess.teach(&db.get_code().unwrap()) {
746 "given an associated type `T` and a method `foo`:
750 fn foo(&self) -> Self::T;
753 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
757 fn foo(&self) -> Self::T { String::new() }
764 /// When the expected `impl Trait` is not defined in the current item, it will come from
765 /// a return type. This can occur when dealing with `TryStream` (#71035).
766 fn suggest_constraining_opaque_associated_type(
768 db: &mut DiagnosticBuilder<'_>,
770 proj_ty: &ty::ProjectionTy<'tcx>,
773 let assoc = self.associated_item(proj_ty.item_def_id);
774 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
775 let opaque_local_def_id = def_id.as_local();
776 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
777 let hir = self.hir();
778 let opaque_hir_id = hir.local_def_id_to_hir_id(opaque_local_def_id);
779 match &hir.expect_item(opaque_hir_id).kind {
780 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
781 _ => bug!("The HirId comes from a `ty::Opaque`"),
787 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
789 self.constrain_generic_bound_associated_type_structured_suggestion(
792 opaque_hir_ty.bounds,
804 fn point_at_methods_that_satisfy_associated_type(
806 db: &mut DiagnosticBuilder<'_>,
807 assoc_container_id: DefId,
808 current_method_ident: Option<Symbol>,
809 proj_ty_item_def_id: DefId,
812 let items = self.associated_items(assoc_container_id);
813 // Find all the methods in the trait that could be called to construct the
814 // expected associated type.
815 // FIXME: consider suggesting the use of associated `const`s.
816 let methods: Vec<(Span, String)> = items
819 .filter(|(name, item)| {
820 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
822 .filter_map(|(_, item)| {
823 let method = self.fn_sig(item.def_id);
824 match *method.output().skip_binder().kind() {
825 ty::Projection(ty::ProjectionTy { item_def_id, .. })
826 if item_def_id == proj_ty_item_def_id =>
829 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
830 format!("consider calling `{}`", self.def_path_str(item.def_id)),
837 if !methods.is_empty() {
838 // Use a single `help:` to show all the methods in the trait that can
839 // be used to construct the expected associated type.
840 let mut span: MultiSpan =
841 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
843 "{some} method{s} {are} available that return{r} `{ty}`",
844 some = if methods.len() == 1 { "a" } else { "some" },
845 s = pluralize!(methods.len()),
846 are = if methods.len() == 1 { "is" } else { "are" },
847 r = if methods.len() == 1 { "s" } else { "" },
850 for (sp, label) in methods.into_iter() {
851 span.push_span_label(sp, label);
853 db.span_help(span, &msg);
859 fn point_at_associated_type(
861 db: &mut DiagnosticBuilder<'_>,
862 body_owner_def_id: DefId,
866 match body_owner_def_id.as_local().map(|id| self.hir().local_def_id_to_hir_id(id)) {
867 Some(hir_id) => hir_id,
868 None => return false,
870 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
871 // `expected` and point at it.
872 let parent_id = self.hir().get_parent_item(hir_id);
873 let item = self.hir().find(parent_id);
874 debug!("expected_projection parent item {:?}", item);
876 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
877 // FIXME: account for `#![feature(specialization)]`
878 for item in &items[..] {
880 hir::AssocItemKind::Type => {
881 // FIXME: account for returning some type in a trait fn impl that has
882 // an assoc type as a return type (#72076).
883 if let hir::Defaultness::Default { has_value: true } = item.defaultness
885 if self.type_of(item.id.def_id) == found {
888 "associated type defaults can't be assumed inside the \
889 trait defining them",
899 Some(hir::Node::Item(hir::Item {
900 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
903 for item in &items[..] {
904 if let hir::AssocItemKind::Type = item.kind {
905 if self.type_of(item.id.def_id) == found {
906 db.span_label(item.span, "expected this associated type");
917 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
918 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
920 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
921 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
922 /// trait bound as the one we're looking for. This can help in cases where the associated
923 /// type is defined on a supertrait of the one present in the bounds.
924 fn constrain_generic_bound_associated_type_structured_suggestion(
926 db: &mut DiagnosticBuilder<'_>,
927 trait_ref: &ty::TraitRef<'tcx>,
928 bounds: hir::GenericBounds<'_>,
929 assoc: &ty::AssocItem,
930 assoc_substs: &[ty::GenericArg<'tcx>],
933 is_bound_surely_present: bool,
935 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
937 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
938 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
942 let matching_trait_bounds = trait_bounds
944 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
945 .collect::<Vec<_>>();
947 let span = match &matching_trait_bounds[..] {
949 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
956 self.constrain_associated_type_structured_suggestion(db, span, assoc, assoc_substs, ty, msg)
959 /// Given a span corresponding to a bound, provide a structured suggestion to set an
960 /// associated type to a given type `ty`.
961 fn constrain_associated_type_structured_suggestion(
963 db: &mut DiagnosticBuilder<'_>,
965 assoc: &ty::AssocItem,
966 assoc_substs: &[ty::GenericArg<'tcx>],
970 if let Ok(has_params) =
971 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
973 let (span, sugg) = if has_params {
974 let pos = span.hi() - BytePos(1);
975 let span = Span::new(pos, pos, span.ctxt(), span.parent());
976 (span, format!(", {} = {}", assoc.ident, ty))
978 let item_args = self.format_generic_args(assoc_substs);
979 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident, item_args, ty))
981 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
987 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
988 let mut item_args = String::new();
989 FmtPrinter::new(self, &mut item_args, hir::def::Namespace::TypeNS)
990 .path_generic_args(Ok, args)
991 .expect("could not write to `String`.");