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