]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/cast.rs
New upstream version 1.18.0+dfsg1
[rustc.git] / src / librustc_typeck / check / cast.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Code for type-checking cast expressions.
12 //!
13 //! A cast `e as U` is valid if one of the following holds:
14 //! * `e` has type `T` and `T` coerces to `U`; *coercion-cast*
15 //! * `e` has type `*T`, `U` is `*U_0`, and either `U_0: Sized` or
16 //! unsize_kind(`T`) = unsize_kind(`U_0`); *ptr-ptr-cast*
17 //! * `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
18 //! * `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*
19 //! * `e` has type `T` and `T` and `U` are any numeric types; *numeric-cast*
20 //! * `e` is a C-like enum and `U` is an integer type; *enum-cast*
21 //! * `e` has type `bool` or `char` and `U` is an integer; *prim-int-cast*
22 //! * `e` has type `u8` and `U` is `char`; *u8-char-cast*
23 //! * `e` has type `&[T; n]` and `U` is `*const T`; *array-ptr-cast*
24 //! * `e` is a function pointer type and `U` has type `*T`,
25 //! while `T: Sized`; *fptr-ptr-cast*
26 //! * `e` is a function pointer type and `U` is an integer; *fptr-addr-cast*
27 //!
28 //! where `&.T` and `*T` are references of either mutability,
29 //! and where unsize_kind(`T`) is the kind of the unsize info
30 //! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or
31 //! `Iterator`, not `Iterator<Item=u8>`) or a length (or `()` if `T: Sized`).
32 //!
33 //! Note that lengths are not adjusted when casting raw slices -
34 //! `T: *const [u16] as *const [u8]` creates a slice that only includes
35 //! half of the original memory.
36 //!
37 //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid
38 //! expression, `e as U2` is not necessarily so (in fact it will only be valid if
39 //! `U1` coerces to `U2`).
40
41 use super::{Diverges, FnCtxt};
42
43 use lint;
44 use hir::def_id::DefId;
45 use rustc::hir;
46 use rustc::traits;
47 use rustc::ty::{self, Ty, TypeFoldable};
48 use rustc::ty::cast::{CastKind, CastTy};
49 use rustc::middle::lang_items;
50 use syntax::ast;
51 use syntax_pos::Span;
52 use util::common::ErrorReported;
53
54 /// Reifies a cast check to be checked once we have full type information for
55 /// a function context.
56 pub struct CastCheck<'tcx> {
57 expr: &'tcx hir::Expr,
58 expr_ty: Ty<'tcx>,
59 expr_diverges: Diverges,
60 cast_ty: Ty<'tcx>,
61 cast_span: Span,
62 span: Span,
63 }
64
65 /// The kind of the unsize info (length or vtable) - we only allow casts between
66 /// fat pointers if their unsize-infos have the same kind.
67 #[derive(Copy, Clone, PartialEq, Eq)]
68 enum UnsizeKind<'tcx> {
69 Vtable(Option<DefId>),
70 Length,
71 /// The unsize info of this projection
72 OfProjection(&'tcx ty::ProjectionTy<'tcx>),
73 /// The unsize info of this parameter
74 OfParam(&'tcx ty::ParamTy),
75 }
76
77 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
78 /// Returns the kind of unsize information of t, or None
79 /// if t is sized or it is unknown.
80 fn unsize_kind(&self, t: Ty<'tcx>) -> Option<UnsizeKind<'tcx>> {
81 match t.sty {
82 ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length),
83 ty::TyDynamic(ref tty, ..) =>
84 Some(UnsizeKind::Vtable(tty.principal().map(|p| p.def_id()))),
85 ty::TyAdt(def, substs) if def.is_struct() => {
86 // FIXME(arielb1): do some kind of normalization
87 match def.struct_variant().fields.last() {
88 None => None,
89 Some(f) => self.unsize_kind(f.ty(self.tcx, substs)),
90 }
91 }
92 // We should really try to normalize here.
93 ty::TyProjection(ref pi) => Some(UnsizeKind::OfProjection(pi)),
94 ty::TyParam(ref p) => Some(UnsizeKind::OfParam(p)),
95 _ => None,
96 }
97 }
98 }
99
100 #[derive(Copy, Clone)]
101 enum CastError {
102 CastToBool,
103 CastToChar,
104 DifferingKinds,
105 /// Cast of thin to fat raw ptr (eg. `*const () as *const [u8]`)
106 SizedUnsizedCast,
107 IllegalCast,
108 NeedDeref,
109 NeedViaPtr,
110 NeedViaThinPtr,
111 NeedViaInt,
112 NonScalar,
113 }
114
115 impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
116 pub fn new(fcx: &FnCtxt<'a, 'gcx, 'tcx>,
117 expr: &'tcx hir::Expr,
118 expr_ty: Ty<'tcx>,
119 expr_diverges: Diverges,
120 cast_ty: Ty<'tcx>,
121 cast_span: Span,
122 span: Span)
123 -> Result<CastCheck<'tcx>, ErrorReported> {
124 let check = CastCheck {
125 expr: expr,
126 expr_ty: expr_ty,
127 expr_diverges: expr_diverges,
128 cast_ty: cast_ty,
129 cast_span: cast_span,
130 span: span,
131 };
132
133 // For better error messages, check for some obviously unsized
134 // cases now. We do a more thorough check at the end, once
135 // inference is more completely known.
136 match cast_ty.sty {
137 ty::TyDynamic(..) | ty::TySlice(..) => {
138 check.report_cast_to_unsized_type(fcx);
139 Err(ErrorReported)
140 }
141 _ => Ok(check),
142 }
143 }
144
145 fn report_cast_error(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, e: CastError) {
146 match e {
147 CastError::NeedDeref => {
148 let error_span = self.span;
149 let cast_ty = fcx.ty_to_string(self.cast_ty);
150 let mut err = fcx.type_error_struct(error_span,
151 |actual| {
152 format!("casting `{}` as `{}` is invalid",
153 actual,
154 cast_ty)
155 },
156 self.expr_ty);
157 err.span_label(error_span,
158 &format!("cannot cast `{}` as `{}`",
159 fcx.ty_to_string(self.expr_ty),
160 cast_ty));
161 if let Ok(snippet) = fcx.sess().codemap().span_to_snippet(self.expr.span) {
162 err.span_help(self.expr.span,
163 &format!("did you mean `*{}`?", snippet));
164 }
165 err.emit();
166 }
167 CastError::NeedViaThinPtr |
168 CastError::NeedViaPtr => {
169 let mut err = fcx.type_error_struct(self.span,
170 |actual| {
171 format!("casting `{}` as `{}` is invalid",
172 actual,
173 fcx.ty_to_string(self.cast_ty))
174 },
175 self.expr_ty);
176 if self.cast_ty.is_uint() {
177 err.help(&format!("cast through {} first",
178 match e {
179 CastError::NeedViaPtr => "a raw pointer",
180 CastError::NeedViaThinPtr => "a thin pointer",
181 _ => bug!(),
182 }));
183 }
184 err.emit();
185 }
186 CastError::NeedViaInt => {
187 fcx.type_error_struct(self.span,
188 |actual| {
189 format!("casting `{}` as `{}` is invalid",
190 actual,
191 fcx.ty_to_string(self.cast_ty))
192 },
193 self.expr_ty)
194 .help(&format!("cast through {} first",
195 match e {
196 CastError::NeedViaInt => "an integer",
197 _ => bug!(),
198 }))
199 .emit();
200 }
201 CastError::CastToBool => {
202 struct_span_err!(fcx.tcx.sess, self.span, E0054, "cannot cast as `bool`")
203 .span_label(self.span, &format!("unsupported cast"))
204 .help("compare with zero instead")
205 .emit();
206 }
207 CastError::CastToChar => {
208 fcx.type_error_message(self.span,
209 |actual| {
210 format!("only `u8` can be cast as `char`, not `{}`",
211 actual)
212 },
213 self.expr_ty);
214 }
215 CastError::NonScalar => {
216 fcx.type_error_message(self.span,
217 |actual| {
218 format!("non-scalar cast: `{}` as `{}`",
219 actual,
220 fcx.ty_to_string(self.cast_ty))
221 },
222 self.expr_ty);
223 }
224 CastError::IllegalCast => {
225 fcx.type_error_message(self.span,
226 |actual| {
227 format!("casting `{}` as `{}` is invalid",
228 actual,
229 fcx.ty_to_string(self.cast_ty))
230 },
231 self.expr_ty);
232 }
233 CastError::SizedUnsizedCast => {
234 fcx.type_error_message(self.span,
235 |actual| {
236 format!("cannot cast thin pointer `{}` to fat pointer \
237 `{}`",
238 actual,
239 fcx.ty_to_string(self.cast_ty))
240 },
241 self.expr_ty)
242 }
243 CastError::DifferingKinds => {
244 fcx.type_error_struct(self.span,
245 |actual| {
246 format!("casting `{}` as `{}` is invalid",
247 actual,
248 fcx.ty_to_string(self.cast_ty))
249 },
250 self.expr_ty)
251 .note("vtable kinds may not match")
252 .emit();
253 }
254 }
255 }
256
257 fn report_cast_to_unsized_type(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
258 if self.cast_ty.references_error() || self.expr_ty.references_error() {
259 return;
260 }
261
262 let tstr = fcx.ty_to_string(self.cast_ty);
263 let mut err =
264 fcx.type_error_struct(self.span,
265 |actual| {
266 format!("cast to unsized type: `{}` as `{}`", actual, tstr)
267 },
268 self.expr_ty);
269 match self.expr_ty.sty {
270 ty::TyRef(_, ty::TypeAndMut { mutbl: mt, .. }) => {
271 let mtstr = match mt {
272 hir::MutMutable => "mut ",
273 hir::MutImmutable => "",
274 };
275 if self.cast_ty.is_trait() {
276 match fcx.tcx.sess.codemap().span_to_snippet(self.cast_span) {
277 Ok(s) => {
278 err.span_suggestion(self.cast_span,
279 "try casting to a reference instead:",
280 format!("&{}{}", mtstr, s));
281 }
282 Err(_) => {
283 span_help!(err, self.cast_span, "did you mean `&{}{}`?", mtstr, tstr)
284 }
285 }
286 } else {
287 span_help!(err,
288 self.span,
289 "consider using an implicit coercion to `&{}{}` instead",
290 mtstr,
291 tstr);
292 }
293 }
294 ty::TyAdt(def, ..) if def.is_box() => {
295 match fcx.tcx.sess.codemap().span_to_snippet(self.cast_span) {
296 Ok(s) => {
297 err.span_suggestion(self.cast_span,
298 "try casting to a `Box` instead:",
299 format!("Box<{}>", s));
300 }
301 Err(_) => span_help!(err, self.cast_span, "did you mean `Box<{}>`?", tstr),
302 }
303 }
304 _ => {
305 span_help!(err,
306 self.expr.span,
307 "consider using a box or reference as appropriate");
308 }
309 }
310 err.emit();
311 }
312
313 fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
314 let t_cast = self.cast_ty;
315 let t_expr = self.expr_ty;
316 if t_cast.is_numeric() && t_expr.is_numeric() {
317 fcx.tables.borrow_mut().lints.add_lint(
318 lint::builtin::TRIVIAL_NUMERIC_CASTS,
319 self.expr.id,
320 self.span,
321 format!("trivial numeric cast: `{}` as `{}`. Cast can be \
322 replaced by coercion, this might require type \
323 ascription or a temporary variable",
324 fcx.ty_to_string(t_expr),
325 fcx.ty_to_string(t_cast)));
326 } else {
327 fcx.tables.borrow_mut().lints.add_lint(
328 lint::builtin::TRIVIAL_CASTS,
329 self.expr.id,
330 self.span,
331 format!("trivial cast: `{}` as `{}`. Cast can be \
332 replaced by coercion, this might require type \
333 ascription or a temporary variable",
334 fcx.ty_to_string(t_expr),
335 fcx.ty_to_string(t_cast)));
336 }
337
338 }
339
340 pub fn check(mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) {
341 self.expr_ty = fcx.structurally_resolved_type(self.span, self.expr_ty);
342 self.cast_ty = fcx.structurally_resolved_type(self.span, self.cast_ty);
343
344 debug!("check_cast({}, {:?} as {:?})",
345 self.expr.id,
346 self.expr_ty,
347 self.cast_ty);
348
349 if !fcx.type_is_known_to_be_sized(self.cast_ty, self.span) {
350 self.report_cast_to_unsized_type(fcx);
351 } else if self.expr_ty.references_error() || self.cast_ty.references_error() {
352 // No sense in giving duplicate error messages
353 } else if self.try_coercion_cast(fcx) {
354 self.trivial_cast_lint(fcx);
355 debug!(" -> CoercionCast");
356 fcx.tables.borrow_mut().cast_kinds.insert(self.expr.id, CastKind::CoercionCast);
357 } else {
358 match self.do_check(fcx) {
359 Ok(k) => {
360 debug!(" -> {:?}", k);
361 fcx.tables.borrow_mut().cast_kinds.insert(self.expr.id, k);
362 }
363 Err(e) => self.report_cast_error(fcx, e),
364 };
365 }
366 }
367
368 /// Check a cast, and report an error if one exists. In some cases, this
369 /// can return Ok and create type errors in the fcx rather than returning
370 /// directly. coercion-cast is handled in check instead of here.
371 fn do_check(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Result<CastKind, CastError> {
372 use rustc::ty::cast::IntTy::*;
373 use rustc::ty::cast::CastTy::*;
374
375 let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty),
376 CastTy::from_ty(self.cast_ty)) {
377 (Some(t_from), Some(t_cast)) => (t_from, t_cast),
378 // Function item types may need to be reified before casts.
379 (None, Some(t_cast)) => {
380 if let ty::TyFnDef(.., f) = self.expr_ty.sty {
381 // Attempt a coercion to a fn pointer type.
382 let res = fcx.try_coerce(self.expr,
383 self.expr_ty,
384 self.expr_diverges,
385 fcx.tcx.mk_fn_ptr(f));
386 if !res.is_ok() {
387 return Err(CastError::NonScalar);
388 }
389 (FnPtr, t_cast)
390 } else {
391 return Err(CastError::NonScalar);
392 }
393 }
394 _ => return Err(CastError::NonScalar),
395 };
396
397 match (t_from, t_cast) {
398 // These types have invariants! can't cast into them.
399 (_, RPtr(_)) | (_, Int(CEnum)) | (_, FnPtr) => Err(CastError::NonScalar),
400
401 // * -> Bool
402 (_, Int(Bool)) => Err(CastError::CastToBool),
403
404 // * -> Char
405 (Int(U(ast::UintTy::U8)), Int(Char)) => Ok(CastKind::U8CharCast), // u8-char-cast
406 (_, Int(Char)) => Err(CastError::CastToChar),
407
408 // prim -> float,ptr
409 (Int(Bool), Float) |
410 (Int(CEnum), Float) |
411 (Int(Char), Float) => Err(CastError::NeedViaInt),
412
413 (Int(Bool), Ptr(_)) |
414 (Int(CEnum), Ptr(_)) |
415 (Int(Char), Ptr(_)) |
416 (Ptr(_), Float) |
417 (FnPtr, Float) |
418 (Float, Ptr(_)) => Err(CastError::IllegalCast),
419
420 // ptr -> *
421 (Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
422 (Ptr(m_expr), Int(_)) => self.check_ptr_addr_cast(fcx, m_expr), // ptr-addr-cast
423 (FnPtr, Int(_)) => Ok(CastKind::FnPtrAddrCast),
424 (RPtr(p), Int(_)) |
425 (RPtr(p), Float) => {
426 match p.ty.sty {
427 ty::TypeVariants::TyInt(_) |
428 ty::TypeVariants::TyUint(_) |
429 ty::TypeVariants::TyFloat(_) => {
430 Err(CastError::NeedDeref)
431 }
432 ty::TypeVariants::TyInfer(t) => {
433 match t {
434 ty::InferTy::IntVar(_) |
435 ty::InferTy::FloatVar(_) |
436 ty::InferTy::FreshIntTy(_) |
437 ty::InferTy::FreshFloatTy(_) => {
438 Err(CastError::NeedDeref)
439 }
440 _ => Err(CastError::NeedViaPtr),
441 }
442 }
443 _ => Err(CastError::NeedViaPtr),
444 }
445 }
446 // * -> ptr
447 (Int(_), Ptr(mt)) => self.check_addr_ptr_cast(fcx, mt), // addr-ptr-cast
448 (FnPtr, Ptr(mt)) => self.check_fptr_ptr_cast(fcx, mt),
449 (RPtr(rmt), Ptr(mt)) => self.check_ref_cast(fcx, rmt, mt), // array-ptr-cast
450
451 // prim -> prim
452 (Int(CEnum), Int(_)) => Ok(CastKind::EnumCast),
453 (Int(Char), Int(_)) |
454 (Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast),
455
456 (Int(_), Int(_)) | (Int(_), Float) | (Float, Int(_)) | (Float, Float) => {
457 Ok(CastKind::NumericCast)
458 }
459 }
460 }
461
462 fn check_ptr_ptr_cast(&self,
463 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
464 m_expr: &'tcx ty::TypeAndMut<'tcx>,
465 m_cast: &'tcx ty::TypeAndMut<'tcx>)
466 -> Result<CastKind, CastError> {
467 debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
468 // ptr-ptr cast. vtables must match.
469
470 // Cast to sized is OK
471 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
472 return Ok(CastKind::PtrPtrCast);
473 }
474
475 // sized -> unsized? report invalid cast (don't complain about vtable kinds)
476 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
477 return Err(CastError::SizedUnsizedCast);
478 }
479
480 // vtable kinds must match
481 match (fcx.unsize_kind(m_cast.ty), fcx.unsize_kind(m_expr.ty)) {
482 (Some(a), Some(b)) if a == b => Ok(CastKind::PtrPtrCast),
483 _ => Err(CastError::DifferingKinds),
484 }
485 }
486
487 fn check_fptr_ptr_cast(&self,
488 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
489 m_cast: &'tcx ty::TypeAndMut<'tcx>)
490 -> Result<CastKind, CastError> {
491 // fptr-ptr cast. must be to sized ptr
492
493 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
494 Ok(CastKind::FnPtrPtrCast)
495 } else {
496 Err(CastError::IllegalCast)
497 }
498 }
499
500 fn check_ptr_addr_cast(&self,
501 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
502 m_expr: &'tcx ty::TypeAndMut<'tcx>)
503 -> Result<CastKind, CastError> {
504 // ptr-addr cast. must be from sized ptr
505
506 if fcx.type_is_known_to_be_sized(m_expr.ty, self.span) {
507 Ok(CastKind::PtrAddrCast)
508 } else {
509 Err(CastError::NeedViaThinPtr)
510 }
511 }
512
513 fn check_ref_cast(&self,
514 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
515 m_expr: &'tcx ty::TypeAndMut<'tcx>,
516 m_cast: &'tcx ty::TypeAndMut<'tcx>)
517 -> Result<CastKind, CastError> {
518 // array-ptr-cast.
519
520 if m_expr.mutbl == hir::MutImmutable && m_cast.mutbl == hir::MutImmutable {
521 if let ty::TyArray(ety, _) = m_expr.ty.sty {
522 // Due to the limitations of LLVM global constants,
523 // region pointers end up pointing at copies of
524 // vector elements instead of the original values.
525 // To allow raw pointers to work correctly, we
526 // need to special-case obtaining a raw pointer
527 // from a region pointer to a vector.
528
529 // this will report a type mismatch if needed
530 fcx.demand_eqtype(self.span, ety, m_cast.ty);
531 return Ok(CastKind::ArrayPtrCast);
532 }
533 }
534
535 Err(CastError::IllegalCast)
536 }
537
538 fn check_addr_ptr_cast(&self,
539 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
540 m_cast: &'tcx ty::TypeAndMut<'tcx>)
541 -> Result<CastKind, CastError> {
542 // ptr-addr cast. pointer must be thin.
543 if fcx.type_is_known_to_be_sized(m_cast.ty, self.span) {
544 Ok(CastKind::AddrPtrCast)
545 } else {
546 Err(CastError::IllegalCast)
547 }
548 }
549
550 fn try_coercion_cast(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> bool {
551 fcx.try_coerce(self.expr, self.expr_ty, self.expr_diverges, self.cast_ty).is_ok()
552 }
553 }
554
555 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
556 fn type_is_known_to_be_sized(&self, ty: Ty<'tcx>, span: Span) -> bool {
557 let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
558 traits::type_known_to_meet_bound(self, ty, lang_item, span)
559 }
560 }