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_constraining_opaque_associated_type(
519 ) || self.suggest_constraint(
528 "for more information, visit \
529 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
536 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
538 values.expected.kind(),
544 // Watch out for various cases of cyclic types and try to explain.
545 if ty.is_closure() || ty.is_generator() {
547 "closures cannot capture themselves or take themselves as argument;\n\
548 this error may be the result of a recent compiler bug-fix,\n\
549 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
550 for more information",
554 TargetFeatureCast(def_id) => {
555 let attrs = self.get_attrs(*def_id);
556 let target_spans = attrs
558 .filter(|attr| attr.has_name(sym::target_feature))
559 .map(|attr| attr.span);
561 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
563 db.span_labels(target_spans, "`#[target_feature]` added here");
569 fn suggest_constraint(
571 db: &mut DiagnosticBuilder<'_>,
573 body_owner_def_id: DefId,
574 proj_ty: &ty::ProjectionTy<'tcx>,
577 let assoc = self.associated_item(proj_ty.item_def_id);
578 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
579 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
580 if let Some(hir_generics) = item.generics() {
581 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
582 // This will also work for `impl Trait`.
583 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
584 let generics = self.generics_of(body_owner_def_id);
585 generics.type_param(param_ty, self).def_id
590 // First look in the `where` clause, as this might be
591 // `fn foo<T>(x: T) where T: Trait`.
592 for predicate in hir_generics.where_clause.predicates {
593 if let hir::WherePredicate::BoundPredicate(pred) = predicate {
594 if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
597 if path.res.opt_def_id() == Some(def_id) {
598 // This predicate is binding type param `A` in `<A as T>::Foo` to
599 // something, potentially `T`.
607 if self.constrain_generic_bound_associated_type_structured_suggestion(
620 for param in hir_generics.params {
621 if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
624 // This is type param `A` in `<A as T>::Foo`.
625 return self.constrain_generic_bound_associated_type_structured_suggestion(
641 /// An associated type was expected and a different type was found.
643 /// We perform a few different checks to see what we can suggest:
645 /// - In the current item, look for associated functions that return the expected type and
646 /// suggest calling them. (Not a structured suggestion.)
647 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
648 /// associated type to the found type.
649 /// - If the associated type has a default type and was expected inside of a `trait`, we
650 /// mention that this is disallowed.
651 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
652 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
653 /// fn that returns the type.
654 fn expected_projection(
656 db: &mut DiagnosticBuilder<'_>,
657 proj_ty: &ty::ProjectionTy<'tcx>,
658 values: &ExpectedFound<Ty<'tcx>>,
659 body_owner_def_id: DefId,
660 cause_code: &ObligationCauseCode<'_>,
663 "consider constraining the associated type `{}` to `{}`",
664 values.expected, values.found
666 let body_owner = self.hir().get_if_local(body_owner_def_id);
667 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
669 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
670 let callable_scope = matches!(
673 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
674 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
675 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
678 let impl_comparison = matches!(
680 ObligationCauseCode::CompareImplMethodObligation { .. }
681 | ObligationCauseCode::CompareImplTypeObligation { .. }
682 | ObligationCauseCode::CompareImplConstObligation
684 let assoc = self.associated_item(proj_ty.item_def_id);
685 if !callable_scope || impl_comparison {
686 // We do not want to suggest calling functions when the reason of the
687 // type error is a comparison of an `impl` with its `trait` or when the
688 // scope is outside of a `Body`.
690 // If we find a suitable associated function that returns the expected type, we don't
691 // want the more general suggestion later in this method about "consider constraining
692 // the associated type or calling a method that returns the associated type".
693 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
695 assoc.container.id(),
696 current_method_ident,
700 // Possibly suggest constraining the associated type to conform to the
702 if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
709 self.suggest_constraining_opaque_associated_type(db, &msg, proj_ty, values.found);
711 if self.point_at_associated_type(db, body_owner_def_id, values.found) {
715 if !impl_comparison {
716 // Generic suggestion when we can't be more specific.
718 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
723 "for more information, visit \
724 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
727 if self.sess.teach(&db.get_code().unwrap()) {
729 "given an associated type `T` and a method `foo`:
733 fn foo(&self) -> Self::T;
736 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
740 fn foo(&self) -> Self::T { String::new() }
747 /// When the expected `impl Trait` is not defined in the current item, it will come from
748 /// a return type. This can occur when dealing with `TryStream` (#71035).
749 fn suggest_constraining_opaque_associated_type(
751 db: &mut DiagnosticBuilder<'_>,
753 proj_ty: &ty::ProjectionTy<'tcx>,
756 let assoc = self.associated_item(proj_ty.item_def_id);
757 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
758 self.constrain_associated_type_structured_suggestion(
760 self.def_span(def_id),
762 proj_ty.trait_ref_and_own_substs(self).1,
771 fn point_at_methods_that_satisfy_associated_type(
773 db: &mut DiagnosticBuilder<'_>,
774 assoc_container_id: DefId,
775 current_method_ident: Option<Symbol>,
776 proj_ty_item_def_id: DefId,
779 let items = self.associated_items(assoc_container_id);
780 // Find all the methods in the trait that could be called to construct the
781 // expected associated type.
782 // FIXME: consider suggesting the use of associated `const`s.
783 let methods: Vec<(Span, String)> = items
786 .filter(|(name, item)| {
787 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
789 .filter_map(|(_, item)| {
790 let method = self.fn_sig(item.def_id);
791 match *method.output().skip_binder().kind() {
792 ty::Projection(ty::ProjectionTy { item_def_id, .. })
793 if item_def_id == proj_ty_item_def_id =>
796 self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
797 format!("consider calling `{}`", self.def_path_str(item.def_id)),
804 if !methods.is_empty() {
805 // Use a single `help:` to show all the methods in the trait that can
806 // be used to construct the expected associated type.
807 let mut span: MultiSpan =
808 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
810 "{some} method{s} {are} available that return{r} `{ty}`",
811 some = if methods.len() == 1 { "a" } else { "some" },
812 s = pluralize!(methods.len()),
813 are = if methods.len() == 1 { "is" } else { "are" },
814 r = if methods.len() == 1 { "s" } else { "" },
817 for (sp, label) in methods.into_iter() {
818 span.push_span_label(sp, label);
820 db.span_help(span, &msg);
826 fn point_at_associated_type(
828 db: &mut DiagnosticBuilder<'_>,
829 body_owner_def_id: DefId,
833 match body_owner_def_id.as_local().map(|id| self.hir().local_def_id_to_hir_id(id)) {
834 Some(hir_id) => hir_id,
835 None => return false,
837 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
838 // `expected` and point at it.
839 let parent_id = self.hir().get_parent_item(hir_id);
840 let item = self.hir().find(parent_id);
841 debug!("expected_projection parent item {:?}", item);
843 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
844 // FIXME: account for `#![feature(specialization)]`
845 for item in &items[..] {
847 hir::AssocItemKind::Type => {
848 // FIXME: account for returning some type in a trait fn impl that has
849 // an assoc type as a return type (#72076).
850 if let hir::Defaultness::Default { has_value: true } = item.defaultness
852 if self.type_of(item.id.def_id) == found {
855 "associated type defaults can't be assumed inside the \
856 trait defining them",
866 Some(hir::Node::Item(hir::Item {
867 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
870 for item in &items[..] {
871 if let hir::AssocItemKind::Type = item.kind {
872 if self.type_of(item.id.def_id) == found {
873 db.span_label(item.span, "expected this associated type");
884 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
885 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
886 fn constrain_generic_bound_associated_type_structured_suggestion(
888 db: &mut DiagnosticBuilder<'_>,
889 trait_ref: &ty::TraitRef<'tcx>,
890 bounds: hir::GenericBounds<'_>,
891 assoc: &ty::AssocItem,
892 assoc_substs: &[ty::GenericArg<'tcx>],
896 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
897 bounds.iter().any(|bound| match bound {
898 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => {
899 // Relate the type param against `T` in `<A as T>::Foo`.
900 ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id)
901 && self.constrain_associated_type_structured_suggestion(
914 /// Given a span corresponding to a bound, provide a structured suggestion to set an
915 /// associated type to a given type `ty`.
916 fn constrain_associated_type_structured_suggestion(
918 db: &mut DiagnosticBuilder<'_>,
920 assoc: &ty::AssocItem,
921 assoc_substs: &[ty::GenericArg<'tcx>],
925 if let Ok(has_params) =
926 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
928 let (span, sugg) = if has_params {
929 let pos = span.hi() - BytePos(1);
930 let span = Span::new(pos, pos, span.ctxt());
931 (span, format!(", {} = {}", assoc.ident, ty))
933 let item_args = self.format_generic_args(assoc_substs);
934 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident, item_args, ty))
936 db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
942 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
943 let mut item_args = String::new();
944 FmtPrinter::new(self, &mut item_args, hir::def::Namespace::TypeNS)
945 .path_generic_args(Ok, args)
946 .expect("could not write to `String`.");