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