1 use crate::hir::def_id::DefId;
2 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
5 use rustc_target::spec::abi;
7 use errors::{Applicability, DiagnosticBuilder};
12 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
13 pub struct ExpectedFound<T> {
18 // Data structures used in type unification
19 #[derive(Clone, Debug)]
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>>>),
48 ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
51 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
52 pub enum UnconstrainedNumeric {
58 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
59 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
60 /// afterwards to present additional details, particularly when it comes to lifetime-related
62 impl<'tcx> fmt::Display for TypeError<'tcx> {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 use self::TypeError::*;
65 fn report_maybe_different(f: &mut fmt::Formatter<'_>,
66 expected: &str, found: &str) -> fmt::Result {
67 // A naive approach to making sure that we're not reporting silly errors such as:
68 // (expected closure, found closure).
69 if expected == found {
70 write!(f, "expected {}, found a different {}", expected, found)
72 write!(f, "expected {}, found {}", expected, found)
76 let br_string = |br: ty::BoundRegion| {
78 ty::BrNamed(_, name) => format!(" {}", name),
83 macro_rules! pluralise {
85 if $x != 1 { "s" } else { "" }
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 pluralise!(values.expected),
109 pluralise!(values.found))
111 FixedArraySize(values) => {
112 write!(f, "expected an array with a fixed size of {} element{}, \
113 found one with {} element{}",
115 pluralise!(values.expected),
117 pluralise!(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 pluralise!(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)
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_to_global(&n).unwrap();
197 match n.assert_usize(tcx) {
198 Some(n) => format!("array of {} elements", n).into(),
199 None => "array".into(),
202 ty::Slice(_) => "slice".into(),
203 ty::RawPtr(_) => "*-ptr".into(),
204 ty::Ref(region, ty, mutbl) => {
205 let tymut = ty::TypeAndMut { ty, mutbl };
206 let tymut_string = tymut.to_string();
207 if tymut_string == "_" || //unknown type name,
208 tymut_string.len() > 10 || //name longer than saying "reference",
209 region.to_string() != "'_" //... or a complex type
211 format!("{}reference", match mutbl {
212 hir::Mutability::MutMutable => "mutable ",
216 format!("&{}", tymut_string).into()
219 ty::FnDef(..) => "fn item".into(),
220 ty::FnPtr(_) => "fn pointer".into(),
221 ty::Dynamic(ref inner, ..) => {
222 if let Some(principal) = inner.principal() {
223 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
228 ty::Closure(..) => "closure".into(),
229 ty::Generator(..) => "generator".into(),
230 ty::GeneratorWitness(..) => "generator witness".into(),
231 ty::Tuple(..) => "tuple".into(),
232 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
233 ty::Infer(ty::IntVar(_)) => "integer".into(),
234 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
235 ty::Placeholder(..) => "placeholder type".into(),
236 ty::Bound(..) => "bound type".into(),
237 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
238 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
239 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
240 ty::Projection(_) => "associated type".into(),
241 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
242 ty::Param(ref p) => {
246 "type parameter".into()
249 ty::Opaque(..) => "opaque type".into(),
250 ty::Error => "type error".into(),
255 impl<'tcx> TyCtxt<'tcx> {
256 pub fn note_and_explain_type_err(self,
257 db: &mut DiagnosticBuilder<'_>,
258 err: &TypeError<'tcx>,
260 use self::TypeError::*;
264 let expected_str = values.expected.sort_string(self);
265 let found_str = values.found.sort_string(self);
266 if expected_str == found_str && expected_str == "closure" {
267 db.note("no two closures, even if identical, have the same type");
268 db.help("consider boxing your closure and/or using it as a trait object");
270 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
271 (&values.found.sty, &values.expected.sty) // Issue #53280
273 if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
274 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
277 "use a float literal",
278 format!("{}.0", snippet),
279 Applicability::MachineApplicable
286 // Watch out for various cases of cyclic types and try to explain.
287 if ty.is_closure() || ty.is_generator() {
288 db.note("closures cannot capture themselves or take themselves as argument;\n\
289 this error may be the result of a recent compiler bug-fix,\n\
290 see https://github.com/rust-lang/rust/issues/46062 for more details");