]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Nuke the entire ctfe from orbit, it's the only way to be sure
[rust.git] / src / librustc / ty / error.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hir::def_id::DefId;
12 use middle::const_val::ConstVal;
13 use ty::{self, BoundRegion, Region, Ty, TyCtxt};
14 use mir::interpret::{Value, PrimVal};
15
16 use std::fmt;
17 use syntax::abi;
18 use syntax::ast;
19 use errors::DiagnosticBuilder;
20 use syntax_pos::Span;
21
22 use hir;
23
24 #[derive(Clone, Copy, Debug)]
25 pub struct ExpectedFound<T> {
26     pub expected: T,
27     pub found: T,
28 }
29
30 // Data structures used in type unification
31 #[derive(Clone, Debug)]
32 pub enum TypeError<'tcx> {
33     Mismatch,
34     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
35     AbiMismatch(ExpectedFound<abi::Abi>),
36     Mutability,
37     TupleSize(ExpectedFound<usize>),
38     FixedArraySize(ExpectedFound<u64>),
39     ArgCount,
40
41     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
42     RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
43     RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
44
45     Sorts(ExpectedFound<Ty<'tcx>>),
46     IntMismatch(ExpectedFound<ty::IntVarValue>),
47     FloatMismatch(ExpectedFound<ast::FloatTy>),
48     Traits(ExpectedFound<DefId>),
49     VariadicMismatch(ExpectedFound<bool>),
50
51     /// Instantiating a type variable with the given type would have
52     /// created a cycle (because it appears somewhere within that
53     /// type).
54     CyclicTy(Ty<'tcx>),
55     ProjectionMismatched(ExpectedFound<DefId>),
56     ProjectionBoundsLength(ExpectedFound<usize>),
57     ExistentialMismatch(ExpectedFound<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>),
58
59     OldStyleLUB(Box<TypeError<'tcx>>),
60 }
61
62 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
63 pub enum UnconstrainedNumeric {
64     UnconstrainedFloat,
65     UnconstrainedInt,
66     Neither,
67 }
68
69 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
70 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
71 /// afterwards to present additional details, particularly when it comes to lifetime-related
72 /// errors.
73 impl<'tcx> fmt::Display for TypeError<'tcx> {
74     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75         use self::TypeError::*;
76         fn report_maybe_different(f: &mut fmt::Formatter,
77                                   expected: String, found: String) -> fmt::Result {
78             // A naive approach to making sure that we're not reporting silly errors such as:
79             // (expected closure, found closure).
80             if expected == found {
81                 write!(f, "expected {}, found a different {}", expected, found)
82             } else {
83                 write!(f, "expected {}, found {}", expected, found)
84             }
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",
92                        values.expected,
93                        values.found)
94             }
95             AbiMismatch(values) => {
96                 write!(f, "expected {} fn, found {} fn",
97                        values.expected,
98                        values.found)
99             }
100             Mutability => write!(f, "types differ in mutability"),
101             FixedArraySize(values) => {
102                 write!(f, "expected an array with a fixed size of {} elements, \
103                            found one with {} elements",
104                        values.expected,
105                        values.found)
106             }
107             TupleSize(values) => {
108                 write!(f, "expected a tuple with {} elements, \
109                            found one with {} elements",
110                        values.expected,
111                        values.found)
112             }
113             ArgCount => {
114                 write!(f, "incorrect number of function parameters")
115             }
116             RegionsDoesNotOutlive(..) => {
117                 write!(f, "lifetime mismatch")
118             }
119             RegionsInsufficientlyPolymorphic(br, _) => {
120                 write!(f,
121                        "expected bound lifetime parameter{}{}, found concrete lifetime",
122                        if br.is_named() { " " } else { "" },
123                        br)
124             }
125             RegionsOverlyPolymorphic(br, _) => {
126                 write!(f,
127                        "expected concrete lifetime, found bound lifetime parameter{}{}",
128                        if br.is_named() { " " } else { "" },
129                        br)
130             }
131             Sorts(values) => ty::tls::with(|tcx| {
132                 report_maybe_different(f, values.expected.sort_string(tcx),
133                                        values.found.sort_string(tcx))
134             }),
135             Traits(values) => ty::tls::with(|tcx| {
136                 report_maybe_different(f,
137                                        format!("trait `{}`",
138                                                tcx.item_path_str(values.expected)),
139                                        format!("trait `{}`",
140                                                tcx.item_path_str(values.found)))
141             }),
142             IntMismatch(ref values) => {
143                 write!(f, "expected `{:?}`, found `{:?}`",
144                        values.expected,
145                        values.found)
146             }
147             FloatMismatch(ref values) => {
148                 write!(f, "expected `{:?}`, found `{:?}`",
149                        values.expected,
150                        values.found)
151             }
152             VariadicMismatch(ref values) => {
153                 write!(f, "expected {} fn, found {} function",
154                        if values.expected { "variadic" } else { "non-variadic" },
155                        if values.found { "variadic" } else { "non-variadic" })
156             }
157             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
158                 write!(f, "expected {}, found {}",
159                        tcx.item_path_str(values.expected),
160                        tcx.item_path_str(values.found))
161             }),
162             ProjectionBoundsLength(ref values) => {
163                 write!(f, "expected {} associated type bindings, found {}",
164                        values.expected,
165                        values.found)
166             },
167             ExistentialMismatch(ref values) => {
168                 report_maybe_different(f, format!("trait `{}`", values.expected),
169                                        format!("trait `{}`", values.found))
170             }
171             OldStyleLUB(ref err) => {
172                 write!(f, "{}", err)
173             }
174         }
175     }
176 }
177
178 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
179     pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
180         match self.sty {
181             ty::TyBool | ty::TyChar | ty::TyInt(_) |
182             ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr | ty::TyNever => self.to_string(),
183             ty::TyTuple(ref tys, _) if tys.is_empty() => self.to_string(),
184
185             ty::TyAdt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
186             ty::TyForeign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)),
187             ty::TyArray(_, n) => {
188                 match n.val {
189                     ConstVal::Value(Value::ByVal(PrimVal::Bytes(n))) =>
190                         format!("array of {} elements", n),
191                     _ => "array".to_string(),
192                 }
193             }
194             ty::TySlice(_) => "slice".to_string(),
195             ty::TyRawPtr(_) => "*-ptr".to_string(),
196             ty::TyRef(region, tymut) => {
197                 let tymut_string = tymut.to_string();
198                 if tymut_string == "_" ||         //unknown type name,
199                    tymut_string.len() > 10 ||     //name longer than saying "reference",
200                    region.to_string() != ""       //... or a complex type
201                 {
202                     match tymut {
203                         ty::TypeAndMut{mutbl, ..} => {
204                             format!("{}reference", match mutbl {
205                                 hir::Mutability::MutMutable => "mutable ",
206                                 _ => ""
207                             })
208                         }
209                     }
210                 } else {
211                     format!("&{}", tymut_string)
212                 }
213             }
214             ty::TyFnDef(..) => format!("fn item"),
215             ty::TyFnPtr(_) => "fn pointer".to_string(),
216             ty::TyDynamic(ref inner, ..) => {
217                 inner.principal().map_or_else(|| "trait".to_string(),
218                     |p| format!("trait {}", tcx.item_path_str(p.def_id())))
219             }
220             ty::TyClosure(..) => "closure".to_string(),
221             ty::TyGenerator(..) => "generator".to_string(),
222             ty::TyGeneratorWitness(..) => "generator witness".to_string(),
223             ty::TyTuple(..) => "tuple".to_string(),
224             ty::TyInfer(ty::TyVar(_)) => "inferred type".to_string(),
225             ty::TyInfer(ty::IntVar(_)) => "integral variable".to_string(),
226             ty::TyInfer(ty::FloatVar(_)) => "floating-point variable".to_string(),
227             ty::TyInfer(ty::FreshTy(_)) => "skolemized type".to_string(),
228             ty::TyInfer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
229             ty::TyInfer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
230             ty::TyProjection(_) => "associated type".to_string(),
231             ty::TyParam(ref p) => {
232                 if p.is_self() {
233                     "Self".to_string()
234                 } else {
235                     "type parameter".to_string()
236                 }
237             }
238             ty::TyAnon(..) => "anonymized type".to_string(),
239             ty::TyError => "type error".to_string(),
240         }
241     }
242 }
243
244 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
245     pub fn note_and_explain_type_err(self,
246                                      db: &mut DiagnosticBuilder,
247                                      err: &TypeError<'tcx>,
248                                      sp: Span) {
249         use self::TypeError::*;
250
251         match err.clone() {
252             Sorts(values) => {
253                 let expected_str = values.expected.sort_string(self);
254                 let found_str = values.found.sort_string(self);
255                 if expected_str == found_str && expected_str == "closure" {
256                     db.note("no two closures, even if identical, have the same type");
257                     db.help("consider boxing your closure and/or using it as a trait object");
258                 }
259             },
260             OldStyleLUB(err) => {
261                 db.note("this was previously accepted by the compiler but has been phased out");
262                 db.note("for more information, see https://github.com/rust-lang/rust/issues/45852");
263
264                 self.note_and_explain_type_err(db, &err, sp);
265             }
266             CyclicTy(ty) => {
267                 // Watch out for various cases of cyclic types and try to explain.
268                 if ty.is_closure() || ty.is_generator() {
269                     db.note("closures cannot capture themselves or take themselves as argument;\n\
270                              this error may be the result of a recent compiler bug-fix,\n\
271                              see https://github.com/rust-lang/rust/issues/46062 for more details");
272                 }
273             }
274             _ => {}
275         }
276     }
277 }