]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Add `ConstError`
[rust.git] / src / librustc / ty / error.rs
1 use crate::hir::def_id::DefId;
2 use crate::ty::{self, BoundRegion, Region, Ty, TyCtxt};
3 use std::borrow::Cow;
4 use std::fmt;
5 use rustc_target::spec::abi;
6 use syntax::ast;
7 use errors::{Applicability, DiagnosticBuilder};
8 use syntax_pos::Span;
9
10 use crate::hir;
11
12 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
13 pub struct ExpectedFound<T> {
14     pub expected: T,
15     pub found: T,
16 }
17
18 // Data structures used in type unification
19 #[derive(Clone, Debug)]
20 pub enum TypeError<'tcx> {
21     Mismatch,
22     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
23     AbiMismatch(ExpectedFound<abi::Abi>),
24     Mutability,
25     TupleSize(ExpectedFound<usize>),
26     FixedArraySize(ExpectedFound<u64>),
27     ArgCount,
28
29     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
30     RegionsInsufficientlyPolymorphic(BoundRegion, Region<'tcx>),
31     RegionsOverlyPolymorphic(BoundRegion, Region<'tcx>),
32     RegionsPlaceholderMismatch,
33
34     Sorts(ExpectedFound<Ty<'tcx>>),
35     IntMismatch(ExpectedFound<ty::IntVarValue>),
36     FloatMismatch(ExpectedFound<ast::FloatTy>),
37     Traits(ExpectedFound<DefId>),
38     VariadicMismatch(ExpectedFound<bool>),
39
40     /// Instantiating a type variable with the given type would have
41     /// created a cycle (because it appears somewhere within that
42     /// type).
43     CyclicTy(Ty<'tcx>),
44     ProjectionMismatched(ExpectedFound<DefId>),
45     ProjectionBoundsLength(ExpectedFound<usize>),
46     ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>),
47
48     ConstError(ConstError<'tcx>),
49 }
50
51 // Data structure used in const unification
52 #[derive(Clone, Debug)]
53 pub enum ConstError<'tcx> {
54     Mismatch(ExpectedFound<&'tcx ty::LazyConst<'tcx>>),
55 }
56
57 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
58 pub enum UnconstrainedNumeric {
59     UnconstrainedFloat,
60     UnconstrainedInt,
61     Neither,
62 }
63
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
67 /// errors.
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)
77             } else {
78                 write!(f, "expected {}, found {}", expected, found)
79             }
80         }
81
82         let br_string = |br: ty::BoundRegion| {
83             match br {
84                 ty::BrNamed(_, name) => format!(" {}", name),
85                 _ => String::new(),
86             }
87         };
88
89         match *self {
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",
94                        values.expected,
95                        values.found)
96             }
97             AbiMismatch(values) => {
98                 write!(f, "expected {} fn, found {} fn",
99                        values.expected,
100                        values.found)
101             }
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",
106                        values.expected,
107                        values.found)
108             }
109             TupleSize(values) => {
110                 write!(f, "expected a tuple with {} elements, \
111                            found one with {} elements",
112                        values.expected,
113                        values.found)
114             }
115             ArgCount => {
116                 write!(f, "incorrect number of function parameters")
117             }
118             RegionsDoesNotOutlive(..) => {
119                 write!(f, "lifetime mismatch")
120             }
121             RegionsInsufficientlyPolymorphic(br, _) => {
122                 write!(f,
123                        "expected bound lifetime parameter{}, found concrete lifetime",
124                        br_string(br))
125             }
126             RegionsOverlyPolymorphic(br, _) => {
127                 write!(f,
128                        "expected concrete lifetime, found bound lifetime parameter{}",
129                        br_string(br))
130             }
131             RegionsPlaceholderMismatch => {
132                 write!(f, "one type is more general than the other")
133             }
134             Sorts(values) => ty::tls::with(|tcx| {
135                 report_maybe_different(f, &values.expected.sort_string(tcx),
136                                        &values.found.sort_string(tcx))
137             }),
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)))
144             }),
145             IntMismatch(ref values) => {
146                 write!(f, "expected `{:?}`, found `{:?}`",
147                        values.expected,
148                        values.found)
149             }
150             FloatMismatch(ref values) => {
151                 write!(f, "expected `{:?}`, found `{:?}`",
152                        values.expected,
153                        values.found)
154             }
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" })
159             }
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))
164             }),
165             ProjectionBoundsLength(ref values) => {
166                 write!(f, "expected {} associated type bindings, found {}",
167                        values.expected,
168                        values.found)
169             },
170             ExistentialMismatch(ref values) => {
171                 report_maybe_different(f, &format!("trait `{}`", values.expected),
172                                        &format!("trait `{}`", values.found))
173             }
174             ConstError(ref err) => {
175                 write!(f, "{}", err)
176             }
177         }
178     }
179 }
180
181 impl<'tcx> fmt::Display for ConstError<'tcx> {
182     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183         use self::ConstError::*;
184
185         match *self {
186             Mismatch(ref values) => {
187                 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
188             }
189         }
190     }
191 }
192
193 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
194     pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
195         match self.sty {
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(),
199
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(),
205             }
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
214                 {
215                     format!("{}reference", match mutbl {
216                         hir::Mutability::MutMutable => "mutable ",
217                         _ => ""
218                     }).into()
219                 } else {
220                     format!("&{}", tymut_string).into()
221                 }
222             }
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()
228                 } else {
229                     "trait".into()
230                 }
231             }
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) => {
247                 if p.is_self() {
248                     "Self".into()
249                 } else {
250                     "type parameter".into()
251                 }
252             }
253             ty::Opaque(..) => "opaque type".into(),
254             ty::Error => "type error".into(),
255         }
256     }
257 }
258
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>,
263                                      sp: Span) {
264         use self::TypeError::*;
265
266         match err.clone() {
267             Sorts(values) => {
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");
273                 }
274                 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
275                        (&values.found.sty, &values.expected.sty) // Issue #53280
276                 {
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 == '_') {
279                             db.span_suggestion(
280                                 sp,
281                                 "use a float literal",
282                                 format!("{}.0", snippet),
283                                 Applicability::MachineApplicable
284                             );
285                         }
286                     }
287                 }
288             },
289             CyclicTy(ty) => {
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");
295                 }
296             }
297             _ => {}
298         }
299     }
300 }