]> git.proxmox.com Git - rustc.git/blob - src/librustc/ty/error.rs
New upstream version 1.14.0+dfsg1
[rustc.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 infer::type_variable;
13 use ty::{self, BoundRegion, Region, Ty, TyCtxt};
14
15 use std::fmt;
16 use syntax::abi;
17 use syntax::ast::{self, Name};
18 use errors::DiagnosticBuilder;
19 use syntax_pos::Span;
20
21 use 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 TupleSize(ExpectedFound<usize>),
37 FixedArraySize(ExpectedFound<usize>),
38 ArgCount,
39 RegionsDoesNotOutlive(&'tcx Region, &'tcx Region),
40 RegionsNotSame(&'tcx Region, &'tcx Region),
41 RegionsNoOverlap(&'tcx Region, &'tcx Region),
42 RegionsInsufficientlyPolymorphic(BoundRegion, &'tcx Region),
43 RegionsOverlyPolymorphic(BoundRegion, &'tcx Region),
44 Sorts(ExpectedFound<Ty<'tcx>>),
45 IntMismatch(ExpectedFound<ty::IntVarValue>),
46 FloatMismatch(ExpectedFound<ast::FloatTy>),
47 Traits(ExpectedFound<DefId>),
48 BuiltinBoundsMismatch(ExpectedFound<ty::BuiltinBounds>),
49 VariadicMismatch(ExpectedFound<bool>),
50 CyclicTy,
51 ProjectionNameMismatched(ExpectedFound<Name>),
52 ProjectionBoundsLength(ExpectedFound<usize>),
53 TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
54 }
55
56 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
57 pub enum UnconstrainedNumeric {
58 UnconstrainedFloat,
59 UnconstrainedInt,
60 Neither,
61 }
62
63 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
64 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
65 /// afterwards to present additional details, particularly when it comes to lifetime-related
66 /// errors.
67 impl<'tcx> fmt::Display for TypeError<'tcx> {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 use self::TypeError::*;
70 fn report_maybe_different(f: &mut fmt::Formatter,
71 expected: String, found: String) -> 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 match *self {
82 CyclicTy => write!(f, "cyclic type of infinite size"),
83 Mismatch => write!(f, "types differ"),
84 UnsafetyMismatch(values) => {
85 write!(f, "expected {} fn, found {} fn",
86 values.expected,
87 values.found)
88 }
89 AbiMismatch(values) => {
90 write!(f, "expected {} fn, found {} fn",
91 values.expected,
92 values.found)
93 }
94 Mutability => write!(f, "types differ in mutability"),
95 FixedArraySize(values) => {
96 write!(f, "expected an array with a fixed size of {} elements, \
97 found one with {} elements",
98 values.expected,
99 values.found)
100 }
101 TupleSize(values) => {
102 write!(f, "expected a tuple with {} elements, \
103 found one with {} elements",
104 values.expected,
105 values.found)
106 }
107 ArgCount => {
108 write!(f, "incorrect number of function parameters")
109 }
110 RegionsDoesNotOutlive(..) => {
111 write!(f, "lifetime mismatch")
112 }
113 RegionsNotSame(..) => {
114 write!(f, "lifetimes are not the same")
115 }
116 RegionsNoOverlap(..) => {
117 write!(f, "lifetimes do not intersect")
118 }
119 RegionsInsufficientlyPolymorphic(br, _) => {
120 write!(f, "expected bound lifetime parameter {}, \
121 found concrete lifetime", br)
122 }
123 RegionsOverlyPolymorphic(br, _) => {
124 write!(f, "expected concrete lifetime, \
125 found bound lifetime parameter {}", br)
126 }
127 Sorts(values) => ty::tls::with(|tcx| {
128 report_maybe_different(f, values.expected.sort_string(tcx),
129 values.found.sort_string(tcx))
130 }),
131 Traits(values) => ty::tls::with(|tcx| {
132 report_maybe_different(f,
133 format!("trait `{}`",
134 tcx.item_path_str(values.expected)),
135 format!("trait `{}`",
136 tcx.item_path_str(values.found)))
137 }),
138 BuiltinBoundsMismatch(values) => {
139 if values.expected.is_empty() {
140 write!(f, "expected no bounds, found `{}`",
141 values.found)
142 } else if values.found.is_empty() {
143 write!(f, "expected bounds `{}`, found no bounds",
144 values.expected)
145 } else {
146 write!(f, "expected bounds `{}`, found bounds `{}`",
147 values.expected,
148 values.found)
149 }
150 }
151 IntMismatch(ref values) => {
152 write!(f, "expected `{:?}`, found `{:?}`",
153 values.expected,
154 values.found)
155 }
156 FloatMismatch(ref values) => {
157 write!(f, "expected `{:?}`, found `{:?}`",
158 values.expected,
159 values.found)
160 }
161 VariadicMismatch(ref values) => {
162 write!(f, "expected {} fn, found {} function",
163 if values.expected { "variadic" } else { "non-variadic" },
164 if values.found { "variadic" } else { "non-variadic" })
165 }
166 ProjectionNameMismatched(ref values) => {
167 write!(f, "expected {}, found {}",
168 values.expected,
169 values.found)
170 }
171 ProjectionBoundsLength(ref values) => {
172 write!(f, "expected {} associated type bindings, found {}",
173 values.expected,
174 values.found)
175 },
176 TyParamDefaultMismatch(ref values) => {
177 write!(f, "conflicting type parameter defaults `{}` and `{}`",
178 values.expected.ty,
179 values.found.ty)
180 }
181 }
182 }
183 }
184
185 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
186 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
187 match self.sty {
188 ty::TyBool | ty::TyChar | ty::TyInt(_) |
189 ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr | ty::TyNever => self.to_string(),
190 ty::TyTuple(ref tys) if tys.is_empty() => self.to_string(),
191
192 ty::TyAdt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
193 ty::TyBox(_) => "box".to_string(),
194 ty::TyArray(_, n) => format!("array of {} elements", n),
195 ty::TySlice(_) => "slice".to_string(),
196 ty::TyRawPtr(_) => "*-ptr".to_string(),
197 ty::TyRef(region, tymut) => {
198 let tymut_string = tymut.to_string();
199 if tymut_string == "_" || //unknown type name,
200 tymut_string.len() > 10 || //name longer than saying "reference",
201 region.to_string() != "" //... or a complex type
202 {
203 match tymut {
204 ty::TypeAndMut{mutbl, ..} => {
205 format!("{}reference", match mutbl {
206 hir::Mutability::MutMutable => "mutable ",
207 _ => ""
208 })
209 }
210 }
211 } else {
212 format!("&{}", tymut_string)
213 }
214 }
215 ty::TyFnDef(..) => format!("fn item"),
216 ty::TyFnPtr(_) => "fn pointer".to_string(),
217 ty::TyTrait(ref inner) => {
218 format!("trait {}", tcx.item_path_str(inner.principal.def_id()))
219 }
220 ty::TyClosure(..) => "closure".to_string(),
221 ty::TyTuple(_) => "tuple".to_string(),
222 ty::TyInfer(ty::TyVar(_)) => "inferred type".to_string(),
223 ty::TyInfer(ty::IntVar(_)) => "integral variable".to_string(),
224 ty::TyInfer(ty::FloatVar(_)) => "floating-point variable".to_string(),
225 ty::TyInfer(ty::FreshTy(_)) => "skolemized type".to_string(),
226 ty::TyInfer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
227 ty::TyInfer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
228 ty::TyProjection(_) => "associated type".to_string(),
229 ty::TyParam(ref p) => {
230 if p.is_self() {
231 "Self".to_string()
232 } else {
233 "type parameter".to_string()
234 }
235 }
236 ty::TyAnon(..) => "anonymized type".to_string(),
237 ty::TyError => "type error".to_string(),
238 }
239 }
240 }
241
242 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
243 pub fn note_and_explain_type_err(self,
244 db: &mut DiagnosticBuilder,
245 err: &TypeError<'tcx>,
246 sp: Span) {
247 use self::TypeError::*;
248
249 match err.clone() {
250 RegionsDoesNotOutlive(subregion, superregion) => {
251 self.note_and_explain_region(db, "", subregion, "...");
252 self.note_and_explain_region(db, "...does not necessarily outlive ",
253 superregion, "");
254 }
255 RegionsNotSame(region1, region2) => {
256 self.note_and_explain_region(db, "", region1, "...");
257 self.note_and_explain_region(db, "...is not the same lifetime as ",
258 region2, "");
259 }
260 RegionsNoOverlap(region1, region2) => {
261 self.note_and_explain_region(db, "", region1, "...");
262 self.note_and_explain_region(db, "...does not overlap ",
263 region2, "");
264 }
265 RegionsInsufficientlyPolymorphic(_, conc_region) => {
266 self.note_and_explain_region(db, "concrete lifetime that was found is ",
267 conc_region, "");
268 }
269 RegionsOverlyPolymorphic(_, &ty::ReVar(_)) => {
270 // don't bother to print out the message below for
271 // inference variables, it's not very illuminating.
272 }
273 RegionsOverlyPolymorphic(_, conc_region) => {
274 self.note_and_explain_region(db, "expected concrete lifetime is ",
275 conc_region, "");
276 }
277 Sorts(values) => {
278 let expected_str = values.expected.sort_string(self);
279 let found_str = values.found.sort_string(self);
280 if expected_str == found_str && expected_str == "closure" {
281 db.span_note(sp,
282 "no two closures, even if identical, have the same type");
283 db.span_help(sp,
284 "consider boxing your closure and/or using it as a trait object");
285 }
286 },
287 TyParamDefaultMismatch(values) => {
288 let expected = values.expected;
289 let found = values.found;
290 db.span_note(sp, &format!("conflicting type parameter defaults `{}` and `{}`",
291 expected.ty,
292 found.ty));
293
294 match
295 self.map.as_local_node_id(expected.def_id)
296 .and_then(|node_id| self.map.opt_span(node_id))
297 {
298 Some(span) => {
299 db.span_note(span, "a default was defined here...");
300 }
301 None => {
302 db.note(&format!("a default is defined on `{}`",
303 self.item_path_str(expected.def_id)));
304 }
305 }
306
307 db.span_note(
308 expected.origin_span,
309 "...that was applied to an unconstrained type variable here");
310
311 match
312 self.map.as_local_node_id(found.def_id)
313 .and_then(|node_id| self.map.opt_span(node_id))
314 {
315 Some(span) => {
316 db.span_note(span, "a second default was defined here...");
317 }
318 None => {
319 db.note(&format!("a second default is defined on `{}`",
320 self.item_path_str(found.def_id)));
321 }
322 }
323
324 db.span_note(found.origin_span,
325 "...that also applies to the same type variable here");
326 }
327 _ => {}
328 }
329 }
330 }