]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/error.rs
Rollup merge of #104708 - jonasspinner:fix-backoff-doc-to-match-implementation, r...
[rust.git] / compiler / rustc_middle / src / ty / error.rs
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};
5 use hir::def::DefKind;
6 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
7 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
8 use rustc_hir as hir;
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;
13
14 use std::borrow::Cow;
15 use std::collections::hash_map::DefaultHasher;
16 use std::fmt;
17 use std::hash::{Hash, Hasher};
18 use std::path::PathBuf;
19
20 use super::print::PrettyPrinter;
21
22 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable, Lift)]
23 pub struct ExpectedFound<T> {
24     pub expected: T,
25     pub found: T,
26 }
27
28 impl<T> ExpectedFound<T> {
29     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
30         if a_is_expected {
31             ExpectedFound { expected: a, found: b }
32         } else {
33             ExpectedFound { expected: b, found: a }
34         }
35     }
36 }
37
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> {
42     Mismatch,
43     ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
44     PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
45     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
46     AbiMismatch(ExpectedFound<abi::Abi>),
47     Mutability,
48     ArgumentMutability(usize),
49     TupleSize(ExpectedFound<usize>),
50     FixedArraySize(ExpectedFound<u64>),
51     ArgCount,
52     FieldMisMatch(Symbol, Symbol),
53
54     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
55     RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
56     RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
57     RegionsPlaceholderMismatch,
58
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>),
65
66     /// Instantiating a type variable with the given type would have
67     /// created a cycle (because it appears somewhere within that
68     /// type).
69     CyclicTy(Ty<'tcx>),
70     CyclicConst(ty::Const<'tcx>),
71     ProjectionMismatched(ExpectedFound<DefId>),
72     ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
73     ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
74
75     IntrinsicCast,
76     /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
77     TargetFeatureCast(DefId),
78 }
79
80 impl TypeError<'_> {
81     pub fn involves_regions(self) -> bool {
82         match self {
83             TypeError::RegionsDoesNotOutlive(_, _)
84             | TypeError::RegionsInsufficientlyPolymorphic(_, _)
85             | TypeError::RegionsOverlyPolymorphic(_, _)
86             | TypeError::RegionsPlaceholderMismatch => true,
87             _ => false,
88         }
89     }
90 }
91
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
95 /// errors.
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<'_>,
101             expected: &str,
102             found: &str,
103         ) -> fmt::Result {
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)
108             } else {
109                 write!(f, "expected {}, found {}", expected, found)
110             }
111         }
112
113         let br_string = |br: ty::BoundRegionKind| match br {
114             ty::BrNamed(_, name) => format!(" {}", name),
115             _ => String::new(),
116         };
117
118         match *self {
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)
124             }
125             PolarityMismatch(values) => {
126                 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
127             }
128             UnsafetyMismatch(values) => {
129                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
130             }
131             AbiMismatch(values) => {
132                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
133             }
134             ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
135             TupleSize(values) => write!(
136                 f,
137                 "expected a tuple with {} element{}, found one with {} element{}",
138                 values.expected,
139                 pluralize!(values.expected),
140                 values.found,
141                 pluralize!(values.found)
142             ),
143             FixedArraySize(values) => write!(
144                 f,
145                 "expected an array with a fixed size of {} element{}, found one with {} element{}",
146                 values.expected,
147                 pluralize!(values.expected),
148                 values.found,
149                 pluralize!(values.found)
150             ),
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")
157             }
158             RegionsOverlyPolymorphic(br, _) => write!(
159                 f,
160                 "expected concrete lifetime, found bound lifetime parameter{}",
161                 br_string(br)
162             ),
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),
168                 ));
169                 if expected == found {
170                     expected = values.expected.sort_string(tcx);
171                     found = values.found.sort_string(tcx);
172                 }
173                 report_maybe_different(f, &expected, &found)
174             }),
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),
179                 ));
180                 if expected == found {
181                     expected = tcx.def_path_str(values.expected);
182                     found = tcx.def_path_str(values.found);
183                 }
184                 report_maybe_different(
185                     f,
186                     &format!("trait `{expected}`"),
187                     &format!("trait `{found}`"),
188                 )
189             }),
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(),
194                 };
195                 let found = match values.found {
196                     ty::IntVarValue::IntType(ty) => ty.name_str(),
197                     ty::IntVarValue::UintType(ty) => ty.name_str(),
198                 };
199                 write!(f, "expected `{}`, found `{}`", expected, found)
200             }
201             FloatMismatch(ref values) => {
202                 write!(
203                     f,
204                     "expected `{}`, found `{}`",
205                     values.expected.name_str(),
206                     values.found.name_str()
207                 )
208             }
209             VariadicMismatch(ref values) => write!(
210                 f,
211                 "expected {} fn, found {} function",
212                 if values.expected { "variadic" } else { "non-variadic" },
213                 if values.found { "variadic" } else { "non-variadic" }
214             ),
215             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
216                 write!(
217                     f,
218                     "expected {}, found {}",
219                     tcx.def_path_str(values.expected),
220                     tcx.def_path_str(values.found)
221                 )
222             }),
223             ExistentialMismatch(ref values) => report_maybe_different(
224                 f,
225                 &format!("trait `{}`", values.expected),
226                 &format!("trait `{}`", values.found),
227             ),
228             ConstMismatch(ref values) => {
229                 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
230             }
231             IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
232             TargetFeatureCast(_) => write!(
233                 f,
234                 "cannot coerce functions with `#[target_feature]` to safe function pointers"
235             ),
236         }
237     }
238 }
239
240 impl<'tcx> TypeError<'tcx> {
241     pub fn must_include_note(self) -> bool {
242         use self::TypeError::*;
243         match self {
244             CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
245             | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
246             | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
247             | VariadicMismatch(_) | TargetFeatureCast(_) => false,
248
249             Mutability
250             | ArgumentMutability(_)
251             | TupleSize(_)
252             | ArgCount
253             | FieldMisMatch(..)
254             | RegionsDoesNotOutlive(..)
255             | RegionsInsufficientlyPolymorphic(..)
256             | RegionsOverlyPolymorphic(..)
257             | RegionsPlaceholderMismatch
258             | Traits(_)
259             | ProjectionMismatched(_)
260             | ExistentialMismatch(_)
261             | ConstMismatch(_)
262             | IntrinsicCast => true,
263         }
264     }
265 }
266
267 impl<'tcx> Ty<'tcx> {
268     pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
269         match *self.kind() {
270             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
271                 format!("`{}`", self).into()
272             }
273             ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
274
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(),
277             ty::Array(t, n) => {
278                 if t.is_simple_ty() {
279                     return format!("array `{}`", self).into();
280                 }
281
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();
286                     }
287                 }
288                 "array".into()
289             }
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),
296                 };
297
298                 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
299                     format!("`*{}`", tymut_string).into()
300                 } else {
301                     // Unknown type name, it's long or has type arguments
302                     "raw pointer".into()
303                 }
304             },
305             ty::Ref(_, ty, mutbl) => {
306                 let tymut = ty::TypeAndMut { ty, mutbl };
307                 let tymut_string = tymut.to_string();
308
309                 if tymut_string != "_"
310                     && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
311                 {
312                     format!("`&{}`", tymut_string).into()
313                 } else {
314                     // Unknown type name, it's long or has type arguments
315                     match mutbl {
316                         hir::Mutability::Mut => "mutable reference",
317                         _ => "reference",
318                     }
319                     .into()
320                 }
321             }
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()
326             }
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::Alias(ty::Projection, _) => "associated type".into(),
341             ty::Param(p) => format!("type parameter `{}`", p).into(),
342             ty::Alias(ty::Opaque, ..) => "opaque type".into(),
343             ty::Error(_) => "type error".into(),
344         }
345     }
346
347     pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
348         match *self.kind() {
349             ty::Infer(_)
350             | ty::Error(_)
351             | ty::Bool
352             | ty::Char
353             | ty::Int(_)
354             | ty::Uint(_)
355             | ty::Float(_)
356             | ty::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",
366                 _ => "reference",
367             }
368             .into(),
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::Alias(ty::Projection, _) => "associated type".into(),
379             ty::Param(_) => "type parameter".into(),
380             ty::Alias(ty::Opaque, ..) => "opaque type".into(),
381         }
382     }
383 }
384
385 impl<'tcx> TyCtxt<'tcx> {
386     pub fn note_and_explain_type_err(
387         self,
388         diag: &mut Diagnostic,
389         err: TypeError<'tcx>,
390         cause: &ObligationCause<'tcx>,
391         sp: Span,
392         body_owner_def_id: DefId,
393     ) {
394         use self::TypeError::*;
395         debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
396         match err {
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");
402                     }
403                     (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => {
404                         // Issue #63167
405                         diag.note("distinct uses of `impl Trait` result in different opaque types");
406                     }
407                     (ty::Float(_), ty::Infer(ty::IntVar(_)))
408                         if let Ok(
409                             // Issue #53280
410                             snippet,
411                         ) = self.sess.source_map().span_to_snippet(sp) =>
412                     {
413                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
414                             diag.span_suggestion(
415                                 sp,
416                                 "use a float literal",
417                                 format!("{}.0", snippet),
418                                 MachineApplicable,
419                             );
420                         }
421                     }
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");
427                         }
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");
431                         }
432                         diag.note(
433                             "a type parameter was expected, but a different one was found; \
434                              you might be missing a type parameter or trait bound",
435                         );
436                         diag.note(
437                             "for more information, visit \
438                              https://doc.rust-lang.org/book/ch10-02-traits.html\
439                              #traits-as-parameters",
440                         );
441                     }
442                     (ty::Alias(ty::Projection, _), ty::Alias(ty::Projection, _)) => {
443                         diag.note("an associated type was expected, but a different one was found");
444                     }
445                     (ty::Param(p), ty::Alias(ty::Projection, proj)) | (ty::Alias(ty::Projection, proj), ty::Param(p))
446                         if self.def_kind(proj.def_id) != DefKind::ImplTraitPlaceholder =>
447                     {
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");
452                         }
453                         let hir = self.hir();
454                         let mut note = true;
455                         if let Some(generics) = generics
456                             .type_param(p, self)
457                             .def_id
458                             .as_local()
459                             .map(|id| hir.local_def_id_to_hir_id(id))
460                             .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
461                             .as_ref()
462                             .and_then(|node| node.generics())
463                         {
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);
467                             let path =
468                                 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
469                             let item_name = self.item_name(proj.def_id);
470                             let item_args = self.format_generic_args(assoc_substs);
471
472                             let path = if path.ends_with('>') {
473                                 format!(
474                                     "{}, {}{} = {}>",
475                                     &path[..path.len() - 1],
476                                     item_name,
477                                     item_args,
478                                     p
479                                 )
480                             } else {
481                                 format!("{}<{}{} = {}>", path, item_name, item_args, p)
482                             };
483                             note = !suggest_constraining_type_param(
484                                 self,
485                                 generics,
486                                 diag,
487                                 &format!("{}", proj.self_ty()),
488                                 &path,
489                                 None,
490                             );
491                         }
492                         if note {
493                             diag.note("you might be missing a type parameter or trait bound");
494                         }
495                     }
496                     (ty::Param(p), ty::Dynamic(..) | ty::Alias(ty::Opaque, ..))
497                     | (ty::Dynamic(..) | ty::Alias(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");
502                         }
503                         diag.help("type parameters must be constrained to match other types");
504                         if self.sess.teach(&diag.get_code().unwrap()) {
505                             diag.help(
506                                 "given a type parameter `T` and a method `foo`:
507 ```
508 trait Trait<T> { fn foo(&self) -> T; }
509 ```
510 the only ways to implement method `foo` are:
511 - constrain `T` with an explicit type:
512 ```
513 impl Trait<String> for X {
514     fn foo(&self) -> String { String::new() }
515 }
516 ```
517 - add a trait bound to `T` and call a method on that trait that returns `Self`:
518 ```
519 impl<T: std::default::Default> Trait<T> for X {
520     fn foo(&self) -> T { <T as std::default::Default>::default() }
521 }
522 ```
523 - change `foo` to return an argument of type `T`:
524 ```
525 impl<T> Trait<T> for X {
526     fn foo(&self, x: T) -> T { x }
527 }
528 ```",
529                             );
530                         }
531                         diag.note(
532                             "for more information, visit \
533                              https://doc.rust-lang.org/book/ch10-02-traits.html\
534                              #traits-as-parameters",
535                         );
536                     }
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");
542                         }
543                         diag.help(&format!(
544                             "every closure has a distinct type and so could not always match the \
545                              caller-chosen type of parameter `{}`",
546                             p
547                         ));
548                     }
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");
554                         }
555                     }
556                     (ty::Alias(ty::Projection, proj_ty), _) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
557                         self.expected_projection(
558                             diag,
559                             proj_ty,
560                             values,
561                             body_owner_def_id,
562                             cause.code(),
563                         );
564                     }
565                     (_, ty::Alias(ty::Projection, proj_ty)) if self.def_kind(proj_ty.def_id) != DefKind::ImplTraitPlaceholder => {
566                         let msg = format!(
567                             "consider constraining the associated type `{}` to `{}`",
568                             values.found, values.expected,
569                         );
570                         if !(self.suggest_constraining_opaque_associated_type(
571                             diag,
572                             &msg,
573                             proj_ty,
574                             values.expected,
575                         ) || self.suggest_constraint(
576                             diag,
577                             &msg,
578                             body_owner_def_id,
579                             proj_ty,
580                             values.expected,
581                         )) {
582                             diag.help(&msg);
583                             diag.note(
584                                 "for more information, visit \
585                                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
586                             );
587                         }
588                     }
589                     _ => {}
590                 }
591                 debug!(
592                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
593                     values.expected,
594                     values.expected.kind(),
595                     values.found,
596                     values.found.kind(),
597                 );
598             }
599             CyclicTy(ty) => {
600                 // Watch out for various cases of cyclic types and try to explain.
601                 if ty.is_closure() || ty.is_generator() {
602                     diag.note(
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",
607                     );
608                 }
609             }
610             TargetFeatureCast(def_id) => {
611                 let target_spans =
612                     self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
613                 diag.note(
614                     "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
615                 );
616                 diag.span_labels(target_spans, "`#[target_feature]` added here");
617             }
618             _ => {}
619         }
620     }
621
622     fn suggest_constraint(
623         self,
624         diag: &mut Diagnostic,
625         msg: &str,
626         body_owner_def_id: DefId,
627         proj_ty: &ty::AliasTy<'tcx>,
628         ty: Ty<'tcx>,
629     ) -> bool {
630         let assoc = self.associated_item(proj_ty.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
639                 } else {
640                     return false;
641                 };
642                 let Some(def_id) = def_id.as_local() else {
643                     return false;
644                 };
645
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(
650                         diag,
651                         &trait_ref,
652                         pred.bounds,
653                         &assoc,
654                         assoc_substs,
655                         ty,
656                         msg,
657                         false,
658                     ) {
659                         return true;
660                     }
661                 }
662             }
663         }
664         false
665     }
666
667     /// An associated type was expected and a different type was found.
668     ///
669     /// We perform a few different checks to see what we can suggest:
670     ///
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(
681         self,
682         diag: &mut Diagnostic,
683         proj_ty: &ty::AliasTy<'tcx>,
684         values: ExpectedFound<Ty<'tcx>>,
685         body_owner_def_id: DefId,
686         cause_code: &ObligationCauseCode<'_>,
687     ) {
688         let msg = format!(
689             "consider constraining the associated type `{}` to `{}`",
690             values.expected, values.found
691         );
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);
694
695         // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
696         let callable_scope = matches!(
697             body_owner,
698             Some(
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(..), .. }),
702             )
703         );
704         let impl_comparison =
705             matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
706         let assoc = self.associated_item(proj_ty.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`.
711         } else {
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(
716                 diag,
717                 assoc.container_id(self),
718                 current_method_ident,
719                 proj_ty.def_id,
720                 values.expected,
721             );
722             // Possibly suggest constraining the associated type to conform to the
723             // found type.
724             if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
725                 || point_at_assoc_fn
726             {
727                 return;
728             }
729         }
730
731         self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
732
733         if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
734             return;
735         }
736
737         if !impl_comparison {
738             // Generic suggestion when we can't be more specific.
739             if callable_scope {
740                 diag.help(&format!(
741                     "{} or calling a method that returns `{}`",
742                     msg, values.expected
743                 ));
744             } else {
745                 diag.help(&msg);
746             }
747             diag.note(
748                 "for more information, visit \
749                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
750             );
751         }
752         if self.sess.teach(&diag.get_code().unwrap()) {
753             diag.help(
754                 "given an associated type `T` and a method `foo`:
755 ```
756 trait Trait {
757 type T;
758 fn foo(&self) -> Self::T;
759 }
760 ```
761 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
762 ```
763 impl Trait for X {
764 type T = String;
765 fn foo(&self) -> Self::T { String::new() }
766 }
767 ```",
768             );
769         }
770     }
771
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(
775         self,
776         diag: &mut Diagnostic,
777         msg: &str,
778         proj_ty: &ty::AliasTy<'tcx>,
779         ty: Ty<'tcx>,
780     ) -> bool {
781         let assoc = self.associated_item(proj_ty.def_id);
782         if let ty::Alias(ty::Opaque, ty::AliasTy { 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`"),
788                 }
789             } else {
790                 return false;
791             };
792
793             let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
794
795             self.constrain_generic_bound_associated_type_structured_suggestion(
796                 diag,
797                 &trait_ref,
798                 opaque_hir_ty.bounds,
799                 assoc,
800                 assoc_substs,
801                 ty,
802                 msg,
803                 true,
804             )
805         } else {
806             false
807         }
808     }
809
810     fn point_at_methods_that_satisfy_associated_type(
811         self,
812         diag: &mut Diagnostic,
813         assoc_container_id: DefId,
814         current_method_ident: Option<Symbol>,
815         proj_ty_item_def_id: DefId,
816         expected: Ty<'tcx>,
817     ) -> bool {
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
823             .items
824             .iter()
825             .filter(|(name, item)| {
826                 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
827             })
828             .filter_map(|(_, item)| {
829                 let method = self.fn_sig(item.def_id);
830                 match *method.output().skip_binder().kind() {
831                     ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. })
832                         if item_def_id == proj_ty_item_def_id =>
833                     {
834                         Some((
835                             self.def_span(item.def_id),
836                             format!("consider calling `{}`", self.def_path_str(item.def_id)),
837                         ))
838                     }
839                     _ => None,
840                 }
841             })
842             .collect();
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();
848             let msg = format!(
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 { "" },
854                 ty = expected
855             );
856             for (sp, label) in methods.into_iter() {
857                 span.push_span_label(sp, label);
858             }
859             diag.span_help(span, &msg);
860             return true;
861         }
862         false
863     }
864
865     fn point_at_associated_type(
866         self,
867         diag: &mut Diagnostic,
868         body_owner_def_id: DefId,
869         found: Ty<'tcx>,
870     ) -> bool {
871         let Some(hir_id) = body_owner_def_id.as_local() else {
872             return false;
873         };
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);
880         match item {
881             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
882                 // FIXME: account for `#![feature(specialization)]`
883                 for item in &items[..] {
884                     match item.kind {
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)
890                             {
891                                 if self.type_of(item.id.owner_id) == found {
892                                     diag.span_label(
893                                         item.span,
894                                         "associated type defaults can't be assumed inside the \
895                                             trait defining them",
896                                     );
897                                     return true;
898                                 }
899                             }
900                         }
901                         _ => {}
902                     }
903                 }
904             }
905             Some(hir::Node::Item(hir::Item {
906                 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
907                 ..
908             })) => {
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");
913                             return true;
914                         }
915                     }
916                 }
917             }
918             _ => {}
919         }
920         false
921     }
922
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`.
925     ///
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(
931         self,
932         diag: &mut Diagnostic,
933         trait_ref: &ty::TraitRef<'tcx>,
934         bounds: hir::GenericBounds<'_>,
935         assoc: &ty::AssocItem,
936         assoc_substs: &[ty::GenericArg<'tcx>],
937         ty: Ty<'tcx>,
938         msg: &str,
939         is_bound_surely_present: bool,
940     ) -> bool {
941         // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
942
943         let trait_bounds = bounds.iter().filter_map(|bound| match bound {
944             hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
945             _ => None,
946         });
947
948         let matching_trait_bounds = trait_bounds
949             .clone()
950             .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
951             .collect::<Vec<_>>();
952
953         let span = match &matching_trait_bounds[..] {
954             &[ptr] => ptr.span,
955             &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
956                 &[ptr] => ptr.span,
957                 _ => return false,
958             },
959             _ => return false,
960         };
961
962         self.constrain_associated_type_structured_suggestion(
963             diag,
964             span,
965             assoc,
966             assoc_substs,
967             ty,
968             msg,
969         )
970     }
971
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(
975         self,
976         diag: &mut Diagnostic,
977         span: Span,
978         assoc: &ty::AssocItem,
979         assoc_substs: &[ty::GenericArg<'tcx>],
980         ty: Ty<'tcx>,
981         msg: &str,
982     ) -> bool {
983         if let Ok(has_params) =
984             self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
985         {
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))
990             } else {
991                 let item_args = self.format_generic_args(assoc_substs);
992                 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
993             };
994             diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
995             return true;
996         }
997         false
998     }
999
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`")
1007             .into_buffer();
1008         if regular.len() <= width {
1009             return (regular, None);
1010         }
1011         let mut short;
1012         loop {
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(
1016                     self,
1017                     hir::def::Namespace::TypeNS,
1018                     rustc_session::Limit(type_limit),
1019                 )
1020                 .pretty_print_type(ty)
1021                 .expect("could not write to `String`")
1022                 .into_buffer()
1023             );
1024             if short.len() <= length_limit || type_limit == 0 {
1025                 break;
1026             }
1027             type_limit -= 1;
1028         }
1029         if regular == short {
1030             return (regular, None);
1031         }
1032         // Multiple types might be shortened in a single error, ensure we create a file for each.
1033         let mut s = DefaultHasher::new();
1034         ty.hash(&mut s);
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, &regular) {
1038             Ok(_) => (short, Some(path)),
1039             Err(_) => (regular, None),
1040         }
1041     }
1042
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`.")
1047             .into_buffer()
1048     }
1049 }