mrubyedge_cli/subcommands/
compile_mrb.rs

1use clap::Args;
2use std::{fs::File, io::Read, path::PathBuf};
3
4use mruby_compiler2_sys as mrbc;
5
6#[derive(Args)]
7pub struct CompileMrbArgs {
8    /// Output file path
9    #[arg(short = 'o', long)]
10    pub output: Option<PathBuf>,
11
12    /// Dump instruction sequences
13    #[arg(long)]
14    pub dump_insns: bool,
15
16    /// Skip generating mrb file
17    #[arg(long)]
18    pub skip_generate_mrb: bool,
19
20    /// Ruby source file to compile
21    pub file: PathBuf,
22}
23
24pub fn execute(args: CompileMrbArgs) -> Result<(), Box<dyn std::error::Error>> {
25    let output = if let Some(output) = &args.output {
26        output.clone()
27    } else {
28        args.file.with_extension("mrb")
29    };
30
31    let mut buf = Vec::new();
32    File::open(&args.file)?.read_to_end(&mut buf)?;
33    let buf = String::from_utf8(buf)?;
34    unsafe {
35        let mut ctx = mrbc::MRubyCompiler2Context::new();
36        if args.dump_insns {
37            ctx.dump_bytecode(&buf)?;
38        }
39        if !args.skip_generate_mrb {
40            ctx.compile_to_file(&buf, &output)?;
41        }
42    }
43
44    Ok(())
45}