]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Rollup merge of #60393 - estebank:pat-sugg, r=oli-obk
[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         match *self {
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",
88                        values.expected,
89                        values.found)
90             }
91             AbiMismatch(values) => {
92                 write!(f, "expected {} fn, found {} fn",
93                        values.expected,
94                        values.found)
95             }
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",
100                        values.expected,
101                        values.found)
102             }
103             TupleSize(values) => {
104                 write!(f, "expected a tuple with {} elements, \
105                            found one with {} elements",
106                        values.expected,
107                        values.found)
108             }
109             ArgCount => {
110                 write!(f, "incorrect number of function parameters")
111             }
112             RegionsDoesNotOutlive(..) => {
113                 write!(f, "lifetime mismatch")
114             }
115             RegionsInsufficientlyPolymorphic(br, _) => {
116                 write!(f,
117                        "expected bound lifetime parameter{}, found concrete lifetime",
118                        br_string(br))
119             }
120             RegionsOverlyPolymorphic(br, _) => {
121                 write!(f,
122                        "expected concrete lifetime, found bound lifetime parameter{}",
123                        br_string(br))
124             }
125             RegionsPlaceholderMismatch => {
126                 write!(f, "one type is more general than the other")
127             }
128             Sorts(values) => ty::tls::with(|tcx| {
129                 report_maybe_different(f, &values.expected.sort_string(tcx),
130                                        &values.found.sort_string(tcx))
131             }),
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)))
138             }),
139             IntMismatch(ref values) => {
140                 write!(f, "expected `{:?}`, found `{:?}`",
141                        values.expected,
142                        values.found)
143             }
144             FloatMismatch(ref values) => {
145                 write!(f, "expected `{:?}`, found `{:?}`",
146                        values.expected,
147                        values.found)
148             }
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" })
153             }
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))
158             }),
159             ProjectionBoundsLength(ref values) => {
160                 write!(f, "expected {} associated type bindings, found {}",
161                        values.expected,
162                        values.found)
163             },
164             ExistentialMismatch(ref values) => {
165                 report_maybe_different(f, &format!("trait `{}`", values.expected),
166                                        &format!("trait `{}`", values.found))
167             }
168             ConstMismatch(ref values) => {
169                 write!(f, "expected `{:?}`, found `{:?}`", values.expected, values.found)
170             }
171         }
172     }
173 }
174
175 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
176     pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
177         match self.sty {
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(),
181
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(),
187             }
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
196                 {
197                     format!("{}reference", match mutbl {
198                         hir::Mutability::MutMutable => "mutable ",
199                         _ => ""
200                     }).into()
201                 } else {
202                     format!("&{}", tymut_string).into()
203                 }
204             }
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()
210                 } else {
211                     "trait".into()
212                 }
213             }
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) => {
229                 if p.is_self() {
230                     "Self".into()
231                 } else {
232                     "type parameter".into()
233                 }
234             }
235             ty::Opaque(..) => "opaque type".into(),
236             ty::Error => "type error".into(),
237         }
238     }
239 }
240
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>,
245                                      sp: Span) {
246         use self::TypeError::*;
247
248         match err.clone() {
249             Sorts(values) => {
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");
255                 }
256                 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
257                        (&values.found.sty, &values.expected.sty) // Issue #53280
258                 {
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 == '_') {
261                             db.span_suggestion(
262                                 sp,
263                                 "use a float literal",
264                                 format!("{}.0", snippet),
265                                 Applicability::MachineApplicable
266                             );
267                         }
268                     }
269                 }
270             },
271             CyclicTy(ty) => {
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");
277                 }
278             }
279             _ => {}
280         }
281     }
282 }