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 ty::{self, BoundRegion, Region, Ty, TyCtxt};
14 use rustc_target::spec::abi;
16 use errors::DiagnosticBuilder;
21 #[derive(Clone, Copy, Debug)]
22 pub struct ExpectedFound<T> {
27 // Data structures used in type unification
28 #[derive(Clone, Debug)]
29 pub enum TypeError<'tcx> {
31 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
32 AbiMismatch(ExpectedFound<abi::Abi>),
34 TupleSize(ExpectedFound<usize>),
35 FixedArraySize(ExpectedFound<u64>),
38 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
39 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
40 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
42 Sorts(ExpectedFound<Ty<'tcx>>),
43 IntMismatch(ExpectedFound<ty::IntVarValue>),
44 FloatMismatch(ExpectedFound<ast::FloatTy>),
45 Traits(ExpectedFound<DefId>),
46 VariadicMismatch(ExpectedFound<bool>),
48 /// Instantiating a type variable with the given type would have
49 /// created a cycle (because it appears somewhere within that
52 ProjectionMismatched(ExpectedFound<DefId>),
53 ProjectionBoundsLength(ExpectedFound<usize>),
54 ExistentialMismatch(ExpectedFound<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>),
56 OldStyleLUB(Box<TypeError<'tcx>>),
59 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
60 pub enum UnconstrainedNumeric {
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
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)
80 write!(f, "expected {}, found {}", expected, found)
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",
92 AbiMismatch(values) => {
93 write!(f, "expected {} fn, found {} fn",
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",
104 TupleSize(values) => {
105 write!(f, "expected a tuple with {} elements, \
106 found one with {} elements",
111 write!(f, "incorrect number of function parameters")
113 RegionsDoesNotOutlive(..) => {
114 write!(f, "lifetime mismatch")
116 RegionsInsufficientlyPolymorphic(br, _) => {
118 "expected bound lifetime parameter{}{}, found concrete lifetime",
119 if br.is_named() { " " } else { "" },
122 RegionsOverlyPolymorphic(br, _) => {
124 "expected concrete lifetime, found bound lifetime parameter{}{}",
125 if br.is_named() { " " } else { "" },
128 Sorts(values) => ty::tls::with(|tcx| {
129 report_maybe_different(f, values.expected.sort_string(tcx),
130 values.found.sort_string(tcx))
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)))
139 IntMismatch(ref values) => {
140 write!(f, "expected `{:?}`, found `{:?}`",
144 FloatMismatch(ref values) => {
145 write!(f, "expected `{:?}`, found `{:?}`",
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" })
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))
159 ProjectionBoundsLength(ref values) => {
160 write!(f, "expected {} associated type bindings, found {}",
164 ExistentialMismatch(ref values) => {
165 report_maybe_different(f, format!("trait `{}`", values.expected),
166 format!("trait `{}`", values.found))
168 OldStyleLUB(ref err) => {
175 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
176 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
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(),
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(),
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
199 format!("{}reference", match mutbl {
200 hir::Mutability::MutMutable => "mutable ",
204 format!("&{}", tymut_string)
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())))
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) => {
229 "type parameter".to_string()
232 ty::TyAnon(..) => "anonymized type".to_string(),
233 ty::TyError => "type error".to_string(),
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>,
243 use self::TypeError::*;
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");
254 OldStyleLUB(err) => {
255 db.note("this was previously accepted by the compiler but has been phased out");
256 db.note("for more information, see https://github.com/rust-lang/rust/issues/45852");
258 self.note_and_explain_type_err(db, &err, sp);
261 // Watch out for various cases of cyclic types and try to explain.
262 if ty.is_closure() || ty.is_generator() {
263 db.note("closures cannot capture themselves or take themselves as argument;\n\
264 this error may be the result of a recent compiler bug-fix,\n\
265 see https://github.com/rust-lang/rust/issues/46062 for more details");