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>>>),
49 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
50 pub enum UnconstrainedNumeric {
56 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
57 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
58 /// afterwards to present additional details, particularly when it comes to lifetime-related
60 impl<'tcx> fmt::Display for TypeError<'tcx> {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 use self::TypeError::*;
63 fn report_maybe_different(f: &mut fmt::Formatter<'_>,
64 expected: &str, found: &str) -> fmt::Result {
65 // A naive approach to making sure that we're not reporting silly errors such as:
66 // (expected closure, found closure).
67 if expected == found {
68 write!(f, "expected {}, found a different {}", expected, found)
70 write!(f, "expected {}, found {}", expected, found)
74 let br_string = |br: ty::BoundRegion| {
76 ty::BrNamed(_, name) => format!(" {}", name),
82 CyclicTy(_) => write!(f, "cyclic type of infinite size"),
83 Mismatch => write!(f, "types differ"),
84 UnsafetyMismatch(values) => {
85 write!(f, "expected {} fn, found {} fn",
89 AbiMismatch(values) => {
90 write!(f, "expected {} fn, found {} fn",
94 Mutability => write!(f, "types differ in mutability"),
95 FixedArraySize(values) => {
96 write!(f, "expected an array with a fixed size of {} elements, \
97 found one with {} elements",
101 TupleSize(values) => {
102 write!(f, "expected a tuple with {} elements, \
103 found one with {} elements",
108 write!(f, "incorrect number of function parameters")
110 RegionsDoesNotOutlive(..) => {
111 write!(f, "lifetime mismatch")
113 RegionsInsufficientlyPolymorphic(br, _) => {
115 "expected bound lifetime parameter{}, found concrete lifetime",
118 RegionsOverlyPolymorphic(br, _) => {
120 "expected concrete lifetime, found bound lifetime parameter{}",
123 RegionsPlaceholderMismatch => {
124 write!(f, "one type is more general than the other")
126 Sorts(values) => ty::tls::with(|tcx| {
127 report_maybe_different(f, &values.expected.sort_string(tcx),
128 &values.found.sort_string(tcx))
130 Traits(values) => ty::tls::with(|tcx| {
131 report_maybe_different(f,
132 &format!("trait `{}`",
133 tcx.def_path_str(values.expected)),
134 &format!("trait `{}`",
135 tcx.def_path_str(values.found)))
137 IntMismatch(ref values) => {
138 write!(f, "expected `{:?}`, found `{:?}`",
142 FloatMismatch(ref values) => {
143 write!(f, "expected `{:?}`, found `{:?}`",
147 VariadicMismatch(ref values) => {
148 write!(f, "expected {} fn, found {} function",
149 if values.expected { "variadic" } else { "non-variadic" },
150 if values.found { "variadic" } else { "non-variadic" })
152 ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
153 write!(f, "expected {}, found {}",
154 tcx.def_path_str(values.expected),
155 tcx.def_path_str(values.found))
157 ProjectionBoundsLength(ref values) => {
158 write!(f, "expected {} associated type bindings, found {}",
162 ExistentialMismatch(ref values) => {
163 report_maybe_different(f, &format!("trait `{}`", values.expected),
164 &format!("trait `{}`", values.found))
170 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
171 pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
173 ty::Bool | ty::Char | ty::Int(_) |
174 ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
175 ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
177 ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
178 ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
179 ty::Array(_, n) => match n.assert_usize(tcx) {
180 Some(n) => format!("array of {} elements", n).into(),
181 None => "array".into(),
183 ty::Slice(_) => "slice".into(),
184 ty::RawPtr(_) => "*-ptr".into(),
185 ty::Ref(region, ty, mutbl) => {
186 let tymut = ty::TypeAndMut { ty, mutbl };
187 let tymut_string = tymut.to_string();
188 if tymut_string == "_" || //unknown type name,
189 tymut_string.len() > 10 || //name longer than saying "reference",
190 region.to_string() != "'_" //... or a complex type
192 format!("{}reference", match mutbl {
193 hir::Mutability::MutMutable => "mutable ",
197 format!("&{}", tymut_string).into()
200 ty::FnDef(..) => "fn item".into(),
201 ty::FnPtr(_) => "fn pointer".into(),
202 ty::Dynamic(ref inner, ..) => {
203 if let Some(principal) = inner.principal() {
204 format!("trait {}", tcx.def_path_str(principal.def_id())).into()
209 ty::Closure(..) => "closure".into(),
210 ty::Generator(..) => "generator".into(),
211 ty::GeneratorWitness(..) => "generator witness".into(),
212 ty::Tuple(..) => "tuple".into(),
213 ty::Infer(ty::TyVar(_)) => "inferred type".into(),
214 ty::Infer(ty::IntVar(_)) => "integer".into(),
215 ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
216 ty::Placeholder(..) => "placeholder type".into(),
217 ty::Bound(..) => "bound type".into(),
218 ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
219 ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
220 ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
221 ty::Projection(_) => "associated type".into(),
222 ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
223 ty::Param(ref p) => {
227 "type parameter".into()
230 ty::Opaque(..) => "opaque type".into(),
231 ty::Error => "type error".into(),
236 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
237 pub fn note_and_explain_type_err(self,
238 db: &mut DiagnosticBuilder<'_>,
239 err: &TypeError<'tcx>,
241 use self::TypeError::*;
245 let expected_str = values.expected.sort_string(self);
246 let found_str = values.found.sort_string(self);
247 if expected_str == found_str && expected_str == "closure" {
248 db.note("no two closures, even if identical, have the same type");
249 db.help("consider boxing your closure and/or using it as a trait object");
251 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
252 (&values.found.sty, &values.expected.sty) // Issue #53280
254 if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
255 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
258 "use a float literal",
259 format!("{}.0", snippet),
260 Applicability::MachineApplicable
267 // Watch out for various cases of cyclic types and try to explain.
268 if ty.is_closure() || ty.is_generator() {
269 db.note("closures cannot capture themselves or take themselves as argument;\n\
270 this error may be the result of a recent compiler bug-fix,\n\
271 see https://github.com/rust-lang/rust/issues/46062 for more details");