Implement rudamentary borrow

This commit is contained in:
Sofia 2025-07-16 23:49:28 +03:00
parent e4ce897f94
commit 965ad5797f
3 changed files with 36 additions and 10 deletions

View File

@ -415,8 +415,14 @@ impl mir::Expression {
}
}
mir::ExprKind::Indexed(expression, val_t, idx_expr) => {
let array = expression.codegen(scope, state)?;
let idx = idx_expr.codegen(scope, state)?;
dbg!(&expression, &idx_expr);
let array = expression
.codegen(scope, state)
.expect("array returned none!");
let idx = idx_expr
.codegen(scope, state)
.expect("index returned none!");
let mut ptr = scope
.block
.build(Instr::GetElemPtr(array, vec![idx]))
@ -468,14 +474,19 @@ impl mir::Expression {
Some(array)
}
mir::ExprKind::Accessed(expression, type_kind, field) => {
let struct_val = expression.codegen(scope, &mut state.load(true))?;
let struct_val = expression.codegen(scope, &mut state.load(true)).unwrap();
let struct_ty = expression.return_type().ok()?.1.known().ok()?;
let TypeKind::CustomType(name) = struct_ty else {
return None;
let struct_ty = expression
.return_type()
.map(|r| r.1.known())
.unwrap()
.unwrap();
let TypeKind::CustomType(name) = struct_ty.deref_borrow() else {
panic!("tried accessing non-custom-type");
};
let TypeDefinitionKind::Struct(struct_ty) = scope.get_typedef(&name)?;
let idx = struct_ty.find_index(field)?;
let TypeDefinitionKind::Struct(struct_ty) = scope.get_typedef(&name).unwrap();
let idx = struct_ty.find_index(field).unwrap();
let mut value = scope
.block
@ -644,6 +655,9 @@ impl TypeKind {
TypeDefinitionKind::Struct(_) => Type::Ptr(Box::new(custom_t)),
}
}
TypeKind::Borrow(type_kind) => {
Type::Ptr(Box::new(type_kind.get_type(type_vals, typedefs)))
}
}
}
}

View File

@ -149,7 +149,7 @@ impl Expression {
Indexed(expression, _, _) => {
let expr_type = expression.return_type()?;
if let (_, TypeKind::Array(elem_ty, _)) = expr_type {
Ok((ReturnKind::Soft, *elem_ty))
Ok((ReturnKind::Soft, TypeKind::Borrow(Box::new(*elem_ty))))
} else {
Err(ReturnTypeOther::IndexingNonArray(expression.1))
}
@ -165,7 +165,10 @@ impl Expression {
TypeKind::Array(Box::new(first.1), expressions.len() as u64),
))
}
Accessed(_, type_kind, _) => Ok((ReturnKind::Soft, type_kind.clone())),
Accessed(_, type_kind, _) => Ok((
ReturnKind::Soft,
TypeKind::Borrow(Box::new(type_kind.clone())),
)),
Struct(name, _) => Ok((ReturnKind::Soft, TypeKind::CustomType(name.clone()))),
}
}
@ -267,6 +270,13 @@ impl TypeKind {
_ => resolved,
}
}
pub fn deref_borrow(&self) -> TypeKind {
match self {
TypeKind::Borrow(type_kind) => *type_kind.clone(),
_ => self.clone(),
}
}
}
#[derive(Debug, Clone, thiserror::Error)]

View File

@ -65,6 +65,8 @@ pub enum TypeKind {
StringPtr,
#[error("[{0}; {1}]")]
Array(Box<TypeKind>, u64),
#[error("Borrow({0})")]
Borrow(Box<TypeKind>),
#[error("{0}")]
CustomType(String),
#[error(transparent)]