Skip to content

Commit d28cae5

Browse files
nobel-shphilberty
authored andcommitted
add ptr to int and int to ptr type cast rules
Added rules to allow type casting pointer as integer types (u*,i*) and integer types to be casted as pointer. gcc/rust/ChangeLog: * typecheck/rust-casts.cc (TypeCastRules::cast_rules): Add rule. gcc/testsuite/ChangeLog: * rust/compile/ptr_int_cast.rs: New test. Signed-off-by: Nobel Singh <nobel2073@gmail.com>
1 parent b5c354d commit d28cae5

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

gcc/rust/typecheck/rust-casts.cc

+25-2
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,16 @@ TypeCastRules::cast_rules ()
210210
}
211211
break;
212212

213+
case TyTy::TypeKind::POINTER: {
214+
// char can't be casted as a ptr
215+
bool from_char
216+
= from.get_ty ()->get_kind () == TyTy::TypeKind::CHAR;
217+
if (!from_char)
218+
return TypeCoercionRules::CoercionResult{{},
219+
to.get_ty ()->clone ()};
220+
}
221+
break;
222+
213223
case TyTy::TypeKind::INFER:
214224
case TyTy::TypeKind::USIZE:
215225
case TyTy::TypeKind::ISIZE:
@@ -254,12 +264,25 @@ TypeCastRules::cast_rules ()
254264
case TyTy::TypeKind::POINTER:
255265
switch (to.get_ty ()->get_kind ())
256266
{
267+
case TyTy::TypeKind::USIZE:
268+
case TyTy::TypeKind::ISIZE:
269+
case TyTy::TypeKind::UINT:
270+
case TyTy::TypeKind::INT: {
271+
// refs should not cast to numeric type
272+
bool from_ptr
273+
= from.get_ty ()->get_kind () == TyTy::TypeKind::POINTER;
274+
if (from_ptr)
275+
{
276+
return TypeCoercionRules::CoercionResult{
277+
{}, to.get_ty ()->clone ()};
278+
}
279+
}
280+
break;
281+
257282
case TyTy::TypeKind::REF:
258283
case TyTy::TypeKind::POINTER:
259284
return check_ptr_ptr_cast ();
260285

261-
// FIXME can you cast a pointer to a integral type?
262-
263286
default:
264287
return TypeCoercionRules::CoercionResult::get_error ();
265288
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
fn main(){
2+
let foo = 1337;
3+
let bar_ptr = &foo as *const i32;
4+
5+
let bar_ptr_usize = bar_ptr as usize;
6+
let bar_ptr_isize = bar_ptr as isize;
7+
let bar_ptr_u64 = bar_ptr as u64;
8+
let bar_ptr_i64 = bar_ptr as i64;
9+
let bar_ptr_i8 = bar_ptr as i8;
10+
let bar_ptr_u8 = bar_ptr as u8;
11+
12+
let _ = bar_ptr_usize as *const i32;
13+
let _ = bar_ptr_isize as *const i32;
14+
let _ = bar_ptr_u64 as *const i32;
15+
let _ = bar_ptr_i64 as *const i32;
16+
let _ = bar_ptr_i8 as *const i32;
17+
let _ = bar_ptr_u8 as *const i32;
18+
}

0 commit comments

Comments
 (0)