1 use crate::traits::{ObligationCause, ObligationCauseCode};
2 use crate::ty::diagnostics::suggest_constraining_type_param;
3 use crate::ty::print::{with_forced_trimmed_paths, 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 let (mut expected, mut found) = with_forced_trimmed_paths!((
166 values.expected.sort_string(tcx),
167 values.found.sort_string(tcx),
169 if expected == found {
170 expected = values.expected.sort_string(tcx);
171 found = values.found.sort_string(tcx);
173 report_maybe_different(f, &expected, &found)
175 Traits(values) => ty::tls::with(|tcx| {
176 let (mut expected, mut found) = with_forced_trimmed_paths!((
177 tcx.def_path_str(values.expected),
178 tcx.def_path_str(values.found),
180 if expected == found {
181 expected = tcx.def_path_str(values.expected);
182 found = tcx.def_path_str(values.found);
184 report_maybe_different(
186 &format!("trait `{expected}`"),
187 &format!("trait `{found}`"),
190 IntMismatch(ref values) => {
191 let expected = match values.expected {
192 ty::IntVarValue::IntType(ty) => ty.name_str(),
193 ty::IntVarValue::UintType(ty) => ty.name_str(),
195 let found = match values.found {
196 ty::IntVarValue::IntType(ty) => ty.name_str(),
197 ty::IntVarValue::UintType(ty) => ty.name_str(),
199 write!(f, "expected `{}`, found `{}`", expected, found)
201 FloatMismatch(ref values) => {
204 "expected `{}`, found `{}`",
205 values.expected.name_str(),
206 values.found.name_str()
209 VariadicMismatch(ref values) => write!(
211 "expected {} fn, found {} function",
212 if values.expected { "variadic" } else { "non-variadic" },
213 if values.found { "variadic" } else { "non-variadic" }
215 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
218 "expected {}, found {}",
219 tcx.def_path_str(values.expected),
220 tcx.def_path_str(values.found)
223 ExistentialMismatch(ref values) => report_maybe_different(
225 &format!("trait `{}`", values.expected),
226 &format!("trait `{}`", values.found),
228 ConstMismatch(ref values) => {
229 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
231 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
232 TargetFeatureCast(_) => write!(
234 "cannot coerce functions with `#[target_feature]` to safe function pointers"
240 impl<'tcx> TypeError<'tcx> {
241 pub fn must_include_note(self) -> bool {
242 use self::TypeError::*;
244 CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
245 | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
246 | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
247 | VariadicMismatch(_) | TargetFeatureCast(_) => false,
250 | ArgumentMutability(_)
254 | RegionsDoesNotOutlive(..)
255 | RegionsInsufficientlyPolymorphic(..)
256 | RegionsOverlyPolymorphic(..)
257 | RegionsPlaceholderMismatch
259 | ProjectionMismatched(_)
260 | ExistentialMismatch(_)
262 | IntrinsicCast => true,
267 impl<'tcx> Ty<'tcx> {
268 pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
270 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
271 format!("`{}`", self).into()
273 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
275 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
276 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
278 if t.is_simple_ty() {
279 return format!("array `{}`", self).into();
282 let n = tcx.lift(n).unwrap();
283 if let ty::ConstKind::Value(v) = n.kind() {
284 if let Some(n) = v.try_to_machine_usize(tcx) {
285 return format!("array of {} element{}", n, pluralize!(n)).into();
290 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
291 ty::Slice(_) => "slice".into(),
292 ty::RawPtr(tymut) => {
293 let tymut_string = match tymut.mutbl {
294 hir::Mutability::Mut => tymut.to_string(),
295 hir::Mutability::Not => format!("const {}", tymut.ty),
298 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
299 format!("`*{}`", tymut_string).into()
301 // Unknown type name, it's long or has type arguments
305 ty::Ref(_, ty, mutbl) => {
306 let tymut = ty::TypeAndMut { ty, mutbl };
307 let tymut_string = tymut.to_string();
309 if tymut_string != "_"
310 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
312 format!("`&{}`", tymut_string).into()
314 // Unknown type name, it's long or has type arguments
316 hir::Mutability::Mut => "mutable reference",
322 ty::FnDef(..) => "fn item".into(),
323 ty::FnPtr(_) => "fn pointer".into(),
324 ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
325 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
327 ty::Dynamic(..) => "trait object".into(),
328 ty::Closure(..) => "closure".into(),
329 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
330 ty::GeneratorWitness(..) => "generator witness".into(),
331 ty::Tuple(..) => "tuple".into(),
332 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
333 ty::Infer(ty::IntVar(_)) => "integer".into(),
334 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
335 ty::Placeholder(..) => "placeholder type".into(),
336 ty::Bound(..) => "bound type".into(),
337 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
338 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
339 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
340 ty::Projection(_) => "associated type".into(),
341 ty::Param(p) => format!("type parameter `{}`", p).into(),
342 ty::Opaque(..) => "opaque type".into(),
343 ty::Error(_) => "type error".into(),
347 pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
357 | ty::Never => "type".into(),
358 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
359 ty::Adt(def, _) => def.descr().into(),
360 ty::Foreign(_) => "extern type".into(),
361 ty::Array(..) => "array".into(),
362 ty::Slice(_) => "slice".into(),
363 ty::RawPtr(_) => "raw pointer".into(),
364 ty::Ref(.., mutbl) => match mutbl {
365 hir::Mutability::Mut => "mutable reference",
369 ty::FnDef(..) => "fn item".into(),
370 ty::FnPtr(_) => "fn pointer".into(),
371 ty::Dynamic(..) => "trait object".into(),
372 ty::Closure(..) => "closure".into(),
373 ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
374 ty::GeneratorWitness(..) => "generator witness".into(),
375 ty::Tuple(..) => "tuple".into(),
376 ty::Placeholder(..) => "higher-ranked type".into(),
377 ty::Bound(..) => "bound type variable".into(),
378 ty::Projection(_) => "associated type".into(),
379 ty::Param(_) => "type parameter".into(),
380 ty::Opaque(..) => "opaque type".into(),
385 impl<'tcx> TyCtxt<'tcx> {
386 pub fn note_and_explain_type_err(
388 diag: &mut Diagnostic,
389 err: TypeError<'tcx>,
390 cause: &ObligationCause<'tcx>,
392 body_owner_def_id: DefId,
394 use self::TypeError::*;
395 debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
397 ArgumentSorts(values, _) | Sorts(values) => {
398 match (values.expected.kind(), values.found.kind()) {
399 (ty::Closure(..), ty::Closure(..)) => {
400 diag.note("no two closures, even if identical, have the same type");
401 diag.help("consider boxing your closure and/or using it as a trait object");
403 (ty::Opaque(..), ty::Opaque(..)) => {
405 diag.note("distinct uses of `impl Trait` result in different opaque types");
407 (ty::Float(_), ty::Infer(ty::IntVar(_)))
411 ) = self.sess.source_map().span_to_snippet(sp) =>
413 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
414 diag.span_suggestion(
416 "use a float literal",
417 format!("{}.0", snippet),
422 (ty::Param(expected), ty::Param(found)) => {
423 let generics = self.generics_of(body_owner_def_id);
424 let e_span = self.def_span(generics.type_param(expected, self).def_id);
425 if !sp.contains(e_span) {
426 diag.span_label(e_span, "expected type parameter");
428 let f_span = self.def_span(generics.type_param(found, self).def_id);
429 if !sp.contains(f_span) {
430 diag.span_label(f_span, "found type parameter");
433 "a type parameter was expected, but a different one was found; \
434 you might be missing a type parameter or trait bound",
437 "for more information, visit \
438 https://doc.rust-lang.org/book/ch10-02-traits.html\
439 #traits-as-parameters",
442 (ty::Projection(_), ty::Projection(_)) => {
443 diag.note("an associated type was expected, but a different one was found");
445 (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p))
446 if self.def_kind(proj.item_def_id) != DefKind::ImplTraitPlaceholder =>
448 let generics = self.generics_of(body_owner_def_id);
449 let p_span = self.def_span(generics.type_param(p, self).def_id);
450 if !sp.contains(p_span) {
451 diag.span_label(p_span, "this type parameter");
453 let hir = self.hir();
455 if let Some(generics) = generics
459 .map(|id| hir.local_def_id_to_hir_id(id))
460 .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
462 .and_then(|node| node.generics())
464 // Synthesize the associated type restriction `Add<Output = Expected>`.
465 // FIXME: extract this logic for use in other diagnostics.
466 let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
468 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
469 let item_name = self.item_name(proj.item_def_id);
470 let item_args = self.format_generic_args(assoc_substs);
472 let path = if path.ends_with('>') {
475 &path[..path.len() - 1],
481 format!("{}<{}{} = {}>", path, item_name, item_args, p)
483 note = !suggest_constraining_type_param(
487 &format!("{}", proj.self_ty()),
493 diag.note("you might be missing a type parameter or trait bound");
496 (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
497 | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
498 let generics = self.generics_of(body_owner_def_id);
499 let p_span = self.def_span(generics.type_param(p, self).def_id);
500 if !sp.contains(p_span) {
501 diag.span_label(p_span, "this type parameter");
503 diag.help("type parameters must be constrained to match other types");
504 if self.sess.teach(&diag.get_code().unwrap()) {
506 "given a type parameter `T` and a method `foo`:
508 trait Trait<T> { fn foo(&self) -> T; }
510 the only ways to implement method `foo` are:
511 - constrain `T` with an explicit type:
513 impl Trait<String> for X {
514 fn foo(&self) -> String { String::new() }
517 - add a trait bound to `T` and call a method on that trait that returns `Self`:
519 impl<T: std::default::Default> Trait<T> for X {
520 fn foo(&self) -> T { <T as std::default::Default>::default() }
523 - change `foo` to return an argument of type `T`:
525 impl<T> Trait<T> for X {
526 fn foo(&self, x: T) -> T { x }
532 "for more information, visit \
533 https://doc.rust-lang.org/book/ch10-02-traits.html\
534 #traits-as-parameters",
537 (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
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 "every closure has a distinct type and so could not always match the \
545 caller-chosen type of parameter `{}`",
549 (ty::Param(p), _) | (_, ty::Param(p)) => {
550 let generics = self.generics_of(body_owner_def_id);
551 let p_span = self.def_span(generics.type_param(p, self).def_id);
552 if !sp.contains(p_span) {
553 diag.span_label(p_span, "this type parameter");
556 (ty::Projection(proj_ty), _) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
557 self.expected_projection(
565 (_, ty::Projection(proj_ty)) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
567 "consider constraining the associated type `{}` to `{}`",
568 values.found, values.expected,
570 if !(self.suggest_constraining_opaque_associated_type(
575 ) || self.suggest_constraint(
584 "for more information, visit \
585 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
592 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
594 values.expected.kind(),
600 // Watch out for various cases of cyclic types and try to explain.
601 if ty.is_closure() || ty.is_generator() {
603 "closures cannot capture themselves or take themselves as argument;\n\
604 this error may be the result of a recent compiler bug-fix,\n\
605 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
606 for more information",
610 TargetFeatureCast(def_id) => {
612 self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
614 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
616 diag.span_labels(target_spans, "`#[target_feature]` added here");
622 fn suggest_constraint(
624 diag: &mut Diagnostic,
626 body_owner_def_id: DefId,
627 proj_ty: &ty::ProjectionTy<'tcx>,
630 let assoc = self.associated_item(proj_ty.item_def_id);
631 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
632 if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
633 if let Some(hir_generics) = item.generics() {
634 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
635 // This will also work for `impl Trait`.
636 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
637 let generics = self.generics_of(body_owner_def_id);
638 generics.type_param(param_ty, self).def_id
642 let Some(def_id) = def_id.as_local() else {
646 // First look in the `where` clause, as this might be
647 // `fn foo<T>(x: T) where T: Trait`.
648 for pred in hir_generics.bounds_for_param(def_id) {
649 if self.constrain_generic_bound_associated_type_structured_suggestion(
667 /// An associated type was expected and a different type was found.
669 /// We perform a few different checks to see what we can suggest:
671 /// - In the current item, look for associated functions that return the expected type and
672 /// suggest calling them. (Not a structured suggestion.)
673 /// - If any of the item's generic bounds can be constrained, we suggest constraining the
674 /// associated type to the found type.
675 /// - If the associated type has a default type and was expected inside of a `trait`, we
676 /// mention that this is disallowed.
677 /// - If all other things fail, and the error is not because of a mismatch between the `trait`
678 /// and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
679 /// fn that returns the type.
680 fn expected_projection(
682 diag: &mut Diagnostic,
683 proj_ty: &ty::ProjectionTy<'tcx>,
684 values: ExpectedFound<Ty<'tcx>>,
685 body_owner_def_id: DefId,
686 cause_code: &ObligationCauseCode<'_>,
689 "consider constraining the associated type `{}` to `{}`",
690 values.expected, values.found
692 let body_owner = self.hir().get_if_local(body_owner_def_id);
693 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
695 // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
696 let callable_scope = matches!(
699 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
700 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
701 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
704 let impl_comparison =
705 matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
706 let assoc = self.associated_item(proj_ty.item_def_id);
707 if !callable_scope || impl_comparison {
708 // We do not want to suggest calling functions when the reason of the
709 // type error is a comparison of an `impl` with its `trait` or when the
710 // scope is outside of a `Body`.
712 // If we find a suitable associated function that returns the expected type, we don't
713 // want the more general suggestion later in this method about "consider constraining
714 // the associated type or calling a method that returns the associated type".
715 let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
717 assoc.container_id(self),
718 current_method_ident,
722 // Possibly suggest constraining the associated type to conform to the
724 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
731 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
733 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
737 if !impl_comparison {
738 // Generic suggestion when we can't be more specific.
741 "{} or calling a method that returns `{}`",
748 "for more information, visit \
749 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
752 if self.sess.teach(&diag.get_code().unwrap()) {
754 "given an associated type `T` and a method `foo`:
758 fn foo(&self) -> Self::T;
761 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
765 fn foo(&self) -> Self::T { String::new() }
772 /// When the expected `impl Trait` is not defined in the current item, it will come from
773 /// a return type. This can occur when dealing with `TryStream` (#71035).
774 fn suggest_constraining_opaque_associated_type(
776 diag: &mut Diagnostic,
778 proj_ty: &ty::ProjectionTy<'tcx>,
781 let assoc = self.associated_item(proj_ty.item_def_id);
782 if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
783 let opaque_local_def_id = def_id.as_local();
784 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
785 match &self.hir().expect_item(opaque_local_def_id).kind {
786 hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
787 _ => bug!("The HirId comes from a `ty::Opaque`"),
793 let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
795 self.constrain_generic_bound_associated_type_structured_suggestion(
798 opaque_hir_ty.bounds,
810 fn point_at_methods_that_satisfy_associated_type(
812 diag: &mut Diagnostic,
813 assoc_container_id: DefId,
814 current_method_ident: Option<Symbol>,
815 proj_ty_item_def_id: DefId,
818 let items = self.associated_items(assoc_container_id);
819 // Find all the methods in the trait that could be called to construct the
820 // expected associated type.
821 // FIXME: consider suggesting the use of associated `const`s.
822 let methods: Vec<(Span, String)> = items
825 .filter(|(name, item)| {
826 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
828 .filter_map(|(_, item)| {
829 let method = self.fn_sig(item.def_id);
830 match *method.output().skip_binder().kind() {
831 ty::Projection(ty::ProjectionTy { item_def_id, .. })
832 if item_def_id == proj_ty_item_def_id =>
835 self.def_span(item.def_id),
836 format!("consider calling `{}`", self.def_path_str(item.def_id)),
843 if !methods.is_empty() {
844 // Use a single `help:` to show all the methods in the trait that can
845 // be used to construct the expected associated type.
846 let mut span: MultiSpan =
847 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
849 "{some} method{s} {are} available that return{r} `{ty}`",
850 some = if methods.len() == 1 { "a" } else { "some" },
851 s = pluralize!(methods.len()),
852 are = pluralize!("is", methods.len()),
853 r = if methods.len() == 1 { "s" } else { "" },
856 for (sp, label) in methods.into_iter() {
857 span.push_span_label(sp, label);
859 diag.span_help(span, &msg);
865 fn point_at_associated_type(
867 diag: &mut Diagnostic,
868 body_owner_def_id: DefId,
871 let Some(hir_id) = body_owner_def_id.as_local() else {
874 let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
875 // When `body_owner` is an `impl` or `trait` item, look in its associated types for
876 // `expected` and point at it.
877 let parent_id = self.hir().get_parent_item(hir_id);
878 let item = self.hir().find_by_def_id(parent_id.def_id);
879 debug!("expected_projection parent item {:?}", item);
881 Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
882 // FIXME: account for `#![feature(specialization)]`
883 for item in &items[..] {
885 hir::AssocItemKind::Type => {
886 // FIXME: account for returning some type in a trait fn impl that has
887 // an assoc type as a return type (#72076).
888 if let hir::Defaultness::Default { has_value: true } =
889 self.impl_defaultness(item.id.owner_id)
891 if self.type_of(item.id.owner_id) == found {
894 "associated type defaults can't be assumed inside the \
895 trait defining them",
905 Some(hir::Node::Item(hir::Item {
906 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
909 for item in &items[..] {
910 if let hir::AssocItemKind::Type = item.kind {
911 if self.type_of(item.id.owner_id) == found {
912 diag.span_label(item.span, "expected this associated type");
923 /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
924 /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
926 /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
927 /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
928 /// trait bound as the one we're looking for. This can help in cases where the associated
929 /// type is defined on a supertrait of the one present in the bounds.
930 fn constrain_generic_bound_associated_type_structured_suggestion(
932 diag: &mut Diagnostic,
933 trait_ref: &ty::TraitRef<'tcx>,
934 bounds: hir::GenericBounds<'_>,
935 assoc: &ty::AssocItem,
936 assoc_substs: &[ty::GenericArg<'tcx>],
939 is_bound_surely_present: bool,
941 // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
943 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
944 hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
948 let matching_trait_bounds = trait_bounds
950 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
951 .collect::<Vec<_>>();
953 let span = match &matching_trait_bounds[..] {
955 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
962 self.constrain_associated_type_structured_suggestion(
972 /// Given a span corresponding to a bound, provide a structured suggestion to set an
973 /// associated type to a given type `ty`.
974 fn constrain_associated_type_structured_suggestion(
976 diag: &mut Diagnostic,
978 assoc: &ty::AssocItem,
979 assoc_substs: &[ty::GenericArg<'tcx>],
983 if let Ok(has_params) =
984 self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
986 let (span, sugg) = if has_params {
987 let pos = span.hi() - BytePos(1);
988 let span = Span::new(pos, pos, span.ctxt(), span.parent());
989 (span, format!(", {} = {}", assoc.ident(self), ty))
991 let item_args = self.format_generic_args(assoc_substs);
992 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
994 diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
1000 pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) {
1001 let width = self.sess.diagnostic_width();
1002 let length_limit = width.saturating_sub(30);
1003 let mut type_limit = 50;
1004 let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1005 .pretty_print_type(ty)
1006 .expect("could not write to `String`")
1008 if regular.len() <= width {
1009 return (regular, None);
1013 // Look for the longest properly trimmed path that still fits in length_limit.
1014 short = with_forced_trimmed_paths!(
1015 FmtPrinter::new_with_limit(
1017 hir::def::Namespace::TypeNS,
1018 rustc_session::Limit(type_limit),
1020 .pretty_print_type(ty)
1021 .expect("could not write to `String`")
1024 if short.len() <= length_limit || type_limit == 0 {
1029 if regular == short {
1030 return (regular, None);
1032 // Multiple types might be shortened in a single error, ensure we create a file for each.
1033 let mut s = DefaultHasher::new();
1035 let hash = s.finish();
1036 let path = self.output_filenames(()).temp_path_ext(&format!("long-type-{hash}.txt"), None);
1037 match std::fs::write(&path, ®ular) {
1038 Ok(_) => (short, Some(path)),
1039 Err(_) => (regular, None),
1043 fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
1044 FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1045 .path_generic_args(Ok, args)
1046 .expect("could not write to `String`.")