]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Rollup merge of #66253 - ohadravid:improve-errors-after-re-rebalance-coherence, r...
[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)]
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     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
251 impl<'tcx> TyCtxt<'tcx> {
252     pub fn note_and_explain_type_err(
253         self,
254         db: &mut DiagnosticBuilder<'_>,
255         err: &TypeError<'tcx>,
256         sp: Span,
257         body_owner_def_id: DefId,
258     ) {
259         use self::TypeError::*;
260
261         match err {
262             Sorts(values) => {
263                 let expected_str = values.expected.sort_string(self);
264                 let found_str = values.found.sort_string(self);
265                 if expected_str == found_str && expected_str == "closure" {
266                     db.note("no two closures, even if identical, have the same type");
267                     db.help("consider boxing your closure and/or using it as a trait object");
268                 }
269                 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
270                     db.note("distinct uses of `impl Trait` result in different opaque types");
271                     let e_str = values.expected.to_string();
272                     let f_str = values.found.to_string();
273                     if &e_str == &f_str && &e_str == "impl std::future::Future" {
274                         // FIXME: use non-string based check.
275                         db.help("if both `Future`s have the same `Output` type, consider \
276                                  `.await`ing on both of them");
277                     }
278                 }
279                 match (&values.expected.kind, &values.found.kind) {
280                     (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
281                         snippet,
282                     ) = self.sess.source_map().span_to_snippet(sp) {
283                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
284                             db.span_suggestion(
285                                 sp,
286                                 "use a float literal",
287                                 format!("{}.0", snippet),
288                                 Applicability::MachineApplicable
289                             );
290                         }
291                     },
292                     (ty::Param(expected), ty::Param(found)) => {
293                         let generics = self.generics_of(body_owner_def_id);
294                         let e_span = self.def_span(generics.type_param(expected, self).def_id);
295                         if !sp.contains(e_span) {
296                             db.span_label(e_span, "expected type parameter");
297                         }
298                         let f_span = self.def_span(generics.type_param(found, self).def_id);
299                         if !sp.contains(f_span) {
300                             db.span_label(f_span, "found type parameter");
301                         }
302                         db.note("a type parameter was expected, but a different one was found; \
303                                  you might be missing a type parameter or trait bound");
304                         db.note("for more information, visit \
305                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
306                                  #traits-as-parameters");
307                     }
308                     (ty::Projection(_), ty::Projection(_)) => {
309                         db.note("an associated type was expected, but a different one was found");
310                     }
311                     (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
312                         db.note("you might be missing a type parameter or trait bound");
313                     }
314                     (ty::Param(p), _) | (_, ty::Param(p)) => {
315                         let generics = self.generics_of(body_owner_def_id);
316                         let p_span = self.def_span(generics.type_param(p, self).def_id);
317                         if !sp.contains(p_span) {
318                             db.span_label(p_span, "this type parameter");
319                         }
320                         db.help("type parameters must be constrained to match other types");
321                         if self.sess.teach(&db.get_code().unwrap()) {
322                             db.help("given a type parameter `T` and a method `foo`:
323 ```
324 trait Trait<T> { fn foo(&self) -> T; }
325 ```
326 the only ways to implement method `foo` are:
327 - constrain `T` with an explicit type:
328 ```
329 impl Trait<String> for X {
330     fn foo(&self) -> String { String::new() }
331 }
332 ```
333 - add a trait bound to `T` and call a method on that trait that returns `Self`:
334 ```
335 impl<T: std::default::Default> Trait<T> for X {
336     fn foo(&self) -> T { <T as std::default::Default>::default() }
337 }
338 ```
339 - change `foo` to return an argument of type `T`:
340 ```
341 impl<T> Trait<T> for X {
342     fn foo(&self, x: T) -> T { x }
343 }
344 ```");
345                         }
346                         db.note("for more information, visit \
347                                  https://doc.rust-lang.org/book/ch10-02-traits.html\
348                                  #traits-as-parameters");
349                     }
350                     (ty::Projection(_), _) => {
351                         db.note(&format!(
352                             "consider constraining the associated type `{}` to `{}` or calling a \
353                              method that returns `{}`",
354                             values.expected,
355                             values.found,
356                             values.expected,
357                         ));
358                         if self.sess.teach(&db.get_code().unwrap()) {
359                             db.help("given an associated type `T` and a method `foo`:
360 ```
361 trait Trait {
362     type T;
363     fn foo(&self) -> Self::T;
364 }
365 ```
366 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
367 ```
368 impl Trait for X {
369     type T = String;
370     fn foo(&self) -> Self::T { String::new() }
371 }
372 ```");
373                         }
374                         db.note("for more information, visit \
375                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
376                     }
377                     (_, ty::Projection(_)) => {
378                         db.note(&format!(
379                             "consider constraining the associated type `{}` to `{}`",
380                             values.found,
381                             values.expected,
382                         ));
383                         db.note("for more information, visit \
384                                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
385                     }
386                     _ => {}
387                 }
388                 debug!(
389                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
390                     values.expected,
391                     values.expected.kind,
392                     values.found,
393                     values.found.kind,
394                 );
395             },
396             CyclicTy(ty) => {
397                 // Watch out for various cases of cyclic types and try to explain.
398                 if ty.is_closure() || ty.is_generator() {
399                     db.note("closures cannot capture themselves or take themselves as argument;\n\
400                              this error may be the result of a recent compiler bug-fix,\n\
401                              see https://github.com/rust-lang/rust/issues/46062 for more details");
402                 }
403             }
404             _ => {}
405         }
406     }
407 }