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