]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/error.rs
Auto merge of #58972 - QuietMisdreavus:intra-doc-link-imports, r=GuillaumeGomez
[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
49 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
50 pub enum UnconstrainedNumeric {
51     UnconstrainedFloat,
52     UnconstrainedInt,
53     Neither,
54 }
55
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
59 /// errors.
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)
69             } else {
70                 write!(f, "expected {}, found {}", expected, found)
71             }
72         }
73
74         let br_string = |br: ty::BoundRegion| {
75             match br {
76                 ty::BrNamed(_, name) => format!(" {}", name),
77                 _ => String::new(),
78             }
79         };
80
81         match *self {
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",
86                        values.expected,
87                        values.found)
88             }
89             AbiMismatch(values) => {
90                 write!(f, "expected {} fn, found {} fn",
91                        values.expected,
92                        values.found)
93             }
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",
98                        values.expected,
99                        values.found)
100             }
101             TupleSize(values) => {
102                 write!(f, "expected a tuple with {} elements, \
103                            found one with {} elements",
104                        values.expected,
105                        values.found)
106             }
107             ArgCount => {
108                 write!(f, "incorrect number of function parameters")
109             }
110             RegionsDoesNotOutlive(..) => {
111                 write!(f, "lifetime mismatch")
112             }
113             RegionsInsufficientlyPolymorphic(br, _) => {
114                 write!(f,
115                        "expected bound lifetime parameter{}, found concrete lifetime",
116                        br_string(br))
117             }
118             RegionsOverlyPolymorphic(br, _) => {
119                 write!(f,
120                        "expected concrete lifetime, found bound lifetime parameter{}",
121                        br_string(br))
122             }
123             RegionsPlaceholderMismatch => {
124                 write!(f, "one type is more general than the other")
125             }
126             Sorts(values) => ty::tls::with(|tcx| {
127                 report_maybe_different(f, &values.expected.sort_string(tcx),
128                                        &values.found.sort_string(tcx))
129             }),
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)))
136             }),
137             IntMismatch(ref values) => {
138                 write!(f, "expected `{:?}`, found `{:?}`",
139                        values.expected,
140                        values.found)
141             }
142             FloatMismatch(ref values) => {
143                 write!(f, "expected `{:?}`, found `{:?}`",
144                        values.expected,
145                        values.found)
146             }
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" })
151             }
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))
156             }),
157             ProjectionBoundsLength(ref values) => {
158                 write!(f, "expected {} associated type bindings, found {}",
159                        values.expected,
160                        values.found)
161             },
162             ExistentialMismatch(ref values) => {
163                 report_maybe_different(f, &format!("trait `{}`", values.expected),
164                                        &format!("trait `{}`", values.found))
165             }
166         }
167     }
168 }
169
170 impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
171     pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
172         match self.sty {
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(),
176
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(),
182             }
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
191                 {
192                     format!("{}reference", match mutbl {
193                         hir::Mutability::MutMutable => "mutable ",
194                         _ => ""
195                     }).into()
196                 } else {
197                     format!("&{}", tymut_string).into()
198                 }
199             }
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()
205                 } else {
206                     "trait".into()
207                 }
208             }
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) => {
224                 if p.is_self() {
225                     "Self".into()
226                 } else {
227                     "type parameter".into()
228                 }
229             }
230             ty::Opaque(..) => "opaque type".into(),
231             ty::Error => "type error".into(),
232         }
233     }
234 }
235
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>,
240                                      sp: Span) {
241         use self::TypeError::*;
242
243         match err.clone() {
244             Sorts(values) => {
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");
250                 }
251                 if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
252                        (&values.found.sty, &values.expected.sty) // Issue #53280
253                 {
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 == '_') {
256                             db.span_suggestion(
257                                 sp,
258                                 "use a float literal",
259                                 format!("{}.0", snippet),
260                                 Applicability::MachineApplicable
261                             );
262                         }
263                     }
264                 }
265             },
266             CyclicTy(ty) => {
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");
272                 }
273             }
274             _ => {}
275         }
276     }
277 }