]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/ty/error.rs
Auto merge of #29858 - fhahn:abort-if-path-has-spaces, r=brson
[rust.git] / src / librustc / middle / 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 middle::def_id::DefId;
12 use middle::subst;
13 use middle::infer::type_variable;
14 use middle::ty::{self, BoundRegion, Region, Ty};
15
16 use std::fmt;
17 use syntax::abi;
18 use syntax::ast::{self, Name};
19 use syntax::codemap::Span;
20
21 use rustc_front::hir;
22
23 #[derive(Clone, Copy, Debug)]
24 pub struct ExpectedFound<T> {
25     pub expected: T,
26     pub found: T
27 }
28
29 // Data structures used in type unification
30 #[derive(Clone, Debug)]
31 pub enum TypeError<'tcx> {
32     Mismatch,
33     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
34     AbiMismatch(ExpectedFound<abi::Abi>),
35     Mutability,
36     BoxMutability,
37     PtrMutability,
38     RefMutability,
39     VecMutability,
40     TupleSize(ExpectedFound<usize>),
41     FixedArraySize(ExpectedFound<usize>),
42     TyParamSize(ExpectedFound<usize>),
43     ArgCount,
44     RegionsDoesNotOutlive(Region, Region),
45     RegionsNotSame(Region, Region),
46     RegionsNoOverlap(Region, Region),
47     RegionsInsufficientlyPolymorphic(BoundRegion, Region),
48     RegionsOverlyPolymorphic(BoundRegion, Region),
49     Sorts(ExpectedFound<Ty<'tcx>>),
50     IntegerAsChar,
51     IntMismatch(ExpectedFound<ty::IntVarValue>),
52     FloatMismatch(ExpectedFound<ast::FloatTy>),
53     Traits(ExpectedFound<DefId>),
54     BuiltinBoundsMismatch(ExpectedFound<ty::BuiltinBounds>),
55     VariadicMismatch(ExpectedFound<bool>),
56     CyclicTy,
57     ConvergenceMismatch(ExpectedFound<bool>),
58     ProjectionNameMismatched(ExpectedFound<Name>),
59     ProjectionBoundsLength(ExpectedFound<usize>),
60     TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
61 }
62
63 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
64 pub enum UnconstrainedNumeric {
65     UnconstrainedFloat,
66     UnconstrainedInt,
67     Neither,
68 }
69
70 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
71 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
72 /// afterwards to present additional details, particularly when it comes to lifetime-related
73 /// errors.
74 impl<'tcx> fmt::Display for TypeError<'tcx> {
75     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76         use self::TypeError::*;
77         fn report_maybe_different(f: &mut fmt::Formatter,
78                                   expected: String, found: String) -> fmt::Result {
79             // A naive approach to making sure that we're not reporting silly errors such as:
80             // (expected closure, found closure).
81             if expected == found {
82                 write!(f, "expected {}, found a different {}", expected, found)
83             } else {
84                 write!(f, "expected {}, found {}", expected, found)
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, "values differ in mutability"),
102             BoxMutability => {
103                 write!(f, "boxed values differ in mutability")
104             }
105             VecMutability => write!(f, "vectors differ in mutability"),
106             PtrMutability => write!(f, "pointers differ in mutability"),
107             RefMutability => write!(f, "references differ in mutability"),
108             TyParamSize(values) => {
109                 write!(f, "expected a type with {} type params, \
110                            found one with {} type params",
111                        values.expected,
112                        values.found)
113             }
114             FixedArraySize(values) => {
115                 write!(f, "expected an array with a fixed size of {} elements, \
116                            found one with {} elements",
117                        values.expected,
118                        values.found)
119             }
120             TupleSize(values) => {
121                 write!(f, "expected a tuple with {} elements, \
122                            found one with {} elements",
123                        values.expected,
124                        values.found)
125             }
126             ArgCount => {
127                 write!(f, "incorrect number of function parameters")
128             }
129             RegionsDoesNotOutlive(..) => {
130                 write!(f, "lifetime mismatch")
131             }
132             RegionsNotSame(..) => {
133                 write!(f, "lifetimes are not the same")
134             }
135             RegionsNoOverlap(..) => {
136                 write!(f, "lifetimes do not intersect")
137             }
138             RegionsInsufficientlyPolymorphic(br, _) => {
139                 write!(f, "expected bound lifetime parameter {}, \
140                            found concrete lifetime", br)
141             }
142             RegionsOverlyPolymorphic(br, _) => {
143                 write!(f, "expected concrete lifetime, \
144                            found bound lifetime parameter {}", br)
145             }
146             Sorts(values) => ty::tls::with(|tcx| {
147                 report_maybe_different(f, values.expected.sort_string(tcx),
148                                        values.found.sort_string(tcx))
149             }),
150             Traits(values) => ty::tls::with(|tcx| {
151                 report_maybe_different(f,
152                                        format!("trait `{}`",
153                                                tcx.item_path_str(values.expected)),
154                                        format!("trait `{}`",
155                                                tcx.item_path_str(values.found)))
156             }),
157             BuiltinBoundsMismatch(values) => {
158                 if values.expected.is_empty() {
159                     write!(f, "expected no bounds, found `{}`",
160                            values.found)
161                 } else if values.found.is_empty() {
162                     write!(f, "expected bounds `{}`, found no bounds",
163                            values.expected)
164                 } else {
165                     write!(f, "expected bounds `{}`, found bounds `{}`",
166                            values.expected,
167                            values.found)
168                 }
169             }
170             IntegerAsChar => {
171                 write!(f, "expected an integral type, found `char`")
172             }
173             IntMismatch(ref values) => {
174                 write!(f, "expected `{:?}`, found `{:?}`",
175                        values.expected,
176                        values.found)
177             }
178             FloatMismatch(ref values) => {
179                 write!(f, "expected `{:?}`, found `{:?}`",
180                        values.expected,
181                        values.found)
182             }
183             VariadicMismatch(ref values) => {
184                 write!(f, "expected {} fn, found {} function",
185                        if values.expected { "variadic" } else { "non-variadic" },
186                        if values.found { "variadic" } else { "non-variadic" })
187             }
188             ConvergenceMismatch(ref values) => {
189                 write!(f, "expected {} fn, found {} function",
190                        if values.expected { "converging" } else { "diverging" },
191                        if values.found { "converging" } else { "diverging" })
192             }
193             ProjectionNameMismatched(ref values) => {
194                 write!(f, "expected {}, found {}",
195                        values.expected,
196                        values.found)
197             }
198             ProjectionBoundsLength(ref values) => {
199                 write!(f, "expected {} associated type bindings, found {}",
200                        values.expected,
201                        values.found)
202             },
203             TyParamDefaultMismatch(ref values) => {
204                 write!(f, "conflicting type parameter defaults `{}` and `{}`",
205                        values.expected.ty,
206                        values.found.ty)
207             }
208         }
209     }
210 }
211
212 impl<'tcx> ty::TyS<'tcx> {
213     fn sort_string(&self, cx: &ty::ctxt) -> String {
214         match self.sty {
215             ty::TyBool | ty::TyChar | ty::TyInt(_) |
216             ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr => self.to_string(),
217             ty::TyTuple(ref tys) if tys.is_empty() => self.to_string(),
218
219             ty::TyEnum(def, _) => format!("enum `{}`", cx.item_path_str(def.did)),
220             ty::TyBox(_) => "box".to_string(),
221             ty::TyArray(_, n) => format!("array of {} elements", n),
222             ty::TySlice(_) => "slice".to_string(),
223             ty::TyRawPtr(_) => "*-ptr".to_string(),
224             ty::TyRef(_, _) => "&-ptr".to_string(),
225             ty::TyBareFn(Some(_), _) => format!("fn item"),
226             ty::TyBareFn(None, _) => "fn pointer".to_string(),
227             ty::TyTrait(ref inner) => {
228                 format!("trait {}", cx.item_path_str(inner.principal_def_id()))
229             }
230             ty::TyStruct(def, _) => {
231                 format!("struct `{}`", cx.item_path_str(def.did))
232             }
233             ty::TyClosure(..) => "closure".to_string(),
234             ty::TyTuple(_) => "tuple".to_string(),
235             ty::TyInfer(ty::TyVar(_)) => "inferred type".to_string(),
236             ty::TyInfer(ty::IntVar(_)) => "integral variable".to_string(),
237             ty::TyInfer(ty::FloatVar(_)) => "floating-point variable".to_string(),
238             ty::TyInfer(ty::FreshTy(_)) => "skolemized type".to_string(),
239             ty::TyInfer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
240             ty::TyInfer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
241             ty::TyProjection(_) => "associated type".to_string(),
242             ty::TyParam(ref p) => {
243                 if p.space == subst::SelfSpace {
244                     "Self".to_string()
245                 } else {
246                     "type parameter".to_string()
247                 }
248             }
249             ty::TyError => "type error".to_string(),
250         }
251     }
252 }
253
254 impl<'tcx> ty::ctxt<'tcx> {
255     pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
256         use self::TypeError::*;
257
258         match err.clone() {
259             RegionsDoesNotOutlive(subregion, superregion) => {
260                 self.note_and_explain_region("", subregion, "...");
261                 self.note_and_explain_region("...does not necessarily outlive ",
262                                            superregion, "");
263             }
264             RegionsNotSame(region1, region2) => {
265                 self.note_and_explain_region("", region1, "...");
266                 self.note_and_explain_region("...is not the same lifetime as ",
267                                            region2, "");
268             }
269             RegionsNoOverlap(region1, region2) => {
270                 self.note_and_explain_region("", region1, "...");
271                 self.note_and_explain_region("...does not overlap ",
272                                            region2, "");
273             }
274             RegionsInsufficientlyPolymorphic(_, conc_region) => {
275                 self.note_and_explain_region("concrete lifetime that was found is ",
276                                            conc_region, "");
277             }
278             RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
279                 // don't bother to print out the message below for
280                 // inference variables, it's not very illuminating.
281             }
282             RegionsOverlyPolymorphic(_, conc_region) => {
283                 self.note_and_explain_region("expected concrete lifetime is ",
284                                            conc_region, "");
285             }
286             Sorts(values) => {
287                 let expected_str = values.expected.sort_string(self);
288                 let found_str = values.found.sort_string(self);
289                 if expected_str == found_str && expected_str == "closure" {
290                     self.sess.span_note(sp,
291                         "no two closures, even if identical, have the same type");
292                     self.sess.span_help(sp,
293                         "consider boxing your closure and/or using it as a trait object");
294                 }
295             },
296             TyParamDefaultMismatch(values) => {
297                 let expected = values.expected;
298                 let found = values.found;
299                 self.sess.span_note(sp,
300                                     &format!("conflicting type parameter defaults `{}` and `{}`",
301                                              expected.ty,
302                                              found.ty));
303
304                 match
305                     self.map.as_local_node_id(expected.def_id)
306                             .and_then(|node_id| self.map.opt_span(node_id))
307                 {
308                     Some(span) => {
309                         self.sess.span_note(span, "a default was defined here...");
310                     }
311                     None => {
312                         self.sess.note(
313                             &format!("a default is defined on `{}`",
314                                      self.item_path_str(expected.def_id)));
315                     }
316                 }
317
318                 self.sess.span_note(
319                     expected.origin_span,
320                     "...that was applied to an unconstrained type variable here");
321
322                 match
323                     self.map.as_local_node_id(found.def_id)
324                             .and_then(|node_id| self.map.opt_span(node_id))
325                 {
326                     Some(span) => {
327                         self.sess.span_note(span, "a second default was defined here...");
328                     }
329                     None => {
330                         self.sess.note(
331                             &format!("a second default is defined on `{}`",
332                                      self.item_path_str(found.def_id)));
333                     }
334                 }
335
336                 self.sess.span_note(
337                     found.origin_span,
338                     "...that also applies to the same type variable here");
339             }
340             _ => {}
341         }
342     }
343 }