use crate::compiler::Program;
use fusevm::Chunk;
use std::path::{Path, PathBuf};
pub const AOT_CLOSURES_TAG: &str = "\u{0}rlang-aot-closures:";
pub const AOT_SOURCE_TAG: &str = "\u{0}rlang-aot-source:";
type CClosure = (Vec<String>, Chunk, Vec<String>);
pub fn build(file: &str) -> Result<String, String> {
let src = std::fs::read_to_string(file).map_err(|e| format!("cannot read {file}: {e}"))?;
let prog = crate::compile(&src)?;
let (nclosures, nops) = (prog.closures.len(), prog.main.ops.len());
crate::cache::store(&src, &prog)?;
Ok(format!(
"built {file}: {nops} top-level ops, {nclosures} closures -> ~/.rlang/scripts.rkyv"
))
}
pub(crate) fn encode_closures(prog: &Program) -> Result<String, String> {
use base64::Engine as _;
let closures: Vec<CClosure> = prog
.closures
.iter()
.map(|c| (c.params.clone(), c.chunk.clone(), c.src.clone()))
.collect();
let blob =
bincode::serialize(&closures).map_err(|e| format!("aot: serialize closures: {e}"))?;
Ok(base64::engine::general_purpose::STANDARD.encode(blob))
}
pub fn compile_executable(file: &str, out: &Path) -> Result<PathBuf, String> {
let src = std::fs::read_to_string(file).map_err(|e| format!("cannot read {file}: {e}"))?;
let prog = crate::compile(&src)?;
let mut main = prog.main.clone();
main.names
.push(format!("{AOT_CLOSURES_TAG}{}", encode_closures(&prog)?));
{
use base64::Engine as _;
let src_b64 = base64::engine::general_purpose::STANDARD.encode(src.as_bytes());
main.names.push(format!("{AOT_SOURCE_TAG}{src_b64}"));
}
let runtime_lib = runtime_staticlib()?;
let obj = out.with_extension("o");
fusevm::aot::compile_object(&main, &obj).map_err(|e| format!("Rscript --aot: {e}"))?;
let stub = out.with_extension("aot_main.c");
std::fs::write(
&stub,
b"extern long rlang_aot_main(void);\nint main(void){return (int)rlang_aot_main();}\n"
as &[u8],
)
.map_err(|e| format!("Rscript --aot: write entry stub: {e}"))?;
let mut cmd = std::process::Command::new("cc");
cmd.arg(&stub).arg(&obj).arg(&runtime_lib);
if cfg!(target_os = "macos") {
cmd.args([
"-framework",
"CoreFoundation",
"-framework",
"Security",
"-liconv",
"-lc++",
]);
} else {
cmd.args(["-lpthread", "-ldl", "-lm", "-lrt"]);
}
cmd.arg("-o").arg(out);
let status = cmd
.status()
.map_err(|e| format!("Rscript --aot: invoking cc: {e}"))?;
let _ = std::fs::remove_file(&stub);
let _ = std::fs::remove_file(&obj);
if !status.success() {
return Err(format!(
"Rscript --aot: link failed (cc exit {:?})",
status.code()
));
}
Ok(out.to_path_buf())
}
fn runtime_staticlib() -> Result<PathBuf, String> {
if let Ok(p) = std::env::var("RLANG_STATICLIB") {
return Ok(PathBuf::from(p));
}
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
if let Some(dir) = exe.parent() {
let cand = dir.join("librlang.a");
if cand.exists() {
return Ok(cand);
}
}
Err("Rscript --aot: could not locate librlang.a (set RLANG_STATICLIB)".to_string())
}