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::pluralize;
8 use errors::{Applicability, DiagnosticBuilder};
13 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
14 pub struct ExpectedFound<T> {
19 // Data structures used in type unification
20 #[derive(Clone, Debug, TypeFoldable)]
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>>>),
48 ObjectUnsafeCoercion(DefId),
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(
68 f: &mut fmt::Formatter<'_>,
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)
77 write!(f, "expected {}, found {}", expected, found)
81 let br_string = |br: ty::BoundRegion| {
83 ty::BrNamed(_, name) => format!(" {}", name),
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, "types differ in mutability"),
102 TupleSize(values) => {
103 write!(f, "expected a tuple with {} element{}, \
104 found one with {} element{}",
106 pluralize!(values.expected),
108 pluralize!(values.found))
110 FixedArraySize(values) => {
111 write!(f, "expected an array with a fixed size of {} element{}, \
112 found one with {} element{}",
114 pluralize!(values.expected),
116 pluralize!(values.found))
119 write!(f, "incorrect number of function parameters")
121 RegionsDoesNotOutlive(..) => {
122 write!(f, "lifetime mismatch")
124 RegionsInsufficientlyPolymorphic(br, _) => {
126 "expected bound lifetime parameter{}, found concrete lifetime",
129 RegionsOverlyPolymorphic(br, _) => {
131 "expected concrete lifetime, found bound lifetime parameter{}",
134 RegionsPlaceholderMismatch => {
135 write!(f, "one type is more general than the other")
137 Sorts(values) => ty::tls::with(|tcx| {
138 report_maybe_different(f, &values.expected.sort_string(tcx),
139 &values.found.sort_string(tcx))
141 Traits(values) => ty::tls::with(|tcx| {
142 report_maybe_different(f,
143 &format!("trait `{}`",
144 tcx.def_path_str(values.expected)),
145 &format!("trait `{}`",
146 tcx.def_path_str(values.found)))
148 IntMismatch(ref values) => {
149 write!(f, "expected `{:?}`, found `{:?}`",
153 FloatMismatch(ref values) => {
154 write!(f, "expected `{:?}`, found `{:?}`",
158 VariadicMismatch(ref values) => {
159 write!(f, "expected {} fn, found {} function",
160 if values.expected { "variadic" } else { "non-variadic" },
161 if values.found { "variadic" } else { "non-variadic" })
163 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
164 write!(f, "expected {}, found {}",
165 tcx.def_path_str(values.expected),
166 tcx.def_path_str(values.found))
168 ProjectionBoundsLength(ref values) => {
169 write!(f, "expected {} associated type binding{}, found {}",
171 pluralize!(values.expected),
174 ExistentialMismatch(ref values) => {
175 report_maybe_different(f, &format!("trait `{}`", values.expected),
176 &format!("trait `{}`", values.found))
178 ConstMismatch(ref values) => {
179 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
182 write!(f, "cannot coerce intrinsics to function pointers")
184 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
189 impl<'tcx> TypeError<'tcx> {
190 pub fn must_include_note(&self) -> bool {
191 use self::TypeError::*;
194 UnsafetyMismatch(_) |
201 VariadicMismatch(_) => false,
206 RegionsDoesNotOutlive(..) |
207 RegionsInsufficientlyPolymorphic(..) |
208 RegionsOverlyPolymorphic(..) |
209 RegionsPlaceholderMismatch |
211 ProjectionMismatched(_) |
212 ProjectionBoundsLength(_) |
213 ExistentialMismatch(_) |
216 ObjectUnsafeCoercion(_) => true,
221 impl<'tcx> ty::TyS<'tcx> {
222 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
224 ty::Bool | ty::Char | ty::Int(_) |
225 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => format!("{}", self).into(),
226 ty::Tuple(ref tys) if tys.is_empty() => format!("{}", self).into(),
228 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
229 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
231 let n = tcx.lift(&n).unwrap();
232 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
233 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
234 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
235 None => "array".into(),
238 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
239 ty::Slice(_) => "slice".into(),
240 ty::RawPtr(_) => "*-ptr".into(),
241 ty::Ref(_, ty, mutbl) => {
242 let tymut = ty::TypeAndMut { ty, mutbl };
243 let tymut_string = tymut.to_string();
244 if tymut_string != "_" && (
245 ty.is_simple_text() || tymut_string.len() < "mutable reference".len()
247 format!("&{}", tymut_string).into()
248 } else { // Unknown type name, it's long or has type arguments
250 hir::Mutability::Mutable => "mutable reference",
255 ty::FnDef(..) => "fn item".into(),
256 ty::FnPtr(_) => "fn pointer".into(),
257 ty::Dynamic(ref inner, ..) => {
258 if let Some(principal) = inner.principal() {
259 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
264 ty::Closure(..) => "closure".into(),
265 ty::Generator(..) => "generator".into(),
266 ty::GeneratorWitness(..) => "generator witness".into(),
267 ty::Tuple(..) => "tuple".into(),
268 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
269 ty::Infer(ty::IntVar(_)) => "integer".into(),
270 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
271 ty::Placeholder(..) => "placeholder type".into(),
272 ty::Bound(..) => "bound type".into(),
273 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
274 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
275 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
276 ty::Projection(_) => "associated type".into(),
277 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
278 ty::Param(p) => format!("type parameter `{}`", p).into(),
279 ty::Opaque(..) => "opaque type".into(),
280 ty::Error => "type error".into(),
284 pub fn prefix_string(&self) -> Cow<'static, str> {
286 ty::Infer(_) | ty::Error | ty::Bool | ty::Char | ty::Int(_) |
287 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => "type".into(),
288 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
289 ty::Adt(def, _) => def.descr().into(),
290 ty::Foreign(_) => "extern type".into(),
291 ty::Array(..) => "array".into(),
292 ty::Slice(_) => "slice".into(),
293 ty::RawPtr(_) => "raw pointer".into(),
294 ty::Ref(.., mutbl) => match mutbl {
295 hir::Mutability::Mutable => "mutable reference",
298 ty::FnDef(..) => "fn item".into(),
299 ty::FnPtr(_) => "fn pointer".into(),
300 ty::Dynamic(..) => "trait object".into(),
301 ty::Closure(..) => "closure".into(),
302 ty::Generator(..) => "generator".into(),
303 ty::GeneratorWitness(..) => "generator witness".into(),
304 ty::Tuple(..) => "tuple".into(),
305 ty::Placeholder(..) => "higher-ranked type".into(),
306 ty::Bound(..) => "bound type variable".into(),
307 ty::Projection(_) => "associated type".into(),
308 ty::UnnormalizedProjection(_) => "associated type".into(),
309 ty::Param(_) => "type parameter".into(),
310 ty::Opaque(..) => "opaque type".into(),
315 impl<'tcx> TyCtxt<'tcx> {
316 pub fn note_and_explain_type_err(
318 db: &mut DiagnosticBuilder<'_>,
319 err: &TypeError<'tcx>,
321 body_owner_def_id: DefId,
323 use self::TypeError::*;
327 let expected_str = values.expected.sort_string(self);
328 let found_str = values.found.sort_string(self);
329 if expected_str == found_str && expected_str == "closure" {
330 db.note("no two closures, even if identical, have the same type");
331 db.help("consider boxing your closure and/or using it as a trait object");
333 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
334 db.note("distinct uses of `impl Trait` result in different opaque types");
335 let e_str = values.expected.to_string();
336 let f_str = values.found.to_string();
337 if &e_str == &f_str && &e_str == "impl std::future::Future" {
338 // FIXME: use non-string based check.
339 db.help("if both `Future`s have the same `Output` type, consider \
340 `.await`ing on both of them");
343 match (&values.expected.kind, &values.found.kind) {
344 (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
346 ) = self.sess.source_map().span_to_snippet(sp) {
347 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
350 "use a float literal",
351 format!("{}.0", snippet),
352 Applicability::MachineApplicable
356 (ty::Param(expected), ty::Param(found)) => {
357 let generics = self.generics_of(body_owner_def_id);
358 let e_span = self.def_span(generics.type_param(expected, self).def_id);
359 if !sp.contains(e_span) {
360 db.span_label(e_span, "expected type parameter");
362 let f_span = self.def_span(generics.type_param(found, self).def_id);
363 if !sp.contains(f_span) {
364 db.span_label(f_span, "found type parameter");
366 db.note("a type parameter was expected, but a different one was found; \
367 you might be missing a type parameter or trait bound");
368 db.note("for more information, visit \
369 https://doc.rust-lang.org/book/ch10-02-traits.html\
370 #traits-as-parameters");
372 (ty::Projection(_), ty::Projection(_)) => {
373 db.note("an associated type was expected, but a different one was found");
375 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
376 db.note("you might be missing a type parameter or trait bound");
378 (ty::Param(p), _) | (_, ty::Param(p)) => {
379 let generics = self.generics_of(body_owner_def_id);
380 let p_span = self.def_span(generics.type_param(p, self).def_id);
381 if !sp.contains(p_span) {
382 db.span_label(p_span, "this type parameter");
384 db.help("type parameters must be constrained to match other types");
385 if self.sess.teach(&db.get_code().unwrap()) {
386 db.help("given a type parameter `T` and a method `foo`:
388 trait Trait<T> { fn foo(&self) -> T; }
390 the only ways to implement method `foo` are:
391 - constrain `T` with an explicit type:
393 impl Trait<String> for X {
394 fn foo(&self) -> String { String::new() }
397 - add a trait bound to `T` and call a method on that trait that returns `Self`:
399 impl<T: std::default::Default> Trait<T> for X {
400 fn foo(&self) -> T { <T as std::default::Default>::default() }
403 - change `foo` to return an argument of type `T`:
405 impl<T> Trait<T> for X {
406 fn foo(&self, x: T) -> T { x }
410 db.note("for more information, visit \
411 https://doc.rust-lang.org/book/ch10-02-traits.html\
412 #traits-as-parameters");
414 (ty::Projection(_), _) => {
416 "consider constraining the associated type `{}` to `{}` or calling a \
417 method that returns `{}`",
422 if self.sess.teach(&db.get_code().unwrap()) {
423 db.help("given an associated type `T` and a method `foo`:
427 fn foo(&self) -> Self::T;
430 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
434 fn foo(&self) -> Self::T { String::new() }
438 db.note("for more information, visit \
439 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
441 (_, ty::Projection(_)) => {
443 "consider constraining the associated type `{}` to `{}`",
447 db.note("for more information, visit \
448 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
453 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
455 values.expected.kind,
461 // Watch out for various cases of cyclic types and try to explain.
462 if ty.is_closure() || ty.is_generator() {
463 db.note("closures cannot capture themselves or take themselves as argument;\n\
464 this error may be the result of a recent compiler bug-fix,\n\
465 see https://github.com/rust-lang/rust/issues/46062 for more details");