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