Skip to content

Commit bad556d

Browse files
Ariel Ben-Yehudaarielb1
Ariel Ben-Yehuda
authored andcommitted
Overhaul cast semantics and make them follow RFC401
This should hopefully fix all cast-related ICEs once and for all. I managed to make diagnostics hate me and give me spurious "decoder error" - removing $build/tmp/extended-errors seems to fix it.
1 parent df3597b commit bad556d

File tree

16 files changed

+611
-365
lines changed

16 files changed

+611
-365
lines changed

src/librustc/diagnostics.rs

-1
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,6 @@ struct Foo<T: 'static> {
801801

802802
register_diagnostics! {
803803
E0011,
804-
E0012,
805804
E0014,
806805
E0016,
807806
E0017,

src/librustc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ pub mod back {
9292
pub mod middle {
9393
pub mod astconv_util;
9494
pub mod astencode;
95+
pub mod cast;
9596
pub mod cfg;
9697
pub mod check_const;
9798
pub mod check_static_recursion;

src/librustc/metadata/common.rs

+1
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ enum_from_u32! {
148148
tag_table_capture_modes = 0x67,
149149
tag_table_object_cast_map = 0x68,
150150
tag_table_const_qualif = 0x69,
151+
tag_table_cast_kinds = 0x6a,
151152
}
152153
}
153154

src/librustc/middle/astencode.rs

+25
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use metadata::tydecode;
2323
use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter};
2424
use metadata::tydecode::{RegionParameter, ClosureSource};
2525
use metadata::tyencode;
26+
use middle::cast;
2627
use middle::check_const::ConstQualif;
2728
use middle::mem_categorization::Typer;
2829
use middle::privacy::{AllPublic, LastMod};
@@ -688,6 +689,10 @@ pub fn encode_closure_kind(ebml_w: &mut Encoder, kind: ty::ClosureKind) {
688689
kind.encode(ebml_w).unwrap();
689690
}
690691

692+
pub fn encode_cast_kind(ebml_w: &mut Encoder, kind: cast::CastKind) {
693+
kind.encode(ebml_w).unwrap();
694+
}
695+
691696
pub trait vtable_decoder_helpers<'tcx> {
692697
fn read_vec_per_param_space<T, F>(&mut self, f: F) -> VecPerParamSpace<T> where
693698
F: FnMut(&mut Self) -> T;
@@ -1248,6 +1253,13 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
12481253
})
12491254
}
12501255

1256+
if let Some(cast_kind) = tcx.cast_kinds.borrow().get(&id) {
1257+
rbml_w.tag(c::tag_table_cast_kinds, |rbml_w| {
1258+
rbml_w.id(id);
1259+
encode_cast_kind(rbml_w, *cast_kind)
1260+
})
1261+
}
1262+
12511263
for &qualif in tcx.const_qualif_map.borrow().get(&id).iter() {
12521264
rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
12531265
rbml_w.id(id);
@@ -1289,6 +1301,8 @@ trait rbml_decoder_decoder_helpers<'tcx> {
12891301
-> subst::Substs<'tcx>;
12901302
fn read_auto_adjustment<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
12911303
-> ty::AutoAdjustment<'tcx>;
1304+
fn read_cast_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
1305+
-> cast::CastKind;
12921306
fn read_closure_kind<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
12931307
-> ty::ClosureKind;
12941308
fn read_closure_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>)
@@ -1641,6 +1655,12 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
16411655
}).unwrap()
16421656
}
16431657

1658+
fn read_cast_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
1659+
-> cast::CastKind
1660+
{
1661+
Decodable::decode(self).unwrap()
1662+
}
1663+
16441664
fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
16451665
-> ty::ClosureKind
16461666
{
@@ -1801,6 +1821,11 @@ fn decode_side_tables(dcx: &DecodeContext,
18011821
dcx.tcx.closure_kinds.borrow_mut().insert(ast_util::local_def(id),
18021822
closure_kind);
18031823
}
1824+
c::tag_table_cast_kinds => {
1825+
let cast_kind =
1826+
val_dsr.read_cast_kind(dcx);
1827+
dcx.tcx.cast_kinds.borrow_mut().insert(id, cast_kind);
1828+
}
18041829
c::tag_table_const_qualif => {
18051830
let qualif: ConstQualif = Decodable::decode(val_dsr).unwrap();
18061831
dcx.tcx.const_qualif_map.borrow_mut().insert(id, qualif);

src/librustc/middle/cast.rs

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
// Helpers for handling cast expressions, used in both
12+
// typeck and trans.
13+
14+
use middle::ty::{self, Ty};
15+
16+
use syntax::ast;
17+
18+
19+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
20+
pub enum IntTy {
21+
U(ast::UintTy),
22+
I,
23+
CEnum,
24+
Bool,
25+
Char
26+
}
27+
28+
// Valid types for the result of a non-coercion cast
29+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
30+
pub enum CastTy<'tcx> {
31+
Int(IntTy),
32+
Float,
33+
FPtr,
34+
Ptr(&'tcx ty::mt<'tcx>),
35+
RPtr(&'tcx ty::mt<'tcx>),
36+
}
37+
38+
/// Cast Kind. See RFC 401 (or librustc_typeck/check/cast.rs)
39+
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
40+
pub enum CastKind {
41+
CoercionCast,
42+
PtrPtrCast,
43+
PtrAddrCast,
44+
AddrPtrCast,
45+
NumericCast,
46+
EnumCast,
47+
PrimIntCast,
48+
U8CharCast,
49+
ArrayPtrCast,
50+
FPtrPtrCast,
51+
FPtrAddrCast
52+
}
53+
54+
impl<'tcx> CastTy<'tcx> {
55+
pub fn recognize(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>)
56+
-> Option<CastTy<'tcx>> {
57+
match t.sty {
58+
ty::ty_bool => Some(CastTy::Int(IntTy::Bool)),
59+
ty::ty_char => Some(CastTy::Int(IntTy::Char)),
60+
ty::ty_int(_) => Some(CastTy::Int(IntTy::I)),
61+
ty::ty_uint(u) => Some(CastTy::Int(IntTy::U(u))),
62+
ty::ty_float(_) => Some(CastTy::Float),
63+
ty::ty_enum(..) if ty::type_is_c_like_enum(
64+
tcx, t) => Some(CastTy::Int(IntTy::CEnum)),
65+
ty::ty_ptr(ref mt) => Some(CastTy::Ptr(mt)),
66+
ty::ty_rptr(_, ref mt) => Some(CastTy::RPtr(mt)),
67+
ty::ty_bare_fn(..) => Some(CastTy::FPtr),
68+
_ => None,
69+
}
70+
}
71+
}

src/librustc/middle/check_const.rs

+13-22
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
// - It's not possible to take the address of a static item with unsafe interior. This is enforced
2525
// by borrowck::gather_loans
2626

27+
use middle::cast::{CastKind};
2728
use middle::const_eval;
2829
use middle::def;
2930
use middle::expr_use_visitor as euv;
@@ -32,11 +33,10 @@ use middle::mem_categorization as mc;
3233
use middle::traits;
3334
use middle::ty::{self, Ty};
3435
use util::nodemap::NodeMap;
35-
use util::ppaux;
36+
use util::ppaux::Repr;
3637

3738
use syntax::ast;
3839
use syntax::codemap::Span;
39-
use syntax::print::pprust;
4040
use syntax::visit::{self, Visitor};
4141

4242
use std::collections::hash_map::Entry;
@@ -197,7 +197,7 @@ impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
197197

198198
impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
199199
fn visit_item(&mut self, i: &ast::Item) {
200-
debug!("visit_item(item={})", pprust::item_to_string(i));
200+
debug!("visit_item(item={})", i.repr(self.tcx));
201201
match i.node {
202202
ast::ItemStatic(_, ast::MutImmutable, ref expr) => {
203203
self.check_static_type(&**expr);
@@ -440,26 +440,17 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>,
440440
}
441441
}
442442
ast::ExprCast(ref from, _) => {
443-
let toty = ty::expr_ty(v.tcx, e);
444-
let fromty = ty::expr_ty(v.tcx, &**from);
445-
let is_legal_cast =
446-
ty::type_is_numeric(toty) ||
447-
ty::type_is_unsafe_ptr(toty) ||
448-
(ty::type_is_bare_fn(toty) && ty::type_is_bare_fn_item(fromty));
449-
if !is_legal_cast {
450-
v.add_qualif(ConstQualif::NOT_CONST);
451-
if v.mode != Mode::Var {
452-
span_err!(v.tcx.sess, e.span, E0012,
453-
"can not cast to `{}` in {}s",
454-
ppaux::ty_to_string(v.tcx, toty), v.msg());
455-
}
456-
}
457-
if ty::type_is_unsafe_ptr(fromty) && ty::type_is_numeric(toty) {
458-
v.add_qualif(ConstQualif::NOT_CONST);
459-
if v.mode != Mode::Var {
460-
span_err!(v.tcx.sess, e.span, E0018,
461-
"can not cast a pointer to an integer in {}s", v.msg());
443+
debug!("Checking const cast(id={})", from.id);
444+
match v.tcx.cast_kinds.borrow().get(&from.id) {
445+
None => v.tcx.sess.span_bug(e.span, "no kind for cast"),
446+
Some(&CastKind::PtrAddrCast) | Some(&CastKind::FPtrAddrCast) => {
447+
v.add_qualif(ConstQualif::NOT_CONST);
448+
if v.mode != Mode::Var {
449+
span_err!(v.tcx.sess, e.span, E0018,
450+
"can not cast a pointer to an integer in {}s", v.msg());
451+
}
462452
}
453+
_ => {}
463454
}
464455
}
465456
ast::ExprPath(..) => {

src/librustc/middle/const_eval.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -992,7 +992,7 @@ fn cast_const<'tcx>(tcx: &ty::ctxt<'tcx>, val: const_val, ty: Ty) -> CastResult
992992
macro_rules! convert_val {
993993
($intermediate_ty:ty, $const_type:ident, $target_ty:ty) => {
994994
match val {
995-
const_bool(b) => Ok($const_type(b as $intermediate_ty as $target_ty)),
995+
const_bool(b) => Ok($const_type(b as u64 as $intermediate_ty as $target_ty)),
996996
const_uint(u) => Ok($const_type(u as $intermediate_ty as $target_ty)),
997997
const_int(i) => Ok($const_type(i as $intermediate_ty as $target_ty)),
998998
const_float(f) => Ok($const_type(f as $intermediate_ty as $target_ty)),

src/librustc/middle/ty.rs

+15-9
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ use session::Session;
4141
use lint;
4242
use metadata::csearch;
4343
use middle;
44+
use middle::cast;
4445
use middle::check_const;
4546
use middle::const_eval;
4647
use middle::def::{self, DefMap, ExportMap};
@@ -288,15 +289,6 @@ pub struct field_ty {
288289
pub origin: ast::DefId, // The DefId of the struct in which the field is declared.
289290
}
290291

291-
// Contains information needed to resolve types and (in the future) look up
292-
// the types of AST nodes.
293-
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
294-
pub struct creader_cache_key {
295-
pub cnum: CrateNum,
296-
pub pos: usize,
297-
pub len: usize
298-
}
299-
300292
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
301293
pub struct ItemVariances {
302294
pub types: VecPerParamSpace<Variance>,
@@ -562,6 +554,15 @@ pub enum vtable_origin<'tcx> {
562554
// expr to the associated trait ref.
563555
pub type ObjectCastMap<'tcx> = RefCell<NodeMap<ty::PolyTraitRef<'tcx>>>;
564556

557+
// Contains information needed to resolve types and (in the future) look up
558+
// the types of AST nodes.
559+
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
560+
pub struct creader_cache_key {
561+
pub cnum: CrateNum,
562+
pub pos: usize,
563+
pub len: usize
564+
}
565+
565566
/// A restriction that certain types must be the same size. The use of
566567
/// `transmute` gives rise to these restrictions. These generally
567568
/// cannot be checked until trans; therefore, each call to `transmute`
@@ -827,6 +828,10 @@ pub struct ctxt<'tcx> {
827828

828829
/// Caches CoerceUnsized kinds for impls on custom types.
829830
pub custom_coerce_unsized_kinds: RefCell<DefIdMap<CustomCoerceUnsized>>,
831+
832+
/// Maps a cast expression to its kind. This is keyed on the
833+
/// *from* expression of the cast, not the cast itself.
834+
pub cast_kinds: RefCell<NodeMap<cast::CastKind>>,
830835
}
831836

832837
impl<'tcx> ctxt<'tcx> {
@@ -2819,6 +2824,7 @@ pub fn mk_ctxt<'tcx>(s: Session,
28192824
type_impls_sized_cache: RefCell::new(HashMap::new()),
28202825
const_qualif_map: RefCell::new(NodeMap()),
28212826
custom_coerce_unsized_kinds: RefCell::new(DefIdMap()),
2827+
cast_kinds: RefCell::new(NodeMap()),
28222828
}
28232829
}
28242830

src/librustc_trans/trans/consts.rs

+40-30
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use trans::declare;
2929
use trans::monomorphize;
3030
use trans::type_::Type;
3131
use trans::type_of;
32+
use middle::cast::{CastTy,IntTy};
3233
use middle::subst::Substs;
3334
use middle::ty::{self, Ty};
3435
use util::ppaux::{Repr, ty_to_string};
@@ -616,53 +617,62 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
616617
}
617618
}
618619
ast::ExprCast(ref base, _) => {
619-
let llty = type_of::type_of(cx, ety);
620-
let (v, basety) = const_expr(cx, &**base, param_substs);
621-
if expr::cast_is_noop(basety, ety) {
620+
let t_1 = ety;
621+
let llty = type_of::type_of(cx, t_1);
622+
let (v, t_e) = const_expr(cx, &**base, param_substs);
623+
debug!("trans_const_cast({} as {})", t_e.repr(cx.tcx()), t_1.repr(cx.tcx()));
624+
if expr::cast_is_noop(cx.tcx(), base, t_e, t_1) {
622625
return v;
623626
}
624-
match (expr::cast_type_kind(cx.tcx(), basety),
625-
expr::cast_type_kind(cx.tcx(), ety)) {
626-
627-
(expr::cast_integral, expr::cast_integral) => {
628-
let s = ty::type_is_signed(basety) as Bool;
627+
if type_is_fat_ptr(cx.tcx(), t_e) {
628+
// Fat pointer casts.
629+
let t_1_inner = ty::deref(t_1, true).expect("cast to non-pointer").ty;
630+
let ptr_ty = type_of::in_memory_type_of(cx, t_1_inner).ptr_to();
631+
let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
632+
ptr_ty);
633+
if type_is_fat_ptr(cx.tcx(), t_1) {
634+
let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
635+
return C_struct(cx, &[addr, info], false)
636+
} else {
637+
return addr;
638+
}
639+
}
640+
match (CastTy::recognize(cx.tcx(), t_e).expect("bad input type for cast"),
641+
CastTy::recognize(cx.tcx(), t_1).expect("bad output type for cast")) {
642+
(CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
643+
let repr = adt::represent_type(cx, t_e);
644+
let discr = adt::const_get_discrim(cx, &*repr, v);
645+
let iv = C_integral(cx.int_type(), discr, false);
646+
let s = adt::is_discr_signed(&*repr) as Bool;
647+
llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
648+
}
649+
(CastTy::Int(_), CastTy::Int(_)) => {
650+
let s = ty::type_is_signed(t_e) as Bool;
629651
llvm::LLVMConstIntCast(v, llty.to_ref(), s)
630652
}
631-
(expr::cast_integral, expr::cast_float) => {
632-
if ty::type_is_signed(basety) {
653+
(CastTy::Int(_), CastTy::Float) => {
654+
if ty::type_is_signed(t_e) {
633655
llvm::LLVMConstSIToFP(v, llty.to_ref())
634656
} else {
635657
llvm::LLVMConstUIToFP(v, llty.to_ref())
636658
}
637659
}
638-
(expr::cast_float, expr::cast_float) => {
660+
(CastTy::Float, CastTy::Float) => {
639661
llvm::LLVMConstFPCast(v, llty.to_ref())
640662
}
641-
(expr::cast_float, expr::cast_integral) => {
642-
if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
663+
(CastTy::Float, CastTy::Int(_)) => {
664+
if ty::type_is_signed(t_1) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
643665
else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
644666
}
645-
(expr::cast_enum, expr::cast_integral) => {
646-
let repr = adt::represent_type(cx, basety);
647-
let discr = adt::const_get_discrim(cx, &*repr, v);
648-
let iv = C_integral(cx.int_type(), discr, false);
649-
let ety_cast = expr::cast_type_kind(cx.tcx(), ety);
650-
match ety_cast {
651-
expr::cast_integral => {
652-
let s = ty::type_is_signed(ety) as Bool;
653-
llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
654-
}
655-
_ => cx.sess().bug("enum cast destination is not \
656-
integral")
657-
}
658-
}
659-
(expr::cast_pointer, expr::cast_pointer) => {
667+
(CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FPtr, CastTy::Ptr(_))
668+
| (CastTy::RPtr(_), CastTy::Ptr(_)) => {
660669
ptrcast(v, llty)
661670
}
662-
(expr::cast_integral, expr::cast_pointer) => {
671+
(CastTy::FPtr, CastTy::FPtr) => ptrcast(v, llty), // isn't this a coercion?
672+
(CastTy::Int(_), CastTy::Ptr(_)) => {
663673
llvm::LLVMConstIntToPtr(v, llty.to_ref())
664674
}
665-
(expr::cast_pointer, expr::cast_integral) => {
675+
(CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FPtr, CastTy::Int(_)) => {
666676
llvm::LLVMConstPtrToInt(v, llty.to_ref())
667677
}
668678
_ => {

0 commit comments

Comments
 (0)