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};
6 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
7 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
9 use rustc_hir::def_id::DefId;
10 use rustc_span::symbol::{sym, Symbol};
11 use rustc_span::{BytePos, Span};
12 use rustc_target::spec::abi;
15 use std::collections::hash_map::DefaultHasher;
17 use std::hash::{Hash, Hasher};
18 use std::path::PathBuf;
20 use super::print::PrettyPrinter;
22 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable, Lift)]
23 pub struct ExpectedFound<T> {
28 impl<T> ExpectedFound<T> {
29 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
31 ExpectedFound { expected: a, found: b }
33 ExpectedFound { expected: b, found: a }
38 // Data structures used in type unification
39 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
40 #[rustc_pass_by_value]
41 pub enum TypeError<'tcx> {
43 ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
44 PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
45 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
46 AbiMismatch(ExpectedFound<abi::Abi>),
48 ArgumentMutability(usize),
49 TupleSize(ExpectedFound<usize>),
50 FixedArraySize(ExpectedFound<u64>),
52 FieldMisMatch(Symbol, Symbol),
54 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
55 RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
56 RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
57 RegionsPlaceholderMismatch,
59 Sorts(ExpectedFound<Ty<'tcx>>),
60 ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
61 IntMismatch(ExpectedFound<ty::IntVarValue>),
62 FloatMismatch(ExpectedFound<ty::FloatTy>),
63 Traits(ExpectedFound<DefId>),
64 VariadicMismatch(ExpectedFound<bool>),
66 /// Instantiating a type variable with the given type would have
67 /// created a cycle (because it appears somewhere within that
70 CyclicConst(ty::Const<'tcx>),
71 ProjectionMismatched(ExpectedFound<DefId>),
72 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
73 ObjectUnsafeCoercion(DefId),
74 ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
77 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
78 TargetFeatureCast(DefId),
82 pub fn involves_regions(self) -> bool {
84 TypeError::RegionsDoesNotOutlive(_, _)
85 | TypeError::RegionsInsufficientlyPolymorphic(_, _)
86 | TypeError::RegionsOverlyPolymorphic(_, _)
87 | TypeError::RegionsPlaceholderMismatch => true,
93 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
94 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
95 /// afterwards to present additional details, particularly when it comes to lifetime-related
97 impl<'tcx> fmt::Display for TypeError<'tcx> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 use self::TypeError::*;
100 fn report_maybe_different(
101 f: &mut fmt::Formatter<'_>,
105 // A naive approach to making sure that we're not reporting silly errors such as:
106 // (expected closure, found closure).
107 if expected == found {
108 write!(f, "expected {}, found a different {}", expected, found)
110 write!(f, "expected {}, found {}", expected, found)
114 let br_string = |br: ty::BoundRegionKind| match br {
115 ty::BrNamed(_, name) => format!(" {}", name),
120 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
121 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
122 Mismatch => write!(f, "types differ"),
123 ConstnessMismatch(values) => {
124 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
126 PolarityMismatch(values) => {
127 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
129 UnsafetyMismatch(values) => {
130 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
132 AbiMismatch(values) => {
133 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
135 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
136 TupleSize(values) => write!(
138 "expected a tuple with {} element{}, found one with {} element{}",
140 pluralize!(values.expected),
142 pluralize!(values.found)
144 FixedArraySize(values) => write!(
146 "expected an array with a fixed size of {} element{}, found one with {} element{}",
148 pluralize!(values.expected),
150 pluralize!(values.found)
152 ArgCount => write!(f, "incorrect number of function parameters"),
153 FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
154 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
155 // Actually naming the region here is a bit confusing because context is lacking
156 RegionsInsufficientlyPolymorphic(..) => {
157 write!(f, "one type is more general than the other")
159 RegionsOverlyPolymorphic(br, _) => write!(
161 "expected concrete lifetime, found bound lifetime parameter{}",
164 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
165 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
166 report_maybe_different(
168 &values.expected.sort_string(tcx),
169 &values.found.sort_string(tcx),
172 Traits(values) => ty::tls::with(|tcx| {
173 report_maybe_different(
175 &format!("trait `{}`", tcx.def_path_str(values.expected)),
176 &format!("trait `{}`", tcx.def_path_str(values.found)),
179 IntMismatch(ref values) => {
180 let expected = match values.expected {
181 ty::IntVarValue::IntType(ty) => ty.name_str(),
182 ty::IntVarValue::UintType(ty) => ty.name_str(),
184 let found = match values.found {
185 ty::IntVarValue::IntType(ty) => ty.name_str(),
186 ty::IntVarValue::UintType(ty) => ty.name_str(),
188 write!(f, "expected `{}`, found `{}`", expected, found)
190 FloatMismatch(ref values) => {
193 "expected `{}`, found `{}`",
194 values.expected.name_str(),
195 values.found.name_str()
198 VariadicMismatch(ref values) => write!(
200 "expected {} fn, found {} function",
201 if values.expected { "variadic" } else { "non-variadic" },
202 if values.found { "variadic" } else { "non-variadic" }
204 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
207 "expected {}, found {}",
208 tcx.def_path_str(values.expected),
209 tcx.def_path_str(values.found)
212 ExistentialMismatch(ref values) => report_maybe_different(
214 &format!("trait `{}`", values.expected),
215 &format!("trait `{}`", values.found),
217 ConstMismatch(ref values) => {
218 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
220 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
221 TargetFeatureCast(_) => write!(
223 "cannot coerce functions with `#[target_feature]` to safe function pointers"
225 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
230 impl<'tcx> TypeError<'tcx> {
231 pub fn must_include_note(self) -> bool {
232 use self::TypeError::*;
234 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
235 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
236 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
237 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
240 | ArgumentMutability(_)
244 | RegionsDoesNotOutlive(..)
245 | RegionsInsufficientlyPolymorphic(..)
246 | RegionsOverlyPolymorphic(..)
247 | RegionsPlaceholderMismatch
249 | ProjectionMismatched(_)
250 | ExistentialMismatch(_)
253 | ObjectUnsafeCoercion(_) => true,
258 impl<'tcx> Ty<'tcx> {
259 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
261 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
262 format!("`{}`", self).into()
264 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
266 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
267 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
269 if t.is_simple_ty() {
270 return format!("array `{}`", self).into();
273 let n = tcx.lift(n).unwrap();
274 if let ty::ConstKind::Value(v) = n.kind() {
275 if let Some(n) = v.try_to_machine_usize(tcx) {
276 return format!("array of {} element{}", n, pluralize!(n)).into();
281 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
282 ty::Slice(_) => "slice".into(),
283 ty::RawPtr(tymut) => {
284 let tymut_string = match tymut.mutbl {
285 hir::Mutability::Mut => tymut.to_string(),
286 hir::Mutability::Not => format!("const {}", tymut.ty),
289 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
290 format!("`*{}`", tymut_string).into()
292 // Unknown type name, it's long or has type arguments
296 ty::Ref(_, ty, mutbl) => {
297 let tymut = ty::TypeAndMut { ty, mutbl };
298 let tymut_string = tymut.to_string();
300 if tymut_string != "_"
301 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
303 format!("`&{}`", tymut_string).into()
305 // Unknown type name, it's long or has type arguments
307 hir::Mutability::Mut => "mutable reference",
313 ty::FnDef(..) => "fn item".into(),
314 ty::FnPtr(_) => "fn pointer".into(),
315 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
316 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
318 ty::Dynamic(..) => "trait object".into(),
319 ty::Closure(..) => "closure".into(),
320 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
321 ty::GeneratorWitness(..) => "generator witness".into(),
322 ty::Tuple(..) => "tuple".into(),
323 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
324 ty::Infer(ty::IntVar(_)) => "integer".into(),
325 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
326 ty::Placeholder(..) => "placeholder type".into(),
327 ty::Bound(..) => "bound type".into(),
328 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
329 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
330 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
331 ty::Projection(_) => "associated type".into(),
332 ty::Param(p) => format!("type parameter `{}`", p).into(),
333 ty::Opaque(..) => "opaque type".into(),
334 ty::Error(_) => "type error".into(),
338 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
348 | ty::Never => "type".into(),
349 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
350 ty::Adt(def, _) => def.descr().into(),
351 ty::Foreign(_) => "extern type".into(),
352 ty::Array(..) => "array".into(),
353 ty::Slice(_) => "slice".into(),
354 ty::RawPtr(_) => "raw pointer".into(),
355 ty::Ref(.., mutbl) => match mutbl {
356 hir::Mutability::Mut => "mutable reference",
360 ty::FnDef(..) => "fn item".into(),
361 ty::FnPtr(_) => "fn pointer".into(),
362 ty::Dynamic(..) => "trait object".into(),
363 ty::Closure(..) => "closure".into(),
364 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
365 ty::GeneratorWitness(..) => "generator witness".into(),
366 ty::Tuple(..) => "tuple".into(),
367 ty::Placeholder(..) => "higher-ranked type".into(),
368 ty::Bound(..) => "bound type variable".into(),
369 ty::Projection(_) => "associated type".into(),
370 ty::Param(_) => "type parameter".into(),
371 ty::Opaque(..) => "opaque type".into(),
376 impl<'tcx> TyCtxt<'tcx> {
377 pub fn note_and_explain_type_err(
379 diag: &mut Diagnostic,
380 err: TypeError<'tcx>,
381 cause: &ObligationCause<'tcx>,
383 body_owner_def_id: DefId,
385 use self::TypeError::*;
386 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
388 ArgumentSorts(values, _) | Sorts(values) => {
389 match (values.expected.kind(), values.found.kind()) {
390 (ty::Closure(..), ty::Closure(..)) => {
391 diag.note("no two closures, even if identical, have the same type");
392 diag.help("consider boxing your closure and/or using it as a trait object");
394 (ty::Opaque(..), ty::Opaque(..)) => {
396 diag.note("distinct uses of `impl Trait` result in different opaque types");
398 (ty::Float(_), ty::Infer(ty::IntVar(_)))
402 ) = self.sess.source_map().span_to_snippet(sp) =>
404 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
405 diag.span_suggestion(
407 "use a float literal",
408 format!("{}.0", snippet),
413 (ty::Param(expected), ty::Param(found)) => {
414 let generics = self.generics_of(body_owner_def_id);
415 let e_span = self.def_span(generics.type_param(expected, self).def_id);
416 if !sp.contains(e_span) {
417 diag.span_label(e_span, "expected type parameter");
419 let f_span = self.def_span(generics.type_param(found, self).def_id);
420 if !sp.contains(f_span) {
421 diag.span_label(f_span, "found type parameter");
424 "a type parameter was expected, but a different one was found; \
425 you might be missing a type parameter or trait bound",
428 "for more information, visit \
429 https://doc.rust-lang.org/book/ch10-02-traits.html\
430 #traits-as-parameters",
433 (ty::Projection(_), ty::Projection(_)) => {
434 diag.note("an associated type was expected, but a different one was found");
436 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p))
437 if self.def_kind(proj.item_def_id) != DefKind::ImplTraitPlaceholder =>
439 let generics = self.generics_of(body_owner_def_id);
440 let p_span = self.def_span(generics.type_param(p, self).def_id);
441 if !sp.contains(p_span) {
442 diag.span_label(p_span, "this type parameter");
444 let hir = self.hir();
446 if let Some(generics) = generics
450 .map(|id| hir.local_def_id_to_hir_id(id))
451 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
453 .and_then(|node| node.generics())
455 // Synthesize the associated type restriction `Add<Output = Expected>`.
456 // FIXME: extract this logic for use in other diagnostics.
457 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
459 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
460 let item_name = self.item_name(proj.item_def_id);
461 let item_args = self.format_generic_args(assoc_substs);
463 let path = if path.ends_with('>') {
466 &path[..path.len() - 1],
472 format!("{}<{}{} = {}>", path, item_name, item_args, p)
474 note = !suggest_constraining_type_param(
478 &format!("{}", proj.self_ty()),
484 diag.note("you might be missing a type parameter or trait bound");
487 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
488 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
489 let generics = self.generics_of(body_owner_def_id);
490 let p_span = self.def_span(generics.type_param(p, self).def_id);
491 if !sp.contains(p_span) {
492 diag.span_label(p_span, "this type parameter");
494 diag.help("type parameters must be constrained to match other types");
495 if self.sess.teach(&diag.get_code().unwrap()) {
497 "given a type parameter `T` and a method `foo`:
499 trait Trait<T> { fn foo(&self) -> T; }
501 the only ways to implement method `foo` are:
502 - constrain `T` with an explicit type:
504 impl Trait<String> for X {
505 fn foo(&self) -> String { String::new() }
508 - add a trait bound to `T` and call a method on that trait that returns `Self`:
510 impl<T: std::default::Default> Trait<T> for X {
511 fn foo(&self) -> T { <T as std::default::Default>::default() }
514 - change `foo` to return an argument of type `T`:
516 impl<T> Trait<T> for X {
517 fn foo(&self, x: T) -> T { x }
523 "for more information, visit \
524 https://doc.rust-lang.org/book/ch10-02-traits.html\
525 #traits-as-parameters",
528 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
529 let generics = self.generics_of(body_owner_def_id);
530 let p_span = self.def_span(generics.type_param(p, self).def_id);
531 if !sp.contains(p_span) {
532 diag.span_label(p_span, "this type parameter");
535 "every closure has a distinct type and so could not always match the \
536 caller-chosen type of parameter `{}`",
540 (ty::Param(p), _) | (_, ty::Param(p)) => {
541 let generics = self.generics_of(body_owner_def_id);
542 let p_span = self.def_span(generics.type_param(p, self).def_id);
543 if !sp.contains(p_span) {
544 diag.span_label(p_span, "this type parameter");
547 (ty::Projection(proj_ty), _) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
548 self.expected_projection(
556 (_, ty::Projection(proj_ty)) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
558 "consider constraining the associated type `{}` to `{}`",
559 values.found, values.expected,
561 if !(self.suggest_constraining_opaque_associated_type(
566 ) || self.suggest_constraint(
575 "for more information, visit \
576 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
583 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
585 values.expected.kind(),
591 // Watch out for various cases of cyclic types and try to explain.
592 if ty.is_closure() || ty.is_generator() {
594 "closures cannot capture themselves or take themselves as argument;\n\
595 this error may be the result of a recent compiler bug-fix,\n\
596 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
597 for more information",
601 TargetFeatureCast(def_id) => {
603 self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
605 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
607 diag.span_labels(target_spans, "`#[target_feature]` added here");
613 fn suggest_constraint(
615 diag: &mut Diagnostic,
617 body_owner_def_id: DefId,
618 proj_ty: &ty::ProjectionTy<'tcx>,
621 let assoc = self.associated_item(proj_ty.item_def_id);
622 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
623 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
624 if let Some(hir_generics) = item.generics() {
625 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
626 // This will also work for `impl Trait`.
627 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
628 let generics = self.generics_of(body_owner_def_id);
629 generics.type_param(param_ty, self).def_id
633 let Some(def_id) = def_id.as_local() else {
637 // First look in the `where` clause, as this might be
638 // `fn foo<T>(x: T) where T: Trait`.
639 for pred in hir_generics.bounds_for_param(def_id) {
640 if self.constrain_generic_bound_associated_type_structured_suggestion(
658 /// An associated type was expected and a different type was found.
660 /// We perform a few different checks to see what we can suggest:
662 /// - In the current item, look for associated functions that return the expected type and
663 /// suggest calling them. (Not a structured suggestion.)
664 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
665 /// associated type to the found type.
666 /// - If the associated type has a default type and was expected inside of a `trait`, we
667 /// mention that this is disallowed.
668 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
669 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
670 /// fn that returns the type.
671 fn expected_projection(
673 diag: &mut Diagnostic,
674 proj_ty: &ty::ProjectionTy<'tcx>,
675 values: ExpectedFound<Ty<'tcx>>,
676 body_owner_def_id: DefId,
677 cause_code: &ObligationCauseCode<'_>,
680 "consider constraining the associated type `{}` to `{}`",
681 values.expected, values.found
683 let body_owner = self.hir().get_if_local(body_owner_def_id);
684 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
686 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
687 let callable_scope = matches!(
690 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
691 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
692 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
695 let impl_comparison =
696 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
697 let assoc = self.associated_item(proj_ty.item_def_id);
698 if !callable_scope || impl_comparison {
699 // We do not want to suggest calling functions when the reason of the
700 // type error is a comparison of an `impl` with its `trait` or when the
701 // scope is outside of a `Body`.
703 // If we find a suitable associated function that returns the expected type, we don't
704 // want the more general suggestion later in this method about "consider constraining
705 // the associated type or calling a method that returns the associated type".
706 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
708 assoc.container_id(self),
709 current_method_ident,
713 // Possibly suggest constraining the associated type to conform to the
715 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
722 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
724 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
728 if !impl_comparison {
729 // Generic suggestion when we can't be more specific.
732 "{} or calling a method that returns `{}`",
739 "for more information, visit \
740 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
743 if self.sess.teach(&diag.get_code().unwrap()) {
745 "given an associated type `T` and a method `foo`:
749 fn foo(&self) -> Self::T;
752 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
756 fn foo(&self) -> Self::T { String::new() }
763 /// When the expected `impl Trait` is not defined in the current item, it will come from
764 /// a return type. This can occur when dealing with `TryStream` (#71035).
765 fn suggest_constraining_opaque_associated_type(
767 diag: &mut Diagnostic,
769 proj_ty: &ty::ProjectionTy<'tcx>,
772 let assoc = self.associated_item(proj_ty.item_def_id);
773 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
774 let opaque_local_def_id = def_id.as_local();
775 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
776 match &self.hir().expect_item(opaque_local_def_id).kind {
777 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
778 _ => bug!("The HirId comes from a `ty::Opaque`"),
784 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
786 self.constrain_generic_bound_associated_type_structured_suggestion(
789 opaque_hir_ty.bounds,
801 fn point_at_methods_that_satisfy_associated_type(
803 diag: &mut Diagnostic,
804 assoc_container_id: DefId,
805 current_method_ident: Option<Symbol>,
806 proj_ty_item_def_id: DefId,
809 let items = self.associated_items(assoc_container_id);
810 // Find all the methods in the trait that could be called to construct the
811 // expected associated type.
812 // FIXME: consider suggesting the use of associated `const`s.
813 let methods: Vec<(Span, String)> = items
816 .filter(|(name, item)| {
817 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
819 .filter_map(|(_, item)| {
820 let method = self.fn_sig(item.def_id);
821 match *method.output().skip_binder().kind() {
822 ty::Projection(ty::ProjectionTy { item_def_id, .. })
823 if item_def_id == proj_ty_item_def_id =>
826 self.def_span(item.def_id),
827 format!("consider calling `{}`", self.def_path_str(item.def_id)),
834 if !methods.is_empty() {
835 // Use a single `help:` to show all the methods in the trait that can
836 // be used to construct the expected associated type.
837 let mut span: MultiSpan =
838 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
840 "{some} method{s} {are} available that return{r} `{ty}`",
841 some = if methods.len() == 1 { "a" } else { "some" },
842 s = pluralize!(methods.len()),
843 are = pluralize!("is", methods.len()),
844 r = if methods.len() == 1 { "s" } else { "" },
847 for (sp, label) in methods.into_iter() {
848 span.push_span_label(sp, label);
850 diag.span_help(span, &msg);
856 fn point_at_associated_type(
858 diag: &mut Diagnostic,
859 body_owner_def_id: DefId,
862 let Some(hir_id) = body_owner_def_id.as_local() else {
865 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
866 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
867 // `expected` and point at it.
868 let parent_id = self.hir().get_parent_item(hir_id);
869 let item = self.hir().find_by_def_id(parent_id.def_id);
870 debug!("expected_projection parent item {:?}", item);
872 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
873 // FIXME: account for `#![feature(specialization)]`
874 for item in &items[..] {
876 hir::AssocItemKind::Type => {
877 // FIXME: account for returning some type in a trait fn impl that has
878 // an assoc type as a return type (#72076).
879 if let hir::Defaultness::Default { has_value: true } =
880 self.impl_defaultness(item.id.owner_id)
882 if self.type_of(item.id.owner_id) == found {
885 "associated type defaults can't be assumed inside the \
886 trait defining them",
896 Some(hir::Node::Item(hir::Item {
897 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
900 for item in &items[..] {
901 if let hir::AssocItemKind::Type = item.kind {
902 if self.type_of(item.id.owner_id) == found {
903 diag.span_label(item.span, "expected this associated type");
914 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
915 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
917 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
918 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
919 /// trait bound as the one we're looking for. This can help in cases where the associated
920 /// type is defined on a supertrait of the one present in the bounds.
921 fn constrain_generic_bound_associated_type_structured_suggestion(
923 diag: &mut Diagnostic,
924 trait_ref: &ty::TraitRef<'tcx>,
925 bounds: hir::GenericBounds<'_>,
926 assoc: &ty::AssocItem,
927 assoc_substs: &[ty::GenericArg<'tcx>],
930 is_bound_surely_present: bool,
932 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
934 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
935 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
939 let matching_trait_bounds = trait_bounds
941 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
942 .collect::<Vec<_>>();
944 let span = match &matching_trait_bounds[..] {
946 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
953 self.constrain_associated_type_structured_suggestion(
963 /// Given a span corresponding to a bound, provide a structured suggestion to set an
964 /// associated type to a given type `ty`.
965 fn constrain_associated_type_structured_suggestion(
967 diag: &mut Diagnostic,
969 assoc: &ty::AssocItem,
970 assoc_substs: &[ty::GenericArg<'tcx>],
974 if let Ok(has_params) =
975 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
977 let (span, sugg) = if has_params {
978 let pos = span.hi() - BytePos(1);
979 let span = Span::new(pos, pos, span.ctxt(), span.parent());
980 (span, format!(", {} = {}", assoc.ident(self), ty))
982 let item_args = self.format_generic_args(assoc_substs);
983 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
985 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
991 pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) {
992 let length_limit = 50;
994 let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS)
995 .pretty_print_type(ty)
996 .expect("could not write to `String`")
998 if regular.len() <= length_limit {
999 return (regular, None);
1001 let short = FmtPrinter::new_with_limit(
1003 hir::def::Namespace::TypeNS,
1004 rustc_session::Limit(type_limit),
1006 .pretty_print_type(ty)
1007 .expect("could not write to `String`")
1009 if regular == short {
1010 return (regular, None);
1012 // Multiple types might be shortened in a single error, ensure we create a file for each.
1013 let mut s = DefaultHasher::new();
1015 let hash = s.finish();
1016 let path = self.output_filenames(()).temp_path_ext(&format!("long-type-{hash}.txt"), None);
1017 match std::fs::write(&path, ®ular) {
1018 Ok(_) => (short, Some(path)),
1019 Err(_) => (regular, None),
1023 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
1024 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1025 .path_generic_args(Ok, args)
1026 .expect("could not write to `String`.")