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