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 ProjectionBoundsLength(ExpectedFound<usize>),
61 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
62 ObjectUnsafeCoercion(DefId),
63 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
66 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
67 TargetFeatureCast(DefId),
70 pub enum UnconstrainedNumeric {
76 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
77 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
78 /// afterwards to present additional details, particularly when it comes to lifetime-related
80 impl<'tcx> fmt::Display for TypeError<'tcx> {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 use self::TypeError::*;
83 fn report_maybe_different(
84 f: &mut fmt::Formatter<'_>,
88 // A naive approach to making sure that we're not reporting silly errors such as:
89 // (expected closure, found closure).
90 if expected == found {
91 write!(f, "expected {}, found a different {}", expected, found)
93 write!(f, "expected {}, found {}", expected, found)
97 let br_string = |br: ty::BoundRegion| match br {
98 ty::BrNamed(_, name) => format!(" {}", name),
103 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
104 Mismatch => write!(f, "types differ"),
105 UnsafetyMismatch(values) => {
106 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
108 AbiMismatch(values) => {
109 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
111 Mutability => write!(f, "types differ in mutability"),
112 TupleSize(values) => write!(
114 "expected a tuple with {} element{}, \
115 found one with {} element{}",
117 pluralize!(values.expected),
119 pluralize!(values.found)
121 FixedArraySize(values) => write!(
123 "expected an array with a fixed size of {} element{}, \
124 found one with {} element{}",
126 pluralize!(values.expected),
128 pluralize!(values.found)
130 ArgCount => write!(f, "incorrect number of function parameters"),
131 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
132 RegionsInsufficientlyPolymorphic(br, _) => write!(
134 "expected bound lifetime parameter{}, found concrete lifetime",
137 RegionsOverlyPolymorphic(br, _) => write!(
139 "expected concrete lifetime, found bound lifetime parameter{}",
142 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
143 Sorts(values) => ty::tls::with(|tcx| {
144 report_maybe_different(
146 &values.expected.sort_string(tcx),
147 &values.found.sort_string(tcx),
150 Traits(values) => ty::tls::with(|tcx| {
151 report_maybe_different(
153 &format!("trait `{}`", tcx.def_path_str(values.expected)),
154 &format!("trait `{}`", tcx.def_path_str(values.found)),
157 IntMismatch(ref values) => {
158 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
160 FloatMismatch(ref values) => {
161 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
163 VariadicMismatch(ref values) => write!(
165 "expected {} fn, found {} function",
166 if values.expected { "variadic" } else { "non-variadic" },
167 if values.found { "variadic" } else { "non-variadic" }
169 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
172 "expected {}, found {}",
173 tcx.def_path_str(values.expected),
174 tcx.def_path_str(values.found)
177 ProjectionBoundsLength(ref values) => write!(
179 "expected {} associated type binding{}, found {}",
181 pluralize!(values.expected),
184 ExistentialMismatch(ref values) => report_maybe_different(
186 &format!("trait `{}`", values.expected),
187 &format!("trait `{}`", values.found),
189 ConstMismatch(ref values) => {
190 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
192 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
193 TargetFeatureCast(_) => write!(
195 "cannot coerce functions with `#[target_feature]` to safe function pointers"
197 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
202 impl<'tcx> TypeError<'tcx> {
203 pub fn must_include_note(&self) -> bool {
204 use self::TypeError::*;
206 CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
207 | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_)
208 | TargetFeatureCast(_) => false,
213 | RegionsDoesNotOutlive(..)
214 | RegionsInsufficientlyPolymorphic(..)
215 | RegionsOverlyPolymorphic(..)
216 | RegionsPlaceholderMismatch
218 | ProjectionMismatched(_)
219 | ProjectionBoundsLength(_)
220 | ExistentialMismatch(_)
223 | ObjectUnsafeCoercion(_) => true,
228 impl<'tcx> ty::TyS<'tcx> {
229 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
231 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
232 format!("`{}`", self).into()
234 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
236 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
237 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
239 let n = tcx.lift(&n).unwrap();
240 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
241 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
242 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
243 None => "array".into(),
246 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
247 ty::Slice(_) => "slice".into(),
248 ty::RawPtr(_) => "*-ptr".into(),
249 ty::Ref(_, ty, mutbl) => {
250 let tymut = ty::TypeAndMut { ty, mutbl };
251 let tymut_string = tymut.to_string();
252 if tymut_string != "_"
253 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
255 format!("`&{}`", tymut_string).into()
257 // Unknown type name, it's long or has type arguments
259 hir::Mutability::Mut => "mutable reference",
265 ty::FnDef(..) => "fn item".into(),
266 ty::FnPtr(_) => "fn pointer".into(),
267 ty::Dynamic(ref inner, ..) => {
268 if let Some(principal) = inner.principal() {
269 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
271 "trait object".into()
274 ty::Closure(..) => "closure".into(),
275 ty::Generator(..) => "generator".into(),
276 ty::GeneratorWitness(..) => "generator witness".into(),
277 ty::Tuple(..) => "tuple".into(),
278 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
279 ty::Infer(ty::IntVar(_)) => "integer".into(),
280 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
281 ty::Placeholder(..) => "placeholder type".into(),
282 ty::Bound(..) => "bound type".into(),
283 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
284 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
285 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
286 ty::Projection(_) => "associated type".into(),
287 ty::Param(p) => format!("type parameter `{}`", p).into(),
288 ty::Opaque(..) => "opaque type".into(),
289 ty::Error => "type error".into(),
293 pub fn prefix_string(&self) -> Cow<'static, str> {
303 | ty::Never => "type".into(),
304 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
305 ty::Adt(def, _) => def.descr().into(),
306 ty::Foreign(_) => "extern type".into(),
307 ty::Array(..) => "array".into(),
308 ty::Slice(_) => "slice".into(),
309 ty::RawPtr(_) => "raw pointer".into(),
310 ty::Ref(.., mutbl) => match mutbl {
311 hir::Mutability::Mut => "mutable reference",
315 ty::FnDef(..) => "fn item".into(),
316 ty::FnPtr(_) => "fn pointer".into(),
317 ty::Dynamic(..) => "trait object".into(),
318 ty::Closure(..) => "closure".into(),
319 ty::Generator(..) => "generator".into(),
320 ty::GeneratorWitness(..) => "generator witness".into(),
321 ty::Tuple(..) => "tuple".into(),
322 ty::Placeholder(..) => "higher-ranked type".into(),
323 ty::Bound(..) => "bound type variable".into(),
324 ty::Projection(_) => "associated type".into(),
325 ty::Param(_) => "type parameter".into(),
326 ty::Opaque(..) => "opaque type".into(),
331 impl<'tcx> TyCtxt<'tcx> {
332 pub fn note_and_explain_type_err(
334 db: &mut DiagnosticBuilder<'_>,
335 err: &TypeError<'tcx>,
336 cause: &ObligationCause<'tcx>,
338 body_owner_def_id: DefId,
340 use self::TypeError::*;
341 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
344 let expected_str = values.expected.sort_string(self);
345 let found_str = values.found.sort_string(self);
346 if expected_str == found_str && expected_str == "closure" {
347 db.note("no two closures, even if identical, have the same type");
348 db.help("consider boxing your closure and/or using it as a trait object");
350 if expected_str == found_str && expected_str == "opaque type" {
352 db.note("distinct uses of `impl Trait` result in different opaque types");
353 let e_str = values.expected.to_string();
354 let f_str = values.found.to_string();
355 if e_str == f_str && &e_str == "impl std::future::Future" {
356 // FIXME: use non-string based check.
358 "if both `Future`s have the same `Output` type, consider \
359 `.await`ing on both of them",
363 match (&values.expected.kind, &values.found.kind) {
364 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
368 ) = self.sess.source_map().span_to_snippet(sp)
370 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
373 "use a float literal",
374 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.as_local_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 = proj.trait_ref(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 path = if path.ends_with('>') {
427 format!("{}, {} = {}>", &path[..path.len() - 1], item_name, p)
429 format!("{}<{} = {}>", path, item_name, p)
431 note = !suggest_constraining_type_param(
435 &format!("{}", proj.self_ty()),
441 db.note("you might be missing a type parameter or trait bound");
444 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
445 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
446 let generics = self.generics_of(body_owner_def_id);
447 let p_span = self.def_span(generics.type_param(p, self).def_id);
448 if !sp.contains(p_span) {
449 db.span_label(p_span, "this type parameter");
451 db.help("type parameters must be constrained to match other types");
452 if self.sess.teach(&db.get_code().unwrap()) {
454 "given a type parameter `T` and a method `foo`:
456 trait Trait<T> { fn foo(&self) -> T; }
458 the only ways to implement method `foo` are:
459 - constrain `T` with an explicit type:
461 impl Trait<String> for X {
462 fn foo(&self) -> String { String::new() }
465 - add a trait bound to `T` and call a method on that trait that returns `Self`:
467 impl<T: std::default::Default> Trait<T> for X {
468 fn foo(&self) -> T { <T as std::default::Default>::default() }
471 - change `foo` to return an argument of type `T`:
473 impl<T> Trait<T> for X {
474 fn foo(&self, x: T) -> T { x }
480 "for more information, visit \
481 https://doc.rust-lang.org/book/ch10-02-traits.html\
482 #traits-as-parameters",
485 (ty::Param(p), _) | (_, ty::Param(p)) => {
486 let generics = self.generics_of(body_owner_def_id);
487 let p_span = self.def_span(generics.type_param(p, self).def_id);
488 if !sp.contains(p_span) {
489 db.span_label(p_span, "this type parameter");
492 (ty::Projection(proj_ty), _) => {
493 self.expected_projection(
501 (_, ty::Projection(proj_ty)) => {
503 "consider constraining the associated type `{}` to `{}`",
504 values.found, values.expected,
506 if !self.suggest_constraint(
515 "for more information, visit \
516 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
523 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
524 values.expected, values.expected.kind, values.found, values.found.kind,
528 // Watch out for various cases of cyclic types and try to explain.
529 if ty.is_closure() || ty.is_generator() {
531 "closures cannot capture themselves or take themselves as argument;\n\
532 this error may be the result of a recent compiler bug-fix,\n\
533 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
534 for more information",
538 TargetFeatureCast(def_id) => {
539 let attrs = self.get_attrs(*def_id);
540 let target_spans = attrs
543 .filter(|attr| attr.has_name(sym::target_feature))
544 .map(|attr| attr.span);
546 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
548 db.span_labels(target_spans, "`#[target_feature]` added here");
554 fn suggest_constraint(
556 db: &mut DiagnosticBuilder<'_>,
558 body_owner_def_id: DefId,
559 proj_ty: &ty::ProjectionTy<'tcx>,
562 let assoc = self.associated_item(proj_ty.item_def_id);
563 let trait_ref = proj_ty.trait_ref(*self);
564 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
565 if let Some(hir_generics) = item.generics() {
566 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
567 // This will also work for `impl Trait`.
568 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind {
569 let generics = self.generics_of(body_owner_def_id);
570 generics.type_param(¶m_ty, *self).def_id
575 // First look in the `where` clause, as this might be
576 // `fn foo<T>(x: T) where T: Trait`.
577 for predicate in hir_generics.where_clause.predicates {
578 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
579 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
582 if path.res.opt_def_id() == Some(def_id) {
583 // This predicate is binding type param `A` in `<A as T>::Foo` to
584 // something, potentially `T`.
592 if self.constrain_generic_bound_associated_type_structured_suggestion(
604 for param in hir_generics.params {
605 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
608 // This is type param `A` in `<A as T>::Foo`.
609 return self.constrain_generic_bound_associated_type_structured_suggestion(
624 /// An associated type was expected and a different type was found.
626 /// We perform a few different checks to see what we can suggest:
628 /// - In the current item, look for associated functions that return the expected type and
629 /// suggest calling them. (Not a structured suggestion.)
630 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
631 /// associated type to the found type.
632 /// - If the associated type has a default type and was expected inside of a `trait`, we
633 /// mention that this is disallowed.
634 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
635 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
636 /// fn that returns the type.
637 fn expected_projection(
639 db: &mut DiagnosticBuilder<'_>,
640 proj_ty: &ty::ProjectionTy<'tcx>,
641 values: &ExpectedFound<Ty<'tcx>>,
642 body_owner_def_id: DefId,
643 cause_code: &ObligationCauseCode<'_>,
646 "consider constraining the associated type `{}` to `{}`",
647 values.expected, values.found
649 let body_owner = self.hir().get_if_local(body_owner_def_id);
650 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
652 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
653 let callable_scope = match body_owner {
655 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
656 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
657 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
661 let impl_comparison = matches!(
663 ObligationCauseCode::CompareImplMethodObligation { .. }
664 | ObligationCauseCode::CompareImplTypeObligation { .. }
665 | ObligationCauseCode::CompareImplConstObligation
667 let assoc = self.associated_item(proj_ty.item_def_id);
668 if !callable_scope || impl_comparison {
669 // We do not want to suggest calling functions when the reason of the
670 // type error is a comparison of an `impl` with its `trait` or when the
671 // scope is outside of a `Body`.
673 // If we find a suitable associated function that returns the expected type, we don't
674 // want the more general suggestion later in this method about "consider constraining
675 // the associated type or calling a method that returns the associated type".
676 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
678 assoc.container.id(),
679 current_method_ident,
683 // Possibly suggest constraining the associated type to conform to the
685 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
692 if let ty::Opaque(def_id, _) = proj_ty.self_ty().kind {
693 // When the expected `impl Trait` is not defined in the current item, it will come from
694 // a return type. This can occur when dealing with `TryStream` (#71035).
695 if self.constrain_associated_type_structured_suggestion(
697 self.def_span(def_id),
706 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
710 if !impl_comparison {
711 // Generic suggestion when we can't be more specific.
713 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
718 "for more information, visit \
719 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
722 if self.sess.teach(&db.get_code().unwrap()) {
724 "given an associated type `T` and a method `foo`:
728 fn foo(&self) -> Self::T;
731 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
735 fn foo(&self) -> Self::T { String::new() }
742 fn point_at_methods_that_satisfy_associated_type(
744 db: &mut DiagnosticBuilder<'_>,
745 assoc_container_id: DefId,
746 current_method_ident: Option<Symbol>,
747 proj_ty_item_def_id: DefId,
750 let items = self.associated_items(assoc_container_id);
751 // Find all the methods in the trait that could be called to construct the
752 // expected associated type.
753 // FIXME: consider suggesting the use of associated `const`s.
754 let methods: Vec<(Span, String)> = items
757 .filter(|(name, item)| {
758 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
760 .filter_map(|(_, item)| {
761 let method = self.fn_sig(item.def_id);
762 match method.output().skip_binder().kind {
763 ty::Projection(ty::ProjectionTy { item_def_id, .. })
764 if item_def_id == proj_ty_item_def_id =>
767 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
768 format!("consider calling `{}`", self.def_path_str(item.def_id)),
775 if !methods.is_empty() {
776 // Use a single `help:` to show all the methods in the trait that can
777 // be used to construct the expected associated type.
778 let mut span: MultiSpan =
779 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
781 "{some} method{s} {are} available that return{r} `{ty}`",
782 some = if methods.len() == 1 { "a" } else { "some" },
783 s = pluralize!(methods.len()),
784 are = if methods.len() == 1 { "is" } else { "are" },
785 r = if methods.len() == 1 { "s" } else { "" },
788 for (sp, label) in methods.into_iter() {
789 span.push_span_label(sp, label);
791 db.span_help(span, &msg);
797 fn point_at_associated_type(
799 db: &mut DiagnosticBuilder<'_>,
800 body_owner_def_id: DefId,
803 let hir_id = match body_owner_def_id.as_local().map(|id| self.hir().as_local_hir_id(id)) {
804 Some(hir_id) => hir_id,
805 None => return false,
807 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
808 // `expected` and point at it.
809 let parent_id = self.hir().get_parent_item(hir_id);
810 let item = self.hir().find(parent_id);
811 debug!("expected_projection parent item {:?}", item);
813 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
814 // FIXME: account for `#![feature(specialization)]`
815 for item in &items[..] {
817 hir::AssocItemKind::Type | hir::AssocItemKind::OpaqueTy => {
818 // FIXME: account for returning some type in a trait fn impl that has
819 // an assoc type as a return type (#72076).
820 if let hir::Defaultness::Default { has_value: true } = item.defaultness
822 if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found {
825 "associated type defaults can't be assumed inside the \
826 trait defining them",
836 Some(hir::Node::Item(hir::Item {
837 kind: hir::ItemKind::Impl { items, .. }, ..
839 for item in &items[..] {
841 hir::AssocItemKind::Type | hir::AssocItemKind::OpaqueTy => {
842 if self.type_of(self.hir().local_def_id(item.id.hir_id)) == found {
843 db.span_label(item.span, "expected this associated type");
856 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
857 /// requirement, provide a strucuted suggestion to constrain it to a given type `ty`.
858 fn constrain_generic_bound_associated_type_structured_suggestion(
860 db: &mut DiagnosticBuilder<'_>,
861 trait_ref: &ty::TraitRef<'tcx>,
862 bounds: hir::GenericBounds<'_>,
863 assoc: &ty::AssocItem,
867 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
868 bounds.iter().any(|bound| match bound {
869 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => {
870 // Relate the type param against `T` in `<A as T>::Foo`.
871 ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)
872 && self.constrain_associated_type_structured_suggestion(
873 db, ptr.span, assoc, ty, msg,
880 /// Given a span corresponding to a bound, provide a structured suggestion to set an
881 /// associated type to a given type `ty`.
882 fn constrain_associated_type_structured_suggestion(
884 db: &mut DiagnosticBuilder<'_>,
886 assoc: &ty::AssocItem,
890 if let Ok(has_params) =
891 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
893 let (span, sugg) = if has_params {
894 let pos = span.hi() - BytePos(1);
895 let span = Span::new(pos, pos, span.ctxt());
896 (span, format!(", {} = {}", assoc.ident, ty))
898 (span.shrink_to_hi(), format!("<{} = {}>", assoc.ident, ty))
900 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);