use std::fmt::Write;
use crate::codegen::backend::{CodegenError, CodegenResult};
use crate::codegen::ir::{MirGlobal, MirLocal, MirRValue, MirType, MirValue};
use super::CBackend;
impl CBackend {
pub(super) fn global_declarator(&self, global: &MirGlobal) -> String {
let c_name = if global.is_extern_decl {
global.name.to_string()
} else {
Self::global_emit_name(&global.name)
};
let decl = if matches!(global.ty, MirType::Array(..)) {
self.fmt_array_decl(&global.ty, &c_name)
} else {
format!("{} {}", self.type_to_c(&global.ty), c_name)
};
if global.is_mut || global.is_extern_decl {
decl
} else {
format!("const {decl}")
}
}
pub(super) fn global_emit_name(name: &str) -> String {
format!("bld_g_{name}")
}
fn global_c_name(&self, name: &str) -> String {
self.value_to_c(&MirValue::Global(name.into()), &[])
}
pub(super) fn global_address_to_c(&self, name: &str) -> String {
let c_name = self.global_c_name(name);
match self.global_types.get(name) {
Some(MirType::Array(..)) => c_name,
_ => format!("&({c_name})"),
}
}
pub(super) fn global_array_element_access(
&self,
base: &MirValue,
base_str: &str,
index_str: &str,
) -> Option<String> {
let MirValue::Global(name) = base else {
return None;
};
match self.global_types.get(name.as_ref())? {
MirType::Array(_, len) => Some(format!(
"{base_str}[bl_idx_chk((long long)({index_str}), {len}ULL)]"
)),
_ => None,
}
}
pub(super) fn emit_global_array_store(
&mut self,
name: &str,
value: &MirRValue,
locals: &[MirLocal],
) -> CodegenResult<bool> {
if !matches!(self.global_types.get(name), Some(MirType::Array(..))) {
return Ok(false);
}
let MirRValue::Use(src) = value else {
return Err(CodegenError::Rejected {
message: format!(
"the C backend cannot store this value into array global `{name}`"
),
location: None,
help: Some("bind the array to a local first, then assign the local".to_string()),
});
};
let src = self.value_to_c(src, locals);
let dst = self.global_c_name(name);
self.write_indent();
writeln!(self.output, "memcpy({dst}, {src}, sizeof({dst}));").unwrap();
Ok(true)
}
}