]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Run `rustfmt --file-lines ...` for changes from previous commits.
[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     ConstMismatch(ExpectedFound<&'tcx ty::Const<'tcx>>),
49 }
50
51 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
52 pub enum UnconstrainedNumeric {
53     UnconstrainedFloat,
54     UnconstrainedInt,
55     Neither,
56 }
57
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
61 /// errors.
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)
71             } else {
72                 write!(f, "expected {}, found {}", expected, found)
73             }
74         }
75
76         let br_string = |br: ty::BoundRegion| {
77             match br {
78                 ty::BrNamed(_, name) => format!(" {}", name),
79                 _ => String::new(),
80             }
81         };
82
83         macro_rules! pluralise {
84             ($x:expr) => {
85                 if $x != 1 { "s" } else { "" }
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             TupleSize(values) => {
104                 write!(f, "expected a tuple with {} element{}, \
105                            found one with {} element{}",
106                        values.expected,
107                        pluralise!(values.expected),
108                        values.found,
109                        pluralise!(values.found))
110             }
111             FixedArraySize(values) => {
112                 write!(f, "expected an array with a fixed size of {} element{}, \
113                            found one with {} element{}",
114                        values.expected,
115                        pluralise!(values.expected),
116                        values.found,
117                        pluralise!(values.found))
118             }
119             ArgCount => {
120                 write!(f, "incorrect number of function parameters")
121             }
122             RegionsDoesNotOutlive(..) => {
123                 write!(f, "lifetime mismatch")
124             }
125             RegionsInsufficientlyPolymorphic(br, _) => {
126                 write!(f,
127                        "expected bound lifetime parameter{}, found concrete lifetime",
128                        br_string(br))
129             }
130             RegionsOverlyPolymorphic(br, _) => {
131                 write!(f,
132                        "expected concrete lifetime, found bound lifetime parameter{}",
133                        br_string(br))
134             }
135             RegionsPlaceholderMismatch => {
136                 write!(f, "one type is more general than the other")
137             }
138             Sorts(values) => ty::tls::with(|tcx| {
139                 report_maybe_different(f, &values.expected.sort_string(tcx),
140                                        &values.found.sort_string(tcx))
141             }),
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)))
148             }),
149             IntMismatch(ref values) => {
150                 write!(f, "expected `{:?}`, found `{:?}`",
151                        values.expected,
152                        values.found)
153             }
154             FloatMismatch(ref values) => {
155                 write!(f, "expected `{:?}`, found `{:?}`",
156                        values.expected,
157                        values.found)
158             }
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" })
163             }
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))
168             }),
169             ProjectionBoundsLength(ref values) => {
170                 write!(f, "expected {} associated type binding{}, found {}",
171                        values.expected,
172                        pluralise!(values.expected),
173                        values.found)
174             },
175             ExistentialMismatch(ref values) => {
176                 report_maybe_different(f, &format!("trait `{}`", values.expected),
177                                        &format!("trait `{}`", values.found))
178             }
179             ConstMismatch(ref values) => {
180                 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
181             }
182         }
183     }
184 }
185
186 impl<'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
187     pub fn sort_string(&self, tcx: TyCtxt<'gcx, 'lcx>) -> Cow<'static, str> {
188         match self.sty {
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(),
192
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(),
195             ty::Array(_, n) => match n.assert_usize(tcx) {
196                 Some(n) => format!("array of {} elements", n).into(),
197                 None => "array".into(),
198             }
199             ty::Slice(_) => "slice".into(),
200             ty::RawPtr(_) => "*-ptr".into(),
201             ty::Ref(region, ty, mutbl) => {
202                 let tymut = ty::TypeAndMut { ty, mutbl };
203                 let tymut_string = tymut.to_string();
204                 if tymut_string == "_" ||         //unknown type name,
205                    tymut_string.len() > 10 ||     //name longer than saying "reference",
206                    region.to_string() != "'_"     //... or a complex type
207                 {
208                     format!("{}reference", match mutbl {
209                         hir::Mutability::MutMutable => "mutable ",
210                         _ => ""
211                     }).into()
212                 } else {
213                     format!("&{}", tymut_string).into()
214                 }
215             }
216             ty::FnDef(..) => "fn item".into(),
217             ty::FnPtr(_) => "fn pointer".into(),
218             ty::Dynamic(ref inner, ..) => {
219                 if let Some(principal) = inner.principal() {
220                     format!("trait {}", tcx.def_path_str(principal.def_id())).into()
221                 } else {
222                     "trait".into()
223                 }
224             }
225             ty::Closure(..) => "closure".into(),
226             ty::Generator(..) => "generator".into(),
227             ty::GeneratorWitness(..) => "generator witness".into(),
228             ty::Tuple(..) => "tuple".into(),
229             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
230             ty::Infer(ty::IntVar(_)) => "integer".into(),
231             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
232             ty::Placeholder(..) => "placeholder type".into(),
233             ty::Bound(..) => "bound type".into(),
234             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
235             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
236             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
237             ty::Projection(_) => "associated type".into(),
238             ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
239             ty::Param(ref p) => {
240                 if p.is_self() {
241                     "Self".into()
242                 } else {
243                     "type parameter".into()
244                 }
245             }
246             ty::Opaque(..) => "opaque type".into(),
247             ty::Error => "type error".into(),
248         }
249     }
250 }
251
252 impl<'gcx, 'tcx> TyCtxt<'gcx, 'tcx> {
253     pub fn note_and_explain_type_err(self,
254                                      db: &mut DiagnosticBuilder<'_>,
255                                      err: &TypeError<'tcx>,
256                                      sp: Span) {
257         use self::TypeError::*;
258
259         match err.clone() {
260             Sorts(values) => {
261                 let expected_str = values.expected.sort_string(self);
262                 let found_str = values.found.sort_string(self);
263                 if expected_str == found_str && expected_str == "closure" {
264                     db.note("no two closures, even if identical, have the same type");
265                     db.help("consider boxing your closure and/or using it as a trait object");
266                 }
267                 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
268                        (&values.found.sty, &values.expected.sty) // Issue #53280
269                 {
270                     if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
271                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
272                             db.span_suggestion(
273                                 sp,
274                                 "use a float literal",
275                                 format!("{}.0", snippet),
276                                 Applicability::MachineApplicable
277                             );
278                         }
279                     }
280                 }
281             },
282             CyclicTy(ty) => {
283                 // Watch out for various cases of cyclic types and try to explain.
284                 if ty.is_closure() || ty.is_generator() {
285                     db.note("closures cannot capture themselves or take themselves as argument;\n\
286                              this error may be the result of a recent compiler bug-fix,\n\
287                              see https://github.com/rust-lang/rust/issues/46062 for more details");
288                 }
289             }
290             _ => {}
291         }
292     }
293 }