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)]
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>>>),
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(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 pluralize!(values.expected),
105 pluralize!(values.found))
107 FixedArraySize(values) => {
108 write!(f, "expected an array with a fixed size of {} element{}, \
109 found one with {} element{}",
111 pluralize!(values.expected),
113 pluralize!(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 pluralize!(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")
181 ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
186 impl<'tcx> ty::TyS<'tcx> {
187 pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
189 ty::Bool | ty::Char | ty::Int(_) |
190 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
191 ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
193 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
194 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
196 let n = tcx.lift(&n).unwrap();
197 match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
199 format!("array of {} element{}", n, pluralize!(n)).into()
201 None => "array".into(),
204 ty::Slice(_) => "slice".into(),
205 ty::RawPtr(_) => "*-ptr".into(),
206 ty::Ref(region, ty, mutbl) => {
207 let tymut = ty::TypeAndMut { ty, mutbl };
208 let tymut_string = tymut.to_string();
209 if tymut_string == "_" || //unknown type name,
210 tymut_string.len() > 10 || //name longer than saying "reference",
211 region.to_string() != "'_" //... or a complex type
213 format!("{}reference", match mutbl {
214 hir::Mutability::Mutable => "mutable ",
218 format!("&{}", tymut_string).into()
221 ty::FnDef(..) => "fn item".into(),
222 ty::FnPtr(_) => "fn pointer".into(),
223 ty::Dynamic(ref inner, ..) => {
224 if let Some(principal) = inner.principal() {
225 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
230 ty::Closure(..) => "closure".into(),
231 ty::Generator(..) => "generator".into(),
232 ty::GeneratorWitness(..) => "generator witness".into(),
233 ty::Tuple(..) => "tuple".into(),
234 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
235 ty::Infer(ty::IntVar(_)) => "integer".into(),
236 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
237 ty::Placeholder(..) => "placeholder type".into(),
238 ty::Bound(..) => "bound type".into(),
239 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
240 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
241 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
242 ty::Projection(_) => "associated type".into(),
243 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
244 ty::Param(p) => format!("type parameter `{}`", p).into(),
245 ty::Opaque(..) => "opaque type".into(),
246 ty::Error => "type error".into(),
251 impl<'tcx> TyCtxt<'tcx> {
252 pub fn note_and_explain_type_err(
254 db: &mut DiagnosticBuilder<'_>,
255 err: &TypeError<'tcx>,
257 body_owner_def_id: DefId,
259 use self::TypeError::*;
263 let expected_str = values.expected.sort_string(self);
264 let found_str = values.found.sort_string(self);
265 if expected_str == found_str && expected_str == "closure" {
266 db.note("no two closures, even if identical, have the same type");
267 db.help("consider boxing your closure and/or using it as a trait object");
269 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
270 db.note("distinct uses of `impl Trait` result in different opaque types");
271 let e_str = values.expected.to_string();
272 let f_str = values.found.to_string();
273 if &e_str == &f_str && &e_str == "impl std::future::Future" {
274 // FIXME: use non-string based check.
275 db.help("if both `Future`s have the same `Output` type, consider \
276 `.await`ing on both of them");
279 match (&values.expected.kind, &values.found.kind) {
280 (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
282 ) = self.sess.source_map().span_to_snippet(sp) {
283 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
286 "use a float literal",
287 format!("{}.0", snippet),
288 Applicability::MachineApplicable
292 (ty::Param(expected), ty::Param(found)) => {
293 let generics = self.generics_of(body_owner_def_id);
294 let e_span = self.def_span(generics.type_param(expected, self).def_id);
295 if !sp.contains(e_span) {
296 db.span_label(e_span, "expected type parameter");
298 let f_span = self.def_span(generics.type_param(found, self).def_id);
299 if !sp.contains(f_span) {
300 db.span_label(f_span, "found type parameter");
302 db.note("a type parameter was expected, but a different one was found; \
303 you might be missing a type parameter or trait bound");
304 db.note("for more information, visit \
305 https://doc.rust-lang.org/book/ch10-02-traits.html\
306 #traits-as-parameters");
308 (ty::Projection(_), ty::Projection(_)) => {
309 db.note("an associated type was expected, but a different one was found");
311 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
312 db.note("you might be missing a type parameter or trait bound");
314 (ty::Param(p), _) | (_, ty::Param(p)) => {
315 let generics = self.generics_of(body_owner_def_id);
316 let p_span = self.def_span(generics.type_param(p, self).def_id);
317 if !sp.contains(p_span) {
318 db.span_label(p_span, "this type parameter");
320 db.help("type parameters must be constrained to match other types");
321 if self.sess.teach(&db.get_code().unwrap()) {
322 db.help("given a type parameter `T` and a method `foo`:
324 trait Trait<T> { fn foo(&self) -> T; }
326 the only ways to implement method `foo` are:
327 - constrain `T` with an explicit type:
329 impl Trait<String> for X {
330 fn foo(&self) -> String { String::new() }
333 - add a trait bound to `T` and call a method on that trait that returns `Self`:
335 impl<T: std::default::Default> Trait<T> for X {
336 fn foo(&self) -> T { <T as std::default::Default>::default() }
339 - change `foo` to return an argument of type `T`:
341 impl<T> Trait<T> for X {
342 fn foo(&self, x: T) -> T { x }
346 db.note("for more information, visit \
347 https://doc.rust-lang.org/book/ch10-02-traits.html\
348 #traits-as-parameters");
350 (ty::Projection(_), _) => {
352 "consider constraining the associated type `{}` to `{}` or calling a \
353 method that returns `{}`",
358 if self.sess.teach(&db.get_code().unwrap()) {
359 db.help("given an associated type `T` and a method `foo`:
363 fn foo(&self) -> Self::T;
366 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
370 fn foo(&self) -> Self::T { String::new() }
374 db.note("for more information, visit \
375 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
377 (_, ty::Projection(_)) => {
379 "consider constraining the associated type `{}` to `{}`",
383 db.note("for more information, visit \
384 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
389 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
391 values.expected.kind,
397 // Watch out for various cases of cyclic types and try to explain.
398 if ty.is_closure() || ty.is_generator() {
399 db.note("closures cannot capture themselves or take themselves as argument;\n\
400 this error may be the result of a recent compiler bug-fix,\n\
401 see https://github.com/rust-lang/rust/issues/46062 for more details");