use std::sync::Arc;
use crate::ast::{self, ExprKind};
use crate::codegen::backend::{CodegenError, CodegenResult};
use crate::codegen::ir::*;
use super::MirLowerer;
fn is_pure_place(expr: &ast::Expr) -> bool {
match &expr.kind {
ExprKind::Ident(_) | ExprKind::Literal(_) => true,
ExprKind::Paren(e) | ExprKind::Deref(e) => is_pure_place(e),
ExprKind::Field { expr: e, .. } | ExprKind::TupleField { expr: e, .. } => is_pure_place(e),
ExprKind::Index { expr: e, index } => is_pure_place(e) && is_pure_place(index),
_ => false,
}
}
impl<'ctx> MirLowerer<'ctx> {
pub(super) fn mutable_global(&self, name: &Arc<str>) -> Option<(Arc<str>, MirType)> {
if self.var_map.contains_key(name) {
return None;
}
let candidates = [self.prefixed_name(name), name.clone()];
candidates.into_iter().find_map(|n| {
let global = self.module.find_global(n.as_ref())?;
(global.is_mut && !global.is_extern_decl).then(|| (n.clone(), global.ty.clone()))
})
}
pub(super) fn is_global_array_name(&self, expr: &ast::Expr) -> bool {
match &expr.kind {
ExprKind::Paren(inner) => self.is_global_array_name(inner),
ExprKind::Ident(id) => {
matches!(self.mutable_global(&id.name), Some((_, MirType::Array(..))))
}
_ => false,
}
}
pub(super) fn global_address(&mut self, name: Arc<str>, ty: MirType) -> CodegenResult<LocalId> {
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let ptr = builder.create_local(MirType::Ptr(Box::new(ty)));
builder.assign(ptr, MirRValue::AddressOfGlobal { is_mut: true, name });
Ok(ptr)
}
pub(super) fn global_place(
&mut self,
ident: &ast::Ident,
) -> CodegenResult<Option<(MirPlace, MirType)>> {
let Some((name, ty)) = self.mutable_global(&ident.name) else {
return Ok(None);
};
let ptr = self.global_address(name, ty.clone())?;
Ok(Some((MirPlace::local(ptr).deref(), ty)))
}
pub(super) fn receiver_place_ref(
&mut self,
receiver: &ast::Expr,
) -> CodegenResult<Option<MirValue>> {
let is_local =
matches!(&receiver.kind, ExprKind::Ident(id) if self.var_map.contains_key(&id.name));
if is_local || !is_pure_place(receiver) {
return Ok(None);
}
let Some((place, ty)) = self.lower_place(receiver)? else {
return Ok(None);
};
if matches!(ty, MirType::Ptr(_)) {
return Ok(None);
}
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let ptr = builder.create_local(MirType::Ptr(Box::new(ty)));
builder.make_ref(ptr, true, place);
Ok(Some(MirValue::Local(ptr)))
}
pub(super) fn global_ref(&mut self, inner: &ast::Expr) -> CodegenResult<Option<MirValue>> {
let ExprKind::Ident(ident) = &inner.kind else {
return Ok(None);
};
let Some((name, ty)) = self.mutable_global(&ident.name) else {
return Ok(None);
};
let ptr = self.global_address(name, ty)?;
Ok(Some(MirValue::Local(ptr)))
}
}