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),
84 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
85 Mismatch => write!(f, "types differ"),
86 UnsafetyMismatch(values) => {
87 write!(f, "expected {} fn, found {} fn",
91 AbiMismatch(values) => {
92 write!(f, "expected {} fn, found {} fn",
96 Mutability => write!(f, "types differ in mutability"),
97 FixedArraySize(values) => {
98 write!(f, "expected an array with a fixed size of {} elements, \
99 found one with {} elements",
103 TupleSize(values) => {
104 write!(f, "expected a tuple with {} elements, \
105 found one with {} elements",
110 write!(f, "incorrect number of function parameters")
112 RegionsDoesNotOutlive(..) => {
113 write!(f, "lifetime mismatch")
115 RegionsInsufficientlyPolymorphic(br, _) => {
117 "expected bound lifetime parameter{}, found concrete lifetime",
120 RegionsOverlyPolymorphic(br, _) => {
122 "expected concrete lifetime, found bound lifetime parameter{}",
125 RegionsPlaceholderMismatch => {
126 write!(f, "one type is more general than the other")
128 Sorts(values) => ty::tls::with(|tcx| {
129 report_maybe_different(f, &values.expected.sort_string(tcx),
130 &values.found.sort_string(tcx))
132 Traits(values) => ty::tls::with(|tcx| {
133 report_maybe_different(f,
134 &format!("trait `{}`",
135 tcx.def_path_str(values.expected)),
136 &format!("trait `{}`",
137 tcx.def_path_str(values.found)))
139 IntMismatch(ref values) => {
140 write!(f, "expected `{:?}`, found `{:?}`",
144 FloatMismatch(ref values) => {
145 write!(f, "expected `{:?}`, found `{:?}`",
149 VariadicMismatch(ref values) => {
150 write!(f, "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| {
155 write!(f, "expected {}, found {}",
156 tcx.def_path_str(values.expected),
157 tcx.def_path_str(values.found))
159 ProjectionBoundsLength(ref values) => {
160 write!(f, "expected {} associated type bindings, found {}",
164 ExistentialMismatch(ref values) => {
165 report_maybe_different(f, &format!("trait `{}`", values.expected),
166 &format!("trait `{}`", values.found))
168 ConstMismatch(ref values) => {
169 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
175 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
176 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
178 ty::Bool | ty::Char | ty::Int(_) |
179 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
180 ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
182 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
183 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
184 ty::Array(_, n) => match n.assert_usize(tcx) {
185 Some(n) => format!("array of {} elements", n).into(),
186 None => "array".into(),
188 ty::Slice(_) => "slice".into(),
189 ty::RawPtr(_) => "*-ptr".into(),
190 ty::Ref(region, ty, mutbl) => {
191 let tymut = ty::TypeAndMut { ty, mutbl };
192 let tymut_string = tymut.to_string();
193 if tymut_string == "_" || //unknown type name,
194 tymut_string.len() > 10 || //name longer than saying "reference",
195 region.to_string() != "'_" //... or a complex type
197 format!("{}reference", match mutbl {
198 hir::Mutability::MutMutable => "mutable ",
202 format!("&{}", tymut_string).into()
205 ty::FnDef(..) => "fn item".into(),
206 ty::FnPtr(_) => "fn pointer".into(),
207 ty::Dynamic(ref inner, ..) => {
208 if let Some(principal) = inner.principal() {
209 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
214 ty::Closure(..) => "closure".into(),
215 ty::Generator(..) => "generator".into(),
216 ty::GeneratorWitness(..) => "generator witness".into(),
217 ty::Tuple(..) => "tuple".into(),
218 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
219 ty::Infer(ty::IntVar(_)) => "integer".into(),
220 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
221 ty::Placeholder(..) => "placeholder type".into(),
222 ty::Bound(..) => "bound type".into(),
223 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
224 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
225 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
226 ty::Projection(_) => "associated type".into(),
227 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
228 ty::Param(ref p) => {
232 "type parameter".into()
235 ty::Opaque(..) => "opaque type".into(),
236 ty::Error => "type error".into(),
241 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
242 pub fn note_and_explain_type_err(self,
243 db: &mut DiagnosticBuilder<'_>,
244 err: &TypeError<'tcx>,
246 use self::TypeError::*;
250 let expected_str = values.expected.sort_string(self);
251 let found_str = values.found.sort_string(self);
252 if expected_str == found_str && expected_str == "closure" {
253 db.note("no two closures, even if identical, have the same type");
254 db.help("consider boxing your closure and/or using it as a trait object");
256 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
257 (&values.found.sty, &values.expected.sty) // Issue #53280
259 if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
260 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
263 "use a float literal",
264 format!("{}.0", snippet),
265 Applicability::MachineApplicable
272 // Watch out for various cases of cyclic types and try to explain.
273 if ty.is_closure() || ty.is_generator() {
274 db.note("closures cannot capture themselves or take themselves as argument;\n\
275 this error may be the result of a recent compiler bug-fix,\n\
276 see https://github.com/rust-lang/rust/issues/46062 for more details");