1 use crate::hir::def_id::DefId;
2 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
5 use rustc_target::spec::abi;
7 use syntax::errors::pluralise;
8 use errors::{Applicability, DiagnosticBuilder};
13 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
14 pub struct ExpectedFound<T> {
19 // Data structures used in type unification
20 #[derive(Clone, Debug)]
21 pub enum TypeError<'tcx> {
23 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
24 AbiMismatch(ExpectedFound<abi::Abi>),
26 TupleSize(ExpectedFound<usize>),
27 FixedArraySize(ExpectedFound<u64>),
30 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
31 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
32 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
33 RegionsPlaceholderMismatch,
35 Sorts(ExpectedFound<Ty<'tcx>>),
36 IntMismatch(ExpectedFound<ty::IntVarValue>),
37 FloatMismatch(ExpectedFound<ast::FloatTy>),
38 Traits(ExpectedFound<DefId>),
39 VariadicMismatch(ExpectedFound<bool>),
41 /// Instantiating a type variable with the given type would have
42 /// created a cycle (because it appears somewhere within that
45 ProjectionMismatched(ExpectedFound<DefId>),
46 ProjectionBoundsLength(ExpectedFound<usize>),
47 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
49 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
54 pub enum UnconstrainedNumeric {
60 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
61 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
62 /// afterwards to present additional details, particularly when it comes to lifetime-related
64 impl<'tcx> fmt::Display for TypeError<'tcx> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 use self::TypeError::*;
67 fn report_maybe_different(f: &mut fmt::Formatter<'_>,
68 expected: &str, found: &str) -> fmt::Result {
69 // A naive approach to making sure that we're not reporting silly errors such as:
70 // (expected closure, found closure).
71 if expected == found {
72 write!(f, "expected {}, found a different {}", expected, found)
74 write!(f, "expected {}, found {}", expected, found)
78 let br_string = |br: ty::BoundRegion| {
80 ty::BrNamed(_, name) => format!(" {}", name),
86 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
87 Mismatch => write!(f, "types differ"),
88 UnsafetyMismatch(values) => {
89 write!(f, "expected {} fn, found {} fn",
93 AbiMismatch(values) => {
94 write!(f, "expected {} fn, found {} fn",
98 Mutability => write!(f, "types differ in mutability"),
99 TupleSize(values) => {
100 write!(f, "expected a tuple with {} element{}, \
101 found one with {} element{}",
103 pluralise!(values.expected),
105 pluralise!(values.found))
107 FixedArraySize(values) => {
108 write!(f, "expected an array with a fixed size of {} element{}, \
109 found one with {} element{}",
111 pluralise!(values.expected),
113 pluralise!(values.found))
116 write!(f, "incorrect number of function parameters")
118 RegionsDoesNotOutlive(..) => {
119 write!(f, "lifetime mismatch")
121 RegionsInsufficientlyPolymorphic(br, _) => {
123 "expected bound lifetime parameter{}, found concrete lifetime",
126 RegionsOverlyPolymorphic(br, _) => {
128 "expected concrete lifetime, found bound lifetime parameter{}",
131 RegionsPlaceholderMismatch => {
132 write!(f, "one type is more general than the other")
134 Sorts(values) => ty::tls::with(|tcx| {
135 report_maybe_different(f, &values.expected.sort_string(tcx),
136 &values.found.sort_string(tcx))
138 Traits(values) => ty::tls::with(|tcx| {
139 report_maybe_different(f,
140 &format!("trait `{}`",
141 tcx.def_path_str(values.expected)),
142 &format!("trait `{}`",
143 tcx.def_path_str(values.found)))
145 IntMismatch(ref values) => {
146 write!(f, "expected `{:?}`, found `{:?}`",
150 FloatMismatch(ref values) => {
151 write!(f, "expected `{:?}`, found `{:?}`",
155 VariadicMismatch(ref values) => {
156 write!(f, "expected {} fn, found {} function",
157 if values.expected { "variadic" } else { "non-variadic" },
158 if values.found { "variadic" } else { "non-variadic" })
160 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
161 write!(f, "expected {}, found {}",
162 tcx.def_path_str(values.expected),
163 tcx.def_path_str(values.found))
165 ProjectionBoundsLength(ref values) => {
166 write!(f, "expected {} associated type binding{}, found {}",
168 pluralise!(values.expected),
171 ExistentialMismatch(ref values) => {
172 report_maybe_different(f, &format!("trait `{}`", values.expected),
173 &format!("trait `{}`", values.found))
175 ConstMismatch(ref values) => {
176 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
179 write!(f, "cannot coerce intrinsics to function pointers")
185 impl<'tcx> ty::TyS<'tcx> {
186 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
188 ty::Bool | ty::Char | ty::Int(_) |
189 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
190 ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
192 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
193 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
195 let n = tcx.lift(&n).unwrap();
196 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
198 format!("array of {} element{}", n, pluralise!(n)).into()
200 None => "array".into(),
203 ty::Slice(_) => "slice".into(),
204 ty::RawPtr(_) => "*-ptr".into(),
205 ty::Ref(region, ty, mutbl) => {
206 let tymut = ty::TypeAndMut { ty, mutbl };
207 let tymut_string = tymut.to_string();
208 if tymut_string == "_" || //unknown type name,
209 tymut_string.len() > 10 || //name longer than saying "reference",
210 region.to_string() != "'_" //... or a complex type
212 format!("{}reference", match mutbl {
213 hir::Mutability::MutMutable => "mutable ",
217 format!("&{}", tymut_string).into()
220 ty::FnDef(..) => "fn item".into(),
221 ty::FnPtr(_) => "fn pointer".into(),
222 ty::Dynamic(ref inner, ..) => {
223 if let Some(principal) = inner.principal() {
224 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
229 ty::Closure(..) => "closure".into(),
230 ty::Generator(..) => "generator".into(),
231 ty::GeneratorWitness(..) => "generator witness".into(),
232 ty::Tuple(..) => "tuple".into(),
233 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
234 ty::Infer(ty::IntVar(_)) => "integer".into(),
235 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
236 ty::Placeholder(..) => "placeholder type".into(),
237 ty::Bound(..) => "bound type".into(),
238 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
239 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
240 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
241 ty::Projection(_) => "associated type".into(),
242 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
243 ty::Param(_) => "type parameter".into(),
244 ty::Opaque(..) => "opaque type".into(),
245 ty::Error => "type error".into(),
250 impl<'tcx> TyCtxt<'tcx> {
251 pub fn note_and_explain_type_err(
253 db: &mut DiagnosticBuilder<'_>,
254 err: &TypeError<'tcx>,
257 use self::TypeError::*;
261 let expected_str = values.expected.sort_string(self);
262 let found_str = values.found.sort_string(self);
263 if expected_str == found_str && expected_str == "closure" {
264 db.note("no two closures, even if identical, have the same type");
265 db.help("consider boxing your closure and/or using it as a trait object");
267 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
268 db.note("distinct uses of `impl Trait` result in different opaque types");
269 let e_str = values.expected.to_string();
270 let f_str = values.found.to_string();
271 if &e_str == &f_str && &e_str == "impl std::future::Future" {
272 // FIXME: use non-string based check.
273 db.help("if both `Future`s have the same `Output` type, consider \
274 `.await`ing on both of them");
277 match (&values.expected.kind, &values.found.kind) {
278 (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
280 ) = self.sess.source_map().span_to_snippet(sp) {
281 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
284 "use a float literal",
285 format!("{}.0", snippet),
286 Applicability::MachineApplicable
290 (ty::Param(_), ty::Param(_)) => {
291 db.note("a type parameter was expected, but a different one was found; \
292 you might be missing a type parameter or trait bound");
293 db.note("for more information, visit \
294 https://doc.rust-lang.org/book/ch10-02-traits.html\
295 #traits-as-parameters");
297 (ty::Projection(_), ty::Projection(_)) => {
298 db.note("an associated type was expected, but a different one was found");
300 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
301 db.note("you might be missing a type parameter or trait bound");
303 (ty::Param(_), _) | (_, ty::Param(_)) => {
304 db.help("type parameters must be constrained to match other types");
305 if self.sess.teach(&db.get_code().unwrap()) {
306 db.help("given a type parameter `T` and a method `foo`:
308 trait Trait<T> { fn foo(&self) -> T; }
310 the only ways to implement method `foo` are:
311 - constrain `T` with an explicit type:
313 impl Trait<String> for X {
314 fn foo(&self) -> String { String::new() }
317 - add a trait bound to `T` and call a method on that trait that returns `Self`:
319 impl<T: std::default::Default> Trait<T> for X {
320 fn foo(&self) -> T { <T as std::default::Default>::default() }
323 - change `foo` to return an argument of type `T`:
325 impl<T> Trait<T> for X {
326 fn foo(&self, x: T) -> T { x }
330 db.note("for more information, visit \
331 https://doc.rust-lang.org/book/ch10-02-traits.html\
332 #traits-as-parameters");
334 (ty::Projection(_), _) => {
336 "consider constraining the associated type `{}` to `{}` or calling a \
337 method that returns `{}`",
342 if self.sess.teach(&db.get_code().unwrap()) {
343 db.help("given an associated type `T` and a method `foo`:
347 fn foo(&self) -> Self::T;
350 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
354 fn foo(&self) -> Self::T { String::new() }
358 db.note("for more information, visit \
359 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
361 (_, ty::Projection(_)) => {
363 "consider constraining the associated type `{}` to `{}`",
367 db.note("for more information, visit \
368 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
373 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
375 values.expected.kind,
381 // Watch out for various cases of cyclic types and try to explain.
382 if ty.is_closure() || ty.is_generator() {
383 db.note("closures cannot capture themselves or take themselves as argument;\n\
384 this error may be the result of a recent compiler bug-fix,\n\
385 see https://github.com/rust-lang/rust/issues/46062 for more details");