]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
review comments: tweak prefix strings
[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::pluralize;
8 use errors::{Applicability, DiagnosticBuilder};
9 use syntax_pos::Span;
10
11 use crate::hir;
12
13 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
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, TypeFoldable)]
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     ObjectUnsafeCoercion(DefId),
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                        pluralize!(values.expected),
104                        values.found,
105                        pluralize!(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                        pluralize!(values.expected),
112                        values.found,
113                        pluralize!(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                        pluralize!(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             ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
182         }
183     }
184 }
185
186 impl<'tcx> ty::TyS<'tcx> {
187     pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
188         match self.kind {
189             ty::Bool | ty::Char | ty::Int(_) |
190             ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
191             ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
192
193             ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
194             ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
195             ty::Array(_, n) => {
196                 let n = tcx.lift(&n).unwrap();
197                 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
198                     Some(n) => {
199                         format!("array of {} element{}", n, pluralize!(n)).into()
200                     }
201                     None => "array".into(),
202                 }
203             }
204             ty::Slice(_) => "slice".into(),
205             ty::RawPtr(_) => "*-ptr".into(),
206             ty::Ref(region, ty, mutbl) => {
207                 let tymut = ty::TypeAndMut { ty, mutbl };
208                 let tymut_string = tymut.to_string();
209                 if tymut_string == "_" ||         //unknown type name,
210                    tymut_string.len() > 10 ||     //name longer than saying "reference",
211                    region.to_string() != "'_"     //... or a complex type
212                 {
213                     format!("{}reference", match mutbl {
214                         hir::Mutability::Mutable => "mutable ",
215                         _ => ""
216                     }).into()
217                 } else {
218                     format!("&{}", tymut_string).into()
219                 }
220             }
221             ty::FnDef(..) => "fn item".into(),
222             ty::FnPtr(_) => "fn pointer".into(),
223             ty::Dynamic(ref inner, ..) => {
224                 if let Some(principal) = inner.principal() {
225                     format!("trait {}", tcx.def_path_str(principal.def_id())).into()
226                 } else {
227                     "trait".into()
228                 }
229             }
230             ty::Closure(..) => "closure".into(),
231             ty::Generator(..) => "generator".into(),
232             ty::GeneratorWitness(..) => "generator witness".into(),
233             ty::Tuple(..) => "tuple".into(),
234             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
235             ty::Infer(ty::IntVar(_)) => "integer".into(),
236             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
237             ty::Placeholder(..) => "placeholder type".into(),
238             ty::Bound(..) => "bound type".into(),
239             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
240             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
241             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
242             ty::Projection(_) => "associated type".into(),
243             ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
244             ty::Param(p) => format!("type parameter `{}`", p).into(),
245             ty::Opaque(..) => "opaque type".into(),
246             ty::Error => "type error".into(),
247         }
248     }
249
250     pub fn prefix_string(&self) -> Cow<'static, str> {
251         debug!("prefix_string {:?} {} {:?}", self, self, self.kind);
252         match self.kind {
253             ty::Infer(_) | ty::Error | ty::Bool | ty::Char | ty::Int(_) |
254             ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => "type".into(),
255             ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
256             ty::Adt(def, _) => def.descr().into(),
257             ty::Foreign(_) => "extern type".into(),
258             ty::Array(..) => "array".into(),
259             ty::Slice(_) => "slice".into(),
260             ty::RawPtr(_) => "raw pointer".into(),
261             ty::Ref(.., mutbl) => match mutbl {
262                 hir::Mutability::Mutable => "mutable reference",
263                 _ => "reference"
264             }.into(),
265             ty::FnDef(..) => "fn item".into(),
266             ty::FnPtr(_) => "fn pointer".into(),
267             ty::Dynamic(..) => "trait object".into(),
268             ty::Closure(..) => "closure".into(),
269             ty::Generator(..) => "generator".into(),
270             ty::GeneratorWitness(..) => "generator witness".into(),
271             ty::Tuple(..) => "tuple".into(),
272             ty::Placeholder(..) => "higher-ranked type".into(),
273             ty::Bound(..) => "bound type variable".into(),
274             ty::Projection(_) => "associated type".into(),
275             ty::UnnormalizedProjection(_) => "associated type".into(),
276             ty::Param(_) => "type parameter".into(),
277             ty::Opaque(..) => "opaque type".into(),
278         }
279     }
280 }
281
282 impl<'tcx> TyCtxt<'tcx> {
283     pub fn note_and_explain_type_err(
284         self,
285         db: &mut DiagnosticBuilder<'_>,
286         err: &TypeError<'tcx>,
287         sp: Span,
288         body_owner_def_id: DefId,
289     ) {
290         use self::TypeError::*;
291
292         match err {
293             Sorts(values) => {
294                 let expected_str = values.expected.sort_string(self);
295                 let found_str = values.found.sort_string(self);
296                 if expected_str == found_str && expected_str == "closure" {
297                     db.note("no two closures, even if identical, have the same type");
298                     db.help("consider boxing your closure and/or using it as a trait object");
299                 }
300                 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
301                     db.note("distinct uses of `impl Trait` result in different opaque types");
302                     let e_str = values.expected.to_string();
303                     let f_str = values.found.to_string();
304                     if &e_str == &f_str && &e_str == "impl std::future::Future" {
305                         // FIXME: use non-string based check.
306                         db.help("if both `Future`s have the same `Output` type, consider \
307                                  `.await`ing on both of them");
308                     }
309                 }
310                 match (&values.expected.kind, &values.found.kind) {
311                     (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
312                         snippet,
313                     ) = self.sess.source_map().span_to_snippet(sp) {
314                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
315                             db.span_suggestion(
316                                 sp,
317                                 "use a float literal",
318                                 format!("{}.0", snippet),
319                                 Applicability::MachineApplicable
320                             );
321                         }
322                     },
323                     (ty::Param(expected), ty::Param(found)) => {
324                         let generics = self.generics_of(body_owner_def_id);
325                         let e_span = self.def_span(generics.type_param(expected, self).def_id);
326                         if !sp.contains(e_span) {
327                             db.span_label(e_span, "expected type parameter");
328                         }
329                         let f_span = self.def_span(generics.type_param(found, self).def_id);
330                         if !sp.contains(f_span) {
331                             db.span_label(f_span, "found type parameter");
332                         }
333                         db.note("a type parameter was expected, but a different one was found; \
334                                  you might be missing a type parameter or trait bound");
335                         db.note("for more information, visit \
336                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
337                                  #traits-as-parameters");
338                     }
339                     (ty::Projection(_), ty::Projection(_)) => {
340                         db.note("an associated type was expected, but a different one was found");
341                     }
342                     (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
343                         db.note("you might be missing a type parameter or trait bound");
344                     }
345                     (ty::Param(p), _) | (_, ty::Param(p)) => {
346                         let generics = self.generics_of(body_owner_def_id);
347                         let p_span = self.def_span(generics.type_param(p, self).def_id);
348                         if !sp.contains(p_span) {
349                             db.span_label(p_span, "this type parameter");
350                         }
351                         db.help("type parameters must be constrained to match other types");
352                         if self.sess.teach(&db.get_code().unwrap()) {
353                             db.help("given a type parameter `T` and a method `foo`:
354 ```
355 trait Trait<T> { fn foo(&self) -> T; }
356 ```
357 the only ways to implement method `foo` are:
358 - constrain `T` with an explicit type:
359 ```
360 impl Trait<String> for X {
361     fn foo(&self) -> String { String::new() }
362 }
363 ```
364 - add a trait bound to `T` and call a method on that trait that returns `Self`:
365 ```
366 impl<T: std::default::Default> Trait<T> for X {
367     fn foo(&self) -> T { <T as std::default::Default>::default() }
368 }
369 ```
370 - change `foo` to return an argument of type `T`:
371 ```
372 impl<T> Trait<T> for X {
373     fn foo(&self, x: T) -> T { x }
374 }
375 ```");
376                         }
377                         db.note("for more information, visit \
378                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
379                                  #traits-as-parameters");
380                     }
381                     (ty::Projection(_), _) => {
382                         db.note(&format!(
383                             "consider constraining the associated type `{}` to `{}` or calling a \
384                              method that returns `{}`",
385                             values.expected,
386                             values.found,
387                             values.expected,
388                         ));
389                         if self.sess.teach(&db.get_code().unwrap()) {
390                             db.help("given an associated type `T` and a method `foo`:
391 ```
392 trait Trait {
393     type T;
394     fn foo(&self) -> Self::T;
395 }
396 ```
397 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
398 ```
399 impl Trait for X {
400     type T = String;
401     fn foo(&self) -> Self::T { String::new() }
402 }
403 ```");
404                         }
405                         db.note("for more information, visit \
406                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
407                     }
408                     (_, ty::Projection(_)) => {
409                         db.note(&format!(
410                             "consider constraining the associated type `{}` to `{}`",
411                             values.found,
412                             values.expected,
413                         ));
414                         db.note("for more information, visit \
415                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
416                     }
417                     _ => {}
418                 }
419                 debug!(
420                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
421                     values.expected,
422                     values.expected.kind,
423                     values.found,
424                     values.found.kind,
425                 );
426             },
427             CyclicTy(ty) => {
428                 // Watch out for various cases of cyclic types and try to explain.
429                 if ty.is_closure() || ty.is_generator() {
430                     db.note("closures cannot capture themselves or take themselves as argument;\n\
431                              this error may be the result of a recent compiler bug-fix,\n\
432                              see https://github.com/rust-lang/rust/issues/46062 for more details");
433                 }
434             }
435             _ => {}
436         }
437     }
438 }