use std::path::{Path, PathBuf};
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 mut chunk = crate::compile(&src).map_err(|e| e.0)?;
chunk.source = file.to_string();
let runtime_lib = runtime_staticlib()?;
let obj = out.with_extension("o");
fusevm::aot::compile_object(&chunk, &obj).map_err(|e| format!("--aot: {e}"))?;
let stub = out.with_extension("aot_main.c");
std::fs::write(
&stub,
b"extern long texrs_aot_main(void);\nint main(void){return (int)texrs_aot_main();}\n"
as &[u8],
)
.map_err(|e| format!("--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 output = cmd
.output()
.map_err(|e| format!("--aot: invoking cc: {e}"))?;
let _ = std::fs::remove_file(&stub);
let _ = std::fs::remove_file(&obj);
if !output.status.success() {
return Err(format!(
"--aot: link failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(out.to_path_buf())
}
fn runtime_staticlib() -> Result<PathBuf, String> {
if let Ok(p) = std::env::var("TEXRS_STATICLIB") {
let p = PathBuf::from(p);
return match p.is_file() {
true => Ok(p),
false => Err(format!(
"--aot: TEXRS_STATICLIB={} is not a file",
p.display()
)),
};
}
let exe = std::env::current_exe().map_err(|e| format!("--aot: current_exe: {e}"))?;
let dir = exe
.parent()
.ok_or_else(|| "--aot: binary has no directory".to_string())?;
let candidates = [
dir.join("libtexrs.a"),
dir.join("../release/libtexrs.a"),
dir.join("../debug/libtexrs.a"),
];
for c in candidates {
if c.is_file() {
return Ok(c);
}
}
Err(
"--aot: no libtexrs.a found -- run `cargo build` first, or set \
TEXRS_STATICLIB"
.to_string(),
)
}