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