Fix pointer-casting

This commit is contained in:
Sofia 2025-07-22 14:19:28 +03:00
parent c03a5188ea
commit e27aa4b8ab
4 changed files with 27 additions and 17 deletions

View File

@ -1,13 +1,13 @@
extern fn puts(message: *str) -> i32; extern fn puts(message: *str) -> i32;
extern fn malloc(size: u64) -> *u8;
extern fn div(numerator: i32, denominator: i32) -> div_t;
struct div_t { struct div_t {
quotient: i32, quotient: i32,
remainder: i32, remainder: i32,
} }
extern fn div(numerator: i32, denominator: i32) -> div_t;
pub fn print(message: *str) { pub fn print(message: *str) {
puts(message); puts(message);
} }
@ -16,6 +16,10 @@ pub fn int_div(numerator: i32, denominator: i32) -> div_t {
return div(numerator, denominator); return div(numerator, denominator);
} }
pub fn allocate(size: u64) -> *u8 {
malloc(size)
}
fn main() -> u16 { fn main() -> u16 {
return 0; return 0;
} }

View File

@ -1030,18 +1030,22 @@ impl mir::Expression {
} }
mir::ExprKind::CastTo(expression, type_kind) => { mir::ExprKind::CastTo(expression, type_kind) => {
let val = expression.codegen(scope, state)?; let val = expression.codegen(scope, state)?;
let cast_instr = val let instr =
.1 if let (TypeKind::UserPtr(_), TypeKind::UserPtr(_)) = (&val.1, type_kind) {
.get_type(scope.type_values, scope.types) val.0.instr()
.cast_instruction( } else {
val.instr(), let cast_instr = val
&type_kind.get_type(scope.type_values, scope.types), .1
) .get_type(scope.type_values, scope.types)
.unwrap(); .cast_instruction(
Some(StackValue( val.instr(),
val.0.derive(scope.block.build(cast_instr).unwrap()), &type_kind.get_type(scope.type_values, scope.types),
type_kind.clone(), )
)) .unwrap();
scope.block.build(cast_instr).unwrap()
};
Some(StackValue(val.0.derive(instr), type_kind.clone()))
} }
}; };
if let Some(value) = &value { if let Some(value) = &value {

View File

@ -1,5 +1,7 @@
// Arithmetic, function calls and imports! // Arithmetic, function calls and imports!
import std::allocate;
fn other() -> i16 { fn other() -> i16 {
return 6; return 6;
} }
@ -7,5 +9,7 @@ fn other() -> i16 {
fn main() -> u32 { fn main() -> u32 {
let value = other() as u32; let value = other() as u32;
return value; let v = (allocate(4) as *u32);
return v[0];
} }

View File

@ -1,8 +1,6 @@
// Arithmetic, function calls and imports! // Arithmetic, function calls and imports!
extern fn malloc(size: u64) -> *u8;
fn main() -> u8 { fn main() -> u8 {
let mut ptr = malloc(4); let mut ptr = malloc(4);