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 ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
76 /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
77 TargetFeatureCast(DefId),
81 pub fn involves_regions(self) -> bool {
83 TypeError::RegionsDoesNotOutlive(_, _)
84 | TypeError::RegionsInsufficientlyPolymorphic(_, _)
85 | TypeError::RegionsOverlyPolymorphic(_, _)
86 | TypeError::RegionsPlaceholderMismatch => true,
92 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
93 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
94 /// afterwards to present additional details, particularly when it comes to lifetime-related
96 impl<'tcx> fmt::Display for TypeError<'tcx> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 use self::TypeError::*;
99 fn report_maybe_different(
100 f: &mut fmt::Formatter<'_>,
104 // A naive approach to making sure that we're not reporting silly errors such as:
105 // (expected closure, found closure).
106 if expected == found {
107 write!(f, "expected {}, found a different {}", expected, found)
109 write!(f, "expected {}, found {}", expected, found)
113 let br_string = |br: ty::BoundRegionKind| match br {
114 ty::BrNamed(_, name) => format!(" {}", name),
119 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
120 CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
121 Mismatch => write!(f, "types differ"),
122 ConstnessMismatch(values) => {
123 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
125 PolarityMismatch(values) => {
126 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
128 UnsafetyMismatch(values) => {
129 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
131 AbiMismatch(values) => {
132 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
134 ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
135 TupleSize(values) => write!(
137 "expected a tuple with {} element{}, found one with {} element{}",
139 pluralize!(values.expected),
141 pluralize!(values.found)
143 FixedArraySize(values) => write!(
145 "expected an array with a fixed size of {} element{}, found one with {} element{}",
147 pluralize!(values.expected),
149 pluralize!(values.found)
151 ArgCount => write!(f, "incorrect number of function parameters"),
152 FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
153 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
154 // Actually naming the region here is a bit confusing because context is lacking
155 RegionsInsufficientlyPolymorphic(..) => {
156 write!(f, "one type is more general than the other")
158 RegionsOverlyPolymorphic(br, _) => write!(
160 "expected concrete lifetime, found bound lifetime parameter{}",
163 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
164 ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
165 report_maybe_different(
167 &values.expected.sort_string(tcx),
168 &values.found.sort_string(tcx),
171 Traits(values) => ty::tls::with(|tcx| {
172 report_maybe_different(
174 &format!("trait `{}`", tcx.def_path_str(values.expected)),
175 &format!("trait `{}`", tcx.def_path_str(values.found)),
178 IntMismatch(ref values) => {
179 let expected = match values.expected {
180 ty::IntVarValue::IntType(ty) => ty.name_str(),
181 ty::IntVarValue::UintType(ty) => ty.name_str(),
183 let found = match values.found {
184 ty::IntVarValue::IntType(ty) => ty.name_str(),
185 ty::IntVarValue::UintType(ty) => ty.name_str(),
187 write!(f, "expected `{}`, found `{}`", expected, found)
189 FloatMismatch(ref values) => {
192 "expected `{}`, found `{}`",
193 values.expected.name_str(),
194 values.found.name_str()
197 VariadicMismatch(ref values) => write!(
199 "expected {} fn, found {} function",
200 if values.expected { "variadic" } else { "non-variadic" },
201 if values.found { "variadic" } else { "non-variadic" }
203 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
206 "expected {}, found {}",
207 tcx.def_path_str(values.expected),
208 tcx.def_path_str(values.found)
211 ExistentialMismatch(ref values) => report_maybe_different(
213 &format!("trait `{}`", values.expected),
214 &format!("trait `{}`", values.found),
216 ConstMismatch(ref values) => {
217 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
219 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
220 TargetFeatureCast(_) => write!(
222 "cannot coerce functions with `#[target_feature]` to safe function pointers"
228 impl<'tcx> TypeError<'tcx> {
229 pub fn must_include_note(self) -> bool {
230 use self::TypeError::*;
232 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
233 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
234 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
235 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
238 | ArgumentMutability(_)
242 | RegionsDoesNotOutlive(..)
243 | RegionsInsufficientlyPolymorphic(..)
244 | RegionsOverlyPolymorphic(..)
245 | RegionsPlaceholderMismatch
247 | ProjectionMismatched(_)
248 | ExistentialMismatch(_)
250 | IntrinsicCast => true,
255 impl<'tcx> Ty<'tcx> {
256 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
258 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
259 format!("`{}`", self).into()
261 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
263 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
264 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
266 if t.is_simple_ty() {
267 return format!("array `{}`", self).into();
270 let n = tcx.lift(n).unwrap();
271 if let ty::ConstKind::Value(v) = n.kind() {
272 if let Some(n) = v.try_to_machine_usize(tcx) {
273 return format!("array of {} element{}", n, pluralize!(n)).into();
278 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
279 ty::Slice(_) => "slice".into(),
280 ty::RawPtr(tymut) => {
281 let tymut_string = match tymut.mutbl {
282 hir::Mutability::Mut => tymut.to_string(),
283 hir::Mutability::Not => format!("const {}", tymut.ty),
286 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
287 format!("`*{}`", tymut_string).into()
289 // Unknown type name, it's long or has type arguments
293 ty::Ref(_, ty, mutbl) => {
294 let tymut = ty::TypeAndMut { ty, mutbl };
295 let tymut_string = tymut.to_string();
297 if tymut_string != "_"
298 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
300 format!("`&{}`", tymut_string).into()
302 // Unknown type name, it's long or has type arguments
304 hir::Mutability::Mut => "mutable reference",
310 ty::FnDef(..) => "fn item".into(),
311 ty::FnPtr(_) => "fn pointer".into(),
312 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
313 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
315 ty::Dynamic(..) => "trait object".into(),
316 ty::Closure(..) => "closure".into(),
317 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
318 ty::GeneratorWitness(..) => "generator witness".into(),
319 ty::Tuple(..) => "tuple".into(),
320 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
321 ty::Infer(ty::IntVar(_)) => "integer".into(),
322 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
323 ty::Placeholder(..) => "placeholder type".into(),
324 ty::Bound(..) => "bound type".into(),
325 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
326 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
327 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
328 ty::Projection(_) => "associated type".into(),
329 ty::Param(p) => format!("type parameter `{}`", p).into(),
330 ty::Opaque(..) => "opaque type".into(),
331 ty::Error(_) => "type error".into(),
335 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
345 | ty::Never => "type".into(),
346 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
347 ty::Adt(def, _) => def.descr().into(),
348 ty::Foreign(_) => "extern type".into(),
349 ty::Array(..) => "array".into(),
350 ty::Slice(_) => "slice".into(),
351 ty::RawPtr(_) => "raw pointer".into(),
352 ty::Ref(.., mutbl) => match mutbl {
353 hir::Mutability::Mut => "mutable reference",
357 ty::FnDef(..) => "fn item".into(),
358 ty::FnPtr(_) => "fn pointer".into(),
359 ty::Dynamic(..) => "trait object".into(),
360 ty::Closure(..) => "closure".into(),
361 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
362 ty::GeneratorWitness(..) => "generator witness".into(),
363 ty::Tuple(..) => "tuple".into(),
364 ty::Placeholder(..) => "higher-ranked type".into(),
365 ty::Bound(..) => "bound type variable".into(),
366 ty::Projection(_) => "associated type".into(),
367 ty::Param(_) => "type parameter".into(),
368 ty::Opaque(..) => "opaque type".into(),
373 impl<'tcx> TyCtxt<'tcx> {
374 pub fn note_and_explain_type_err(
376 diag: &mut Diagnostic,
377 err: TypeError<'tcx>,
378 cause: &ObligationCause<'tcx>,
380 body_owner_def_id: DefId,
382 use self::TypeError::*;
383 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
385 ArgumentSorts(values, _) | Sorts(values) => {
386 match (values.expected.kind(), values.found.kind()) {
387 (ty::Closure(..), ty::Closure(..)) => {
388 diag.note("no two closures, even if identical, have the same type");
389 diag.help("consider boxing your closure and/or using it as a trait object");
391 (ty::Opaque(..), ty::Opaque(..)) => {
393 diag.note("distinct uses of `impl Trait` result in different opaque types");
395 (ty::Float(_), ty::Infer(ty::IntVar(_)))
399 ) = self.sess.source_map().span_to_snippet(sp) =>
401 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
402 diag.span_suggestion(
404 "use a float literal",
405 format!("{}.0", snippet),
410 (ty::Param(expected), ty::Param(found)) => {
411 let generics = self.generics_of(body_owner_def_id);
412 let e_span = self.def_span(generics.type_param(expected, self).def_id);
413 if !sp.contains(e_span) {
414 diag.span_label(e_span, "expected type parameter");
416 let f_span = self.def_span(generics.type_param(found, self).def_id);
417 if !sp.contains(f_span) {
418 diag.span_label(f_span, "found type parameter");
421 "a type parameter was expected, but a different one was found; \
422 you might be missing a type parameter or trait bound",
425 "for more information, visit \
426 https://doc.rust-lang.org/book/ch10-02-traits.html\
427 #traits-as-parameters",
430 (ty::Projection(_), ty::Projection(_)) => {
431 diag.note("an associated type was expected, but a different one was found");
433 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p))
434 if self.def_kind(proj.item_def_id) != DefKind::ImplTraitPlaceholder =>
436 let generics = self.generics_of(body_owner_def_id);
437 let p_span = self.def_span(generics.type_param(p, self).def_id);
438 if !sp.contains(p_span) {
439 diag.span_label(p_span, "this type parameter");
441 let hir = self.hir();
443 if let Some(generics) = generics
447 .map(|id| hir.local_def_id_to_hir_id(id))
448 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
450 .and_then(|node| node.generics())
452 // Synthesize the associated type restriction `Add<Output = Expected>`.
453 // FIXME: extract this logic for use in other diagnostics.
454 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
456 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
457 let item_name = self.item_name(proj.item_def_id);
458 let item_args = self.format_generic_args(assoc_substs);
460 let path = if path.ends_with('>') {
463 &path[..path.len() - 1],
469 format!("{}<{}{} = {}>", path, item_name, item_args, p)
471 note = !suggest_constraining_type_param(
475 &format!("{}", proj.self_ty()),
481 diag.note("you might be missing a type parameter or trait bound");
484 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
485 | (ty::Dynamic(..) | ty::Opaque(..), 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 diag.span_label(p_span, "this type parameter");
491 diag.help("type parameters must be constrained to match other types");
492 if self.sess.teach(&diag.get_code().unwrap()) {
494 "given a type parameter `T` and a method `foo`:
496 trait Trait<T> { fn foo(&self) -> T; }
498 the only ways to implement method `foo` are:
499 - constrain `T` with an explicit type:
501 impl Trait<String> for X {
502 fn foo(&self) -> String { String::new() }
505 - add a trait bound to `T` and call a method on that trait that returns `Self`:
507 impl<T: std::default::Default> Trait<T> for X {
508 fn foo(&self) -> T { <T as std::default::Default>::default() }
511 - change `foo` to return an argument of type `T`:
513 impl<T> Trait<T> for X {
514 fn foo(&self, x: T) -> T { x }
520 "for more information, visit \
521 https://doc.rust-lang.org/book/ch10-02-traits.html\
522 #traits-as-parameters",
525 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
526 let generics = self.generics_of(body_owner_def_id);
527 let p_span = self.def_span(generics.type_param(p, self).def_id);
528 if !sp.contains(p_span) {
529 diag.span_label(p_span, "this type parameter");
532 "every closure has a distinct type and so could not always match the \
533 caller-chosen type of parameter `{}`",
537 (ty::Param(p), _) | (_, ty::Param(p)) => {
538 let generics = self.generics_of(body_owner_def_id);
539 let p_span = self.def_span(generics.type_param(p, self).def_id);
540 if !sp.contains(p_span) {
541 diag.span_label(p_span, "this type parameter");
544 (ty::Projection(proj_ty), _) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
545 self.expected_projection(
553 (_, ty::Projection(proj_ty)) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
555 "consider constraining the associated type `{}` to `{}`",
556 values.found, values.expected,
558 if !(self.suggest_constraining_opaque_associated_type(
563 ) || self.suggest_constraint(
572 "for more information, visit \
573 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
580 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
582 values.expected.kind(),
588 // Watch out for various cases of cyclic types and try to explain.
589 if ty.is_closure() || ty.is_generator() {
591 "closures cannot capture themselves or take themselves as argument;\n\
592 this error may be the result of a recent compiler bug-fix,\n\
593 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
594 for more information",
598 TargetFeatureCast(def_id) => {
600 self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
602 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
604 diag.span_labels(target_spans, "`#[target_feature]` added here");
610 fn suggest_constraint(
612 diag: &mut Diagnostic,
614 body_owner_def_id: DefId,
615 proj_ty: &ty::ProjectionTy<'tcx>,
618 let assoc = self.associated_item(proj_ty.item_def_id);
619 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
620 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
621 if let Some(hir_generics) = item.generics() {
622 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
623 // This will also work for `impl Trait`.
624 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
625 let generics = self.generics_of(body_owner_def_id);
626 generics.type_param(param_ty, self).def_id
630 let Some(def_id) = def_id.as_local() else {
634 // First look in the `where` clause, as this might be
635 // `fn foo<T>(x: T) where T: Trait`.
636 for pred in hir_generics.bounds_for_param(def_id) {
637 if self.constrain_generic_bound_associated_type_structured_suggestion(
655 /// An associated type was expected and a different type was found.
657 /// We perform a few different checks to see what we can suggest:
659 /// - In the current item, look for associated functions that return the expected type and
660 /// suggest calling them. (Not a structured suggestion.)
661 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
662 /// associated type to the found type.
663 /// - If the associated type has a default type and was expected inside of a `trait`, we
664 /// mention that this is disallowed.
665 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
666 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
667 /// fn that returns the type.
668 fn expected_projection(
670 diag: &mut Diagnostic,
671 proj_ty: &ty::ProjectionTy<'tcx>,
672 values: ExpectedFound<Ty<'tcx>>,
673 body_owner_def_id: DefId,
674 cause_code: &ObligationCauseCode<'_>,
677 "consider constraining the associated type `{}` to `{}`",
678 values.expected, values.found
680 let body_owner = self.hir().get_if_local(body_owner_def_id);
681 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
683 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
684 let callable_scope = matches!(
687 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
688 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
689 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
692 let impl_comparison =
693 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
694 let assoc = self.associated_item(proj_ty.item_def_id);
695 if !callable_scope || impl_comparison {
696 // We do not want to suggest calling functions when the reason of the
697 // type error is a comparison of an `impl` with its `trait` or when the
698 // scope is outside of a `Body`.
700 // If we find a suitable associated function that returns the expected type, we don't
701 // want the more general suggestion later in this method about "consider constraining
702 // the associated type or calling a method that returns the associated type".
703 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
705 assoc.container_id(self),
706 current_method_ident,
710 // Possibly suggest constraining the associated type to conform to the
712 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
719 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
721 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
725 if !impl_comparison {
726 // Generic suggestion when we can't be more specific.
729 "{} or calling a method that returns `{}`",
736 "for more information, visit \
737 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
740 if self.sess.teach(&diag.get_code().unwrap()) {
742 "given an associated type `T` and a method `foo`:
746 fn foo(&self) -> Self::T;
749 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
753 fn foo(&self) -> Self::T { String::new() }
760 /// When the expected `impl Trait` is not defined in the current item, it will come from
761 /// a return type. This can occur when dealing with `TryStream` (#71035).
762 fn suggest_constraining_opaque_associated_type(
764 diag: &mut Diagnostic,
766 proj_ty: &ty::ProjectionTy<'tcx>,
769 let assoc = self.associated_item(proj_ty.item_def_id);
770 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
771 let opaque_local_def_id = def_id.as_local();
772 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
773 match &self.hir().expect_item(opaque_local_def_id).kind {
774 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
775 _ => bug!("The HirId comes from a `ty::Opaque`"),
781 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
783 self.constrain_generic_bound_associated_type_structured_suggestion(
786 opaque_hir_ty.bounds,
798 fn point_at_methods_that_satisfy_associated_type(
800 diag: &mut Diagnostic,
801 assoc_container_id: DefId,
802 current_method_ident: Option<Symbol>,
803 proj_ty_item_def_id: DefId,
806 let items = self.associated_items(assoc_container_id);
807 // Find all the methods in the trait that could be called to construct the
808 // expected associated type.
809 // FIXME: consider suggesting the use of associated `const`s.
810 let methods: Vec<(Span, String)> = items
813 .filter(|(name, item)| {
814 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
816 .filter_map(|(_, item)| {
817 let method = self.fn_sig(item.def_id);
818 match *method.output().skip_binder().kind() {
819 ty::Projection(ty::ProjectionTy { item_def_id, .. })
820 if item_def_id == proj_ty_item_def_id =>
823 self.def_span(item.def_id),
824 format!("consider calling `{}`", self.def_path_str(item.def_id)),
831 if !methods.is_empty() {
832 // Use a single `help:` to show all the methods in the trait that can
833 // be used to construct the expected associated type.
834 let mut span: MultiSpan =
835 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
837 "{some} method{s} {are} available that return{r} `{ty}`",
838 some = if methods.len() == 1 { "a" } else { "some" },
839 s = pluralize!(methods.len()),
840 are = pluralize!("is", methods.len()),
841 r = if methods.len() == 1 { "s" } else { "" },
844 for (sp, label) in methods.into_iter() {
845 span.push_span_label(sp, label);
847 diag.span_help(span, &msg);
853 fn point_at_associated_type(
855 diag: &mut Diagnostic,
856 body_owner_def_id: DefId,
859 let Some(hir_id) = body_owner_def_id.as_local() else {
862 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
863 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
864 // `expected` and point at it.
865 let parent_id = self.hir().get_parent_item(hir_id);
866 let item = self.hir().find_by_def_id(parent_id.def_id);
867 debug!("expected_projection parent item {:?}", item);
869 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
870 // FIXME: account for `#![feature(specialization)]`
871 for item in &items[..] {
873 hir::AssocItemKind::Type => {
874 // FIXME: account for returning some type in a trait fn impl that has
875 // an assoc type as a return type (#72076).
876 if let hir::Defaultness::Default { has_value: true } =
877 self.impl_defaultness(item.id.owner_id)
879 if self.type_of(item.id.owner_id) == found {
882 "associated type defaults can't be assumed inside the \
883 trait defining them",
893 Some(hir::Node::Item(hir::Item {
894 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
897 for item in &items[..] {
898 if let hir::AssocItemKind::Type = item.kind {
899 if self.type_of(item.id.owner_id) == found {
900 diag.span_label(item.span, "expected this associated type");
911 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
912 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
914 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
915 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
916 /// trait bound as the one we're looking for. This can help in cases where the associated
917 /// type is defined on a supertrait of the one present in the bounds.
918 fn constrain_generic_bound_associated_type_structured_suggestion(
920 diag: &mut Diagnostic,
921 trait_ref: &ty::TraitRef<'tcx>,
922 bounds: hir::GenericBounds<'_>,
923 assoc: &ty::AssocItem,
924 assoc_substs: &[ty::GenericArg<'tcx>],
927 is_bound_surely_present: bool,
929 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
931 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
932 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
936 let matching_trait_bounds = trait_bounds
938 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
939 .collect::<Vec<_>>();
941 let span = match &matching_trait_bounds[..] {
943 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
950 self.constrain_associated_type_structured_suggestion(
960 /// Given a span corresponding to a bound, provide a structured suggestion to set an
961 /// associated type to a given type `ty`.
962 fn constrain_associated_type_structured_suggestion(
964 diag: &mut Diagnostic,
966 assoc: &ty::AssocItem,
967 assoc_substs: &[ty::GenericArg<'tcx>],
971 if let Ok(has_params) =
972 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
974 let (span, sugg) = if has_params {
975 let pos = span.hi() - BytePos(1);
976 let span = Span::new(pos, pos, span.ctxt(), span.parent());
977 (span, format!(", {} = {}", assoc.ident(self), ty))
979 let item_args = self.format_generic_args(assoc_substs);
980 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
982 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
988 pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) {
989 let length_limit = 50;
991 let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS)
992 .pretty_print_type(ty)
993 .expect("could not write to `String`")
995 if regular.len() <= length_limit {
996 return (regular, None);
998 let short = FmtPrinter::new_with_limit(
1000 hir::def::Namespace::TypeNS,
1001 rustc_session::Limit(type_limit),
1003 .pretty_print_type(ty)
1004 .expect("could not write to `String`")
1006 if regular == short {
1007 return (regular, None);
1009 // Multiple types might be shortened in a single error, ensure we create a file for each.
1010 let mut s = DefaultHasher::new();
1012 let hash = s.finish();
1013 let path = self.output_filenames(()).temp_path_ext(&format!("long-type-{hash}.txt"), None);
1014 match std::fs::write(&path, ®ular) {
1015 Ok(_) => (short, Some(path)),
1016 Err(_) => (regular, None),
1020 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
1021 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1022 .path_generic_args(Ok, args)
1023 .expect("could not write to `String`.")