Skip to content

Commit ebddfcb

Browse files
committed
Auto merge of #46973 - arielb1:tuple-casting, r=estebank
Update check::cast::pointer_kind logic to new rustc Make the match exhaustive, adding handling for anonymous types and tuple coercions on the way. Also, exit early when type errors are detected, to avoid error cascades and the like. Fixes #33690. Fixes #46365. Fixes #46880.
2 parents 4a7c072 + 6aca330 commit ebddfcb

9 files changed

+167
-12
lines changed

src/librustc/ty/cast.rs

+3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use syntax::ast;
2020
pub enum IntTy {
2121
U(ast::UintTy),
2222
I,
23+
Ivar,
2324
CEnum,
2425
Bool,
2526
Char
@@ -63,6 +64,8 @@ impl<'tcx> CastTy<'tcx> {
6364
ty::TyBool => Some(CastTy::Int(IntTy::Bool)),
6465
ty::TyChar => Some(CastTy::Int(IntTy::Char)),
6566
ty::TyInt(_) => Some(CastTy::Int(IntTy::I)),
67+
ty::TyInfer(ty::InferTy::IntVar(_)) => Some(CastTy::Int(IntTy::Ivar)),
68+
ty::TyInfer(ty::InferTy::FloatVar(_)) => Some(CastTy::Float),
6669
ty::TyUint(u) => Some(CastTy::Int(IntTy::U(u))),
6770
ty::TyFloat(_) => Some(CastTy::Float),
6871
ty::TyAdt(d,_) if d.is_enum() && d.is_payloadfree() =>

src/librustc_typeck/check/cast.rs

+53-12
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ use rustc::session::Session;
4848
use rustc::traits;
4949
use rustc::ty::{self, Ty, TypeFoldable};
5050
use rustc::ty::cast::{CastKind, CastTy};
51+
use rustc::ty::subst::Substs;
5152
use rustc::middle::lang_items;
5253
use syntax::ast;
5354
use syntax_pos::Span;
@@ -77,43 +78,74 @@ enum PointerKind<'tcx> {
7778
Length,
7879
/// The unsize info of this projection
7980
OfProjection(&'tcx ty::ProjectionTy<'tcx>),
81+
/// The unsize info of this anon ty
82+
OfAnon(DefId, &'tcx Substs<'tcx>),
8083
/// The unsize info of this parameter
8184
OfParam(&'tcx ty::ParamTy),
8285
}
8386

8487
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
8588
/// Returns the kind of unsize information of t, or None
8689
/// if t is unknown.
87-
fn pointer_kind(&self, t: Ty<'tcx>, span: Span) -> Option<PointerKind<'tcx>> {
90+
fn pointer_kind(&self, t: Ty<'tcx>, span: Span) ->
91+
Result<Option<PointerKind<'tcx>>, ErrorReported>
92+
{
93+
debug!("pointer_kind({:?}, {:?})", t, span);
94+
95+
let t = self.resolve_type_vars_if_possible(&t);
96+
97+
if t.references_error() {
98+
return Err(ErrorReported);
99+
}
100+
88101
if self.type_is_known_to_be_sized(t, span) {
89-
return Some(PointerKind::Thin);
102+
return Ok(Some(PointerKind::Thin));
90103
}
91104

92-
match t.sty {
105+
Ok(match t.sty {
93106
ty::TySlice(_) | ty::TyStr => Some(PointerKind::Length),
94107
ty::TyDynamic(ref tty, ..) =>
95108
Some(PointerKind::Vtable(tty.principal().map(|p| p.def_id()))),
96109
ty::TyAdt(def, substs) if def.is_struct() => {
97-
// FIXME(arielb1): do some kind of normalization
98110
match def.struct_variant().fields.last() {
99111
None => Some(PointerKind::Thin),
100-
Some(f) => self.pointer_kind(f.ty(self.tcx, substs), span),
112+
Some(f) => {
113+
let field_ty = self.field_ty(span, f, substs);
114+
self.pointer_kind(field_ty, span)?
115+
}
101116
}
102117
}
118+
ty::TyTuple(fields, _) => match fields.last() {
119+
None => Some(PointerKind::Thin),
120+
Some(f) => self.pointer_kind(f, span)?
121+
},
122+
103123
// Pointers to foreign types are thin, despite being unsized
104124
ty::TyForeign(..) => Some(PointerKind::Thin),
105125
// We should really try to normalize here.
106126
ty::TyProjection(ref pi) => Some(PointerKind::OfProjection(pi)),
127+
ty::TyAnon(def_id, substs) => Some(PointerKind::OfAnon(def_id, substs)),
107128
ty::TyParam(ref p) => Some(PointerKind::OfParam(p)),
108129
// Insufficient type information.
109130
ty::TyInfer(_) => None,
110-
_ => panic!(),
111-
}
131+
132+
ty::TyBool | ty::TyChar | ty::TyInt(..) | ty::TyUint(..) |
133+
ty::TyFloat(_) | ty::TyArray(..) |
134+
ty::TyRawPtr(_) | ty::TyRef(..) | ty::TyFnDef(..) |
135+
ty::TyFnPtr(..) | ty::TyClosure(..) | ty::TyGenerator(..) |
136+
ty::TyAdt(..) | ty::TyNever | ty::TyError => {
137+
self.tcx.sess.delay_span_bug(
138+
span, &format!("`{:?}` should be sized but is not?", t));
139+
return Err(ErrorReported);
140+
}
141+
})
112142
}
113143
}
114144

115145
#[derive(Copy, Clone)]
116146
enum CastError {
147+
ErrorReported,
148+
117149
CastToBool,
118150
CastToChar,
119151
DifferingKinds,
@@ -129,6 +161,12 @@ enum CastError {
129161
UnknownCastPtrKind,
130162
}
131163

164+
impl From<ErrorReported> for CastError {
165+
fn from(ErrorReported: ErrorReported) -> Self {
166+
CastError::ErrorReported
167+
}
168+
}
169+
132170
fn make_invalid_casting_error<'a, 'gcx, 'tcx>(sess: &'a Session,
133171
span: Span,
134172
expr_ty: Ty<'tcx>,
@@ -173,6 +211,9 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
173211

174212
fn report_cast_error(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, e: CastError) {
175213
match e {
214+
CastError::ErrorReported => {
215+
// an error has already been reported
216+
}
176217
CastError::NeedDeref => {
177218
let error_span = self.span;
178219
let mut err = make_invalid_casting_error(fcx.tcx.sess, self.span, self.expr_ty,
@@ -480,8 +521,8 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
480521
debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
481522
// ptr-ptr cast. vtables must match.
482523

483-
let expr_kind = fcx.pointer_kind(m_expr.ty, self.span);
484-
let cast_kind = fcx.pointer_kind(m_cast.ty, self.span);
524+
let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
525+
let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
485526

486527
let cast_kind = match cast_kind {
487528
// We can't cast if target pointer kind is unknown
@@ -519,7 +560,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
519560
-> Result<CastKind, CastError> {
520561
// fptr-ptr cast. must be to thin ptr
521562

522-
match fcx.pointer_kind(m_cast.ty, self.span) {
563+
match fcx.pointer_kind(m_cast.ty, self.span)? {
523564
None => Err(CastError::UnknownCastPtrKind),
524565
Some(PointerKind::Thin) => Ok(CastKind::FnPtrPtrCast),
525566
_ => Err(CastError::IllegalCast),
@@ -532,7 +573,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
532573
-> Result<CastKind, CastError> {
533574
// ptr-addr cast. must be from thin ptr
534575

535-
match fcx.pointer_kind(m_expr.ty, self.span) {
576+
match fcx.pointer_kind(m_expr.ty, self.span)? {
536577
None => Err(CastError::UnknownExprPtrKind),
537578
Some(PointerKind::Thin) => Ok(CastKind::PtrAddrCast),
538579
_ => Err(CastError::NeedViaThinPtr),
@@ -569,7 +610,7 @@ impl<'a, 'gcx, 'tcx> CastCheck<'tcx> {
569610
m_cast: &'tcx ty::TypeAndMut<'tcx>)
570611
-> Result<CastKind, CastError> {
571612
// ptr-addr cast. pointer must be thin.
572-
match fcx.pointer_kind(m_cast.ty, self.span) {
613+
match fcx.pointer_kind(m_cast.ty, self.span)? {
573614
None => Err(CastError::UnknownCastPtrKind),
574615
Some(PointerKind::Thin) => Ok(CastKind::AddrPtrCast),
575616
_ => Err(CastError::IllegalCast),

src/test/run-pass/cast-rfc0401-vtable-kinds.rs

+17
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
// Check that you can cast between different pointers to trait objects
1212
// whose vtable have the same kind (both lengths, or both trait pointers).
1313

14+
#![feature(unsized_tuple_coercion)]
15+
1416
trait Foo<T> {
1517
fn foo(&self, _: T) -> u32 { 42 }
1618
}
@@ -39,6 +41,11 @@ fn foo_to_bar<T:?Sized>(u: *const FooS<T>) -> *const BarS<T> {
3941
u as *const BarS<T>
4042
}
4143

44+
fn tuple_i32_to_u32<T:?Sized>(u: *const (i32, T)) -> *const (u32, T) {
45+
u as *const (u32, T)
46+
}
47+
48+
4249
fn main() {
4350
let x = 4u32;
4451
let y : &Foo<u32> = &x;
@@ -51,4 +58,14 @@ fn main() {
5158
let bar_ref : *const BarS<[u32]> = foo_to_bar(u);
5259
let z : &BarS<[u32]> = unsafe{&*bar_ref};
5360
assert_eq!(&z.0, &[0,1,2]);
61+
62+
// this assumes that tuple reprs for (i32, _) and (u32, _) are
63+
// the same.
64+
let s = (0i32, [0, 1, 2]);
65+
let u: &(i32, [u8]) = &s;
66+
let u: *const (i32, [u8]) = u;
67+
let u_u32 : *const (u32, [u8]) = tuple_i32_to_u32(u);
68+
unsafe {
69+
assert_eq!(&(*u_u32).1, &[0, 1, 2]);
70+
}
5471
}
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Copyright 2017 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+
fn main() {
12+
let error = error; //~ ERROR cannot find value `error`
13+
14+
// These used to cause errors.
15+
0 as f32;
16+
0.0 as u32;
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error[E0425]: cannot find value `error` in this scope
2+
--> $DIR/cast-errors-issue-43825.rs:12:17
3+
|
4+
12 | let error = error; //~ ERROR cannot find value `error`
5+
| ^^^^^ not found in this scope
6+
7+
error: aborting due to previous error
8+

src/test/ui/casts-differing-anon.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2017 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+
#![feature(conservative_impl_trait)]
12+
13+
use std::fmt;
14+
15+
fn foo() -> Box<impl fmt::Debug+?Sized> {
16+
let x : Box<[u8]> = Box::new([0]);
17+
x
18+
}
19+
fn bar() -> Box<impl fmt::Debug+?Sized> {
20+
let y: Box<fmt::Debug> = Box::new([0]);
21+
y
22+
}
23+
24+
fn main() {
25+
let f = foo();
26+
let b = bar();
27+
28+
// this is an `*mut [u8]` in practice
29+
let f_raw : *mut _ = Box::into_raw(f);
30+
// this is an `*mut fmt::Debug` in practice
31+
let mut b_raw = Box::into_raw(b);
32+
// ... and they should not be mixable
33+
b_raw = f_raw as *mut _; //~ ERROR is invalid
34+
}
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error[E0606]: casting `*mut impl std::fmt::Debug+?Sized` as `*mut impl std::fmt::Debug+?Sized` is invalid
2+
--> $DIR/casts-differing-anon.rs:33:13
3+
|
4+
33 | b_raw = f_raw as *mut _; //~ ERROR is invalid
5+
| ^^^^^^^^^^^^^^^
6+
|
7+
= note: vtable kinds may not match
8+
9+
error: aborting due to previous error
10+

src/test/ui/casts-issue-46365.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Copyright 2017 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+
struct Lorem {
12+
ipsum: Ipsum //~ ERROR cannot find type `Ipsum`
13+
}
14+
15+
fn main() {
16+
let _foo: *mut Lorem = 0 as *mut _; // no error here
17+
}

src/test/ui/casts-issue-46365.stderr

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error[E0412]: cannot find type `Ipsum` in this scope
2+
--> $DIR/casts-issue-46365.rs:12:12
3+
|
4+
12 | ipsum: Ipsum //~ ERROR cannot find type `Ipsum`
5+
| ^^^^^ not found in this scope
6+
7+
error: aborting due to previous error
8+

0 commit comments

Comments
 (0)