feat: add a backed using cranelift ir and codegen crates

This commit is contained in:
2026-04-20 23:27:16 +02:00
parent c3ee0d6e67
commit 35255a924a
6 changed files with 834 additions and 8 deletions
+44 -8
View File
@@ -1,17 +1,34 @@
use std::{env::args, fs::read_to_string, process::exit};
use std::{fs::read_to_string, path::PathBuf, process::exit};
use clap::Parser as ClapParser;
use crate::frontend::parser::Parser;
use crate::frontend::sema::Sema;
pub mod backend;
pub mod frontend;
fn main() {
let Some(path) = args().nth(1) else {
eprintln!("usage: compiler <file>");
exit(1);
};
use crate::backend::cranelift::CraneliftBackend;
let content = read_to_string(&path).unwrap_or_else(|err| {
#[derive(ClapParser)]
#[command(version, about, long_about = None)]
struct Cli {
/// The input source file to compile
input: String,
/// The output file path
#[arg(short, long)]
output: Option<String>,
/// Emit Cranelift IR instead of an object file
#[arg(long)]
emit_ir: bool,
}
fn main() {
let cli = Cli::parse();
let content = read_to_string(&cli.input).unwrap_or_else(|err| {
eprintln!("error: failed to read source file ({:?})", err);
exit(1);
});
@@ -38,5 +55,24 @@ fn main() {
exit(1);
}
println!("{:#?}", typed_module);
let backend = CraneliftBackend::new();
let (ir, obj_bytes) = backend.compile_module(&typed_module);
if cli.emit_ir {
println!("{}", ir);
} else {
let output_path = cli.output.unwrap_or_else(|| {
PathBuf::from(&cli.input)
.with_extension("o")
.to_string_lossy()
.into_owned()
});
std::fs::write(&output_path, obj_bytes).unwrap_or_else(|err| {
eprintln!("error: failed to write object file: {:?}", err);
exit(1);
});
println!("Generated object file: {}", output_path);
}
}