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