1 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
3 use rustc_hir::def_id::DefId;
5 use errors::{Applicability, DiagnosticBuilder};
7 use rustc_target::spec::abi;
9 use syntax::errors::pluralize;
14 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
15 pub struct ExpectedFound<T> {
20 // Data structures used in type unification
21 #[derive(Clone, Debug, TypeFoldable)]
22 pub enum TypeError<'tcx> {
24 UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
25 AbiMismatch(ExpectedFound<abi::Abi>),
27 TupleSize(ExpectedFound<usize>),
28 FixedArraySize(ExpectedFound<u64>),
31 RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
32 RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
33 RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
34 RegionsPlaceholderMismatch,
36 Sorts(ExpectedFound<Ty<'tcx>>),
37 IntMismatch(ExpectedFound<ty::IntVarValue>),
38 FloatMismatch(ExpectedFound<ast::FloatTy>),
39 Traits(ExpectedFound<DefId>),
40 VariadicMismatch(ExpectedFound<bool>),
42 /// Instantiating a type variable with the given type would have
43 /// created a cycle (because it appears somewhere within that
46 ProjectionMismatched(ExpectedFound<DefId>),
47 ProjectionBoundsLength(ExpectedFound<usize>),
48 ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
49 ObjectUnsafeCoercion(DefId),
50 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
55 pub enum UnconstrainedNumeric {
61 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
62 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
63 /// afterwards to present additional details, particularly when it comes to lifetime-related
65 impl<'tcx> fmt::Display for TypeError<'tcx> {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 use self::TypeError::*;
68 fn report_maybe_different(
69 f: &mut fmt::Formatter<'_>,
73 // A naive approach to making sure that we're not reporting silly errors such as:
74 // (expected closure, found closure).
75 if expected == found {
76 write!(f, "expected {}, found a different {}", expected, found)
78 write!(f, "expected {}, found {}", expected, found)
82 let br_string = |br: ty::BoundRegion| match br {
83 ty::BrNamed(_, name) => format!(" {}", name),
88 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
89 Mismatch => write!(f, "types differ"),
90 UnsafetyMismatch(values) => {
91 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
93 AbiMismatch(values) => {
94 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
96 Mutability => write!(f, "types differ in mutability"),
97 TupleSize(values) => write!(
99 "expected a tuple with {} element{}, \
100 found one with {} element{}",
102 pluralize!(values.expected),
104 pluralize!(values.found)
106 FixedArraySize(values) => write!(
108 "expected an array with a fixed size of {} element{}, \
109 found one with {} element{}",
111 pluralize!(values.expected),
113 pluralize!(values.found)
115 ArgCount => write!(f, "incorrect number of function parameters"),
116 RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
117 RegionsInsufficientlyPolymorphic(br, _) => write!(
119 "expected bound lifetime parameter{}, found concrete lifetime",
122 RegionsOverlyPolymorphic(br, _) => write!(
124 "expected concrete lifetime, found bound lifetime parameter{}",
127 RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
128 Sorts(values) => ty::tls::with(|tcx| {
129 report_maybe_different(
131 &values.expected.sort_string(tcx),
132 &values.found.sort_string(tcx),
135 Traits(values) => ty::tls::with(|tcx| {
136 report_maybe_different(
138 &format!("trait `{}`", tcx.def_path_str(values.expected)),
139 &format!("trait `{}`", tcx.def_path_str(values.found)),
142 IntMismatch(ref values) => {
143 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
145 FloatMismatch(ref values) => {
146 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
148 VariadicMismatch(ref values) => write!(
150 "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| {
157 "expected {}, found {}",
158 tcx.def_path_str(values.expected),
159 tcx.def_path_str(values.found)
162 ProjectionBoundsLength(ref values) => write!(
164 "expected {} associated type binding{}, found {}",
166 pluralize!(values.expected),
169 ExistentialMismatch(ref values) => report_maybe_different(
171 &format!("trait `{}`", values.expected),
172 &format!("trait `{}`", values.found),
174 ConstMismatch(ref values) => {
175 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
177 IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
178 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
183 impl<'tcx> TypeError<'tcx> {
184 pub fn must_include_note(&self) -> bool {
185 use self::TypeError::*;
187 CyclicTy(_) | UnsafetyMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
188 | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | VariadicMismatch(_) => false,
193 | RegionsDoesNotOutlive(..)
194 | RegionsInsufficientlyPolymorphic(..)
195 | RegionsOverlyPolymorphic(..)
196 | RegionsPlaceholderMismatch
198 | ProjectionMismatched(_)
199 | ProjectionBoundsLength(_)
200 | ExistentialMismatch(_)
203 | ObjectUnsafeCoercion(_) => true,
208 impl<'tcx> ty::TyS<'tcx> {
209 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
211 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
212 format!("`{}`", self).into()
214 ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
216 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
217 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
219 let n = tcx.lift(&n).unwrap();
220 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
221 _ if t.is_simple_ty() => format!("array `{}`", self).into(),
222 Some(n) => format!("array of {} element{} ", n, pluralize!(n)).into(),
223 None => "array".into(),
226 ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
227 ty::Slice(_) => "slice".into(),
228 ty::RawPtr(_) => "*-ptr".into(),
229 ty::Ref(_, ty, mutbl) => {
230 let tymut = ty::TypeAndMut { ty, mutbl };
231 let tymut_string = tymut.to_string();
232 if tymut_string != "_"
233 && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
235 format!("`&{}`", tymut_string).into()
237 // Unknown type name, it's long or has type arguments
239 hir::Mutability::Mut => "mutable reference",
245 ty::FnDef(..) => "fn item".into(),
246 ty::FnPtr(_) => "fn pointer".into(),
247 ty::Dynamic(ref inner, ..) => {
248 if let Some(principal) = inner.principal() {
249 format!("trait `{}`", tcx.def_path_str(principal.def_id())).into()
254 ty::Closure(..) => "closure".into(),
255 ty::Generator(..) => "generator".into(),
256 ty::GeneratorWitness(..) => "generator witness".into(),
257 ty::Tuple(..) => "tuple".into(),
258 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
259 ty::Infer(ty::IntVar(_)) => "integer".into(),
260 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
261 ty::Placeholder(..) => "placeholder type".into(),
262 ty::Bound(..) => "bound type".into(),
263 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
264 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
265 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
266 ty::Projection(_) => "associated type".into(),
267 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
268 ty::Param(p) => format!("type parameter `{}`", p).into(),
269 ty::Opaque(..) => "opaque type".into(),
270 ty::Error => "type error".into(),
274 pub fn prefix_string(&self) -> Cow<'static, str> {
284 | ty::Never => "type".into(),
285 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
286 ty::Adt(def, _) => def.descr().into(),
287 ty::Foreign(_) => "extern type".into(),
288 ty::Array(..) => "array".into(),
289 ty::Slice(_) => "slice".into(),
290 ty::RawPtr(_) => "raw pointer".into(),
291 ty::Ref(.., mutbl) => match mutbl {
292 hir::Mutability::Mut => "mutable reference",
296 ty::FnDef(..) => "fn item".into(),
297 ty::FnPtr(_) => "fn pointer".into(),
298 ty::Dynamic(..) => "trait object".into(),
299 ty::Closure(..) => "closure".into(),
300 ty::Generator(..) => "generator".into(),
301 ty::GeneratorWitness(..) => "generator witness".into(),
302 ty::Tuple(..) => "tuple".into(),
303 ty::Placeholder(..) => "higher-ranked type".into(),
304 ty::Bound(..) => "bound type variable".into(),
305 ty::Projection(_) => "associated type".into(),
306 ty::UnnormalizedProjection(_) => "associated type".into(),
307 ty::Param(_) => "type parameter".into(),
308 ty::Opaque(..) => "opaque type".into(),
313 impl<'tcx> TyCtxt<'tcx> {
314 pub fn note_and_explain_type_err(
316 db: &mut DiagnosticBuilder<'_>,
317 err: &TypeError<'tcx>,
319 body_owner_def_id: DefId,
321 use self::TypeError::*;
325 let expected_str = values.expected.sort_string(self);
326 let found_str = values.found.sort_string(self);
327 if expected_str == found_str && expected_str == "closure" {
328 db.note("no two closures, even if identical, have the same type");
329 db.help("consider boxing your closure and/or using it as a trait object");
331 if expected_str == found_str && expected_str == "opaque type" {
333 db.note("distinct uses of `impl Trait` result in different opaque types");
334 let e_str = values.expected.to_string();
335 let f_str = values.found.to_string();
336 if &e_str == &f_str && &e_str == "impl std::future::Future" {
337 // FIXME: use non-string based check.
339 "if both `Future`s have the same `Output` type, consider \
340 `.await`ing on both of them",
344 match (&values.expected.kind, &values.found.kind) {
345 (ty::Float(_), ty::Infer(ty::IntVar(_))) => {
349 ) = self.sess.source_map().span_to_snippet(sp)
351 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
354 "use a float literal",
355 format!("{}.0", snippet),
356 Applicability::MachineApplicable,
361 (ty::Param(expected), ty::Param(found)) => {
362 let generics = self.generics_of(body_owner_def_id);
363 let e_span = self.def_span(generics.type_param(expected, self).def_id);
364 if !sp.contains(e_span) {
365 db.span_label(e_span, "expected type parameter");
367 let f_span = self.def_span(generics.type_param(found, self).def_id);
368 if !sp.contains(f_span) {
369 db.span_label(f_span, "found type parameter");
372 "a type parameter was expected, but a different one was found; \
373 you might be missing a type parameter or trait bound",
376 "for more information, visit \
377 https://doc.rust-lang.org/book/ch10-02-traits.html\
378 #traits-as-parameters",
381 (ty::Projection(_), ty::Projection(_)) => {
382 db.note("an associated type was expected, but a different one was found");
384 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
385 db.note("you might be missing a type parameter or trait bound");
387 (ty::Param(p), _) | (_, ty::Param(p)) => {
388 let generics = self.generics_of(body_owner_def_id);
389 let p_span = self.def_span(generics.type_param(p, self).def_id);
390 if !sp.contains(p_span) {
391 db.span_label(p_span, "this type parameter");
393 db.help("type parameters must be constrained to match other types");
394 if self.sess.teach(&db.get_code().unwrap()) {
396 "given a type parameter `T` and a method `foo`:
398 trait Trait<T> { fn foo(&self) -> T; }
400 the only ways to implement method `foo` are:
401 - constrain `T` with an explicit type:
403 impl Trait<String> for X {
404 fn foo(&self) -> String { String::new() }
407 - add a trait bound to `T` and call a method on that trait that returns `Self`:
409 impl<T: std::default::Default> Trait<T> for X {
410 fn foo(&self) -> T { <T as std::default::Default>::default() }
413 - change `foo` to return an argument of type `T`:
415 impl<T> Trait<T> for X {
416 fn foo(&self, x: T) -> T { x }
422 "for more information, visit \
423 https://doc.rust-lang.org/book/ch10-02-traits.html\
424 #traits-as-parameters",
427 (ty::Projection(_), _) => {
429 "consider constraining the associated type `{}` to `{}` or calling a \
430 method that returns `{}`",
431 values.expected, values.found, values.expected,
433 if self.sess.teach(&db.get_code().unwrap()) {
435 "given an associated type `T` and a method `foo`:
439 fn foo(&self) -> Self::T;
442 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
446 fn foo(&self) -> Self::T { String::new() }
452 "for more information, visit \
453 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
456 (_, ty::Projection(_)) => {
458 "consider constraining the associated type `{}` to `{}`",
459 values.found, values.expected,
462 "for more information, visit \
463 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
469 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
470 values.expected, values.expected.kind, values.found, values.found.kind,
474 // Watch out for various cases of cyclic types and try to explain.
475 if ty.is_closure() || ty.is_generator() {
477 "closures cannot capture themselves or take themselves as argument;\n\
478 this error may be the result of a recent compiler bug-fix,\n\
479 see https://github.com/rust-lang/rust/issues/46062 for more details",