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