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.
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.
11 use middle::def_id::DefId;
13 use middle::infer::type_variable;
14 use middle::ty::{self, BoundRegion, Region, Ty};
18 use syntax::ast::{self, Name};
19 use syntax::codemap::Span;
23 #[derive(Clone, Copy, Debug)]
24 pub struct ExpectedFound<T> {
29 // Data structures used in type unification
30 #[derive(Clone, Debug)]
31 pub enum TypeError<'tcx> {
33 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
34 AbiMismatch(ExpectedFound<abi::Abi>),
40 TupleSize(ExpectedFound<usize>),
41 FixedArraySize(ExpectedFound<usize>),
42 TyParamSize(ExpectedFound<usize>),
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>>),
51 IntMismatch(ExpectedFound<ty::IntVarValue>),
52 FloatMismatch(ExpectedFound<ast::FloatTy>),
53 Traits(ExpectedFound<DefId>),
54 BuiltinBoundsMismatch(ExpectedFound<ty::BuiltinBounds>),
55 VariadicMismatch(ExpectedFound<bool>),
57 ConvergenceMismatch(ExpectedFound<bool>),
58 ProjectionNameMismatched(ExpectedFound<Name>),
59 ProjectionBoundsLength(ExpectedFound<usize>),
60 TyParamDefaultMismatch(ExpectedFound<type_variable::Default<'tcx>>)
63 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
64 pub enum UnconstrainedNumeric {
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
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)
84 write!(f, "expected {}, found {}", expected, found)
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",
96 AbiMismatch(values) => {
97 write!(f, "expected {} fn, found {} fn",
101 Mutability => write!(f, "values differ in mutability"),
103 write!(f, "boxed values differ in mutability")
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",
114 FixedArraySize(values) => {
115 write!(f, "expected an array with a fixed size of {} elements, \
116 found one with {} elements",
120 TupleSize(values) => {
121 write!(f, "expected a tuple with {} elements, \
122 found one with {} elements",
127 write!(f, "incorrect number of function parameters")
129 RegionsDoesNotOutlive(..) => {
130 write!(f, "lifetime mismatch")
132 RegionsNotSame(..) => {
133 write!(f, "lifetimes are not the same")
135 RegionsNoOverlap(..) => {
136 write!(f, "lifetimes do not intersect")
138 RegionsInsufficientlyPolymorphic(br, _) => {
139 write!(f, "expected bound lifetime parameter {}, \
140 found concrete lifetime", br)
142 RegionsOverlyPolymorphic(br, _) => {
143 write!(f, "expected concrete lifetime, \
144 found bound lifetime parameter {}", br)
146 Sorts(values) => ty::tls::with(|tcx| {
147 report_maybe_different(f, values.expected.sort_string(tcx),
148 values.found.sort_string(tcx))
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)))
157 BuiltinBoundsMismatch(values) => {
158 if values.expected.is_empty() {
159 write!(f, "expected no bounds, found `{}`",
161 } else if values.found.is_empty() {
162 write!(f, "expected bounds `{}`, found no bounds",
165 write!(f, "expected bounds `{}`, found bounds `{}`",
171 write!(f, "expected an integral type, found `char`")
173 IntMismatch(ref values) => {
174 write!(f, "expected `{:?}`, found `{:?}`",
178 FloatMismatch(ref values) => {
179 write!(f, "expected `{:?}`, found `{:?}`",
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" })
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" })
193 ProjectionNameMismatched(ref values) => {
194 write!(f, "expected {}, found {}",
198 ProjectionBoundsLength(ref values) => {
199 write!(f, "expected {} associated type bindings, found {}",
203 TyParamDefaultMismatch(ref values) => {
204 write!(f, "conflicting type parameter defaults `{}` and `{}`",
212 impl<'tcx> ty::TyS<'tcx> {
213 fn sort_string(&self, cx: &ty::ctxt) -> String {
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(),
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()))
230 ty::TyStruct(def, _) => {
231 format!("struct `{}`", cx.item_path_str(def.did))
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 {
246 "type parameter".to_string()
249 ty::TyError => "type error".to_string(),
254 impl<'tcx> ty::ctxt<'tcx> {
255 pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
256 use self::TypeError::*;
259 RegionsDoesNotOutlive(subregion, superregion) => {
260 self.note_and_explain_region("", subregion, "...");
261 self.note_and_explain_region("...does not necessarily outlive ",
264 RegionsNotSame(region1, region2) => {
265 self.note_and_explain_region("", region1, "...");
266 self.note_and_explain_region("...is not the same lifetime as ",
269 RegionsNoOverlap(region1, region2) => {
270 self.note_and_explain_region("", region1, "...");
271 self.note_and_explain_region("...does not overlap ",
274 RegionsInsufficientlyPolymorphic(_, conc_region) => {
275 self.note_and_explain_region("concrete lifetime that was found is ",
278 RegionsOverlyPolymorphic(_, ty::ReVar(_)) => {
279 // don't bother to print out the message below for
280 // inference variables, it's not very illuminating.
282 RegionsOverlyPolymorphic(_, conc_region) => {
283 self.note_and_explain_region("expected concrete lifetime is ",
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 &format!("no two closures, even if identical, have the same type"));
292 self.sess.span_help(sp,
293 &format!("consider boxing your closure and/or \
294 using it as a trait object"));
297 TyParamDefaultMismatch(values) => {
298 let expected = values.expected;
299 let found = values.found;
300 self.sess.span_note(sp,
301 &format!("conflicting type parameter defaults `{}` and `{}`",
305 match (expected.def_id.is_local(),
306 self.map.opt_span(expected.def_id.node)) {
307 (true, Some(span)) => {
308 self.sess.span_note(span,
309 &format!("a default was defined here..."));
313 &format!("a default is defined on `{}`",
314 self.item_path_str(expected.def_id)));
319 expected.origin_span,
320 &format!("...that was applied to an unconstrained type variable here"));
322 match (found.def_id.is_local(),
323 self.map.opt_span(found.def_id.node)) {
324 (true, Some(span)) => {
325 self.sess.span_note(span,
326 &format!("a second default was defined here..."));
330 &format!("a second default is defined on `{}`",
331 self.item_path_str(found.def_id)));
337 &format!("...that also applies to the same type variable here"));