1 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
2 use rustc_errors::{pluralize, Applicability, DiagnosticBuilder};
4 use rustc_hir::def_id::DefId;
6 use rustc_target::spec::abi;
12 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
13 pub struct ExpectedFound<T> {
18 impl<T> ExpectedFound<T> {
19 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
21 ExpectedFound { expected: a, found: b }
23 ExpectedFound { expected: b, found: a }
28 // Data structures used in type unification
29 #[derive(Clone, Debug, TypeFoldable)]
30 pub enum TypeError<'tcx> {
32 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
33 AbiMismatch(ExpectedFound<abi::Abi>),
35 TupleSize(ExpectedFound<usize>),
36 FixedArraySize(ExpectedFound<u64>),
39 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
40 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
41 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
42 RegionsPlaceholderMismatch,
44 Sorts(ExpectedFound<Ty<'tcx>>),
45 IntMismatch(ExpectedFound<ty::IntVarValue>),
46 FloatMismatch(ExpectedFound<ast::FloatTy>),
47 Traits(ExpectedFound<DefId>),
48 VariadicMismatch(ExpectedFound<bool>),
50 /// Instantiating a type variable with the given type would have
51 /// created a cycle (because it appears somewhere within that
54 ProjectionMismatched(ExpectedFound<DefId>),
55 ProjectionBoundsLength(ExpectedFound<usize>),
56 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
57 ObjectUnsafeCoercion(DefId),
58 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
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(
77 f: &mut fmt::Formatter<'_>,
81 // A naive approach to making sure that we're not reporting silly errors such as:
82 // (expected closure, found closure).
83 if expected == found {
84 write!(f, "expected {}, found a different {}", expected, found)
86 write!(f, "expected {}, found {}", expected, found)
90 let br_string = |br: ty::BoundRegion| match br {
91 ty::BrNamed(_, name) => format!(" {}", name),
96 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
97 Mismatch => write!(f, "types differ"),
98 UnsafetyMismatch(values) => {
99 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
101 AbiMismatch(values) => {
102 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
104 Mutability => write!(f, "types differ in mutability"),
105 TupleSize(values) => write!(
107 "expected a tuple with {} element{}, \
108 found one with {} element{}",
110 pluralize!(values.expected),
112 pluralize!(values.found)
114 FixedArraySize(values) => write!(
116 "expected an array with a fixed size of {} element{}, \
117 found one with {} element{}",
119 pluralize!(values.expected),
121 pluralize!(values.found)
123 ArgCount => write!(f, "incorrect number of function parameters"),
124 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
125 RegionsInsufficientlyPolymorphic(br, _) => write!(
127 "expected bound lifetime parameter{}, found concrete lifetime",
130 RegionsOverlyPolymorphic(br, _) => write!(
132 "expected concrete lifetime, found bound lifetime parameter{}",
135 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
136 Sorts(values) => ty::tls::with(|tcx| {
137 report_maybe_different(
139 &values.expected.sort_string(tcx),
140 &values.found.sort_string(tcx),
143 Traits(values) => ty::tls::with(|tcx| {
144 report_maybe_different(
146 &format!("trait `{}`", tcx.def_path_str(values.expected)),
147 &format!("trait `{}`", tcx.def_path_str(values.found)),
150 IntMismatch(ref values) => {
151 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
153 FloatMismatch(ref values) => {
154 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
156 VariadicMismatch(ref values) => write!(
158 "expected {} fn, found {} function",
159 if values.expected { "variadic" } else { "non-variadic" },
160 if values.found { "variadic" } else { "non-variadic" }
162 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
165 "expected {}, found {}",
166 tcx.def_path_str(values.expected),
167 tcx.def_path_str(values.found)
170 ProjectionBoundsLength(ref values) => write!(
172 "expected {} associated type binding{}, found {}",
174 pluralize!(values.expected),
177 ExistentialMismatch(ref values) => report_maybe_different(
179 &format!("trait `{}`", values.expected),
180 &format!("trait `{}`", values.found),
182 ConstMismatch(ref values) => {
183 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
185 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
186 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
191 impl<'tcx> TypeError<'tcx> {
192 pub fn must_include_note(&self) -> bool {
193 use self::TypeError::*;
195 CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
196 | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) => false,
201 | RegionsDoesNotOutlive(..)
202 | RegionsInsufficientlyPolymorphic(..)
203 | RegionsOverlyPolymorphic(..)
204 | RegionsPlaceholderMismatch
206 | ProjectionMismatched(_)
207 | ProjectionBoundsLength(_)
208 | ExistentialMismatch(_)
211 | ObjectUnsafeCoercion(_) => true,
216 impl<'tcx> ty::TyS<'tcx> {
217 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
219 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
220 format!("`{}`", self).into()
222 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
224 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
225 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
227 let n = tcx.lift(&n).unwrap();
228 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
229 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
230 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
231 None => "array".into(),
234 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
235 ty::Slice(_) => "slice".into(),
236 ty::RawPtr(_) => "*-ptr".into(),
237 ty::Ref(_, ty, mutbl) => {
238 let tymut = ty::TypeAndMut { ty, mutbl };
239 let tymut_string = tymut.to_string();
240 if tymut_string != "_"
241 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
243 format!("`&{}`", tymut_string).into()
245 // Unknown type name, it's long or has type arguments
247 hir::Mutability::Mut => "mutable reference",
253 ty::FnDef(..) => "fn item".into(),
254 ty::FnPtr(_) => "fn pointer".into(),
255 ty::Dynamic(ref inner, ..) => {
256 if let Some(principal) = inner.principal() {
257 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
259 "trait object".into()
262 ty::Closure(..) => "closure".into(),
263 ty::Generator(..) => "generator".into(),
264 ty::GeneratorWitness(..) => "generator witness".into(),
265 ty::Tuple(..) => "tuple".into(),
266 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
267 ty::Infer(ty::IntVar(_)) => "integer".into(),
268 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
269 ty::Placeholder(..) => "placeholder type".into(),
270 ty::Bound(..) => "bound type".into(),
271 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
272 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
273 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
274 ty::Projection(_) => "associated type".into(),
275 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
276 ty::Param(p) => format!("type parameter `{}`", p).into(),
277 ty::Opaque(..) => "opaque type".into(),
278 ty::Error => "type error".into(),
282 pub fn prefix_string(&self) -> Cow<'static, str> {
292 | ty::Never => "type".into(),
293 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
294 ty::Adt(def, _) => def.descr().into(),
295 ty::Foreign(_) => "extern type".into(),
296 ty::Array(..) => "array".into(),
297 ty::Slice(_) => "slice".into(),
298 ty::RawPtr(_) => "raw pointer".into(),
299 ty::Ref(.., mutbl) => match mutbl {
300 hir::Mutability::Mut => "mutable reference",
304 ty::FnDef(..) => "fn item".into(),
305 ty::FnPtr(_) => "fn pointer".into(),
306 ty::Dynamic(..) => "trait object".into(),
307 ty::Closure(..) => "closure".into(),
308 ty::Generator(..) => "generator".into(),
309 ty::GeneratorWitness(..) => "generator witness".into(),
310 ty::Tuple(..) => "tuple".into(),
311 ty::Placeholder(..) => "higher-ranked type".into(),
312 ty::Bound(..) => "bound type variable".into(),
313 ty::Projection(_) => "associated type".into(),
314 ty::UnnormalizedProjection(_) => "associated type".into(),
315 ty::Param(_) => "type parameter".into(),
316 ty::Opaque(..) => "opaque type".into(),
321 impl<'tcx> TyCtxt<'tcx> {
322 pub fn note_and_explain_type_err(
324 db: &mut DiagnosticBuilder<'_>,
325 err: &TypeError<'tcx>,
327 body_owner_def_id: DefId,
329 use self::TypeError::*;
333 let expected_str = values.expected.sort_string(self);
334 let found_str = values.found.sort_string(self);
335 if expected_str == found_str && expected_str == "closure" {
336 db.note("no two closures, even if identical, have the same type");
337 db.help("consider boxing your closure and/or using it as a trait object");
339 if expected_str == found_str && expected_str == "opaque type" {
341 db.note("distinct uses of `impl Trait` result in different opaque types");
342 let e_str = values.expected.to_string();
343 let f_str = values.found.to_string();
344 if &e_str == &f_str && &e_str == "impl std::future::Future" {
345 // FIXME: use non-string based check.
347 "if both `Future`s have the same `Output` type, consider \
348 `.await`ing on both of them",
352 match (&values.expected.kind, &values.found.kind) {
353 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
357 ) = self.sess.source_map().span_to_snippet(sp)
359 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
362 "use a float literal",
363 format!("{}.0", snippet),
364 Applicability::MachineApplicable,
369 (ty::Param(expected), ty::Param(found)) => {
370 let generics = self.generics_of(body_owner_def_id);
371 let e_span = self.def_span(generics.type_param(expected, self).def_id);
372 if !sp.contains(e_span) {
373 db.span_label(e_span, "expected type parameter");
375 let f_span = self.def_span(generics.type_param(found, self).def_id);
376 if !sp.contains(f_span) {
377 db.span_label(f_span, "found type parameter");
380 "a type parameter was expected, but a different one was found; \
381 you might be missing a type parameter or trait bound",
384 "for more information, visit \
385 https://doc.rust-lang.org/book/ch10-02-traits.html\
386 #traits-as-parameters",
389 (ty::Projection(_), ty::Projection(_)) => {
390 db.note("an associated type was expected, but a different one was found");
392 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
393 db.note("you might be missing a type parameter or trait bound");
395 (ty::Param(p), _) | (_, ty::Param(p)) => {
396 let generics = self.generics_of(body_owner_def_id);
397 let p_span = self.def_span(generics.type_param(p, self).def_id);
398 if !sp.contains(p_span) {
399 db.span_label(p_span, "this type parameter");
401 db.help("type parameters must be constrained to match other types");
402 if self.sess.teach(&db.get_code().unwrap()) {
404 "given a type parameter `T` and a method `foo`:
406 trait Trait<T> { fn foo(&self) -> T; }
408 the only ways to implement method `foo` are:
409 - constrain `T` with an explicit type:
411 impl Trait<String> for X {
412 fn foo(&self) -> String { String::new() }
415 - add a trait bound to `T` and call a method on that trait that returns `Self`:
417 impl<T: std::default::Default> Trait<T> for X {
418 fn foo(&self) -> T { <T as std::default::Default>::default() }
421 - change `foo` to return an argument of type `T`:
423 impl<T> Trait<T> for X {
424 fn foo(&self, x: T) -> T { x }
430 "for more information, visit \
431 https://doc.rust-lang.org/book/ch10-02-traits.html\
432 #traits-as-parameters",
435 (ty::Projection(_), _) => {
437 "consider constraining the associated type `{}` to `{}` or calling a \
438 method that returns `{}`",
439 values.expected, values.found, values.expected,
441 if self.sess.teach(&db.get_code().unwrap()) {
443 "given an associated type `T` and a method `foo`:
447 fn foo(&self) -> Self::T;
450 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
454 fn foo(&self) -> Self::T { String::new() }
460 "for more information, visit \
461 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
464 (_, ty::Projection(_)) => {
466 "consider constraining the associated type `{}` to `{}`",
467 values.found, values.expected,
470 "for more information, visit \
471 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
477 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
478 values.expected, values.expected.kind, values.found, values.found.kind,
482 // Watch out for various cases of cyclic types and try to explain.
483 if ty.is_closure() || ty.is_generator() {
485 "closures cannot capture themselves or take themselves as argument;\n\
486 this error may be the result of a recent compiler bug-fix,\n\
487 see https://github.com/rust-lang/rust/issues/46062 for more details",