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 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
37 AbiMismatch(ExpectedFound<abi::Abi>),
39 TupleSize(ExpectedFound<usize>),
40 FixedArraySize(ExpectedFound<u64>),
43 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
44 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
45 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
46 RegionsPlaceholderMismatch,
48 Sorts(ExpectedFound<Ty<'tcx>>),
49 IntMismatch(ExpectedFound<ty::IntVarValue>),
50 FloatMismatch(ExpectedFound<ty::FloatTy>),
51 Traits(ExpectedFound<DefId>),
52 VariadicMismatch(ExpectedFound<bool>),
54 /// Instantiating a type variable with the given type would have
55 /// created a cycle (because it appears somewhere within that
58 CyclicConst(&'tcx ty::Const<'tcx>),
59 ProjectionMismatched(ExpectedFound<DefId>),
61 ExpectedFound<&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>>,
63 ObjectUnsafeCoercion(DefId),
64 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
67 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
68 TargetFeatureCast(DefId),
71 pub enum UnconstrainedNumeric {
77 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
78 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
79 /// afterwards to present additional details, particularly when it comes to lifetime-related
81 impl<'tcx> fmt::Display for TypeError<'tcx> {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 use self::TypeError::*;
84 fn report_maybe_different(
85 f: &mut fmt::Formatter<'_>,
89 // A naive approach to making sure that we're not reporting silly errors such as:
90 // (expected closure, found closure).
91 if expected == found {
92 write!(f, "expected {}, found a different {}", expected, found)
94 write!(f, "expected {}, found {}", expected, found)
98 let br_string = |br: ty::BoundRegionKind| match br {
99 ty::BrNamed(_, name) => format!(" {}", name),
104 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
105 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
106 Mismatch => write!(f, "types differ"),
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 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 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 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
162 FloatMismatch(ref values) => {
163 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
165 VariadicMismatch(ref values) => write!(
167 "expected {} fn, found {} function",
168 if values.expected { "variadic" } else { "non-variadic" },
169 if values.found { "variadic" } else { "non-variadic" }
171 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
174 "expected {}, found {}",
175 tcx.def_path_str(values.expected),
176 tcx.def_path_str(values.found)
179 ExistentialMismatch(ref values) => report_maybe_different(
181 &format!("trait `{}`", values.expected),
182 &format!("trait `{}`", values.found),
184 ConstMismatch(ref values) => {
185 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
187 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
188 TargetFeatureCast(_) => write!(
190 "cannot coerce functions with `#[target_feature]` to safe function pointers"
192 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
197 impl<'tcx> TypeError<'tcx> {
198 pub fn must_include_note(&self) -> bool {
199 use self::TypeError::*;
201 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_)
202 | FixedArraySize(_) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
203 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
208 | RegionsDoesNotOutlive(..)
209 | RegionsInsufficientlyPolymorphic(..)
210 | RegionsOverlyPolymorphic(..)
211 | RegionsPlaceholderMismatch
213 | ProjectionMismatched(_)
214 | ExistentialMismatch(_)
217 | ObjectUnsafeCoercion(_) => true,
222 impl<'tcx> ty::TyS<'tcx> {
223 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
225 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
226 format!("`{}`", self).into()
228 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
230 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
231 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
233 if t.is_simple_ty() {
234 return format!("array `{}`", self).into();
237 let n = tcx.lift(n).unwrap();
238 if let ty::ConstKind::Value(v) = n.val {
239 if let Some(n) = v.try_to_machine_usize(tcx) {
240 return format!("array of {} element{}", n, pluralize!(n)).into();
245 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
246 ty::Slice(_) => "slice".into(),
247 ty::RawPtr(_) => "*-ptr".into(),
248 ty::Ref(_, ty, mutbl) => {
249 let tymut = ty::TypeAndMut { ty, mutbl };
250 let tymut_string = tymut.to_string();
251 if tymut_string != "_"
252 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
254 format!("`&{}`", tymut_string).into()
256 // Unknown type name, it's long or has type arguments
258 hir::Mutability::Mut => "mutable reference",
264 ty::FnDef(..) => "fn item".into(),
265 ty::FnPtr(_) => "fn pointer".into(),
266 ty::Dynamic(ref inner, ..) => {
267 if let Some(principal) = inner.principal() {
268 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
270 "trait object".into()
273 ty::Closure(..) => "closure".into(),
274 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
275 ty::GeneratorWitness(..) => "generator witness".into(),
276 ty::Tuple(..) => "tuple".into(),
277 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
278 ty::Infer(ty::IntVar(_)) => "integer".into(),
279 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
280 ty::Placeholder(..) => "placeholder type".into(),
281 ty::Bound(..) => "bound type".into(),
282 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
283 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
284 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
285 ty::Projection(_) => "associated type".into(),
286 ty::Param(p) => format!("type parameter `{}`", p).into(),
287 ty::Opaque(..) => "opaque type".into(),
288 ty::Error(_) => "type error".into(),
292 pub fn prefix_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
302 | ty::Never => "type".into(),
303 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
304 ty::Adt(def, _) => def.descr().into(),
305 ty::Foreign(_) => "extern type".into(),
306 ty::Array(..) => "array".into(),
307 ty::Slice(_) => "slice".into(),
308 ty::RawPtr(_) => "raw pointer".into(),
309 ty::Ref(.., mutbl) => match mutbl {
310 hir::Mutability::Mut => "mutable reference",
314 ty::FnDef(..) => "fn item".into(),
315 ty::FnPtr(_) => "fn pointer".into(),
316 ty::Dynamic(..) => "trait object".into(),
317 ty::Closure(..) => "closure".into(),
318 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
319 ty::GeneratorWitness(..) => "generator witness".into(),
320 ty::Tuple(..) => "tuple".into(),
321 ty::Placeholder(..) => "higher-ranked type".into(),
322 ty::Bound(..) => "bound type variable".into(),
323 ty::Projection(_) => "associated type".into(),
324 ty::Param(_) => "type parameter".into(),
325 ty::Opaque(..) => "opaque type".into(),
330 impl<'tcx> TyCtxt<'tcx> {
331 pub fn note_and_explain_type_err(
333 db: &mut DiagnosticBuilder<'_>,
334 err: &TypeError<'tcx>,
335 cause: &ObligationCause<'tcx>,
337 body_owner_def_id: DefId,
339 use self::TypeError::*;
340 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
343 match (values.expected.kind(), values.found.kind()) {
344 (ty::Closure(..), ty::Closure(..)) => {
345 db.note("no two closures, even if identical, have the same type");
346 db.help("consider boxing your closure and/or using it as a trait object");
348 (ty::Opaque(..), ty::Opaque(..)) => {
350 db.note("distinct uses of `impl Trait` result in different opaque types");
352 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
356 ) = self.sess.source_map().span_to_snippet(sp)
358 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
361 "use a float literal",
362 format!("{}.0", snippet),
368 (ty::Param(expected), ty::Param(found)) => {
369 let generics = self.generics_of(body_owner_def_id);
370 let e_span = self.def_span(generics.type_param(expected, self).def_id);
371 if !sp.contains(e_span) {
372 db.span_label(e_span, "expected type parameter");
374 let f_span = self.def_span(generics.type_param(found, self).def_id);
375 if !sp.contains(f_span) {
376 db.span_label(f_span, "found type parameter");
379 "a type parameter was expected, but a different one was found; \
380 you might be missing a type parameter or trait bound",
383 "for more information, visit \
384 https://doc.rust-lang.org/book/ch10-02-traits.html\
385 #traits-as-parameters",
388 (ty::Projection(_), ty::Projection(_)) => {
389 db.note("an associated type was expected, but a different one was found");
391 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
392 let generics = self.generics_of(body_owner_def_id);
393 let p_span = self.def_span(generics.type_param(p, self).def_id);
394 if !sp.contains(p_span) {
395 db.span_label(p_span, "this type parameter");
397 let hir = self.hir();
399 if let Some(generics) = generics
403 .map(|id| hir.local_def_id_to_hir_id(id))
404 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
406 .and_then(|node| node.generics())
408 // Synthesize the associated type restriction `Add<Output = Expected>`.
409 // FIXME: extract this logic for use in other diagnostics.
410 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
412 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
413 let item_name = self.item_name(proj.item_def_id);
414 let item_args = self.format_generic_args(assoc_substs);
416 let path = if path.ends_with('>') {
419 &path[..path.len() - 1],
425 format!("{}<{}{} = {}>", path, item_name, item_args, p)
427 note = !suggest_constraining_type_param(
431 &format!("{}", proj.self_ty()),
437 db.note("you might be missing a type parameter or trait bound");
440 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
441 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
442 let generics = self.generics_of(body_owner_def_id);
443 let p_span = self.def_span(generics.type_param(p, self).def_id);
444 if !sp.contains(p_span) {
445 db.span_label(p_span, "this type parameter");
447 db.help("type parameters must be constrained to match other types");
448 if self.sess.teach(&db.get_code().unwrap()) {
450 "given a type parameter `T` and a method `foo`:
452 trait Trait<T> { fn foo(&self) -> T; }
454 the only ways to implement method `foo` are:
455 - constrain `T` with an explicit type:
457 impl Trait<String> for X {
458 fn foo(&self) -> String { String::new() }
461 - add a trait bound to `T` and call a method on that trait that returns `Self`:
463 impl<T: std::default::Default> Trait<T> for X {
464 fn foo(&self) -> T { <T as std::default::Default>::default() }
467 - change `foo` to return an argument of type `T`:
469 impl<T> Trait<T> for X {
470 fn foo(&self, x: T) -> T { x }
476 "for more information, visit \
477 https://doc.rust-lang.org/book/ch10-02-traits.html\
478 #traits-as-parameters",
481 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
482 let generics = self.generics_of(body_owner_def_id);
483 let p_span = self.def_span(generics.type_param(p, self).def_id);
484 if !sp.contains(p_span) {
485 db.span_label(p_span, "this type parameter");
488 "every closure has a distinct type and so could not always match the \
489 caller-chosen type of parameter `{}`",
493 (ty::Param(p), _) | (_, ty::Param(p)) => {
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 (ty::Projection(proj_ty), _) => {
501 self.expected_projection(
509 (_, ty::Projection(proj_ty)) => {
511 "consider constraining the associated type `{}` to `{}`",
512 values.found, values.expected,
514 if !self.suggest_constraint(
523 "for more information, visit \
524 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
531 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
533 values.expected.kind(),
539 // Watch out for various cases of cyclic types and try to explain.
540 if ty.is_closure() || ty.is_generator() {
542 "closures cannot capture themselves or take themselves as argument;\n\
543 this error may be the result of a recent compiler bug-fix,\n\
544 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
545 for more information",
549 TargetFeatureCast(def_id) => {
550 let attrs = self.get_attrs(*def_id);
551 let target_spans = attrs
553 .filter(|attr| attr.has_name(sym::target_feature))
554 .map(|attr| attr.span);
556 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
558 db.span_labels(target_spans, "`#[target_feature]` added here");
564 fn suggest_constraint(
566 db: &mut DiagnosticBuilder<'_>,
568 body_owner_def_id: DefId,
569 proj_ty: &ty::ProjectionTy<'tcx>,
572 let assoc = self.associated_item(proj_ty.item_def_id);
573 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
574 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
575 if let Some(hir_generics) = item.generics() {
576 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
577 // This will also work for `impl Trait`.
578 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
579 let generics = self.generics_of(body_owner_def_id);
580 generics.type_param(param_ty, self).def_id
585 // First look in the `where` clause, as this might be
586 // `fn foo<T>(x: T) where T: Trait`.
587 for predicate in hir_generics.where_clause.predicates {
588 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
589 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
592 if path.res.opt_def_id() == Some(def_id) {
593 // This predicate is binding type param `A` in `<A as T>::Foo` to
594 // something, potentially `T`.
602 if self.constrain_generic_bound_associated_type_structured_suggestion(
615 for param in hir_generics.params {
616 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
619 // This is type param `A` in `<A as T>::Foo`.
620 return self.constrain_generic_bound_associated_type_structured_suggestion(
636 /// An associated type was expected and a different type was found.
638 /// We perform a few different checks to see what we can suggest:
640 /// - In the current item, look for associated functions that return the expected type and
641 /// suggest calling them. (Not a structured suggestion.)
642 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
643 /// associated type to the found type.
644 /// - If the associated type has a default type and was expected inside of a `trait`, we
645 /// mention that this is disallowed.
646 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
647 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
648 /// fn that returns the type.
649 fn expected_projection(
651 db: &mut DiagnosticBuilder<'_>,
652 proj_ty: &ty::ProjectionTy<'tcx>,
653 values: &ExpectedFound<Ty<'tcx>>,
654 body_owner_def_id: DefId,
655 cause_code: &ObligationCauseCode<'_>,
658 "consider constraining the associated type `{}` to `{}`",
659 values.expected, values.found
661 let body_owner = self.hir().get_if_local(body_owner_def_id);
662 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
664 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
665 let callable_scope = matches!(
668 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
669 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
670 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
673 let impl_comparison = matches!(
675 ObligationCauseCode::CompareImplMethodObligation { .. }
676 | ObligationCauseCode::CompareImplTypeObligation { .. }
677 | ObligationCauseCode::CompareImplConstObligation
679 let assoc = self.associated_item(proj_ty.item_def_id);
680 if !callable_scope || impl_comparison {
681 // We do not want to suggest calling functions when the reason of the
682 // type error is a comparison of an `impl` with its `trait` or when the
683 // scope is outside of a `Body`.
685 // If we find a suitable associated function that returns the expected type, we don't
686 // want the more general suggestion later in this method about "consider constraining
687 // the associated type or calling a method that returns the associated type".
688 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
690 assoc.container.id(),
691 current_method_ident,
695 // Possibly suggest constraining the associated type to conform to the
697 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
704 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
705 // When the expected `impl Trait` is not defined in the current item, it will come from
706 // a return type. This can occur when dealing with `TryStream` (#71035).
707 if self.constrain_associated_type_structured_suggestion(
709 self.def_span(def_id),
711 proj_ty.trait_ref_and_own_substs(self).1,
719 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
723 if !impl_comparison {
724 // Generic suggestion when we can't be more specific.
726 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
731 "for more information, visit \
732 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
735 if self.sess.teach(&db.get_code().unwrap()) {
737 "given an associated type `T` and a method `foo`:
741 fn foo(&self) -> Self::T;
744 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
748 fn foo(&self) -> Self::T { String::new() }
755 fn point_at_methods_that_satisfy_associated_type(
757 db: &mut DiagnosticBuilder<'_>,
758 assoc_container_id: DefId,
759 current_method_ident: Option<Symbol>,
760 proj_ty_item_def_id: DefId,
763 let items = self.associated_items(assoc_container_id);
764 // Find all the methods in the trait that could be called to construct the
765 // expected associated type.
766 // FIXME: consider suggesting the use of associated `const`s.
767 let methods: Vec<(Span, String)> = items
770 .filter(|(name, item)| {
771 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
773 .filter_map(|(_, item)| {
774 let method = self.fn_sig(item.def_id);
775 match *method.output().skip_binder().kind() {
776 ty::Projection(ty::ProjectionTy { item_def_id, .. })
777 if item_def_id == proj_ty_item_def_id =>
780 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
781 format!("consider calling `{}`", self.def_path_str(item.def_id)),
788 if !methods.is_empty() {
789 // Use a single `help:` to show all the methods in the trait that can
790 // be used to construct the expected associated type.
791 let mut span: MultiSpan =
792 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
794 "{some} method{s} {are} available that return{r} `{ty}`",
795 some = if methods.len() == 1 { "a" } else { "some" },
796 s = pluralize!(methods.len()),
797 are = if methods.len() == 1 { "is" } else { "are" },
798 r = if methods.len() == 1 { "s" } else { "" },
801 for (sp, label) in methods.into_iter() {
802 span.push_span_label(sp, label);
804 db.span_help(span, &msg);
810 fn point_at_associated_type(
812 db: &mut DiagnosticBuilder<'_>,
813 body_owner_def_id: DefId,
817 match body_owner_def_id.as_local().map(|id| self.hir().local_def_id_to_hir_id(id)) {
818 Some(hir_id) => hir_id,
819 None => return false,
821 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
822 // `expected` and point at it.
823 let parent_id = self.hir().get_parent_item(hir_id);
824 let item = self.hir().find(parent_id);
825 debug!("expected_projection parent item {:?}", item);
827 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
828 // FIXME: account for `#![feature(specialization)]`
829 for item in &items[..] {
831 hir::AssocItemKind::Type => {
832 // FIXME: account for returning some type in a trait fn impl that has
833 // an assoc type as a return type (#72076).
834 if let hir::Defaultness::Default { has_value: true } = item.defaultness
836 if self.type_of(item.id.def_id) == found {
839 "associated type defaults can't be assumed inside the \
840 trait defining them",
850 Some(hir::Node::Item(hir::Item {
851 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
854 for item in &items[..] {
855 if let hir::AssocItemKind::Type = item.kind {
856 if self.type_of(item.id.def_id) == found {
857 db.span_label(item.span, "expected this associated type");
868 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
869 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
870 fn constrain_generic_bound_associated_type_structured_suggestion(
872 db: &mut DiagnosticBuilder<'_>,
873 trait_ref: &ty::TraitRef<'tcx>,
874 bounds: hir::GenericBounds<'_>,
875 assoc: &ty::AssocItem,
876 assoc_substs: &[ty::GenericArg<'tcx>],
880 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
881 bounds.iter().any(|bound| match bound {
882 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => {
883 // Relate the type param against `T` in `<A as T>::Foo`.
884 ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)
885 && self.constrain_associated_type_structured_suggestion(
898 /// Given a span corresponding to a bound, provide a structured suggestion to set an
899 /// associated type to a given type `ty`.
900 fn constrain_associated_type_structured_suggestion(
902 db: &mut DiagnosticBuilder<'_>,
904 assoc: &ty::AssocItem,
905 assoc_substs: &[ty::GenericArg<'tcx>],
909 if let Ok(has_params) =
910 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
912 let (span, sugg) = if has_params {
913 let pos = span.hi() - BytePos(1);
914 let span = Span::new(pos, pos, span.ctxt());
915 (span, format!(", {} = {}", assoc.ident, ty))
917 let item_args = self.format_generic_args(assoc_substs);
918 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident, item_args, ty))
920 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
926 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
927 let mut item_args = String::new();
928 FmtPrinter::new(self, &mut item_args, hir::def::Namespace::TypeNS)
929 .path_generic_args(Ok, args)
930 .expect("could not write to `String`.");