use crate::ast::Span;
use crate::compiler::Program;
use crate::host::{self, FuncDef, TryDef};
use fusevm::{Chunk, VM};
use std::path::{Path, PathBuf};
use std::sync::Arc;
fn restore_op_hash(chunk: &mut Chunk) {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
chunk.ops.hash(&mut h);
chunk.constants.hash(&mut h);
chunk.op_hash = h.finish();
for sub in &mut chunk.sub_chunks {
restore_op_hash(sub);
}
}
const PROG_IMAGE_TAG: &str = "\u{1}pythonrs-prog-image:";
#[derive(serde::Serialize, serde::Deserialize)]
struct ProgImage {
functions: Vec<FuncDef>,
tries: Vec<TryDef>,
#[serde(default)]
source: String,
#[serde(default)]
filename: String,
#[serde(default)]
positions: Vec<(u64, Vec<Span>)>,
}
pub fn emit_executable(
prog: &Program,
src: &str,
filename: &str,
out: &Path,
) -> Result<(), String> {
let obj = std::env::temp_dir().join("pythonrs_aot.o");
emit_object(prog, src, filename, &obj)?;
let main_c = std::env::temp_dir().join("pythonrs_aot_main.c");
std::fs::write(
&main_c,
"extern long pythonrs_aot_run_embedded(void);\n\
int main(void) { return (int)pythonrs_aot_run_embedded(); }\n",
)
.map_err(|e| e.to_string())?;
let lib = staticlib_path()?;
let mut cmd = std::process::Command::new("cc");
cmd.arg(&main_c).arg(&obj).arg(&lib).arg("-o").arg(out);
if cfg!(target_os = "macos") {
cmd.args([
"-framework",
"CoreFoundation",
"-framework",
"Security",
"-liconv",
"-lc++",
]);
} else {
cmd.args(["-lpthread", "-ldl", "-lm", "-lrt"]);
}
let status = cmd.status().map_err(|e| format!("cc: {e}"))?;
if !status.success() {
return Err(format!("link failed (cc exit {:?})", status.code()));
}
Ok(())
}
fn emit_object(prog: &Program, src: &str, filename: &str, obj: &Path) -> Result<(), String> {
let mut chunk = prog.main.clone();
let image = ProgImage {
functions: prog.functions.iter().map(|(_, f)| f.clone()).collect(),
tries: prog.tries.clone(),
source: src.to_string(),
filename: filename.to_string(),
positions: prog.positions.clone(),
};
let json = serde_json::to_string(&image).map_err(|e| e.to_string())?;
chunk.names.push(format!("{PROG_IMAGE_TAG}{json}"));
fusevm::aot::compile_object(&chunk, obj).map_err(|e| format!("pythonrs --build: {e}"))
}
fn staticlib_path() -> Result<PathBuf, String> {
if let Ok(p) = std::env::var("PYTHONRS_STATICLIB") {
return Ok(PathBuf::from(p));
}
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let lib = exe.parent().ok_or("no exe dir")?.join("libpythonrs.a");
if lib.exists() {
Ok(lib)
} else {
Err(format!(
"libpythonrs.a not found next to {}; build the staticlib or set PYTHONRS_STATICLIB",
exe.display()
))
}
}
#[no_mangle]
pub unsafe extern "C" fn fusevm_aot_register_builtins(vm: *mut VM) {
let vm = unsafe { &mut *vm };
crate::builtins::install(vm);
vm.set_numeric_hook(Arc::new(crate::builtins::numeric_hook));
vm.enable_tracing_jit();
let images: Vec<ProgImage> = vm
.chunk
.names
.iter()
.filter_map(|n| n.strip_prefix(PROG_IMAGE_TAG))
.filter_map(|j| serde_json::from_str(j).ok())
.collect();
for mut img in images {
let has_file = !img.filename.is_empty();
host::init_runtime(
vec![if has_file {
img.filename.clone()
} else {
String::new()
}],
has_file.then(|| img.filename.clone()),
&img.source,
if has_file { &img.filename } else { "<string>" },
has_file && !img.filename.starts_with('<'),
);
for (op_hash, table) in img.positions {
host::register_positions(op_hash, table);
}
for f in &mut img.functions {
restore_op_hash(&mut f.chunk);
}
for t in &mut img.tries {
restore_op_hash(&mut t.body);
for h in &mut t.handlers {
let (typ, handler) = (&mut h.typ, &mut h.body);
if let Some(typ) = typ {
restore_op_hash(typ);
}
restore_op_hash(handler);
}
if let Some(e) = &mut t.orelse {
restore_op_hash(e);
}
if let Some(fb) = &mut t.finalbody {
restore_op_hash(fb);
}
}
host::with_host(|h| h.load_program(img.functions, img.tries));
}
}
#[no_mangle]
pub extern "C" fn pythonrs_aot_run_embedded() -> i64 {
#[allow(improper_ctypes)]
extern "C" {
static fusevm_aot_chunk_blob: u8;
static fusevm_aot_chunk_len: u64;
fn fusevm_aot_entry(vm: *mut VM) -> i64;
}
let mut chunk: Chunk = unsafe {
let len = fusevm_aot_chunk_len as usize;
let bytes = std::slice::from_raw_parts(&fusevm_aot_chunk_blob as *const u8, len);
let Some(body) = bytes.strip_prefix(fusevm::aot::AOT_CHUNK_MAGIC.as_slice()) else {
eprintln!(
"pythonrs aot: this binary was built by a different fusevm — expected chunk \
format {}; rebuild it",
String::from_utf8_lossy(fusevm::aot::AOT_CHUNK_MAGIC)
);
return 1;
};
match bincode::deserialize(body) {
Ok(c) => c,
Err(e) => {
eprintln!("pythonrs aot: corrupt embedded chunk: {e}");
return 1;
}
}
};
restore_op_hash(&mut chunk);
let mut vm = VM::new(chunk);
unsafe { fusevm_aot_register_builtins(&mut vm as *mut VM) };
unsafe { fusevm_aot_entry(&mut vm as *mut VM) };
let native_error = match vm.take_aot_result() {
fusevm::VMResult::Error(e) => {
crate::builtins::record_err_line(&vm);
Some(e)
}
_ => None,
};
crate::stdio::flush_io();
let code = match host::with_host(|h| h.take_error()).or(native_error) {
None => 0,
Some(e) => match host::classify_top_error(&e) {
host::TopExit::SystemExit { code, message } => {
if let Some(msg) = message {
eprint!("{msg}");
}
code as i64
}
host::TopExit::Uncaught { traceback } => {
eprint!("{traceback}");
1
}
},
};
crate::stdio::flush_std_files();
code
}