Skip to content

Commit

Permalink
add ptr->int and int->ptr type cast rules
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
nobel-sh committed Dec 22, 2024
1 parent b5c354d commit 1f1a346
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
23 changes: 22 additions & 1 deletion gcc/rust/typecheck/rust-casts.cc
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,15 @@ TypeCastRules::cast_rules ()
case TyTy::TypeKind::INT:
return TypeCoercionRules::CoercionResult{{}, to.get_ty ()->clone ()};

case TyTy::TypeKind::POINTER: {
// char can't be casted as ptr
bool from_char
= from.get_ty ()->get_kind () == TyTy::TypeKind::CHAR;
if (!from_char)
return TypeCoercionRules::CoercionResult{{},
to.get_ty ()->clone ()};
}

default:
return TypeCoercionRules::CoercionResult::get_error ();
}
Expand Down Expand Up @@ -258,7 +267,19 @@ TypeCastRules::cast_rules ()
case TyTy::TypeKind::POINTER:
return check_ptr_ptr_cast ();

// FIXME can you cast a pointer to a integral type?
case TyTy::TypeKind::USIZE:
case TyTy::TypeKind::ISIZE:
case TyTy::TypeKind::UINT:
case TyTy::TypeKind::INT: {
// refs should not cast to numeric type
bool from_ptr
= from.get_ty ()->get_kind () == TyTy::TypeKind::POINTER;
if (from_ptr)
{
return TypeCoercionRules::CoercionResult{
{}, to.get_ty ()->clone ()};
}
}

default:
return TypeCoercionRules::CoercionResult::get_error ();
Expand Down
18 changes: 18 additions & 0 deletions gcc/testsuite/rust/compile/ptr_int_cast.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fn main(){
let foo = 1337;
let bar_ptr = &foo as *const i32;

let bar_ptr_usize = bar_ptr as usize;
let bar_ptr_isize = bar_ptr as isize;
let bar_ptr_u64 = bar_ptr as u64;
let bar_ptr_i64 = bar_ptr as i64;
let bar_ptr_i8 = bar_ptr as i8;
let bar_ptr_u8 = bar_ptr as u8;

let _ = bar_ptr_usize as *const i32;
let _ = bar_ptr_isize as *const i32;
let _ = bar_ptr_u64 as *const i32;
let _ = bar_ptr_i64 as *const i32;
let _ = bar_ptr_i8 as *const i32;
let _ = bar_ptr_u8 as *const i32;
}

0 comments on commit 1f1a346

Please sign in to comment.