]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
f58e5e4fb69f6a52f78a0b3248c6375b13924181
[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 errors::{Applicability, DiagnosticBuilder};
8 use syntax_pos::Span;
9
10 use crate::hir;
11
12 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
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)]
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 }
48
49 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
50 pub enum UnconstrainedNumeric {
51     UnconstrainedFloat,
52     UnconstrainedInt,
53     Neither,
54 }
55
56 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
57 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
58 /// afterwards to present additional details, particularly when it comes to lifetime-related
59 /// errors.
60 impl<'tcx> fmt::Display for TypeError<'tcx> {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         use self::TypeError::*;
63         fn report_maybe_different(f: &mut fmt::Formatter<'_>,
64                                   expected: &str, found: &str) -> fmt::Result {
65             // A naive approach to making sure that we're not reporting silly errors such as:
66             // (expected closure, found closure).
67             if expected == found {
68                 write!(f, "expected {}, found a different {}", expected, found)
69             } else {
70                 write!(f, "expected {}, found {}", expected, found)
71             }
72         }
73
74         match *self {
75             CyclicTy(_) => write!(f, "cyclic type of infinite size"),
76             Mismatch => write!(f, "types differ"),
77             UnsafetyMismatch(values) => {
78                 write!(f, "expected {} fn, found {} fn",
79                        values.expected,
80                        values.found)
81             }
82             AbiMismatch(values) => {
83                 write!(f, "expected {} fn, found {} fn",
84                        values.expected,
85                        values.found)
86             }
87             Mutability => write!(f, "types differ in mutability"),
88             FixedArraySize(values) => {
89                 write!(f, "expected an array with a fixed size of {} elements, \
90                            found one with {} elements",
91                        values.expected,
92                        values.found)
93             }
94             TupleSize(values) => {
95                 write!(f, "expected a tuple with {} elements, \
96                            found one with {} elements",
97                        values.expected,
98                        values.found)
99             }
100             ArgCount => {
101                 write!(f, "incorrect number of function parameters")
102             }
103             RegionsDoesNotOutlive(..) => {
104                 write!(f, "lifetime mismatch")
105             }
106             RegionsInsufficientlyPolymorphic(br, _) => {
107                 write!(f,
108                        "expected bound lifetime parameter{}{}, found concrete lifetime",
109                        if br.is_named() { " " } else { "" },
110                        br)
111             }
112             RegionsOverlyPolymorphic(br, _) => {
113                 write!(f,
114                        "expected concrete lifetime, found bound lifetime parameter{}{}",
115                        if br.is_named() { " " } else { "" },
116                        br)
117             }
118             RegionsPlaceholderMismatch => {
119                 write!(f, "one type is more general than the other")
120             }
121             Sorts(values) => ty::tls::with(|tcx| {
122                 report_maybe_different(f, &values.expected.sort_string(tcx),
123                                        &values.found.sort_string(tcx))
124             }),
125             Traits(values) => ty::tls::with(|tcx| {
126                 report_maybe_different(f,
127                                        &format!("trait `{}`",
128                                                 tcx.item_path_str(values.expected)),
129                                        &format!("trait `{}`",
130                                                 tcx.item_path_str(values.found)))
131             }),
132             IntMismatch(ref values) => {
133                 write!(f, "expected `{:?}`, found `{:?}`",
134                        values.expected,
135                        values.found)
136             }
137             FloatMismatch(ref values) => {
138                 write!(f, "expected `{:?}`, found `{:?}`",
139                        values.expected,
140                        values.found)
141             }
142             VariadicMismatch(ref values) => {
143                 write!(f, "expected {} fn, found {} function",
144                        if values.expected { "variadic" } else { "non-variadic" },
145                        if values.found { "variadic" } else { "non-variadic" })
146             }
147             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
148                 write!(f, "expected {}, found {}",
149                        tcx.item_path_str(values.expected),
150                        tcx.item_path_str(values.found))
151             }),
152             ProjectionBoundsLength(ref values) => {
153                 write!(f, "expected {} associated type bindings, found {}",
154                        values.expected,
155                        values.found)
156             },
157             ExistentialMismatch(ref values) => {
158                 report_maybe_different(f, &format!("trait `{}`", values.expected),
159                                        &format!("trait `{}`", values.found))
160             }
161         }
162     }
163 }
164
165 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
166     pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
167         match self.sty {
168             ty::Bool | ty::Char | ty::Int(_) |
169             ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
170             ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
171
172             ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)).into(),
173             ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)).into(),
174             ty::Array(_, n) => match n {
175                 ty::LazyConst::Evaluated(n) => match n.assert_usize(tcx) {
176                     Some(n) => format!("array of {} elements", n).into(),
177                     None => "array".into(),
178                 },
179                 ty::LazyConst::Unevaluated(..) => "array".into(),
180             }
181             ty::Slice(_) => "slice".into(),
182             ty::RawPtr(_) => "*-ptr".into(),
183             ty::Ref(region, ty, mutbl) => {
184                 let tymut = ty::TypeAndMut { ty, mutbl };
185                 let tymut_string = tymut.to_string();
186                 if tymut_string == "_" ||         //unknown type name,
187                    tymut_string.len() > 10 ||     //name longer than saying "reference",
188                    region.to_string() != ""       //... or a complex type
189                 {
190                     format!("{}reference", match mutbl {
191                         hir::Mutability::MutMutable => "mutable ",
192                         _ => ""
193                     }).into()
194                 } else {
195                     format!("&{}", tymut_string).into()
196                 }
197             }
198             ty::FnDef(..) => "fn item".into(),
199             ty::FnPtr(_) => "fn pointer".into(),
200             ty::Dynamic(ref inner, ..) => {
201                 if let Some(principal) = inner.principal() {
202                     format!("trait {}", tcx.item_path_str(principal.def_id())).into()
203                 } else {
204                     "trait".into()
205                 }
206             }
207             ty::Closure(..) => "closure".into(),
208             ty::Generator(..) => "generator".into(),
209             ty::GeneratorWitness(..) => "generator witness".into(),
210             ty::Tuple(..) => "tuple".into(),
211             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
212             ty::Infer(ty::IntVar(_)) => "integer".into(),
213             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
214             ty::Placeholder(..) => "placeholder type".into(),
215             ty::Bound(..) => "bound type".into(),
216             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
217             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
218             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
219             ty::Projection(_) => "associated type".into(),
220             ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
221             ty::Param(ref p) => {
222                 if p.is_self() {
223                     "Self".into()
224                 } else {
225                     "type parameter".into()
226                 }
227             }
228             ty::Opaque(..) => "opaque type".into(),
229             ty::Error => "type error".into(),
230         }
231     }
232 }
233
234 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
235     pub fn note_and_explain_type_err(self,
236                                      db: &mut DiagnosticBuilder<'_>,
237                                      err: &TypeError<'tcx>,
238                                      sp: Span) {
239         use self::TypeError::*;
240
241         match err.clone() {
242             Sorts(values) => {
243                 let expected_str = values.expected.sort_string(self);
244                 let found_str = values.found.sort_string(self);
245                 if expected_str == found_str && expected_str == "closure" {
246                     db.note("no two closures, even if identical, have the same type");
247                     db.help("consider boxing your closure and/or using it as a trait object");
248                 }
249                 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
250                        (&values.found.sty, &values.expected.sty) // Issue #53280
251                 {
252                     if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
253                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
254                             db.span_suggestion(
255                                 sp,
256                                 "use a float literal",
257                                 format!("{}.0", snippet),
258                                 Applicability::MachineApplicable
259                             );
260                         }
261                     }
262                 }
263             },
264             CyclicTy(ty) => {
265                 // Watch out for various cases of cyclic types and try to explain.
266                 if ty.is_closure() || ty.is_generator() {
267                     db.note("closures cannot capture themselves or take themselves as argument;\n\
268                              this error may be the result of a recent compiler bug-fix,\n\
269                              see https://github.com/rust-lang/rust/issues/46062 for more details");
270                 }
271             }
272             _ => {}
273         }
274     }
275 }