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 hir::def_id::DefId;
12 use middle::const_val::ConstVal;
13 use ty::{self, BoundRegion, Region, Ty, TyCtxt};
14 use mir::interpret::{Value, PrimVal};
19 use errors::DiagnosticBuilder;
24 #[derive(Clone, Copy, Debug)]
25 pub struct ExpectedFound<T> {
30 // Data structures used in type unification
31 #[derive(Clone, Debug)]
32 pub enum TypeError<'tcx> {
34 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
35 AbiMismatch(ExpectedFound<abi::Abi>),
37 TupleSize(ExpectedFound<usize>),
38 FixedArraySize(ExpectedFound<u64>),
41 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
42 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
43 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
45 Sorts(ExpectedFound<Ty<'tcx>>),
46 IntMismatch(ExpectedFound<ty::IntVarValue>),
47 FloatMismatch(ExpectedFound<ast::FloatTy>),
48 Traits(ExpectedFound<DefId>),
49 VariadicMismatch(ExpectedFound<bool>),
51 /// Instantiating a type variable with the given type would have
52 /// created a cycle (because it appears somewhere within that
55 ProjectionMismatched(ExpectedFound<DefId>),
56 ProjectionBoundsLength(ExpectedFound<usize>),
57 ExistentialMismatch(ExpectedFound<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>),
59 OldStyleLUB(Box<TypeError<'tcx>>),
62 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
63 pub enum UnconstrainedNumeric {
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
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)
83 write!(f, "expected {}, found {}", expected, found)
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",
95 AbiMismatch(values) => {
96 write!(f, "expected {} fn, found {} fn",
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",
107 TupleSize(values) => {
108 write!(f, "expected a tuple with {} elements, \
109 found one with {} elements",
114 write!(f, "incorrect number of function parameters")
116 RegionsDoesNotOutlive(..) => {
117 write!(f, "lifetime mismatch")
119 RegionsInsufficientlyPolymorphic(br, _) => {
121 "expected bound lifetime parameter{}{}, found concrete lifetime",
122 if br.is_named() { " " } else { "" },
125 RegionsOverlyPolymorphic(br, _) => {
127 "expected concrete lifetime, found bound lifetime parameter{}{}",
128 if br.is_named() { " " } else { "" },
131 Sorts(values) => ty::tls::with(|tcx| {
132 report_maybe_different(f, values.expected.sort_string(tcx),
133 values.found.sort_string(tcx))
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)))
142 IntMismatch(ref values) => {
143 write!(f, "expected `{:?}`, found `{:?}`",
147 FloatMismatch(ref values) => {
148 write!(f, "expected `{:?}`, found `{:?}`",
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" })
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))
162 ProjectionBoundsLength(ref values) => {
163 write!(f, "expected {} associated type bindings, found {}",
167 ExistentialMismatch(ref values) => {
168 report_maybe_different(f, format!("trait `{}`", values.expected),
169 format!("trait `{}`", values.found))
171 OldStyleLUB(ref err) => {
178 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
179 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
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(),
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) => {
189 ConstVal::Value(Value::ByVal(PrimVal::Bytes(n))) =>
190 format!("array of {} elements", n),
191 _ => "array".to_string(),
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
203 ty::TypeAndMut{mutbl, ..} => {
204 format!("{}reference", match mutbl {
205 hir::Mutability::MutMutable => "mutable ",
211 format!("&{}", tymut_string)
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())))
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) => {
235 "type parameter".to_string()
238 ty::TyAnon(..) => "anonymized type".to_string(),
239 ty::TyError => "type error".to_string(),
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>,
249 use self::TypeError::*;
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");
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");
264 self.note_and_explain_type_err(db, &err, sp);
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");