1 use crate::traits::{ObligationCause, ObligationCauseCode};
2 use crate::ty::diagnostics::suggest_constraining_type_param;
3 use crate::ty::{self, BoundRegion, 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;
17 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
18 pub struct ExpectedFound<T> {
23 impl<T> ExpectedFound<T> {
24 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
26 ExpectedFound { expected: a, found: b }
28 ExpectedFound { expected: b, found: a }
33 // Data structures used in type unification
34 #[derive(Clone, Debug, TypeFoldable)]
35 pub enum TypeError<'tcx> {
37 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
38 AbiMismatch(ExpectedFound<abi::Abi>),
40 TupleSize(ExpectedFound<usize>),
41 FixedArraySize(ExpectedFound<u64>),
44 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
45 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
46 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
47 RegionsPlaceholderMismatch,
49 Sorts(ExpectedFound<Ty<'tcx>>),
50 IntMismatch(ExpectedFound<ty::IntVarValue>),
51 FloatMismatch(ExpectedFound<ast::FloatTy>),
52 Traits(ExpectedFound<DefId>),
53 VariadicMismatch(ExpectedFound<bool>),
55 /// Instantiating a type variable with the given type would have
56 /// created a cycle (because it appears somewhere within that
59 ProjectionMismatched(ExpectedFound<DefId>),
60 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
61 ObjectUnsafeCoercion(DefId),
62 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
65 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
66 TargetFeatureCast(DefId),
69 pub enum UnconstrainedNumeric {
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::BoundRegion| match br {
97 ty::BrNamed(_, name) => format!(" {}", name),
102 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
103 Mismatch => write!(f, "types differ"),
104 UnsafetyMismatch(values) => {
105 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
107 AbiMismatch(values) => {
108 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
110 Mutability => write!(f, "types differ in mutability"),
111 TupleSize(values) => write!(
113 "expected a tuple with {} element{}, \
114 found one with {} element{}",
116 pluralize!(values.expected),
118 pluralize!(values.found)
120 FixedArraySize(values) => write!(
122 "expected an array with a fixed size of {} element{}, \
123 found one with {} element{}",
125 pluralize!(values.expected),
127 pluralize!(values.found)
129 ArgCount => write!(f, "incorrect number of function parameters"),
130 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
131 RegionsInsufficientlyPolymorphic(br, _) => write!(
133 "expected bound lifetime parameter{}, found concrete lifetime",
136 RegionsOverlyPolymorphic(br, _) => write!(
138 "expected concrete lifetime, found bound lifetime parameter{}",
141 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
142 Sorts(values) => ty::tls::with(|tcx| {
143 report_maybe_different(
145 &values.expected.sort_string(tcx),
146 &values.found.sort_string(tcx),
149 Traits(values) => ty::tls::with(|tcx| {
150 report_maybe_different(
152 &format!("trait `{}`", tcx.def_path_str(values.expected)),
153 &format!("trait `{}`", tcx.def_path_str(values.found)),
156 IntMismatch(ref values) => {
157 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
159 FloatMismatch(ref values) => {
160 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
162 VariadicMismatch(ref values) => write!(
164 "expected {} fn, found {} function",
165 if values.expected { "variadic" } else { "non-variadic" },
166 if values.found { "variadic" } else { "non-variadic" }
168 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
171 "expected {}, found {}",
172 tcx.def_path_str(values.expected),
173 tcx.def_path_str(values.found)
176 ExistentialMismatch(ref values) => report_maybe_different(
178 &format!("trait `{}`", values.expected),
179 &format!("trait `{}`", values.found),
181 ConstMismatch(ref values) => {
182 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
184 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
185 TargetFeatureCast(_) => write!(
187 "cannot coerce functions with `#[target_feature]` to safe function pointers"
189 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
194 impl<'tcx> TypeError<'tcx> {
195 pub fn must_include_note(&self) -> bool {
196 use self::TypeError::*;
198 CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
199 | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_)
200 | TargetFeatureCast(_) => false,
205 | RegionsDoesNotOutlive(..)
206 | RegionsInsufficientlyPolymorphic(..)
207 | RegionsOverlyPolymorphic(..)
208 | RegionsPlaceholderMismatch
210 | ProjectionMismatched(_)
211 | ExistentialMismatch(_)
214 | ObjectUnsafeCoercion(_) => true,
219 impl<'tcx> ty::TyS<'tcx> {
220 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
222 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
223 format!("`{}`", self).into()
225 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
227 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
228 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
230 let n = tcx.lift(&n).unwrap();
231 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
232 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
233 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
234 None => "array".into(),
237 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
238 ty::Slice(_) => "slice".into(),
239 ty::RawPtr(_) => "*-ptr".into(),
240 ty::Ref(_, ty, mutbl) => {
241 let tymut = ty::TypeAndMut { ty, mutbl };
242 let tymut_string = tymut.to_string();
243 if tymut_string != "_"
244 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
246 format!("`&{}`", tymut_string).into()
248 // Unknown type name, it's long or has type arguments
250 hir::Mutability::Mut => "mutable reference",
256 ty::FnDef(..) => "fn item".into(),
257 ty::FnPtr(_) => "fn pointer".into(),
258 ty::Dynamic(ref inner, ..) => {
259 if let Some(principal) = inner.principal() {
260 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
262 "trait object".into()
265 ty::Closure(..) => "closure".into(),
266 ty::Generator(..) => "generator".into(),
267 ty::GeneratorWitness(..) => "generator witness".into(),
268 ty::Tuple(..) => "tuple".into(),
269 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
270 ty::Infer(ty::IntVar(_)) => "integer".into(),
271 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
272 ty::Placeholder(..) => "placeholder type".into(),
273 ty::Bound(..) => "bound type".into(),
274 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
275 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
276 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
277 ty::Projection(_) => "associated type".into(),
278 ty::Param(p) => format!("type parameter `{}`", p).into(),
279 ty::Opaque(..) => "opaque type".into(),
280 ty::Error(_) => "type error".into(),
284 pub fn prefix_string(&self) -> Cow<'static, str> {
294 | ty::Never => "type".into(),
295 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
296 ty::Adt(def, _) => def.descr().into(),
297 ty::Foreign(_) => "extern type".into(),
298 ty::Array(..) => "array".into(),
299 ty::Slice(_) => "slice".into(),
300 ty::RawPtr(_) => "raw pointer".into(),
301 ty::Ref(.., mutbl) => match mutbl {
302 hir::Mutability::Mut => "mutable reference",
306 ty::FnDef(..) => "fn item".into(),
307 ty::FnPtr(_) => "fn pointer".into(),
308 ty::Dynamic(..) => "trait object".into(),
309 ty::Closure(..) => "closure".into(),
310 ty::Generator(..) => "generator".into(),
311 ty::GeneratorWitness(..) => "generator witness".into(),
312 ty::Tuple(..) => "tuple".into(),
313 ty::Placeholder(..) => "higher-ranked type".into(),
314 ty::Bound(..) => "bound type variable".into(),
315 ty::Projection(_) => "associated type".into(),
316 ty::Param(_) => "type parameter".into(),
317 ty::Opaque(..) => "opaque type".into(),
322 impl<'tcx> TyCtxt<'tcx> {
323 pub fn note_and_explain_type_err(
325 db: &mut DiagnosticBuilder<'_>,
326 err: &TypeError<'tcx>,
327 cause: &ObligationCause<'tcx>,
329 body_owner_def_id: DefId,
331 use self::TypeError::*;
332 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
335 let expected_str = values.expected.sort_string(self);
336 let found_str = values.found.sort_string(self);
337 if expected_str == found_str && expected_str == "closure" {
338 db.note("no two closures, even if identical, have the same type");
339 db.help("consider boxing your closure and/or using it as a trait object");
341 if expected_str == found_str && expected_str == "opaque type" {
343 db.note("distinct uses of `impl Trait` result in different opaque types");
344 let e_str = values.expected.to_string();
345 let f_str = values.found.to_string();
346 if e_str == f_str && &e_str == "impl std::future::Future" {
347 // FIXME: use non-string based check.
349 "if both `Future`s have the same `Output` type, consider \
350 `.await`ing on both of them",
354 match (&values.expected.kind, &values.found.kind) {
355 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
359 ) = self.sess.source_map().span_to_snippet(sp)
361 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
364 "use a float literal",
365 format!("{}.0", snippet),
371 (ty::Param(expected), ty::Param(found)) => {
372 let generics = self.generics_of(body_owner_def_id);
373 let e_span = self.def_span(generics.type_param(expected, self).def_id);
374 if !sp.contains(e_span) {
375 db.span_label(e_span, "expected type parameter");
377 let f_span = self.def_span(generics.type_param(found, self).def_id);
378 if !sp.contains(f_span) {
379 db.span_label(f_span, "found type parameter");
382 "a type parameter was expected, but a different one was found; \
383 you might be missing a type parameter or trait bound",
386 "for more information, visit \
387 https://doc.rust-lang.org/book/ch10-02-traits.html\
388 #traits-as-parameters",
391 (ty::Projection(_), ty::Projection(_)) => {
392 db.note("an associated type was expected, but a different one was found");
394 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
395 let generics = self.generics_of(body_owner_def_id);
396 let p_span = self.def_span(generics.type_param(p, self).def_id);
397 if !sp.contains(p_span) {
398 db.span_label(p_span, "this type parameter");
400 let hir = self.hir();
402 if let Some(generics) = generics
406 .map(|id| hir.as_local_hir_id(id))
407 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
409 .and_then(|node| node.generics())
411 // Synthesize the associated type restriction `Add<Output = Expected>`.
412 // FIXME: extract this logic for use in other diagnostics.
413 let trait_ref = proj.trait_ref(self);
415 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
416 let item_name = self.item_name(proj.item_def_id);
417 let path = if path.ends_with('>') {
418 format!("{}, {} = {}>", &path[..path.len() - 1], item_name, p)
420 format!("{}<{} = {}>", path, item_name, p)
422 note = !suggest_constraining_type_param(
426 &format!("{}", proj.self_ty()),
432 db.note("you might be missing a type parameter or trait bound");
435 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
436 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
437 let generics = self.generics_of(body_owner_def_id);
438 let p_span = self.def_span(generics.type_param(p, self).def_id);
439 if !sp.contains(p_span) {
440 db.span_label(p_span, "this type parameter");
442 db.help("type parameters must be constrained to match other types");
443 if self.sess.teach(&db.get_code().unwrap()) {
445 "given a type parameter `T` and a method `foo`:
447 trait Trait<T> { fn foo(&self) -> T; }
449 the only ways to implement method `foo` are:
450 - constrain `T` with an explicit type:
452 impl Trait<String> for X {
453 fn foo(&self) -> String { String::new() }
456 - add a trait bound to `T` and call a method on that trait that returns `Self`:
458 impl<T: std::default::Default> Trait<T> for X {
459 fn foo(&self) -> T { <T as std::default::Default>::default() }
462 - change `foo` to return an argument of type `T`:
464 impl<T> Trait<T> for X {
465 fn foo(&self, x: T) -> T { x }
471 "for more information, visit \
472 https://doc.rust-lang.org/book/ch10-02-traits.html\
473 #traits-as-parameters",
476 (ty::Param(p), _) | (_, ty::Param(p)) => {
477 let generics = self.generics_of(body_owner_def_id);
478 let p_span = self.def_span(generics.type_param(p, self).def_id);
479 if !sp.contains(p_span) {
480 db.span_label(p_span, "this type parameter");
483 (ty::Projection(proj_ty), _) => {
484 self.expected_projection(
492 (_, ty::Projection(proj_ty)) => {
494 "consider constraining the associated type `{}` to `{}`",
495 values.found, values.expected,
497 if !self.suggest_constraint(
506 "for more information, visit \
507 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
514 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
515 values.expected, values.expected.kind, values.found, values.found.kind,
519 // Watch out for various cases of cyclic types and try to explain.
520 if ty.is_closure() || ty.is_generator() {
522 "closures cannot capture themselves or take themselves as argument;\n\
523 this error may be the result of a recent compiler bug-fix,\n\
524 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
525 for more information",
529 TargetFeatureCast(def_id) => {
530 let attrs = self.get_attrs(*def_id);
531 let target_spans = attrs
534 .filter(|attr| attr.has_name(sym::target_feature))
535 .map(|attr| attr.span);
537 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
539 db.span_labels(target_spans, "`#[target_feature]` added here");
545 fn suggest_constraint(
547 db: &mut DiagnosticBuilder<'_>,
549 body_owner_def_id: DefId,
550 proj_ty: &ty::ProjectionTy<'tcx>,
553 let assoc = self.associated_item(proj_ty.item_def_id);
554 let trait_ref = proj_ty.trait_ref(*self);
555 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
556 if let Some(hir_generics) = item.generics() {
557 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
558 // This will also work for `impl Trait`.
559 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind {
560 let generics = self.generics_of(body_owner_def_id);
561 generics.type_param(¶m_ty, *self).def_id
566 // First look in the `where` clause, as this might be
567 // `fn foo<T>(x: T) where T: Trait`.
568 for predicate in hir_generics.where_clause.predicates {
569 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
570 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
573 if path.res.opt_def_id() == Some(def_id) {
574 // This predicate is binding type param `A` in `<A as T>::Foo` to
575 // something, potentially `T`.
583 if self.constrain_generic_bound_associated_type_structured_suggestion(
595 for param in hir_generics.params {
596 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
599 // This is type param `A` in `<A as T>::Foo`.
600 return self.constrain_generic_bound_associated_type_structured_suggestion(
615 /// An associated type was expected and a different type was found.
617 /// We perform a few different checks to see what we can suggest:
619 /// - In the current item, look for associated functions that return the expected type and
620 /// suggest calling them. (Not a structured suggestion.)
621 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
622 /// associated type to the found type.
623 /// - If the associated type has a default type and was expected inside of a `trait`, we
624 /// mention that this is disallowed.
625 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
626 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
627 /// fn that returns the type.
628 fn expected_projection(
630 db: &mut DiagnosticBuilder<'_>,
631 proj_ty: &ty::ProjectionTy<'tcx>,
632 values: &ExpectedFound<Ty<'tcx>>,
633 body_owner_def_id: DefId,
634 cause_code: &ObligationCauseCode<'_>,
637 "consider constraining the associated type `{}` to `{}`",
638 values.expected, values.found
640 let body_owner = self.hir().get_if_local(body_owner_def_id);
641 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
643 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
644 let callable_scope = match body_owner {
646 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
647 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
648 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
652 let impl_comparison = matches!(
654 ObligationCauseCode::CompareImplMethodObligation { .. }
655 | ObligationCauseCode::CompareImplTypeObligation { .. }
656 | ObligationCauseCode::CompareImplConstObligation
658 let assoc = self.associated_item(proj_ty.item_def_id);
659 if !callable_scope || impl_comparison {
660 // We do not want to suggest calling functions when the reason of the
661 // type error is a comparison of an `impl` with its `trait` or when the
662 // scope is outside of a `Body`.
664 // If we find a suitable associated function that returns the expected type, we don't
665 // want the more general suggestion later in this method about "consider constraining
666 // the associated type or calling a method that returns the associated type".
667 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
669 assoc.container.id(),
670 current_method_ident,
674 // Possibly suggest constraining the associated type to conform to the
676 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
683 if let ty::Opaque(def_id, _) = proj_ty.self_ty().kind {
684 // When the expected `impl Trait` is not defined in the current item, it will come from
685 // a return type. This can occur when dealing with `TryStream` (#71035).
686 if self.constrain_associated_type_structured_suggestion(
688 self.def_span(def_id),
697 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
701 if !impl_comparison {
702 // Generic suggestion when we can't be more specific.
704 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
709 "for more information, visit \
710 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
713 if self.sess.teach(&db.get_code().unwrap()) {
715 "given an associated type `T` and a method `foo`:
719 fn foo(&self) -> Self::T;
722 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
726 fn foo(&self) -> Self::T { String::new() }
733 fn point_at_methods_that_satisfy_associated_type(
735 db: &mut DiagnosticBuilder<'_>,
736 assoc_container_id: DefId,
737 current_method_ident: Option<Symbol>,
738 proj_ty_item_def_id: DefId,
741 let items = self.associated_items(assoc_container_id);
742 // Find all the methods in the trait that could be called to construct the
743 // expected associated type.
744 // FIXME: consider suggesting the use of associated `const`s.
745 let methods: Vec<(Span, String)> = items
748 .filter(|(name, item)| {
749 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
751 .filter_map(|(_, item)| {
752 let method = self.fn_sig(item.def_id);
753 match method.output().skip_binder().kind {
754 ty::Projection(ty::ProjectionTy { item_def_id, .. })
755 if item_def_id == proj_ty_item_def_id =>
758 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
759 format!("consider calling `{}`", self.def_path_str(item.def_id)),
766 if !methods.is_empty() {
767 // Use a single `help:` to show all the methods in the trait that can
768 // be used to construct the expected associated type.
769 let mut span: MultiSpan =
770 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
772 "{some} method{s} {are} available that return{r} `{ty}`",
773 some = if methods.len() == 1 { "a" } else { "some" },
774 s = pluralize!(methods.len()),
775 are = if methods.len() == 1 { "is" } else { "are" },
776 r = if methods.len() == 1 { "s" } else { "" },
779 for (sp, label) in methods.into_iter() {
780 span.push_span_label(sp, label);
782 db.span_help(span, &msg);
788 fn point_at_associated_type(
790 db: &mut DiagnosticBuilder<'_>,
791 body_owner_def_id: DefId,
794 let hir_id = match body_owner_def_id.as_local().map(|id| self.hir().as_local_hir_id(id)) {
795 Some(hir_id) => hir_id,
796 None => return false,
798 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
799 // `expected` and point at it.
800 let parent_id = self.hir().get_parent_item(hir_id);
801 let item = self.hir().find(parent_id);
802 debug!("expected_projection parent item {:?}", item);
804 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
805 // FIXME: account for `#![feature(specialization)]`
806 for item in &items[..] {
808 hir::AssocItemKind::Type => {
809 // FIXME: account for returning some type in a trait fn impl that has
810 // an assoc type as a return type (#72076).
811 if let hir::Defaultness::Default { has_value: true } = item.defaultness
813 if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found {
816 "associated type defaults can't be assumed inside the \
817 trait defining them",
827 Some(hir::Node::Item(hir::Item {
828 kind: hir::ItemKind::Impl { items, .. }, ..
830 for item in &items[..] {
832 hir::AssocItemKind::Type => {
833 if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found {
834 db.span_label(item.span, "expected this associated type");
847 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
848 /// requirement, provide a strucuted suggestion to constrain it to a given type `ty`.
849 fn constrain_generic_bound_associated_type_structured_suggestion(
851 db: &mut DiagnosticBuilder<'_>,
852 trait_ref: &ty::TraitRef<'tcx>,
853 bounds: hir::GenericBounds<'_>,
854 assoc: &ty::AssocItem,
858 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
859 bounds.iter().any(|bound| match bound {
860 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => {
861 // Relate the type param against `T` in `<A as T>::Foo`.
862 ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)
863 && self.constrain_associated_type_structured_suggestion(
864 db, ptr.span, assoc, ty, msg,
871 /// Given a span corresponding to a bound, provide a structured suggestion to set an
872 /// associated type to a given type `ty`.
873 fn constrain_associated_type_structured_suggestion(
875 db: &mut DiagnosticBuilder<'_>,
877 assoc: &ty::AssocItem,
881 if let Ok(has_params) =
882 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
884 let (span, sugg) = if has_params {
885 let pos = span.hi() - BytePos(1);
886 let span = Span::new(pos, pos, span.ctxt());
887 (span, format!(", {} = {}", assoc.ident, ty))
889 (span.shrink_to_hi(), format!("<{} = {}>", assoc.ident, ty))
891 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);