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 ConstError(ConstError<'tcx>),
51 // Data structure used in const unification
52 #[derive(Clone, Debug)]
53 pub enum ConstError<'tcx> {
54 Mismatch(ExpectedFound<&'tcx ty::LazyConst<'tcx>>),
57 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
58 pub enum UnconstrainedNumeric {
64 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
65 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
66 /// afterwards to present additional details, particularly when it comes to lifetime-related
68 impl<'tcx> fmt::Display for TypeError<'tcx> {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 use self::TypeError::*;
71 fn report_maybe_different(f: &mut fmt::Formatter<'_>,
72 expected: &str, found: &str) -> fmt::Result {
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 FixedArraySize(values) => {
104 write!(f, "expected an array with a fixed size of {} elements, \
105 found one with {} elements",
109 TupleSize(values) => {
110 write!(f, "expected a tuple with {} elements, \
111 found one with {} elements",
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 bindings, found {}",
170 ExistentialMismatch(ref values) => {
171 report_maybe_different(f, &format!("trait `{}`", values.expected),
172 &format!("trait `{}`", values.found))
174 ConstError(ref err) => {
181 impl<'tcx> fmt::Display for ConstError<'tcx> {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 use self::ConstError::*;
186 Mismatch(ref values) => {
187 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
193 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
194 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
196 ty::Bool | ty::Char | ty::Int(_) |
197 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
198 ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
200 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
201 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
202 ty::Array(_, n) => match n.assert_usize(tcx) {
203 Some(n) => format!("array of {} elements", n).into(),
204 None => "array".into(),
206 ty::Slice(_) => "slice".into(),
207 ty::RawPtr(_) => "*-ptr".into(),
208 ty::Ref(region, ty, mutbl) => {
209 let tymut = ty::TypeAndMut { ty, mutbl };
210 let tymut_string = tymut.to_string();
211 if tymut_string == "_" || //unknown type name,
212 tymut_string.len() > 10 || //name longer than saying "reference",
213 region.to_string() != "'_" //... or a complex type
215 format!("{}reference", match mutbl {
216 hir::Mutability::MutMutable => "mutable ",
220 format!("&{}", tymut_string).into()
223 ty::FnDef(..) => "fn item".into(),
224 ty::FnPtr(_) => "fn pointer".into(),
225 ty::Dynamic(ref inner, ..) => {
226 if let Some(principal) = inner.principal() {
227 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
232 ty::Closure(..) => "closure".into(),
233 ty::Generator(..) => "generator".into(),
234 ty::GeneratorWitness(..) => "generator witness".into(),
235 ty::Tuple(..) => "tuple".into(),
236 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
237 ty::Infer(ty::IntVar(_)) => "integer".into(),
238 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
239 ty::Placeholder(..) => "placeholder type".into(),
240 ty::Bound(..) => "bound type".into(),
241 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
242 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
243 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
244 ty::Projection(_) => "associated type".into(),
245 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
246 ty::Param(ref p) => {
250 "type parameter".into()
253 ty::Opaque(..) => "opaque type".into(),
254 ty::Error => "type error".into(),
259 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
260 pub fn note_and_explain_type_err(self,
261 db: &mut DiagnosticBuilder<'_>,
262 err: &TypeError<'tcx>,
264 use self::TypeError::*;
268 let expected_str = values.expected.sort_string(self);
269 let found_str = values.found.sort_string(self);
270 if expected_str == found_str && expected_str == "closure" {
271 db.note("no two closures, even if identical, have the same type");
272 db.help("consider boxing your closure and/or using it as a trait object");
274 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
275 (&values.found.sty, &values.expected.sty) // Issue #53280
277 if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
278 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
281 "use a float literal",
282 format!("{}.0", snippet),
283 Applicability::MachineApplicable
290 // Watch out for various cases of cyclic types and try to explain.
291 if ty.is_closure() || ty.is_generator() {
292 db.note("closures cannot capture themselves or take themselves as argument;\n\
293 this error may be the result of a recent compiler bug-fix,\n\
294 see https://github.com/rust-lang/rust/issues/46062 for more details");