Fix casting within setters

This commit is contained in:
Sofia 2025-07-22 19:31:35 +03:00
parent 81ce1dfc2e
commit 3d73c52cb4
12 changed files with 84 additions and 63 deletions

View File

@ -389,7 +389,6 @@ impl Builder {
return Err(()); // TODO error: invalid amount of params return Err(()); // TODO error: invalid amount of params
} }
for (a, b) in param_types.iter().zip(params) { for (a, b) in param_types.iter().zip(params) {
dbg!(&a, &b.get_type(&self));
if *a != b.get_type(&self)? { if *a != b.get_type(&self)? {
return Err(()); // TODO error: params do not match return Err(()); // TODO error: params do not match
} }
@ -479,7 +478,7 @@ impl Builder {
Instr::SIToFP(instr, ty) => instr.cast_to(self, &ty).map(|_| ()), Instr::SIToFP(instr, ty) => instr.cast_to(self, &ty).map(|_| ()),
Instr::PtrToInt(instr, ty) => instr.cast_to(self, &ty).map(|_| ()), Instr::PtrToInt(instr, ty) => instr.cast_to(self, &ty).map(|_| ()),
Instr::IntToPtr(instr, ty) => instr.cast_to(self, &ty).map(|_| ()), Instr::IntToPtr(instr, ty) => instr.cast_to(self, &ty).map(|_| ()),
Instr::BitCast(instr, ty) => Ok(()), Instr::BitCast(..) => Ok(()),
} }
} }
} }

View File

@ -41,7 +41,7 @@ pub fn add_char(string: &mut String, c: char) {
(*string).inner = allocate((*string).max_length) as *char; (*string).inner = allocate((*string).max_length) as *char;
} }
(*string).inner[(*string).length] = c; (*string).inner[(*string).length] = c;
(*string).inner[((*string).length + 1)] = '\0'; (((*string).inner) as *u8)[((*string).length + 1)] = 0;
(*string).length = (*string).length + 1; (*string).length = (*string).length + 1;
} }

View File

@ -4,7 +4,7 @@ use crate::{
ast::{self}, ast::{self},
mir::{ mir::{
self, ModuleMap, NamedVariableRef, SourceModuleId, StmtKind, StructField, StructType, self, ModuleMap, NamedVariableRef, SourceModuleId, StmtKind, StructField, StructType,
TypeKey, CustomTypeKey,
}, },
}; };
@ -322,7 +322,7 @@ impl ast::TypeKind {
mir::TypeKind::Array(Box::new(type_kind.clone().into_mir(source_mod)), *length) mir::TypeKind::Array(Box::new(type_kind.clone().into_mir(source_mod)), *length)
} }
ast::TypeKind::Custom(name) => { ast::TypeKind::Custom(name) => {
mir::TypeKind::CustomType(TypeKey(name.clone(), source_mod)) mir::TypeKind::CustomType(CustomTypeKey(name.clone(), source_mod))
} }
ast::TypeKind::Borrow(type_kind, mutable) => { ast::TypeKind::Borrow(type_kind, mutable) => {
mir::TypeKind::Borrow(Box::new(type_kind.clone().into_mir(source_mod)), *mutable) mir::TypeKind::Borrow(Box::new(type_kind.clone().into_mir(source_mod)), *mutable)

View File

@ -18,8 +18,8 @@ use crate::{
error_raporting::ErrorModules, error_raporting::ErrorModules,
lexer::{FullToken, Position}, lexer::{FullToken, Position},
mir::{ mir::{
self, implement::TypeCategory, Metadata, ModuleMap, NamedVariableRef, SourceModuleId, self, implement::TypeCategory, CustomTypeKey, Metadata, ModuleMap, NamedVariableRef,
StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKey, TypeKind, SourceModuleId, StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKind,
VagueLiteral, VagueLiteral,
}, },
}; };
@ -59,7 +59,7 @@ struct ModuleCodegen<'ctx> {
module: Module<'ctx>, module: Module<'ctx>,
tokens: &'ctx Vec<FullToken>, tokens: &'ctx Vec<FullToken>,
debug_types: Option<HashMap<TypeKind, DebugTypeValue>>, debug_types: Option<HashMap<TypeKind, DebugTypeValue>>,
type_values: HashMap<TypeKey, TypeValue>, type_values: HashMap<CustomTypeKey, TypeValue>,
} }
impl<'ctx> std::fmt::Debug for ModuleCodegen<'ctx> { impl<'ctx> std::fmt::Debug for ModuleCodegen<'ctx> {
@ -77,7 +77,7 @@ pub struct Scope<'ctx, 'scope> {
function: &'ctx StackFunction<'ctx>, function: &'ctx StackFunction<'ctx>,
block: Block<'ctx>, block: Block<'ctx>,
types: &'scope HashMap<TypeValue, TypeDefinition>, types: &'scope HashMap<TypeValue, TypeDefinition>,
type_values: &'scope HashMap<TypeKey, TypeValue>, type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
functions: &'scope HashMap<String, StackFunction<'ctx>>, functions: &'scope HashMap<String, StackFunction<'ctx>>,
stack_values: HashMap<String, StackValue>, stack_values: HashMap<String, StackValue>,
debug: Option<Debug<'ctx>>, debug: Option<Debug<'ctx>>,
@ -169,7 +169,7 @@ impl<'ctx, 'a> Scope<'ctx, 'a> {
old_block old_block
} }
fn get_typedef(&self, key: &TypeKey) -> Option<&TypeDefinition> { fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> {
self.type_values.get(key).and_then(|v| self.types.get(v)) self.type_values.get(key).and_then(|v| self.types.get(v))
} }
} }
@ -255,7 +255,7 @@ impl mir::Module {
typedefs.sort_by(|a, b| b.source_module.cmp(&a.source_module)); typedefs.sort_by(|a, b| b.source_module.cmp(&a.source_module));
for typedef in typedefs { for typedef in typedefs {
let type_key = TypeKey(typedef.name.clone(), typedef.source_module); let type_key = CustomTypeKey(typedef.name.clone(), typedef.source_module);
let type_value = match &typedef.kind { let type_value = match &typedef.kind {
TypeDefinitionKind::Struct(StructType(fields)) => { TypeDefinitionKind::Struct(StructType(fields)) => {
module.custom_type(CustomTypeKind::NamedStruct(NamedStruct( module.custom_type(CustomTypeKind::NamedStruct(NamedStruct(
@ -391,8 +391,6 @@ impl mir::Module {
&debug_scope, &debug_scope,
mir_function.signature().into_debug(tokens, compile_unit), mir_function.signature().into_debug(tokens, compile_unit),
) { ) {
dbg!(mir_function.name.clone());
dbg!(p_name.clone());
// debug.metadata( // debug.metadata(
// &location, // &location,
// DebugMetadata::ParamVar(DebugParamVariable { // DebugMetadata::ParamVar(DebugParamVariable {
@ -956,7 +954,7 @@ impl mir::Expression {
} }
} }
mir::ExprKind::Struct(name, items) => { mir::ExprKind::Struct(name, items) => {
let type_key = TypeKey(name.clone(), scope.module_id); let type_key = CustomTypeKey(name.clone(), scope.module_id);
let struct_ty = Type::CustomType(*scope.type_values.get(&type_key)?); let struct_ty = Type::CustomType(*scope.type_values.get(&type_key)?);
let load_n = format!("{}.load", name); let load_n = format!("{}.load", name);
@ -1062,10 +1060,30 @@ 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)?;
if val.1 == *type_kind { if val.1 == *type_kind {
Some(val) Some(val)
} else if let (TypeKind::UserPtr(_), TypeKind::UserPtr(_)) = (&val.1, type_kind) { } else {
Some(StackValue( match (&val.1, type_kind) {
(TypeKind::CodegenPtr(inner), TypeKind::UserPtr(_)) => match *inner.clone()
{
TypeKind::UserPtr(_) => Some(StackValue(
val.0.derive(
scope
.block
.build(Instr::BitCast(
val.instr(),
Type::Ptr(Box::new(
type_kind.get_type(scope.type_values, scope.types),
)),
))
.unwrap(),
),
TypeKind::CodegenPtr(Box::new(type_kind.clone())),
)),
_ => panic!(),
},
(TypeKind::UserPtr(_), TypeKind::UserPtr(_)) => Some(StackValue(
val.0.derive( val.0.derive(
scope scope
.block .block
@ -1076,8 +1094,8 @@ impl mir::Expression {
.unwrap(), .unwrap(),
), ),
type_kind.clone(), type_kind.clone(),
)) )),
} else { _ => {
let cast_instr = val let cast_instr = val
.1 .1
.get_type(scope.type_values, scope.types) .get_type(scope.type_values, scope.types)
@ -1093,6 +1111,8 @@ impl mir::Expression {
)) ))
} }
} }
}
}
}; };
if let Some(value) = &value { if let Some(value) = &value {
value.instr().maybe_location(&mut scope.block, location); value.instr().maybe_location(&mut scope.block, location);
@ -1257,7 +1277,7 @@ impl mir::Literal {
impl TypeKind { impl TypeKind {
fn get_type( fn get_type(
&self, &self,
type_vals: &HashMap<TypeKey, TypeValue>, type_vals: &HashMap<CustomTypeKey, TypeValue>,
typedefs: &HashMap<TypeValue, TypeDefinition>, typedefs: &HashMap<TypeValue, TypeDefinition>,
) -> Type { ) -> Type {
match &self { match &self {
@ -1321,7 +1341,7 @@ impl TypeKind {
scope: DebugProgramValue, scope: DebugProgramValue,
debug_info: &DebugInformation, debug_info: &DebugInformation,
debug_types: &HashMap<TypeKind, DebugTypeValue>, debug_types: &HashMap<TypeKind, DebugTypeValue>,
type_values: &HashMap<TypeKey, TypeValue>, type_values: &HashMap<CustomTypeKey, TypeValue>,
types: &HashMap<TypeValue, TypeDefinition>, types: &HashMap<TypeValue, TypeDefinition>,
local_mod: SourceModuleId, local_mod: SourceModuleId,
tokens: &Vec<FullToken>, tokens: &Vec<FullToken>,

View File

@ -345,7 +345,7 @@ impl Display for TypeKind {
Display::fmt(len, f)?; Display::fmt(len, f)?;
f.write_char(']') f.write_char(']')
} }
TypeKind::CustomType(TypeKey(name, mod_id)) => write!(f, "{}:{}", mod_id, name), TypeKind::CustomType(CustomTypeKey(name, mod_id)) => write!(f, "{}:{}", mod_id, name),
TypeKind::Borrow(type_kind, false) => { TypeKind::Borrow(type_kind, false) => {
write!(f, "&")?; write!(f, "&")?;
Display::fmt(type_kind, f) Display::fmt(type_kind, f)

View File

@ -412,7 +412,7 @@ impl Expression {
Accessed(_, type_kind, _) => Ok((ReturnKind::Soft, type_kind.clone())), Accessed(_, type_kind, _) => Ok((ReturnKind::Soft, type_kind.clone())),
Struct(name, _) => Ok(( Struct(name, _) => Ok((
ReturnKind::Soft, ReturnKind::Soft,
TypeKind::CustomType(TypeKey(name.clone(), mod_id)), TypeKind::CustomType(CustomTypeKey(name.clone(), mod_id)),
)), )),
Borrow(var, mutable) => { Borrow(var, mutable) => {
let ret_type = var.return_type()?; let ret_type = var.return_type()?;

View File

@ -10,7 +10,7 @@ use std::{
use crate::{ use crate::{
compile_module, compile_module,
error_raporting::{ErrorModules, ReidError}, error_raporting::{ErrorModules, ReidError},
mir::{SourceModuleId, TypeDefinition, TypeKey, TypeKind}, mir::{SourceModuleId, TypeDefinition, CustomTypeKey, TypeKind},
parse_module, parse_module,
}; };
@ -232,7 +232,7 @@ impl<'map> Pass for LinkerPass<'map> {
} }
} }
fn import_type(base: &String, ty: &TypeKind) -> (TypeKind, Vec<TypeKey>) { fn import_type(base: &String, ty: &TypeKind) -> (TypeKind, Vec<CustomTypeKey>) {
let mut imported_types = Vec::new(); let mut imported_types = Vec::new();
let ty = match &ty { let ty = match &ty {
TypeKind::CustomType(key) => { TypeKind::CustomType(key) => {
@ -258,9 +258,9 @@ impl<'map> Pass for LinkerPass<'map> {
fn find_inner_types( fn find_inner_types(
typedef: &TypeDefinition, typedef: &TypeDefinition,
mut seen: HashSet<TypeKey>, mut seen: HashSet<CustomTypeKey>,
mod_id: SourceModuleId, mod_id: SourceModuleId,
) -> Vec<TypeKey> { ) -> Vec<CustomTypeKey> {
match &typedef.kind { match &typedef.kind {
crate::mir::TypeDefinitionKind::Struct(struct_type) => { crate::mir::TypeDefinitionKind::Struct(struct_type) => {
let typenames = struct_type let typenames = struct_type
@ -268,18 +268,18 @@ impl<'map> Pass for LinkerPass<'map> {
.iter() .iter()
.filter(|t| matches!(t.1, TypeKind::CustomType(..))) .filter(|t| matches!(t.1, TypeKind::CustomType(..)))
.map(|t| match &t.1 { .map(|t| match &t.1 {
TypeKind::CustomType(TypeKey(t, _)) => t, TypeKind::CustomType(CustomTypeKey(t, _)) => t,
_ => panic!(), _ => panic!(),
}) })
.cloned() .cloned()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for typename in typenames { for typename in typenames {
if seen.contains(&TypeKey(typename.clone(), mod_id)) { if seen.contains(&CustomTypeKey(typename.clone(), mod_id)) {
continue; continue;
} }
let inner = find_inner_types(typedef, seen.clone(), mod_id); let inner = find_inner_types(typedef, seen.clone(), mod_id);
seen.insert(TypeKey(typename, mod_id)); seen.insert(CustomTypeKey(typename, mod_id));
seen.extend(inner); seen.extend(inner);
} }
@ -297,7 +297,7 @@ impl<'map> Pass for LinkerPass<'map> {
for typekey in imported_types.clone() { for typekey in imported_types.clone() {
let typedef = imported_mod_typedefs let typedef = imported_mod_typedefs
.iter() .iter()
.find(|ty| TypeKey(ty.name.clone(), imported_mod_id) == typekey) .find(|ty| CustomTypeKey(ty.name.clone(), imported_mod_id) == typekey)
.unwrap(); .unwrap();
let inner = find_inner_types(typedef, seen.clone(), imported_mod_id); let inner = find_inner_types(typedef, seen.clone(), imported_mod_id);
seen.extend(inner); seen.extend(inner);
@ -306,7 +306,7 @@ impl<'map> Pass for LinkerPass<'map> {
for typekey in seen.into_iter() { for typekey in seen.into_iter() {
let typedef = imported_mod_typedefs let typedef = imported_mod_typedefs
.iter() .iter()
.find(|ty| TypeKey(ty.name.clone(), imported_mod_id) == typekey) .find(|ty| CustomTypeKey(ty.name.clone(), imported_mod_id) == typekey)
.unwrap() .unwrap()
.clone(); .clone();

View File

@ -78,7 +78,7 @@ impl TokenRange {
} }
#[derive(Hash, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] #[derive(Hash, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct TypeKey(pub String, pub SourceModuleId); pub struct CustomTypeKey(pub String, pub SourceModuleId);
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TypeKind { pub enum TypeKind {
@ -103,7 +103,7 @@ pub enum TypeKind {
F128PPC, F128PPC,
Char, Char,
Array(Box<TypeKind>, u64), Array(Box<TypeKind>, u64),
CustomType(TypeKey), CustomType(CustomTypeKey),
Borrow(Box<TypeKind>, bool), Borrow(Box<TypeKind>, bool),
UserPtr(Box<TypeKind>), UserPtr(Box<TypeKind>),
CodegenPtr(Box<TypeKind>), CodegenPtr(Box<TypeKind>),

View File

@ -117,7 +117,7 @@ impl<Key: std::hash::Hash + Eq, T: Clone + std::fmt::Debug> Storage<Key, T> {
pub struct Scope<Data: Clone + Default> { pub struct Scope<Data: Clone + Default> {
pub function_returns: Storage<String, ScopeFunction>, pub function_returns: Storage<String, ScopeFunction>,
pub variables: Storage<String, ScopeVariable>, pub variables: Storage<String, ScopeVariable>,
pub types: Storage<TypeKey, TypeDefinition>, pub types: Storage<CustomTypeKey, TypeDefinition>,
/// Hard Return type of this scope, if inside a function /// Hard Return type of this scope, if inside a function
pub return_type_hint: Option<TypeKind>, pub return_type_hint: Option<TypeKind>,
pub data: Data, pub data: Data,
@ -134,18 +134,18 @@ impl<Data: Clone + Default> Scope<Data> {
} }
} }
pub fn get_struct_type(&self, key: &TypeKey) -> Option<&StructType> { pub fn get_struct_type(&self, key: &CustomTypeKey) -> Option<&StructType> {
let ty = self.types.get(&key)?; let ty = self.types.get(&key)?;
match &ty.kind { match &ty.kind {
TypeDefinitionKind::Struct(struct_ty) => Some(struct_ty), TypeDefinitionKind::Struct(struct_ty) => Some(struct_ty),
} }
} }
pub fn find_type(&self, name: &String) -> Option<&TypeKey> { pub fn find_type(&self, name: &String) -> Option<&CustomTypeKey> {
self.types self.types
.0 .0
.iter() .iter()
.find(|(TypeKey(n, _), _)| n == name) .find(|(CustomTypeKey(n, _), _)| n == name)
.map(|(key, _)| key) .map(|(key, _)| key)
} }
} }
@ -295,7 +295,7 @@ impl Module {
scope scope
.types .types
.set( .set(
TypeKey(typedef.name.clone(), self.module_id), CustomTypeKey(typedef.name.clone(), self.module_id),
typedef.clone(), typedef.clone(),
) )
.ok(); .ok();

View File

@ -138,7 +138,7 @@ fn check_typedefs_for_recursion<'a, 'b>(
match &typedef.kind { match &typedef.kind {
TypeDefinitionKind::Struct(StructType(fields)) => { TypeDefinitionKind::Struct(StructType(fields)) => {
for field_ty in fields.iter().map(|StructField(_, ty, _)| ty) { for field_ty in fields.iter().map(|StructField(_, ty, _)| ty) {
if let TypeKind::CustomType(TypeKey(name, _)) = field_ty { if let TypeKind::CustomType(CustomTypeKey(name, _)) = field_ty {
if seen.contains(name) { if seen.contains(name) {
state.ok::<_, Infallible>( state.ok::<_, Infallible>(
Err(ErrorKind::RecursiveTypeDefinition( Err(ErrorKind::RecursiveTypeDefinition(
@ -636,7 +636,7 @@ impl Expression {
} }
} }
ExprKind::Struct(struct_name, items) => { ExprKind::Struct(struct_name, items) => {
let type_key = TypeKey(struct_name.clone(), state.module_id.unwrap()); let type_key = CustomTypeKey(struct_name.clone(), state.module_id.unwrap());
let struct_def = state let struct_def = state
.scope .scope
.get_struct_type(&type_key) .get_struct_type(&type_key)

View File

@ -14,7 +14,7 @@ use super::{
typecheck::ErrorKind, typecheck::ErrorKind,
typerefs::{ScopeTypeRefs, TypeRef, TypeRefs}, typerefs::{ScopeTypeRefs, TypeRef, TypeRefs},
Block, ExprKind, Expression, FunctionDefinition, FunctionDefinitionKind, IfExpression, Module, Block, ExprKind, Expression, FunctionDefinition, FunctionDefinitionKind, IfExpression, Module,
ReturnKind, StmtKind, TypeKey, ReturnKind, StmtKind, CustomTypeKey,
TypeKind::*, TypeKind::*,
VagueType::*, VagueType::*,
}; };
@ -339,7 +339,7 @@ impl Expression {
} }
} }
ExprKind::Struct(struct_name, fields) => { ExprKind::Struct(struct_name, fields) => {
let type_key = TypeKey(struct_name.clone(), state.module_id.unwrap()); let type_key = CustomTypeKey(struct_name.clone(), state.module_id.unwrap());
let expected_struct_ty = state let expected_struct_ty = state
.scope .scope
.get_struct_type(&type_key) .get_struct_type(&type_key)

View File

@ -13,5 +13,7 @@ fn main() -> i32 {
print(&test); print(&test);
free_string(&mut test);
return 0; return 0;
} }