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 // Data structures used in type unification
19 #[derive(Clone, Debug, TypeFoldable)]
20 pub enum TypeError<'tcx> {
22 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
23 AbiMismatch(ExpectedFound<abi::Abi>),
25 TupleSize(ExpectedFound<usize>),
26 FixedArraySize(ExpectedFound<u64>),
29 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
30 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
31 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
32 RegionsPlaceholderMismatch,
34 Sorts(ExpectedFound<Ty<'tcx>>),
35 IntMismatch(ExpectedFound<ty::IntVarValue>),
36 FloatMismatch(ExpectedFound<ast::FloatTy>),
37 Traits(ExpectedFound<DefId>),
38 VariadicMismatch(ExpectedFound<bool>),
40 /// Instantiating a type variable with the given type would have
41 /// created a cycle (because it appears somewhere within that
44 ProjectionMismatched(ExpectedFound<DefId>),
45 ProjectionBoundsLength(ExpectedFound<usize>),
46 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
47 ObjectUnsafeCoercion(DefId),
48 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
53 pub enum UnconstrainedNumeric {
59 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
60 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
61 /// afterwards to present additional details, particularly when it comes to lifetime-related
63 impl<'tcx> fmt::Display for TypeError<'tcx> {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 use self::TypeError::*;
66 fn report_maybe_different(
67 f: &mut fmt::Formatter<'_>,
71 // A naive approach to making sure that we're not reporting silly errors such as:
72 // (expected closure, found closure).
73 if expected == found {
74 write!(f, "expected {}, found a different {}", expected, found)
76 write!(f, "expected {}, found {}", expected, found)
80 let br_string = |br: ty::BoundRegion| match br {
81 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", values.expected, values.found)
91 AbiMismatch(values) => {
92 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
94 Mutability => write!(f, "types differ in mutability"),
95 TupleSize(values) => write!(
97 "expected a tuple with {} element{}, \
98 found one with {} element{}",
100 pluralize!(values.expected),
102 pluralize!(values.found)
104 FixedArraySize(values) => write!(
106 "expected an array with a fixed size of {} element{}, \
107 found one with {} element{}",
109 pluralize!(values.expected),
111 pluralize!(values.found)
113 ArgCount => write!(f, "incorrect number of function parameters"),
114 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
115 RegionsInsufficientlyPolymorphic(br, _) => write!(
117 "expected bound lifetime parameter{}, found concrete lifetime",
120 RegionsOverlyPolymorphic(br, _) => write!(
122 "expected concrete lifetime, found bound lifetime parameter{}",
125 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
126 Sorts(values) => ty::tls::with(|tcx| {
127 report_maybe_different(
129 &values.expected.sort_string(tcx),
130 &values.found.sort_string(tcx),
133 Traits(values) => ty::tls::with(|tcx| {
134 report_maybe_different(
136 &format!("trait `{}`", tcx.def_path_str(values.expected)),
137 &format!("trait `{}`", tcx.def_path_str(values.found)),
140 IntMismatch(ref values) => {
141 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
143 FloatMismatch(ref values) => {
144 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
146 VariadicMismatch(ref values) => write!(
148 "expected {} fn, found {} function",
149 if values.expected { "variadic" } else { "non-variadic" },
150 if values.found { "variadic" } else { "non-variadic" }
152 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
155 "expected {}, found {}",
156 tcx.def_path_str(values.expected),
157 tcx.def_path_str(values.found)
160 ProjectionBoundsLength(ref values) => write!(
162 "expected {} associated type binding{}, found {}",
164 pluralize!(values.expected),
167 ExistentialMismatch(ref values) => report_maybe_different(
169 &format!("trait `{}`", values.expected),
170 &format!("trait `{}`", values.found),
172 ConstMismatch(ref values) => {
173 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
175 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
176 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
181 impl<'tcx> TypeError<'tcx> {
182 pub fn must_include_note(&self) -> bool {
183 use self::TypeError::*;
185 CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
186 | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) => false,
191 | RegionsDoesNotOutlive(..)
192 | RegionsInsufficientlyPolymorphic(..)
193 | RegionsOverlyPolymorphic(..)
194 | RegionsPlaceholderMismatch
196 | ProjectionMismatched(_)
197 | ProjectionBoundsLength(_)
198 | ExistentialMismatch(_)
201 | ObjectUnsafeCoercion(_) => true,
206 impl<'tcx> ty::TyS<'tcx> {
207 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
209 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
210 format!("`{}`", self).into()
212 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
214 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
215 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
217 let n = tcx.lift(&n).unwrap();
218 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
219 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
220 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
221 None => "array".into(),
224 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
225 ty::Slice(_) => "slice".into(),
226 ty::RawPtr(_) => "*-ptr".into(),
227 ty::Ref(_, ty, mutbl) => {
228 let tymut = ty::TypeAndMut { ty, mutbl };
229 let tymut_string = tymut.to_string();
230 if tymut_string != "_"
231 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
233 format!("`&{}`", tymut_string).into()
235 // Unknown type name, it's long or has type arguments
237 hir::Mutability::Mut => "mutable reference",
243 ty::FnDef(..) => "fn item".into(),
244 ty::FnPtr(_) => "fn pointer".into(),
245 ty::Dynamic(ref inner, ..) => {
246 if let Some(principal) = inner.principal() {
247 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
249 "trait object".into()
252 ty::Closure(..) => "closure".into(),
253 ty::Generator(..) => "generator".into(),
254 ty::GeneratorWitness(..) => "generator witness".into(),
255 ty::Tuple(..) => "tuple".into(),
256 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
257 ty::Infer(ty::IntVar(_)) => "integer".into(),
258 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
259 ty::Placeholder(..) => "placeholder type".into(),
260 ty::Bound(..) => "bound type".into(),
261 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
262 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
263 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
264 ty::Projection(_) => "associated type".into(),
265 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
266 ty::Param(p) => format!("type parameter `{}`", p).into(),
267 ty::Opaque(..) => "opaque type".into(),
268 ty::Error => "type error".into(),
272 pub fn prefix_string(&self) -> Cow<'static, str> {
282 | ty::Never => "type".into(),
283 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
284 ty::Adt(def, _) => def.descr().into(),
285 ty::Foreign(_) => "extern type".into(),
286 ty::Array(..) => "array".into(),
287 ty::Slice(_) => "slice".into(),
288 ty::RawPtr(_) => "raw pointer".into(),
289 ty::Ref(.., mutbl) => match mutbl {
290 hir::Mutability::Mut => "mutable reference",
294 ty::FnDef(..) => "fn item".into(),
295 ty::FnPtr(_) => "fn pointer".into(),
296 ty::Dynamic(..) => "trait object".into(),
297 ty::Closure(..) => "closure".into(),
298 ty::Generator(..) => "generator".into(),
299 ty::GeneratorWitness(..) => "generator witness".into(),
300 ty::Tuple(..) => "tuple".into(),
301 ty::Placeholder(..) => "higher-ranked type".into(),
302 ty::Bound(..) => "bound type variable".into(),
303 ty::Projection(_) => "associated type".into(),
304 ty::UnnormalizedProjection(_) => "associated type".into(),
305 ty::Param(_) => "type parameter".into(),
306 ty::Opaque(..) => "opaque type".into(),
311 impl<'tcx> TyCtxt<'tcx> {
312 pub fn note_and_explain_type_err(
314 db: &mut DiagnosticBuilder<'_>,
315 err: &TypeError<'tcx>,
317 body_owner_def_id: DefId,
319 use self::TypeError::*;
323 let expected_str = values.expected.sort_string(self);
324 let found_str = values.found.sort_string(self);
325 if expected_str == found_str && expected_str == "closure" {
326 db.note("no two closures, even if identical, have the same type");
327 db.help("consider boxing your closure and/or using it as a trait object");
329 if expected_str == found_str && expected_str == "opaque type" {
331 db.note("distinct uses of `impl Trait` result in different opaque types");
332 let e_str = values.expected.to_string();
333 let f_str = values.found.to_string();
334 if &e_str == &f_str && &e_str == "impl std::future::Future" {
335 // FIXME: use non-string based check.
337 "if both `Future`s have the same `Output` type, consider \
338 `.await`ing on both of them",
342 match (&values.expected.kind, &values.found.kind) {
343 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
347 ) = self.sess.source_map().span_to_snippet(sp)
349 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
352 "use a float literal",
353 format!("{}.0", snippet),
354 Applicability::MachineApplicable,
359 (ty::Param(expected), ty::Param(found)) => {
360 let generics = self.generics_of(body_owner_def_id);
361 let e_span = self.def_span(generics.type_param(expected, self).def_id);
362 if !sp.contains(e_span) {
363 db.span_label(e_span, "expected type parameter");
365 let f_span = self.def_span(generics.type_param(found, self).def_id);
366 if !sp.contains(f_span) {
367 db.span_label(f_span, "found type parameter");
370 "a type parameter was expected, but a different one was found; \
371 you might be missing a type parameter or trait bound",
374 "for more information, visit \
375 https://doc.rust-lang.org/book/ch10-02-traits.html\
376 #traits-as-parameters",
379 (ty::Projection(_), ty::Projection(_)) => {
380 db.note("an associated type was expected, but a different one was found");
382 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
383 db.note("you might be missing a type parameter or trait bound");
385 (ty::Param(p), _) | (_, ty::Param(p)) => {
386 let generics = self.generics_of(body_owner_def_id);
387 let p_span = self.def_span(generics.type_param(p, self).def_id);
388 if !sp.contains(p_span) {
389 db.span_label(p_span, "this type parameter");
391 db.help("type parameters must be constrained to match other types");
392 if self.sess.teach(&db.get_code().unwrap()) {
394 "given a type parameter `T` and a method `foo`:
396 trait Trait<T> { fn foo(&self) -> T; }
398 the only ways to implement method `foo` are:
399 - constrain `T` with an explicit type:
401 impl Trait<String> for X {
402 fn foo(&self) -> String { String::new() }
405 - add a trait bound to `T` and call a method on that trait that returns `Self`:
407 impl<T: std::default::Default> Trait<T> for X {
408 fn foo(&self) -> T { <T as std::default::Default>::default() }
411 - change `foo` to return an argument of type `T`:
413 impl<T> Trait<T> for X {
414 fn foo(&self, x: T) -> T { x }
420 "for more information, visit \
421 https://doc.rust-lang.org/book/ch10-02-traits.html\
422 #traits-as-parameters",
425 (ty::Projection(_), _) => {
427 "consider constraining the associated type `{}` to `{}` or calling a \
428 method that returns `{}`",
429 values.expected, values.found, values.expected,
431 if self.sess.teach(&db.get_code().unwrap()) {
433 "given an associated type `T` and a method `foo`:
437 fn foo(&self) -> Self::T;
440 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
444 fn foo(&self) -> Self::T { String::new() }
450 "for more information, visit \
451 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
454 (_, ty::Projection(_)) => {
456 "consider constraining the associated type `{}` to `{}`",
457 values.found, values.expected,
460 "for more information, visit \
461 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
467 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
468 values.expected, values.expected.kind, values.found, values.found.kind,
472 // Watch out for various cases of cyclic types and try to explain.
473 if ty.is_closure() || ty.is_generator() {
475 "closures cannot capture themselves or take themselves as argument;\n\
476 this error may be the result of a recent compiler bug-fix,\n\
477 see https://github.com/rust-lang/rust/issues/46062 for more details",