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