2 use crate::hir
::def_id
::DefId
;
3 use crate::ty
::{self, BoundRegion, Region, Ty, TyCtxt}
;
5 use errors
::{Applicability, DiagnosticBuilder}
;
6 use rustc_target
::spec
::abi
;
8 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
| {
84 ty
::BrNamed(_
, name
) => format
!(" {}", name
),
90 CyclicTy(_
) => write
!(f
, "cyclic type of infinite size"),
91 Mismatch
=> write
!(f
, "types differ"),
92 UnsafetyMismatch(values
) => {
93 write
!(f
, "expected {} fn, found {} fn",
97 AbiMismatch(values
) => {
98 write
!(f
, "expected {} fn, found {} fn",
102 Mutability
=> write
!(f
, "types differ in mutability"),
103 TupleSize(values
) => {
104 write
!(f
, "expected a tuple with {} element{}, \
105 found one with {} element{}",
107 pluralize
!(values
.expected
),
109 pluralize
!(values
.found
))
111 FixedArraySize(values
) => {
112 write
!(f
, "expected an array with a fixed size of {} element{}, \
113 found one with {} element{}",
115 pluralize
!(values
.expected
),
117 pluralize
!(values
.found
))
120 write
!(f
, "incorrect number of function parameters")
122 RegionsDoesNotOutlive(..) => {
123 write
!(f
, "lifetime mismatch")
125 RegionsInsufficientlyPolymorphic(br
, _
) => {
127 "expected bound lifetime parameter{}, found concrete lifetime",
130 RegionsOverlyPolymorphic(br
, _
) => {
132 "expected concrete lifetime, found bound lifetime parameter{}",
135 RegionsPlaceholderMismatch
=> {
136 write
!(f
, "one type is more general than the other")
138 Sorts(values
) => ty
::tls
::with(|tcx
| {
139 report_maybe_different(f
, &values
.expected
.sort_string(tcx
),
140 &values
.found
.sort_string(tcx
))
142 Traits(values
) => ty
::tls
::with(|tcx
| {
143 report_maybe_different(f
,
144 &format
!("trait `{}`",
145 tcx
.def_path_str(values
.expected
)),
146 &format
!("trait `{}`",
147 tcx
.def_path_str(values
.found
)))
149 IntMismatch(ref values
) => {
150 write
!(f
, "expected `{:?}`, found `{:?}`",
154 FloatMismatch(ref values
) => {
155 write
!(f
, "expected `{:?}`, found `{:?}`",
159 VariadicMismatch(ref values
) => {
160 write
!(f
, "expected {} fn, found {} function",
161 if values
.expected { "variadic" }
else { "non-variadic" }
,
162 if values
.found { "variadic" }
else { "non-variadic" }
)
164 ProjectionMismatched(ref values
) => ty
::tls
::with(|tcx
| {
165 write
!(f
, "expected {}, found {}",
166 tcx
.def_path_str(values
.expected
),
167 tcx
.def_path_str(values
.found
))
169 ProjectionBoundsLength(ref values
) => {
170 write
!(f
, "expected {} associated type binding{}, found {}",
172 pluralize
!(values
.expected
),
175 ExistentialMismatch(ref values
) => {
176 report_maybe_different(f
, &format
!("trait `{}`", values
.expected
),
177 &format
!("trait `{}`", values
.found
))
179 ConstMismatch(ref values
) => {
180 write
!(f
, "expected `{}`, found `{}`", values
.expected
, values
.found
)
183 write
!(f
, "cannot coerce intrinsics to function pointers")
185 ObjectUnsafeCoercion(_
) => write
!(f
, "coercion to object-unsafe trait object"),
190 impl<'tcx
> TypeError
<'tcx
> {
191 pub fn must_include_note(&self) -> bool
{
192 use self::TypeError
::*;
195 UnsafetyMismatch(_
) |
202 VariadicMismatch(_
) => false,
207 RegionsDoesNotOutlive(..) |
208 RegionsInsufficientlyPolymorphic(..) |
209 RegionsOverlyPolymorphic(..) |
210 RegionsPlaceholderMismatch
|
212 ProjectionMismatched(_
) |
213 ProjectionBoundsLength(_
) |
214 ExistentialMismatch(_
) |
217 ObjectUnsafeCoercion(_
) => true,
222 impl<'tcx
> ty
::TyS
<'tcx
> {
223 pub fn sort_string(&self, tcx
: TyCtxt
<'_
>) -> Cow
<'
static, str> {
225 ty
::Bool
| ty
::Char
| ty
::Int(_
) |
226 ty
::Uint(_
) | ty
::Float(_
) | ty
::Str
| ty
::Never
=> format
!("`{}`", self).into(),
227 ty
::Tuple(ref tys
) if tys
.is_empty() => format
!("`{}`", self).into(),
229 ty
::Adt(def
, _
) => format
!("{} `{}`", def
.descr(), tcx
.def_path_str(def
.did
)).into(),
230 ty
::Foreign(def_id
) => format
!("extern type `{}`", tcx
.def_path_str(def_id
)).into(),
232 let n
= tcx
.lift(&n
).unwrap();
233 match n
.try_eval_usize(tcx
, ty
::ParamEnv
::empty()) {
234 _
if t
.is_simple_ty() => format
!("array `{}`", self).into(),
235 Some(n
) => format
!("array of {} element{} ", n
, pluralize
!(n
)).into(),
236 None
=> "array".into(),
239 ty
::Slice(ty
) if ty
.is_simple_ty() => format
!("slice `{}`", self).into(),
240 ty
::Slice(_
) => "slice".into(),
241 ty
::RawPtr(_
) => "*-ptr".into(),
242 ty
::Ref(_
, ty
, mutbl
) => {
243 let tymut
= ty
::TypeAndMut { ty, mutbl }
;
244 let tymut_string
= tymut
.to_string();
245 if tymut_string
!= "_" && (
246 ty
.is_simple_text() || tymut_string
.len() < "mutable reference".len()
248 format
!("`&{}`", tymut_string
).into()
249 } else { // Unknown type name, it's long or has type arguments
251 hir
::Mutability
::Mutable
=> "mutable reference",
256 ty
::FnDef(..) => "fn item".into(),
257 ty
::FnPtr(_
) => "fn pointer".into(),
258 ty
::Dynamic(ref inner
, ..) => {
259 if let Some(principal
) = inner
.principal() {
260 format
!("trait `{}`", tcx
.def_path_str(principal
.def_id())).into()
265 ty
::Closure(..) => "closure".into(),
266 ty
::Generator(..) => "generator".into(),
267 ty
::GeneratorWitness(..) => "generator witness".into(),
268 ty
::Tuple(..) => "tuple".into(),
269 ty
::Infer(ty
::TyVar(_
)) => "inferred type".into(),
270 ty
::Infer(ty
::IntVar(_
)) => "integer".into(),
271 ty
::Infer(ty
::FloatVar(_
)) => "floating-point number".into(),
272 ty
::Placeholder(..) => "placeholder type".into(),
273 ty
::Bound(..) => "bound type".into(),
274 ty
::Infer(ty
::FreshTy(_
)) => "fresh type".into(),
275 ty
::Infer(ty
::FreshIntTy(_
)) => "fresh integral type".into(),
276 ty
::Infer(ty
::FreshFloatTy(_
)) => "fresh floating-point type".into(),
277 ty
::Projection(_
) => "associated type".into(),
278 ty
::UnnormalizedProjection(_
) => "non-normalized associated type".into(),
279 ty
::Param(p
) => format
!("type parameter `{}`", p
).into(),
280 ty
::Opaque(..) => "opaque type".into(),
281 ty
::Error
=> "type error".into(),
285 pub fn prefix_string(&self) -> Cow
<'
static, str> {
287 ty
::Infer(_
) | ty
::Error
| ty
::Bool
| ty
::Char
| ty
::Int(_
) |
288 ty
::Uint(_
) | ty
::Float(_
) | ty
::Str
| ty
::Never
=> "type".into(),
289 ty
::Tuple(ref tys
) if tys
.is_empty() => "unit type".into(),
290 ty
::Adt(def
, _
) => def
.descr().into(),
291 ty
::Foreign(_
) => "extern type".into(),
292 ty
::Array(..) => "array".into(),
293 ty
::Slice(_
) => "slice".into(),
294 ty
::RawPtr(_
) => "raw pointer".into(),
295 ty
::Ref(.., mutbl
) => match mutbl
{
296 hir
::Mutability
::Mutable
=> "mutable reference",
299 ty
::FnDef(..) => "fn item".into(),
300 ty
::FnPtr(_
) => "fn pointer".into(),
301 ty
::Dynamic(..) => "trait object".into(),
302 ty
::Closure(..) => "closure".into(),
303 ty
::Generator(..) => "generator".into(),
304 ty
::GeneratorWitness(..) => "generator witness".into(),
305 ty
::Tuple(..) => "tuple".into(),
306 ty
::Placeholder(..) => "higher-ranked type".into(),
307 ty
::Bound(..) => "bound type variable".into(),
308 ty
::Projection(_
) => "associated type".into(),
309 ty
::UnnormalizedProjection(_
) => "associated type".into(),
310 ty
::Param(_
) => "type parameter".into(),
311 ty
::Opaque(..) => "opaque type".into(),
316 impl<'tcx
> TyCtxt
<'tcx
> {
317 pub fn note_and_explain_type_err(
319 db
: &mut DiagnosticBuilder
<'_
>,
320 err
: &TypeError
<'tcx
>,
322 body_owner_def_id
: DefId
,
324 use self::TypeError
::*;
328 let expected_str
= values
.expected
.sort_string(self);
329 let found_str
= values
.found
.sort_string(self);
330 if expected_str
== found_str
&& expected_str
== "closure" {
331 db
.note("no two closures, even if identical, have the same type");
332 db
.help("consider boxing your closure and/or using it as a trait object");
334 if expected_str
== found_str
&& expected_str
== "opaque type" { // Issue #63167
335 db
.note("distinct uses of `impl Trait` result in different opaque types");
336 let e_str
= values
.expected
.to_string();
337 let f_str
= values
.found
.to_string();
338 if &e_str
== &f_str
&& &e_str
== "impl std::future::Future" {
339 // FIXME: use non-string based check.
340 db
.help("if both `Future`s have the same `Output` type, consider \
341 `.await`ing on both of them");
344 match (&values
.expected
.kind
, &values
.found
.kind
) {
345 (ty
::Float(_
), ty
::Infer(ty
::IntVar(_
))) => if let Ok( // Issue #53280
347 ) = self.sess
.source_map().span_to_snippet(sp
) {
348 if snippet
.chars().all(|c
| c
.is_digit(10) || c
== '
-'
|| c
== '_'
) {
351 "use a float literal",
352 format
!("{}.0", snippet
),
353 Applicability
::MachineApplicable
357 (ty
::Param(expected
), ty
::Param(found
)) => {
358 let generics
= self.generics_of(body_owner_def_id
);
359 let e_span
= self.def_span(generics
.type_param(expected
, self).def_id
);
360 if !sp
.contains(e_span
) {
361 db
.span_label(e_span
, "expected type parameter");
363 let f_span
= self.def_span(generics
.type_param(found
, self).def_id
);
364 if !sp
.contains(f_span
) {
365 db
.span_label(f_span
, "found type parameter");
367 db
.note("a type parameter was expected, but a different one was found; \
368 you might be missing a type parameter or trait bound");
369 db
.note("for more information, visit \
370 https://doc.rust-lang.org/book/ch10-02-traits.html\
371 #traits-as-parameters");
373 (ty
::Projection(_
), ty
::Projection(_
)) => {
374 db
.note("an associated type was expected, but a different one was found");
376 (ty
::Param(_
), ty
::Projection(_
)) | (ty
::Projection(_
), ty
::Param(_
)) => {
377 db
.note("you might be missing a type parameter or trait bound");
379 (ty
::Param(p
), _
) | (_
, ty
::Param(p
)) => {
380 let generics
= self.generics_of(body_owner_def_id
);
381 let p_span
= self.def_span(generics
.type_param(p
, self).def_id
);
382 if !sp
.contains(p_span
) {
383 db
.span_label(p_span
, "this type parameter");
385 db
.help("type parameters must be constrained to match other types");
386 if self.sess
.teach(&db
.get_code().unwrap()) {
387 db
.help("given a type parameter `T` and a method `foo`:
389 trait Trait<T> { fn foo(&self) -> T; }
391 the only ways to implement method `foo` are:
392 - constrain `T` with an explicit type:
394 impl Trait<String> for X {
395 fn foo(&self) -> String { String::new() }
398 - add a trait bound to `T` and call a method on that trait that returns `Self`:
400 impl<T: std::default::Default> Trait<T> for X {
401 fn foo(&self) -> T { <T as std::default::Default>::default() }
404 - change `foo` to return an argument of type `T`:
406 impl<T> Trait<T> for X {
407 fn foo(&self, x: T) -> T { x }
411 db
.note("for more information, visit \
412 https://doc.rust-lang.org/book/ch10-02-traits.html\
413 #traits-as-parameters");
415 (ty
::Projection(_
), _
) => {
417 "consider constraining the associated type `{}` to `{}` or calling a \
418 method that returns `{}`",
423 if self.sess
.teach(&db
.get_code().unwrap()) {
424 db
.help("given an associated type `T` and a method `foo`:
428 fn foo(&self) -> Self::T;
431 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
435 fn foo(&self) -> Self::T { String::new() }
439 db
.note("for more information, visit \
440 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
442 (_
, ty
::Projection(_
)) => {
444 "consider constraining the associated type `{}` to `{}`",
448 db
.note("for more information, visit \
449 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html");
454 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
456 values
.expected
.kind
,
462 // Watch out for various cases of cyclic types and try to explain.
463 if ty
.is_closure() || ty
.is_generator() {
464 db
.note("closures cannot capture themselves or take themselves as argument;\n\
465 this error may be the result of a recent compiler bug-fix,\n\
466 see https://github.com/rust-lang/rust/issues/46062 for more details");