use std::collections::HashMap;
use std::fmt::Write;
use crate::codegen::backend::{CodegenError, CodegenResult};
use crate::codegen::ir::{
AggregateKind, LocalId, MirLocal, MirModule, MirRValue, MirType, MirValue, TypeDefKind,
};
use super::CBackend;
pub(super) type StructFields = HashMap<String, Vec<(String, MirType)>>;
pub(super) fn struct_fields(module: &MirModule) -> StructFields {
let mut table = StructFields::new();
for def in &module.types {
if let TypeDefKind::Struct { fields, .. } = &def.kind {
let named = fields
.iter()
.enumerate()
.map(|(i, (name, ty))| {
let name = name
.as_ref()
.map(|n| n.to_string())
.unwrap_or_else(|| format!("field{i}"));
(name, ty.clone())
})
.collect();
table.insert(def.name.to_string(), named);
}
}
table
}
fn is_array(ty: &MirType) -> bool {
matches!(ty, MirType::Array(..))
}
fn local_ty(locals: &[MirLocal], id: LocalId) -> Option<&MirType> {
locals.get(id.0 as usize).map(|l| &l.ty)
}
fn value_is_array(value: &MirValue, locals: &[MirLocal]) -> bool {
matches!(value, MirValue::Local(id) if local_ty(locals, *id).is_some_and(is_array))
}
impl CBackend {
fn struct_field_type(&self, ty: Option<&MirType>, field: &str) -> Option<&MirType> {
let name = match ty? {
MirType::Struct(name) => name,
MirType::Ptr(inner) => match inner.as_ref() {
MirType::Struct(name) => name,
_ => return None,
},
_ => return None,
};
let fields = self.struct_fields.get(name.as_ref())?;
fields.iter().find(|(n, _)| n == field).map(|(_, t)| t)
}
fn array_source(&self, value: &MirValue, locals: &[MirLocal]) -> CodegenResult<String> {
match value {
MirValue::Local(_) if value_is_array(value, locals) => {
Ok(self.value_to_c(value, locals))
}
MirValue::Global(_) => Ok(self.value_to_c(value, locals)),
other => Err(CodegenError::Unsupported(format!(
"the C backend cannot copy an array from `{other}`: it is not an array local"
))),
}
}
fn emit_array_copy(
&mut self,
target: &str,
size_of: &str,
value: &MirValue,
locals: &[MirLocal],
) -> CodegenResult<()> {
let src = self.array_source(value, locals)?;
self.write_indent();
writeln!(self.output, "memcpy({target}, {src}, sizeof({size_of}));").unwrap();
Ok(())
}
pub(super) fn emit_struct_with_array_members(
&mut self,
dest_name: &str,
kind: &AggregateKind,
operands: &[MirValue],
locals: &[MirLocal],
) -> CodegenResult<bool> {
let AggregateKind::Struct(name) = kind else {
return Ok(false);
};
let Some(fields) = self.struct_fields.get(name.as_ref()).cloned() else {
return Ok(false);
};
if !fields.iter().any(|(_, ty)| is_array(ty)) {
return Ok(false);
}
if fields.len() != operands.len() {
return Err(CodegenError::Unsupported(format!(
"struct `{name}` has {} fields and an array among them, but the literal gives {}",
fields.len(),
operands.len()
)));
}
for ((field, ty), value) in fields.iter().zip(operands) {
let target = format!("{dest_name}.{}", Self::escape_c_keyword(field));
if is_array(ty) {
self.emit_array_copy(&target, &target, value, locals)?;
} else {
self.write_indent();
let value = self.value_to_c(value, locals);
writeln!(self.output, "{target} = {value};").unwrap();
}
}
Ok(true)
}
pub(super) fn check_aggregate_has_no_array_member(
&self,
kind: &AggregateKind,
operands: &[MirValue],
locals: &[MirLocal],
) -> CodegenResult<()> {
let what = match kind {
AggregateKind::Tuple => "a tuple".to_string(),
AggregateKind::Variant(name, _, variant) => format!("`{name}::{variant}`"),
AggregateKind::Struct(name) => {
let known = self.struct_fields.get(name.as_ref());
if !known.is_some_and(|f| f.iter().any(|(_, ty)| is_array(ty))) {
return Ok(());
}
format!("struct `{name}` in this position")
}
AggregateKind::Array(_) | AggregateKind::Closure(_) => return Ok(()),
};
if matches!(kind, AggregateKind::Struct(_))
|| operands.iter().any(|v| value_is_array(v, locals))
{
return Err(CodegenError::Unsupported(format!(
"the C backend cannot build {what} with a fixed array inside it; \
put the array in a named struct and bind the struct with `let`"
)));
}
Ok(())
}
fn emit_store_if_array(
&mut self,
target: &str,
ty: Option<&MirType>,
value: &MirRValue,
locals: &[MirLocal],
) -> CodegenResult<bool> {
if !ty.is_some_and(is_array) {
return Ok(false);
}
let MirRValue::Use(src) = value else {
return Err(CodegenError::Unsupported(format!(
"the C backend cannot store this array expression into `{target}`"
)));
};
self.emit_array_copy(target, target, src, locals)?;
Ok(true)
}
pub(super) fn emit_array_field_store(
&mut self,
base: LocalId,
field: &str,
value: &MirRValue,
locals: &[MirLocal],
) -> CodegenResult<bool> {
let base_ty = local_ty(locals, base);
let field_ty = self.struct_field_type(base_ty, field).cloned();
let arrow =
matches!(base_ty, Some(MirType::Ptr(_))) && !base_ty.is_some_and(Self::is_slice_ref);
let target = format!(
"{}{}{}",
self.local_name(base, locals),
if arrow { "->" } else { "." },
Self::escape_c_keyword(field)
);
self.emit_store_if_array(&target, field_ty.as_ref(), value, locals)
}
pub(super) fn emit_array_deref_store(
&mut self,
ptr: LocalId,
value: &MirRValue,
locals: &[MirLocal],
) -> CodegenResult<bool> {
let Some(MirType::Ptr(inner)) = local_ty(locals, ptr) else {
return Ok(false);
};
if !is_array(inner) {
return Ok(false);
}
let MirRValue::Use(src) = value else {
return Err(CodegenError::Unsupported(
"the C backend cannot store this array expression through a pointer".to_string(),
));
};
let size_of = self.type_to_c(inner);
let target = self.local_name(ptr, locals);
self.emit_array_copy(&target, &size_of, src, locals)?;
Ok(true)
}
pub(super) fn emit_array_element_store(
&mut self,
target: &str,
elem_ty: &MirType,
value: &MirRValue,
locals: &[MirLocal],
) -> CodegenResult<bool> {
self.emit_store_if_array(target, Some(elem_ty), value, locals)
}
}