]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Rollup merge of #68869 - GuillaumeGomez:err-explanation-e0271, r=Dylan-DPC
[rust.git] / src / librustc / ty / error.rs
1 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
2 use rustc_errors::{pluralize, Applicability, DiagnosticBuilder};
3 use rustc_hir as hir;
4 use rustc_hir::def_id::DefId;
5 use rustc_span::Span;
6 use rustc_target::spec::abi;
7 use syntax::ast;
8
9 use std::borrow::Cow;
10 use std::fmt;
11
12 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
13 pub struct ExpectedFound<T> {
14     pub expected: T,
15     pub found: T,
16 }
17
18 impl<T> ExpectedFound<T> {
19     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
20         if a_is_expected {
21             ExpectedFound { expected: a, found: b }
22         } else {
23             ExpectedFound { expected: b, found: a }
24         }
25     }
26 }
27
28 // Data structures used in type unification
29 #[derive(Clone, Debug, TypeFoldable)]
30 pub enum TypeError<'tcx> {
31     Mismatch,
32     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
33     AbiMismatch(ExpectedFound<abi::Abi>),
34     Mutability,
35     TupleSize(ExpectedFound<usize>),
36     FixedArraySize(ExpectedFound<u64>),
37     ArgCount,
38
39     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
40     RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
41     RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
42     RegionsPlaceholderMismatch,
43
44     Sorts(ExpectedFound<Ty<'tcx>>),
45     IntMismatch(ExpectedFound<ty::IntVarValue>),
46     FloatMismatch(ExpectedFound<ast::FloatTy>),
47     Traits(ExpectedFound<DefId>),
48     VariadicMismatch(ExpectedFound<bool>),
49
50     /// Instantiating a type variable with the given type would have
51     /// created a cycle (because it appears somewhere within that
52     /// type).
53     CyclicTy(Ty<'tcx>),
54     ProjectionMismatched(ExpectedFound<DefId>),
55     ProjectionBoundsLength(ExpectedFound<usize>),
56     ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
57     ObjectUnsafeCoercion(DefId),
58     ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
59
60     IntrinsicCast,
61 }
62
63 pub enum UnconstrainedNumeric {
64     UnconstrainedFloat,
65     UnconstrainedInt,
66     Neither,
67 }
68
69 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
70 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
71 /// afterwards to present additional details, particularly when it comes to lifetime-related
72 /// errors.
73 impl<'tcx> fmt::Display for TypeError<'tcx> {
74     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75         use self::TypeError::*;
76         fn report_maybe_different(
77             f: &mut fmt::Formatter<'_>,
78             expected: &str,
79             found: &str,
80         ) -> fmt::Result {
81             // A naive approach to making sure that we're not reporting silly errors such as:
82             // (expected closure, found closure).
83             if expected == found {
84                 write!(f, "expected {}, found a different {}", expected, found)
85             } else {
86                 write!(f, "expected {}, found {}", expected, found)
87             }
88         }
89
90         let br_string = |br: ty::BoundRegion| match br {
91             ty::BrNamed(_, name) => format!(" {}", name),
92             _ => String::new(),
93         };
94
95         match *self {
96             CyclicTy(_) => write!(f, "cyclic type of infinite size"),
97             Mismatch => write!(f, "types differ"),
98             UnsafetyMismatch(values) => {
99                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
100             }
101             AbiMismatch(values) => {
102                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
103             }
104             Mutability => write!(f, "types differ in mutability"),
105             TupleSize(values) => write!(
106                 f,
107                 "expected a tuple with {} element{}, \
108                            found one with {} element{}",
109                 values.expected,
110                 pluralize!(values.expected),
111                 values.found,
112                 pluralize!(values.found)
113             ),
114             FixedArraySize(values) => write!(
115                 f,
116                 "expected an array with a fixed size of {} element{}, \
117                            found one with {} element{}",
118                 values.expected,
119                 pluralize!(values.expected),
120                 values.found,
121                 pluralize!(values.found)
122             ),
123             ArgCount => write!(f, "incorrect number of function parameters"),
124             RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
125             RegionsInsufficientlyPolymorphic(br, _) => write!(
126                 f,
127                 "expected bound lifetime parameter{}, found concrete lifetime",
128                 br_string(br)
129             ),
130             RegionsOverlyPolymorphic(br, _) => write!(
131                 f,
132                 "expected concrete lifetime, found bound lifetime parameter{}",
133                 br_string(br)
134             ),
135             RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
136             Sorts(values) => ty::tls::with(|tcx| {
137                 report_maybe_different(
138                     f,
139                     &values.expected.sort_string(tcx),
140                     &values.found.sort_string(tcx),
141                 )
142             }),
143             Traits(values) => ty::tls::with(|tcx| {
144                 report_maybe_different(
145                     f,
146                     &format!("trait `{}`", tcx.def_path_str(values.expected)),
147                     &format!("trait `{}`", tcx.def_path_str(values.found)),
148                 )
149             }),
150             IntMismatch(ref values) => {
151                 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
152             }
153             FloatMismatch(ref values) => {
154                 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
155             }
156             VariadicMismatch(ref values) => write!(
157                 f,
158                 "expected {} fn, found {} function",
159                 if values.expected { "variadic" } else { "non-variadic" },
160                 if values.found { "variadic" } else { "non-variadic" }
161             ),
162             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
163                 write!(
164                     f,
165                     "expected {}, found {}",
166                     tcx.def_path_str(values.expected),
167                     tcx.def_path_str(values.found)
168                 )
169             }),
170             ProjectionBoundsLength(ref values) => write!(
171                 f,
172                 "expected {} associated type binding{}, found {}",
173                 values.expected,
174                 pluralize!(values.expected),
175                 values.found
176             ),
177             ExistentialMismatch(ref values) => report_maybe_different(
178                 f,
179                 &format!("trait `{}`", values.expected),
180                 &format!("trait `{}`", values.found),
181             ),
182             ConstMismatch(ref values) => {
183                 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
184             }
185             IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
186             ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
187         }
188     }
189 }
190
191 impl<'tcx> TypeError<'tcx> {
192     pub fn must_include_note(&self) -> bool {
193         use self::TypeError::*;
194         match self {
195             CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
196             | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) => false,
197
198             Mutability
199             | TupleSize(_)
200             | ArgCount
201             | RegionsDoesNotOutlive(..)
202             | RegionsInsufficientlyPolymorphic(..)
203             | RegionsOverlyPolymorphic(..)
204             | RegionsPlaceholderMismatch
205             | Traits(_)
206             | ProjectionMismatched(_)
207             | ProjectionBoundsLength(_)
208             | ExistentialMismatch(_)
209             | ConstMismatch(_)
210             | IntrinsicCast
211             | ObjectUnsafeCoercion(_) => true,
212         }
213     }
214 }
215
216 impl<'tcx> ty::TyS<'tcx> {
217     pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
218         match self.kind {
219             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
220                 format!("`{}`", self).into()
221             }
222             ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
223
224             ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
225             ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
226             ty::Array(t, n) => {
227                 let n = tcx.lift(&n).unwrap();
228                 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
229                     _ if t.is_simple_ty() => format!("array `{}`", self).into(),
230                     Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
231                     None => "array".into(),
232                 }
233             }
234             ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
235             ty::Slice(_) => "slice".into(),
236             ty::RawPtr(_) => "*-ptr".into(),
237             ty::Ref(_, ty, mutbl) => {
238                 let tymut = ty::TypeAndMut { ty, mutbl };
239                 let tymut_string = tymut.to_string();
240                 if tymut_string != "_"
241                     && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
242                 {
243                     format!("`&{}`", tymut_string).into()
244                 } else {
245                     // Unknown type name, it's long or has type arguments
246                     match mutbl {
247                         hir::Mutability::Mut => "mutable reference",
248                         _ => "reference",
249                     }
250                     .into()
251                 }
252             }
253             ty::FnDef(..) => "fn item".into(),
254             ty::FnPtr(_) => "fn pointer".into(),
255             ty::Dynamic(ref inner, ..) => {
256                 if let Some(principal) = inner.principal() {
257                     format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
258                 } else {
259                     "trait object".into()
260                 }
261             }
262             ty::Closure(..) => "closure".into(),
263             ty::Generator(..) => "generator".into(),
264             ty::GeneratorWitness(..) => "generator witness".into(),
265             ty::Tuple(..) => "tuple".into(),
266             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
267             ty::Infer(ty::IntVar(_)) => "integer".into(),
268             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
269             ty::Placeholder(..) => "placeholder type".into(),
270             ty::Bound(..) => "bound type".into(),
271             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
272             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
273             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
274             ty::Projection(_) => "associated type".into(),
275             ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
276             ty::Param(p) => format!("type parameter `{}`", p).into(),
277             ty::Opaque(..) => "opaque type".into(),
278             ty::Error => "type error".into(),
279         }
280     }
281
282     pub fn prefix_string(&self) -> Cow<'static, str> {
283         match self.kind {
284             ty::Infer(_)
285             | ty::Error
286             | ty::Bool
287             | ty::Char
288             | ty::Int(_)
289             | ty::Uint(_)
290             | ty::Float(_)
291             | ty::Str
292             | ty::Never => "type".into(),
293             ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
294             ty::Adt(def, _) => def.descr().into(),
295             ty::Foreign(_) => "extern type".into(),
296             ty::Array(..) => "array".into(),
297             ty::Slice(_) => "slice".into(),
298             ty::RawPtr(_) => "raw pointer".into(),
299             ty::Ref(.., mutbl) => match mutbl {
300                 hir::Mutability::Mut => "mutable reference",
301                 _ => "reference",
302             }
303             .into(),
304             ty::FnDef(..) => "fn item".into(),
305             ty::FnPtr(_) => "fn pointer".into(),
306             ty::Dynamic(..) => "trait object".into(),
307             ty::Closure(..) => "closure".into(),
308             ty::Generator(..) => "generator".into(),
309             ty::GeneratorWitness(..) => "generator witness".into(),
310             ty::Tuple(..) => "tuple".into(),
311             ty::Placeholder(..) => "higher-ranked type".into(),
312             ty::Bound(..) => "bound type variable".into(),
313             ty::Projection(_) => "associated type".into(),
314             ty::UnnormalizedProjection(_) => "associated type".into(),
315             ty::Param(_) => "type parameter".into(),
316             ty::Opaque(..) => "opaque type".into(),
317         }
318     }
319 }
320
321 impl<'tcx> TyCtxt<'tcx> {
322     pub fn note_and_explain_type_err(
323         self,
324         db: &mut DiagnosticBuilder<'_>,
325         err: &TypeError<'tcx>,
326         sp: Span,
327         body_owner_def_id: DefId,
328     ) {
329         use self::TypeError::*;
330
331         match err {
332             Sorts(values) => {
333                 let expected_str = values.expected.sort_string(self);
334                 let found_str = values.found.sort_string(self);
335                 if expected_str == found_str && expected_str == "closure" {
336                     db.note("no two closures, even if identical, have the same type");
337                     db.help("consider boxing your closure and/or using it as a trait object");
338                 }
339                 if expected_str == found_str && expected_str == "opaque type" {
340                     // Issue #63167
341                     db.note("distinct uses of `impl Trait` result in different opaque types");
342                     let e_str = values.expected.to_string();
343                     let f_str = values.found.to_string();
344                     if &e_str == &f_str && &e_str == "impl std::future::Future" {
345                         // FIXME: use non-string based check.
346                         db.help(
347                             "if both `Future`s have the same `Output` type, consider \
348                                  `.await`ing on both of them",
349                         );
350                     }
351                 }
352                 match (&values.expected.kind, &values.found.kind) {
353                     (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
354                         if let Ok(
355                             // Issue #53280
356                             snippet,
357                         ) = self.sess.source_map().span_to_snippet(sp)
358                         {
359                             if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
360                                 db.span_suggestion(
361                                     sp,
362                                     "use a float literal",
363                                     format!("{}.0", snippet),
364                                     Applicability::MachineApplicable,
365                                 );
366                             }
367                         }
368                     }
369                     (ty::Param(expected), ty::Param(found)) => {
370                         let generics = self.generics_of(body_owner_def_id);
371                         let e_span = self.def_span(generics.type_param(expected, self).def_id);
372                         if !sp.contains(e_span) {
373                             db.span_label(e_span, "expected type parameter");
374                         }
375                         let f_span = self.def_span(generics.type_param(found, self).def_id);
376                         if !sp.contains(f_span) {
377                             db.span_label(f_span, "found type parameter");
378                         }
379                         db.note(
380                             "a type parameter was expected, but a different one was found; \
381                                  you might be missing a type parameter or trait bound",
382                         );
383                         db.note(
384                             "for more information, visit \
385                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
386                                  #traits-as-parameters",
387                         );
388                     }
389                     (ty::Projection(_), ty::Projection(_)) => {
390                         db.note("an associated type was expected, but a different one was found");
391                     }
392                     (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
393                         db.note("you might be missing a type parameter or trait bound");
394                     }
395                     (ty::Param(p), _) | (_, ty::Param(p)) => {
396                         let generics = self.generics_of(body_owner_def_id);
397                         let p_span = self.def_span(generics.type_param(p, self).def_id);
398                         if !sp.contains(p_span) {
399                             db.span_label(p_span, "this type parameter");
400                         }
401                         db.help("type parameters must be constrained to match other types");
402                         if self.sess.teach(&db.get_code().unwrap()) {
403                             db.help(
404                                 "given a type parameter `T` and a method `foo`:
405 ```
406 trait Trait<T> { fn foo(&self) -> T; }
407 ```
408 the only ways to implement method `foo` are:
409 - constrain `T` with an explicit type:
410 ```
411 impl Trait<String> for X {
412     fn foo(&self) -> String { String::new() }
413 }
414 ```
415 - add a trait bound to `T` and call a method on that trait that returns `Self`:
416 ```
417 impl<T: std::default::Default> Trait<T> for X {
418     fn foo(&self) -> T { <T as std::default::Default>::default() }
419 }
420 ```
421 - change `foo` to return an argument of type `T`:
422 ```
423 impl<T> Trait<T> for X {
424     fn foo(&self, x: T) -> T { x }
425 }
426 ```",
427                             );
428                         }
429                         db.note(
430                             "for more information, visit \
431                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
432                                  #traits-as-parameters",
433                         );
434                     }
435                     (ty::Projection(_), _) => {
436                         db.note(&format!(
437                             "consider constraining the associated type `{}` to `{}` or calling a \
438                              method that returns `{}`",
439                             values.expected, values.found, values.expected,
440                         ));
441                         if self.sess.teach(&db.get_code().unwrap()) {
442                             db.help(
443                                 "given an associated type `T` and a method `foo`:
444 ```
445 trait Trait {
446     type T;
447     fn foo(&self) -> Self::T;
448 }
449 ```
450 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
451 ```
452 impl Trait for X {
453     type T = String;
454     fn foo(&self) -> Self::T { String::new() }
455 }
456 ```",
457                             );
458                         }
459                         db.note(
460                             "for more information, visit \
461                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
462                         );
463                     }
464                     (_, ty::Projection(_)) => {
465                         db.note(&format!(
466                             "consider constraining the associated type `{}` to `{}`",
467                             values.found, values.expected,
468                         ));
469                         db.note(
470                             "for more information, visit \
471                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
472                         );
473                     }
474                     _ => {}
475                 }
476                 debug!(
477                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
478                     values.expected, values.expected.kind, values.found, values.found.kind,
479                 );
480             }
481             CyclicTy(ty) => {
482                 // Watch out for various cases of cyclic types and try to explain.
483                 if ty.is_closure() || ty.is_generator() {
484                     db.note(
485                         "closures cannot capture themselves or take themselves as argument;\n\
486                              this error may be the result of a recent compiler bug-fix,\n\
487                              see https://github.com/rust-lang/rust/issues/46062 for more details",
488                     );
489                 }
490             }
491             _ => {}
492         }
493     }
494 }