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