]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/error.rs
Merge commit '984330a6ee3c4d15626685d6dc8b7b759ff630bd' into clippyup
[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::{FmtPrinter, Printer};
4 use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt};
5 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
6 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
7 use rustc_hir as hir;
8 use rustc_hir::def_id::DefId;
9 use rustc_span::symbol::{sym, Symbol};
10 use rustc_span::{BytePos, Span};
11 use rustc_target::spec::abi;
12
13 use std::borrow::Cow;
14 use std::fmt;
15
16 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
17 pub struct ExpectedFound<T> {
18     pub expected: T,
19     pub found: T,
20 }
21
22 impl<T> ExpectedFound<T> {
23     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
24         if a_is_expected {
25             ExpectedFound { expected: a, found: b }
26         } else {
27             ExpectedFound { expected: b, found: a }
28         }
29     }
30 }
31
32 // Data structures used in type unification
33 #[derive(Clone, Debug, TypeFoldable)]
34 pub enum TypeError<'tcx> {
35     Mismatch,
36     ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
37     PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
38     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
39     AbiMismatch(ExpectedFound<abi::Abi>),
40     Mutability,
41     ArgumentMutability(usize),
42     TupleSize(ExpectedFound<usize>),
43     FixedArraySize(ExpectedFound<u64>),
44     ArgCount,
45     FieldMisMatch(Symbol, Symbol),
46
47     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
48     RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
49     RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
50     RegionsPlaceholderMismatch,
51
52     Sorts(ExpectedFound<Ty<'tcx>>),
53     ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
54     IntMismatch(ExpectedFound<ty::IntVarValue>),
55     FloatMismatch(ExpectedFound<ty::FloatTy>),
56     Traits(ExpectedFound<DefId>),
57     VariadicMismatch(ExpectedFound<bool>),
58
59     /// Instantiating a type variable with the given type would have
60     /// created a cycle (because it appears somewhere within that
61     /// type).
62     CyclicTy(Ty<'tcx>),
63     CyclicConst(ty::Const<'tcx>),
64     ProjectionMismatched(ExpectedFound<DefId>),
65     ExistentialMismatch(
66         ExpectedFound<&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>>,
67     ),
68     ObjectUnsafeCoercion(DefId),
69     ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
70
71     IntrinsicCast,
72     /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
73     TargetFeatureCast(DefId),
74 }
75
76 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
77 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
78 /// afterwards to present additional details, particularly when it comes to lifetime-related
79 /// errors.
80 impl<'tcx> fmt::Display for TypeError<'tcx> {
81     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82         use self::TypeError::*;
83         fn report_maybe_different(
84             f: &mut fmt::Formatter<'_>,
85             expected: &str,
86             found: &str,
87         ) -> fmt::Result {
88             // A naive approach to making sure that we're not reporting silly errors such as:
89             // (expected closure, found closure).
90             if expected == found {
91                 write!(f, "expected {}, found a different {}", expected, found)
92             } else {
93                 write!(f, "expected {}, found {}", expected, found)
94             }
95         }
96
97         let br_string = |br: ty::BoundRegionKind| match br {
98             ty::BrNamed(_, name) => format!(" {}", name),
99             _ => String::new(),
100         };
101
102         match *self {
103             CyclicTy(_) => write!(f, "cyclic type of infinite size"),
104             CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
105             Mismatch => write!(f, "types differ"),
106             ConstnessMismatch(values) => {
107                 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
108             }
109             PolarityMismatch(values) => {
110                 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
111             }
112             UnsafetyMismatch(values) => {
113                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
114             }
115             AbiMismatch(values) => {
116                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
117             }
118             ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
119             TupleSize(values) => write!(
120                 f,
121                 "expected a tuple with {} element{}, found one with {} element{}",
122                 values.expected,
123                 pluralize!(values.expected),
124                 values.found,
125                 pluralize!(values.found)
126             ),
127             FixedArraySize(values) => write!(
128                 f,
129                 "expected an array with a fixed size of {} element{}, found one with {} element{}",
130                 values.expected,
131                 pluralize!(values.expected),
132                 values.found,
133                 pluralize!(values.found)
134             ),
135             ArgCount => write!(f, "incorrect number of function parameters"),
136             FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
137             RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
138             RegionsInsufficientlyPolymorphic(br, _) => write!(
139                 f,
140                 "expected bound lifetime parameter{}, found concrete lifetime",
141                 br_string(br)
142             ),
143             RegionsOverlyPolymorphic(br, _) => write!(
144                 f,
145                 "expected concrete lifetime, found bound lifetime parameter{}",
146                 br_string(br)
147             ),
148             RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
149             ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
150                 report_maybe_different(
151                     f,
152                     &values.expected.sort_string(tcx),
153                     &values.found.sort_string(tcx),
154                 )
155             }),
156             Traits(values) => ty::tls::with(|tcx| {
157                 report_maybe_different(
158                     f,
159                     &format!("trait `{}`", tcx.def_path_str(values.expected)),
160                     &format!("trait `{}`", tcx.def_path_str(values.found)),
161                 )
162             }),
163             IntMismatch(ref values) => {
164                 let expected = match values.expected {
165                     ty::IntVarValue::IntType(ty) => ty.name_str(),
166                     ty::IntVarValue::UintType(ty) => ty.name_str(),
167                 };
168                 let found = match values.found {
169                     ty::IntVarValue::IntType(ty) => ty.name_str(),
170                     ty::IntVarValue::UintType(ty) => ty.name_str(),
171                 };
172                 write!(f, "expected `{}`, found `{}`", expected, found)
173             }
174             FloatMismatch(ref values) => {
175                 write!(
176                     f,
177                     "expected `{}`, found `{}`",
178                     values.expected.name_str(),
179                     values.found.name_str()
180                 )
181             }
182             VariadicMismatch(ref values) => write!(
183                 f,
184                 "expected {} fn, found {} function",
185                 if values.expected { "variadic" } else { "non-variadic" },
186                 if values.found { "variadic" } else { "non-variadic" }
187             ),
188             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
189                 write!(
190                     f,
191                     "expected {}, found {}",
192                     tcx.def_path_str(values.expected),
193                     tcx.def_path_str(values.found)
194                 )
195             }),
196             ExistentialMismatch(ref values) => report_maybe_different(
197                 f,
198                 &format!("trait `{}`", values.expected),
199                 &format!("trait `{}`", values.found),
200             ),
201             ConstMismatch(ref values) => {
202                 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
203             }
204             IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
205             TargetFeatureCast(_) => write!(
206                 f,
207                 "cannot coerce functions with `#[target_feature]` to safe function pointers"
208             ),
209             ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
210         }
211     }
212 }
213
214 impl<'tcx> TypeError<'tcx> {
215     pub fn must_include_note(&self) -> bool {
216         use self::TypeError::*;
217         match self {
218             CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
219             | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
220             | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
221             | VariadicMismatch(_) | TargetFeatureCast(_) => false,
222
223             Mutability
224             | ArgumentMutability(_)
225             | TupleSize(_)
226             | ArgCount
227             | FieldMisMatch(..)
228             | RegionsDoesNotOutlive(..)
229             | RegionsInsufficientlyPolymorphic(..)
230             | RegionsOverlyPolymorphic(..)
231             | RegionsPlaceholderMismatch
232             | Traits(_)
233             | ProjectionMismatched(_)
234             | ExistentialMismatch(_)
235             | ConstMismatch(_)
236             | IntrinsicCast
237             | ObjectUnsafeCoercion(_) => true,
238         }
239     }
240 }
241
242 impl<'tcx> Ty<'tcx> {
243     pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
244         match *self.kind() {
245             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
246                 format!("`{}`", self).into()
247             }
248             ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
249
250             ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
251             ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
252             ty::Array(t, n) => {
253                 if t.is_simple_ty() {
254                     return format!("array `{}`", self).into();
255                 }
256
257                 let n = tcx.lift(n).unwrap();
258                 if let ty::ConstKind::Value(v) = n.val() {
259                     if let Some(n) = v.try_to_machine_usize(tcx) {
260                         return format!("array of {} element{}", n, pluralize!(n)).into();
261                     }
262                 }
263                 "array".into()
264             }
265             ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
266             ty::Slice(_) => "slice".into(),
267             ty::RawPtr(_) => "*-ptr".into(),
268             ty::Ref(_, ty, mutbl) => {
269                 let tymut = ty::TypeAndMut { ty, mutbl };
270                 let tymut_string = tymut.to_string();
271                 if tymut_string != "_"
272                     && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
273                 {
274                     format!("`&{}`", tymut_string).into()
275                 } else {
276                     // Unknown type name, it's long or has type arguments
277                     match mutbl {
278                         hir::Mutability::Mut => "mutable reference",
279                         _ => "reference",
280                     }
281                     .into()
282                 }
283             }
284             ty::FnDef(..) => "fn item".into(),
285             ty::FnPtr(_) => "fn pointer".into(),
286             ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
287                 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
288             }
289             ty::Dynamic(..) => "trait object".into(),
290             ty::Closure(..) => "closure".into(),
291             ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
292             ty::GeneratorWitness(..) => "generator witness".into(),
293             ty::Tuple(..) => "tuple".into(),
294             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
295             ty::Infer(ty::IntVar(_)) => "integer".into(),
296             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
297             ty::Placeholder(..) => "placeholder type".into(),
298             ty::Bound(..) => "bound type".into(),
299             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
300             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
301             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
302             ty::Projection(_) => "associated type".into(),
303             ty::Param(p) => format!("type parameter `{}`", p).into(),
304             ty::Opaque(..) => "opaque type".into(),
305             ty::Error(_) => "type error".into(),
306         }
307     }
308
309     pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
310         match *self.kind() {
311             ty::Infer(_)
312             | ty::Error(_)
313             | ty::Bool
314             | ty::Char
315             | ty::Int(_)
316             | ty::Uint(_)
317             | ty::Float(_)
318             | ty::Str
319             | ty::Never => "type".into(),
320             ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
321             ty::Adt(def, _) => def.descr().into(),
322             ty::Foreign(_) => "extern type".into(),
323             ty::Array(..) => "array".into(),
324             ty::Slice(_) => "slice".into(),
325             ty::RawPtr(_) => "raw pointer".into(),
326             ty::Ref(.., mutbl) => match mutbl {
327                 hir::Mutability::Mut => "mutable reference",
328                 _ => "reference",
329             }
330             .into(),
331             ty::FnDef(..) => "fn item".into(),
332             ty::FnPtr(_) => "fn pointer".into(),
333             ty::Dynamic(..) => "trait object".into(),
334             ty::Closure(..) => "closure".into(),
335             ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
336             ty::GeneratorWitness(..) => "generator witness".into(),
337             ty::Tuple(..) => "tuple".into(),
338             ty::Placeholder(..) => "higher-ranked type".into(),
339             ty::Bound(..) => "bound type variable".into(),
340             ty::Projection(_) => "associated type".into(),
341             ty::Param(_) => "type parameter".into(),
342             ty::Opaque(..) => "opaque type".into(),
343         }
344     }
345 }
346
347 impl<'tcx> TyCtxt<'tcx> {
348     pub fn note_and_explain_type_err(
349         self,
350         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
351         db: &mut Diagnostic,
352         err: &TypeError<'tcx>,
353         cause: &ObligationCause<'tcx>,
354         sp: Span,
355         body_owner_def_id: DefId,
356     ) {
357         use self::TypeError::*;
358         debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
359         match err {
360             ArgumentSorts(values, _) | Sorts(values) => {
361                 match (values.expected.kind(), values.found.kind()) {
362                     (ty::Closure(..), ty::Closure(..)) => {
363                         db.note("no two closures, even if identical, have the same type");
364                         db.help("consider boxing your closure and/or using it as a trait object");
365                     }
366                     (ty::Opaque(..), ty::Opaque(..)) => {
367                         // Issue #63167
368                         db.note("distinct uses of `impl Trait` result in different opaque types");
369                     }
370                     (ty::Float(_), ty::Infer(ty::IntVar(_)))
371                         if let Ok(
372                             // Issue #53280
373                             snippet,
374                         ) = self.sess.source_map().span_to_snippet(sp) =>
375                     {
376                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
377                             db.span_suggestion(
378                                 sp,
379                                 "use a float literal",
380                                 format!("{}.0", snippet),
381                                 MachineApplicable,
382                             );
383                         }
384                     }
385                     (ty::Param(expected), ty::Param(found)) => {
386                         let generics = self.generics_of(body_owner_def_id);
387                         let e_span = self.def_span(generics.type_param(expected, self).def_id);
388                         if !sp.contains(e_span) {
389                             db.span_label(e_span, "expected type parameter");
390                         }
391                         let f_span = self.def_span(generics.type_param(found, self).def_id);
392                         if !sp.contains(f_span) {
393                             db.span_label(f_span, "found type parameter");
394                         }
395                         db.note(
396                             "a type parameter was expected, but a different one was found; \
397                              you might be missing a type parameter or trait bound",
398                         );
399                         db.note(
400                             "for more information, visit \
401                              https://doc.rust-lang.org/book/ch10-02-traits.html\
402                              #traits-as-parameters",
403                         );
404                     }
405                     (ty::Projection(_), ty::Projection(_)) => {
406                         db.note("an associated type was expected, but a different one was found");
407                     }
408                     (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p)) => {
409                         let generics = self.generics_of(body_owner_def_id);
410                         let p_span = self.def_span(generics.type_param(p, self).def_id);
411                         if !sp.contains(p_span) {
412                             db.span_label(p_span, "this type parameter");
413                         }
414                         let hir = self.hir();
415                         let mut note = true;
416                         if let Some(generics) = generics
417                             .type_param(p, self)
418                             .def_id
419                             .as_local()
420                             .map(|id| hir.local_def_id_to_hir_id(id))
421                             .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
422                             .as_ref()
423                             .and_then(|node| node.generics())
424                         {
425                             // Synthesize the associated type restriction `Add<Output = Expected>`.
426                             // FIXME: extract this logic for use in other diagnostics.
427                             let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
428                             let path =
429                                 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
430                             let item_name = self.item_name(proj.item_def_id);
431                             let item_args = self.format_generic_args(assoc_substs);
432
433                             let path = if path.ends_with('>') {
434                                 format!(
435                                     "{}, {}{} = {}>",
436                                     &path[..path.len() - 1],
437                                     item_name,
438                                     item_args,
439                                     p
440                                 )
441                             } else {
442                                 format!("{}<{}{} = {}>", path, item_name, item_args, p)
443                             };
444                             note = !suggest_constraining_type_param(
445                                 self,
446                                 generics,
447                                 db,
448                                 &format!("{}", proj.self_ty()),
449                                 &path,
450                                 None,
451                             );
452                         }
453                         if note {
454                             db.note("you might be missing a type parameter or trait bound");
455                         }
456                     }
457                     (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
458                     | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
459                         let generics = self.generics_of(body_owner_def_id);
460                         let p_span = self.def_span(generics.type_param(p, self).def_id);
461                         if !sp.contains(p_span) {
462                             db.span_label(p_span, "this type parameter");
463                         }
464                         db.help("type parameters must be constrained to match other types");
465                         if self.sess.teach(&db.get_code().unwrap()) {
466                             db.help(
467                                 "given a type parameter `T` and a method `foo`:
468 ```
469 trait Trait<T> { fn foo(&self) -> T; }
470 ```
471 the only ways to implement method `foo` are:
472 - constrain `T` with an explicit type:
473 ```
474 impl Trait<String> for X {
475     fn foo(&self) -> String { String::new() }
476 }
477 ```
478 - add a trait bound to `T` and call a method on that trait that returns `Self`:
479 ```
480 impl<T: std::default::Default> Trait<T> for X {
481     fn foo(&self) -> T { <T as std::default::Default>::default() }
482 }
483 ```
484 - change `foo` to return an argument of type `T`:
485 ```
486 impl<T> Trait<T> for X {
487     fn foo(&self, x: T) -> T { x }
488 }
489 ```",
490                             );
491                         }
492                         db.note(
493                             "for more information, visit \
494                              https://doc.rust-lang.org/book/ch10-02-traits.html\
495                              #traits-as-parameters",
496                         );
497                     }
498                     (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
499                         let generics = self.generics_of(body_owner_def_id);
500                         let p_span = self.def_span(generics.type_param(p, self).def_id);
501                         if !sp.contains(p_span) {
502                             db.span_label(p_span, "this type parameter");
503                         }
504                         db.help(&format!(
505                             "every closure has a distinct type and so could not always match the \
506                              caller-chosen type of parameter `{}`",
507                             p
508                         ));
509                     }
510                     (ty::Param(p), _) | (_, ty::Param(p)) => {
511                         let generics = self.generics_of(body_owner_def_id);
512                         let p_span = self.def_span(generics.type_param(p, self).def_id);
513                         if !sp.contains(p_span) {
514                             db.span_label(p_span, "this type parameter");
515                         }
516                     }
517                     (ty::Projection(proj_ty), _) => {
518                         self.expected_projection(
519                             db,
520                             proj_ty,
521                             values,
522                             body_owner_def_id,
523                             cause.code(),
524                         );
525                     }
526                     (_, ty::Projection(proj_ty)) => {
527                         let msg = format!(
528                             "consider constraining the associated type `{}` to `{}`",
529                             values.found, values.expected,
530                         );
531                         if !(self.suggest_constraining_opaque_associated_type(
532                             db,
533                             &msg,
534                             proj_ty,
535                             values.expected,
536                         ) || self.suggest_constraint(
537                             db,
538                             &msg,
539                             body_owner_def_id,
540                             proj_ty,
541                             values.expected,
542                         )) {
543                             db.help(&msg);
544                             db.note(
545                                 "for more information, visit \
546                                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
547                             );
548                         }
549                     }
550                     _ => {}
551                 }
552                 debug!(
553                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
554                     values.expected,
555                     values.expected.kind(),
556                     values.found,
557                     values.found.kind(),
558                 );
559             }
560             CyclicTy(ty) => {
561                 // Watch out for various cases of cyclic types and try to explain.
562                 if ty.is_closure() || ty.is_generator() {
563                     db.note(
564                         "closures cannot capture themselves or take themselves as argument;\n\
565                          this error may be the result of a recent compiler bug-fix,\n\
566                          see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
567                          for more information",
568                     );
569                 }
570             }
571             TargetFeatureCast(def_id) => {
572                 let attrs = self.get_attrs(*def_id);
573                 let target_spans = attrs
574                     .iter()
575                     .filter(|attr| attr.has_name(sym::target_feature))
576                     .map(|attr| attr.span);
577                 db.note(
578                     "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
579                 );
580                 db.span_labels(target_spans, "`#[target_feature]` added here");
581             }
582             _ => {}
583         }
584     }
585
586     fn suggest_constraint(
587         self,
588         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
589         db: &mut Diagnostic,
590         msg: &str,
591         body_owner_def_id: DefId,
592         proj_ty: &ty::ProjectionTy<'tcx>,
593         ty: Ty<'tcx>,
594     ) -> bool {
595         let assoc = self.associated_item(proj_ty.item_def_id);
596         let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
597         if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
598             if let Some(hir_generics) = item.generics() {
599                 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
600                 // This will also work for `impl Trait`.
601                 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
602                     let generics = self.generics_of(body_owner_def_id);
603                     generics.type_param(param_ty, self).def_id
604                 } else {
605                     return false;
606                 };
607
608                 // First look in the `where` clause, as this might be
609                 // `fn foo<T>(x: T) where T: Trait`.
610                 for predicate in hir_generics.where_clause.predicates {
611                     if let hir::WherePredicate::BoundPredicate(pred) = predicate {
612                         if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) =
613                             pred.bounded_ty.kind
614                         {
615                             if path.res.opt_def_id() == Some(def_id) {
616                                 // This predicate is binding type param `A` in `<A as T>::Foo` to
617                                 // something, potentially `T`.
618                             } else {
619                                 continue;
620                             }
621                         } else {
622                             continue;
623                         }
624
625                         if self.constrain_generic_bound_associated_type_structured_suggestion(
626                             db,
627                             &trait_ref,
628                             pred.bounds,
629                             &assoc,
630                             assoc_substs,
631                             ty,
632                             msg,
633                             false,
634                         ) {
635                             return true;
636                         }
637                     }
638                 }
639                 for param in hir_generics.params {
640                     if self.hir().opt_local_def_id(param.hir_id).map(|id| id.to_def_id())
641                         == Some(def_id)
642                     {
643                         // This is type param `A` in `<A as T>::Foo`.
644                         return self.constrain_generic_bound_associated_type_structured_suggestion(
645                             db,
646                             &trait_ref,
647                             param.bounds,
648                             &assoc,
649                             assoc_substs,
650                             ty,
651                             msg,
652                             false,
653                         );
654                     }
655                 }
656             }
657         }
658         false
659     }
660
661     /// An associated type was expected and a different type was found.
662     ///
663     /// We perform a few different checks to see what we can suggest:
664     ///
665     ///  - In the current item, look for associated functions that return the expected type and
666     ///    suggest calling them. (Not a structured suggestion.)
667     ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
668     ///    associated type to the found type.
669     ///  - If the associated type has a default type and was expected inside of a `trait`, we
670     ///    mention that this is disallowed.
671     ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
672     ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
673     ///    fn that returns the type.
674     fn expected_projection(
675         self,
676         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
677         db: &mut Diagnostic,
678         proj_ty: &ty::ProjectionTy<'tcx>,
679         values: &ExpectedFound<Ty<'tcx>>,
680         body_owner_def_id: DefId,
681         cause_code: &ObligationCauseCode<'_>,
682     ) {
683         let msg = format!(
684             "consider constraining the associated type `{}` to `{}`",
685             values.expected, values.found
686         );
687         let body_owner = self.hir().get_if_local(body_owner_def_id);
688         let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
689
690         // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
691         let callable_scope = matches!(
692             body_owner,
693             Some(
694                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
695                     | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
696                     | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
697             )
698         );
699         let impl_comparison = matches!(
700             cause_code,
701             ObligationCauseCode::CompareImplMethodObligation { .. }
702                 | ObligationCauseCode::CompareImplTypeObligation { .. }
703                 | ObligationCauseCode::CompareImplConstObligation
704         );
705         let assoc = self.associated_item(proj_ty.item_def_id);
706         if !callable_scope || impl_comparison {
707             // We do not want to suggest calling functions when the reason of the
708             // type error is a comparison of an `impl` with its `trait` or when the
709             // scope is outside of a `Body`.
710         } else {
711             // If we find a suitable associated function that returns the expected type, we don't
712             // want the more general suggestion later in this method about "consider constraining
713             // the associated type or calling a method that returns the associated type".
714             let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
715                 db,
716                 assoc.container.id(),
717                 current_method_ident,
718                 proj_ty.item_def_id,
719                 values.expected,
720             );
721             // Possibly suggest constraining the associated type to conform to the
722             // found type.
723             if self.suggest_constraint(db, &msg, body_owner_def_id, proj_ty, values.found)
724                 || point_at_assoc_fn
725             {
726                 return;
727             }
728         }
729
730         self.suggest_constraining_opaque_associated_type(db, &msg, proj_ty, values.found);
731
732         if self.point_at_associated_type(db, body_owner_def_id, values.found) {
733             return;
734         }
735
736         if !impl_comparison {
737             // Generic suggestion when we can't be more specific.
738             if callable_scope {
739                 db.help(&format!("{} or calling a method that returns `{}`", msg, values.expected));
740             } else {
741                 db.help(&msg);
742             }
743             db.note(
744                 "for more information, visit \
745                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
746             );
747         }
748         if self.sess.teach(&db.get_code().unwrap()) {
749             db.help(
750                 "given an associated type `T` and a method `foo`:
751 ```
752 trait Trait {
753 type T;
754 fn foo(&self) -> Self::T;
755 }
756 ```
757 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
758 ```
759 impl Trait for X {
760 type T = String;
761 fn foo(&self) -> Self::T { String::new() }
762 }
763 ```",
764             );
765         }
766     }
767
768     /// When the expected `impl Trait` is not defined in the current item, it will come from
769     /// a return type. This can occur when dealing with `TryStream` (#71035).
770     fn suggest_constraining_opaque_associated_type(
771         self,
772         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
773         db: &mut Diagnostic,
774         msg: &str,
775         proj_ty: &ty::ProjectionTy<'tcx>,
776         ty: Ty<'tcx>,
777     ) -> bool {
778         let assoc = self.associated_item(proj_ty.item_def_id);
779         if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
780             let opaque_local_def_id = def_id.as_local();
781             let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
782                 match &self.hir().expect_item(opaque_local_def_id).kind {
783                     hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
784                     _ => bug!("The HirId comes from a `ty::Opaque`"),
785                 }
786             } else {
787                 return false;
788             };
789
790             let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
791
792             self.constrain_generic_bound_associated_type_structured_suggestion(
793                 db,
794                 &trait_ref,
795                 opaque_hir_ty.bounds,
796                 assoc,
797                 assoc_substs,
798                 ty,
799                 msg,
800                 true,
801             )
802         } else {
803             false
804         }
805     }
806
807     fn point_at_methods_that_satisfy_associated_type(
808         self,
809         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
810         db: &mut Diagnostic,
811         assoc_container_id: DefId,
812         current_method_ident: Option<Symbol>,
813         proj_ty_item_def_id: DefId,
814         expected: Ty<'tcx>,
815     ) -> bool {
816         let items = self.associated_items(assoc_container_id);
817         // Find all the methods in the trait that could be called to construct the
818         // expected associated type.
819         // FIXME: consider suggesting the use of associated `const`s.
820         let methods: Vec<(Span, String)> = items
821             .items
822             .iter()
823             .filter(|(name, item)| {
824                 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
825             })
826             .filter_map(|(_, item)| {
827                 let method = self.fn_sig(item.def_id);
828                 match *method.output().skip_binder().kind() {
829                     ty::Projection(ty::ProjectionTy { item_def_id, .. })
830                         if item_def_id == proj_ty_item_def_id =>
831                     {
832                         Some((
833                             self.sess.source_map().guess_head_span(self.def_span(item.def_id)),
834                             format!("consider calling `{}`", self.def_path_str(item.def_id)),
835                         ))
836                     }
837                     _ => None,
838                 }
839             })
840             .collect();
841         if !methods.is_empty() {
842             // Use a single `help:` to show all the methods in the trait that can
843             // be used to construct the expected associated type.
844             let mut span: MultiSpan =
845                 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
846             let msg = format!(
847                 "{some} method{s} {are} available that return{r} `{ty}`",
848                 some = if methods.len() == 1 { "a" } else { "some" },
849                 s = pluralize!(methods.len()),
850                 are = pluralize!("is", methods.len()),
851                 r = if methods.len() == 1 { "s" } else { "" },
852                 ty = expected
853             );
854             for (sp, label) in methods.into_iter() {
855                 span.push_span_label(sp, label);
856             }
857             db.span_help(span, &msg);
858             return true;
859         }
860         false
861     }
862
863     fn point_at_associated_type(
864         self,
865         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
866         db: &mut Diagnostic,
867         body_owner_def_id: DefId,
868         found: Ty<'tcx>,
869     ) -> bool {
870         let Some(hir_id) = body_owner_def_id.as_local() else {
871             return false;
872         };
873         let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
874         // When `body_owner` is an `impl` or `trait` item, look in its associated types for
875         // `expected` and point at it.
876         let parent_id = self.hir().get_parent_item(hir_id);
877         let item = self.hir().find_by_def_id(parent_id);
878         debug!("expected_projection parent item {:?}", item);
879         match item {
880             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
881                 // FIXME: account for `#![feature(specialization)]`
882                 for item in &items[..] {
883                     match item.kind {
884                         hir::AssocItemKind::Type => {
885                             // FIXME: account for returning some type in a trait fn impl that has
886                             // an assoc type as a return type (#72076).
887                             if let hir::Defaultness::Default { has_value: true } = item.defaultness
888                             {
889                                 if self.type_of(item.id.def_id) == found {
890                                     db.span_label(
891                                         item.span,
892                                         "associated type defaults can't be assumed inside the \
893                                             trait defining them",
894                                     );
895                                     return true;
896                                 }
897                             }
898                         }
899                         _ => {}
900                     }
901                 }
902             }
903             Some(hir::Node::Item(hir::Item {
904                 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
905                 ..
906             })) => {
907                 for item in &items[..] {
908                     if let hir::AssocItemKind::Type = item.kind {
909                         if self.type_of(item.id.def_id) == found {
910                             db.span_label(item.span, "expected this associated type");
911                             return true;
912                         }
913                     }
914                 }
915             }
916             _ => {}
917         }
918         false
919     }
920
921     /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
922     /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
923     ///
924     /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
925     /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
926     /// trait bound as the one we're looking for. This can help in cases where the associated
927     /// type is defined on a supertrait of the one present in the bounds.
928     fn constrain_generic_bound_associated_type_structured_suggestion(
929         self,
930         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
931         db: &mut Diagnostic,
932         trait_ref: &ty::TraitRef<'tcx>,
933         bounds: hir::GenericBounds<'_>,
934         assoc: &ty::AssocItem,
935         assoc_substs: &[ty::GenericArg<'tcx>],
936         ty: Ty<'tcx>,
937         msg: &str,
938         is_bound_surely_present: bool,
939     ) -> bool {
940         // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
941
942         let trait_bounds = bounds.iter().filter_map(|bound| match bound {
943             hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
944             _ => None,
945         });
946
947         let matching_trait_bounds = trait_bounds
948             .clone()
949             .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
950             .collect::<Vec<_>>();
951
952         let span = match &matching_trait_bounds[..] {
953             &[ptr] => ptr.span,
954             &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
955                 &[ptr] => ptr.span,
956                 _ => return false,
957             },
958             _ => return false,
959         };
960
961         self.constrain_associated_type_structured_suggestion(db, span, assoc, assoc_substs, ty, msg)
962     }
963
964     /// Given a span corresponding to a bound, provide a structured suggestion to set an
965     /// associated type to a given type `ty`.
966     fn constrain_associated_type_structured_suggestion(
967         self,
968         // FIXME(eddyb) rename this since it's no longer a `DiagnosticBuilder`.
969         db: &mut Diagnostic,
970         span: Span,
971         assoc: &ty::AssocItem,
972         assoc_substs: &[ty::GenericArg<'tcx>],
973         ty: Ty<'tcx>,
974         msg: &str,
975     ) -> bool {
976         if let Ok(has_params) =
977             self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
978         {
979             let (span, sugg) = if has_params {
980                 let pos = span.hi() - BytePos(1);
981                 let span = Span::new(pos, pos, span.ctxt(), span.parent());
982                 (span, format!(", {} = {}", assoc.ident(self), ty))
983             } else {
984                 let item_args = self.format_generic_args(assoc_substs);
985                 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
986             };
987             db.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
988             return true;
989         }
990         false
991     }
992
993     fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
994         FmtPrinter::new(self, hir::def::Namespace::TypeNS)
995             .path_generic_args(Ok, args)
996             .expect("could not write to `String`.")
997             .into_buffer()
998     }
999 }