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(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(),
250 pub fn prefix_string(&self) -> Cow<'static, str> {
251 debug!("prefix_string {:?} {} {:?}", self, self, self.kind);
253 ty::Infer(_) | ty::Error | ty::Bool | ty::Char | ty::Int(_) |
254 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => "type".into(),
255 ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
256 ty::Adt(def, _) => def.descr().into(),
257 ty::Foreign(_) => "extern type".into(),
258 ty::Array(..) => "array".into(),
259 ty::Slice(_) => "slice".into(),
260 ty::RawPtr(_) => "raw pointer".into(),
261 ty::Ref(.., mutbl) => match mutbl {
262 hir::Mutability::Mutable => "mutable reference",
265 ty::FnDef(..) => "fn item".into(),
266 ty::FnPtr(_) => "fn pointer".into(),
267 ty::Dynamic(..) => "trait object".into(),
268 ty::Closure(..) => "closure".into(),
269 ty::Generator(..) => "generator".into(),
270 ty::GeneratorWitness(..) => "generator witness".into(),
271 ty::Tuple(..) => "tuple".into(),
272 ty::Placeholder(..) => "higher-ranked type".into(),
273 ty::Bound(..) => "bound type variable".into(),
274 ty::Projection(_) => "associated type".into(),
275 ty::UnnormalizedProjection(_) => "associated type".into(),
276 ty::Param(_) => "type parameter".into(),
277 ty::Opaque(..) => "opaque type".into(),
282 impl<'tcx> TyCtxt<'tcx> {
283 pub fn note_and_explain_type_err(
285 db: &mut DiagnosticBuilder<'_>,
286 err: &TypeError<'tcx>,
288 body_owner_def_id: DefId,
290 use self::TypeError::*;
294 let expected_str = values.expected.sort_string(self);
295 let found_str = values.found.sort_string(self);
296 if expected_str == found_str && expected_str == "closure" {
297 db.note("no two closures, even if identical, have the same type");
298 db.help("consider boxing your closure and/or using it as a trait object");
300 if expected_str == found_str && expected_str == "opaque type" { // Issue #63167
301 db.note("distinct uses of `impl Trait` result in different opaque types");
302 let e_str = values.expected.to_string();
303 let f_str = values.found.to_string();
304 if &e_str == &f_str && &e_str == "impl std::future::Future" {
305 // FIXME: use non-string based check.
306 db.help("if both `Future`s have the same `Output` type, consider \
307 `.await`ing on both of them");
310 match (&values.expected.kind, &values.found.kind) {
311 (ty::Float(_), ty::Infer(ty::IntVar(_))) => if let Ok( // Issue #53280
313 ) = self.sess.source_map().span_to_snippet(sp) {
314 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
317 "use a float literal",
318 format!("{}.0", snippet),
319 Applicability::MachineApplicable
323 (ty::Param(expected), ty::Param(found)) => {
324 let generics = self.generics_of(body_owner_def_id);
325 let e_span = self.def_span(generics.type_param(expected, self).def_id);
326 if !sp.contains(e_span) {
327 db.span_label(e_span, "expected type parameter");
329 let f_span = self.def_span(generics.type_param(found, self).def_id);
330 if !sp.contains(f_span) {
331 db.span_label(f_span, "found type parameter");
333 db.note("a type parameter was expected, but a different one was found; \
334 you might be missing a type parameter or trait bound");
335 db.note("for more information, visit \
336 https://doc.rust-lang.org/book/ch10-02-traits.html\
337 #traits-as-parameters");
339 (ty::Projection(_), ty::Projection(_)) => {
340 db.note("an associated type was expected, but a different one was found");
342 (ty::Param(_), ty::Projection(_)) | (ty::Projection(_), ty::Param(_)) => {
343 db.note("you might be missing a type parameter or trait bound");
345 (ty::Param(p), _) | (_, ty::Param(p)) => {
346 let generics = self.generics_of(body_owner_def_id);
347 let p_span = self.def_span(generics.type_param(p, self).def_id);
348 if !sp.contains(p_span) {
349 db.span_label(p_span, "this type parameter");
351 db.help("type parameters must be constrained to match other types");
352 if self.sess.teach(&db.get_code().unwrap()) {
353 db.help("given a type parameter `T` and a method `foo`:
355 trait Trait<T> { fn foo(&self) -> T; }
357 the only ways to implement method `foo` are:
358 - constrain `T` with an explicit type:
360 impl Trait<String> for X {
361 fn foo(&self) -> String { String::new() }
364 - add a trait bound to `T` and call a method on that trait that returns `Self`:
366 impl<T: std::default::Default> Trait<T> for X {
367 fn foo(&self) -> T { <T as std::default::Default>::default() }
370 - change `foo` to return an argument of type `T`:
372 impl<T> Trait<T> for X {
373 fn foo(&self, x: T) -> T { x }
377 db.note("for more information, visit \
378 https://doc.rust-lang.org/book/ch10-02-traits.html\
379 #traits-as-parameters");
381 (ty::Projection(_), _) => {
383 "consider constraining the associated type `{}` to `{}` or calling a \
384 method that returns `{}`",
389 if self.sess.teach(&db.get_code().unwrap()) {
390 db.help("given an associated type `T` and a method `foo`:
394 fn foo(&self) -> Self::T;
397 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
401 fn foo(&self) -> Self::T { String::new() }
405 db.note("for more information, visit \
406 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
408 (_, ty::Projection(_)) => {
410 "consider constraining the associated type `{}` to `{}`",
414 db.note("for more information, visit \
415 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
420 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
422 values.expected.kind,
428 // Watch out for various cases of cyclic types and try to explain.
429 if ty.is_closure() || ty.is_generator() {
430 db.note("closures cannot capture themselves or take themselves as argument;\n\
431 this error may be the result of a recent compiler bug-fix,\n\
432 see https://github.com/rust-lang/rust/issues/46062 for more details");