use clap::Parser;
use color_eyre::Report;
use std::{fs::File, io::BufReader, path::PathBuf};
use wasm2spirv::{config::Config, Compilation};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Cli {
source: PathBuf,
#[arg(long, default_value_t = false)]
from_wasm: bool,
#[arg(long)]
from_json: Option<PathBuf>,
#[arg(long, short)]
output: Option<PathBuf>,
#[arg(long, short)]
quiet: bool,
#[arg(long, default_value_t = false)]
optimize: bool,
#[arg(long, default_value_t = false)]
validate: bool,
#[arg(long, default_value_t = false)]
show_glsl: bool,
#[arg(long, default_value_t = false)]
show_hlsl: bool,
#[arg(long, default_value_t = false)]
show_msl: bool,
#[arg(long, default_value_t = false)]
show_asm: bool,
}
pub fn main() -> color_eyre::Result<()> {
let _ = color_eyre::install();
let Cli {
source,
from_wasm,
from_json,
output,
quiet,
optimize,
validate,
show_asm,
show_glsl,
show_hlsl,
show_msl,
} = Cli::parse();
if !quiet {
tracing_subscriber::fmt::try_init().map_err(Report::msg)?;
}
let mut config: Config = match (from_wasm, from_json) {
(true, None) => todo!(),
(false, Some(json)) => {
let mut file = BufReader::new(File::open(json)?);
serde_json::from_reader(&mut file)?
}
(false, None) => {
return Err(Report::msg(
"One of 'from-wasm', 'from-binary' or 'from-json' must be enabled",
));
}
_ => {
return Err(Report::msg(
"Only one of 'from-wasm', 'from-binary' or 'from-json' must be enabled",
))
}
};
config.enable_capabilities();
let bytes = wat::parse_file(source)?;
let mut compilation = Compilation::new(config, &bytes)?;
if validate {
compilation.validate()?;
}
if optimize {
compilation = compilation.into_optimized()?;
}
if let Some(output) = output {
let bytes = compilation.bytes()?;
std::fs::write(output, &bytes)?;
}
if show_asm {
println!("{}", compilation.assembly()?)
}
if show_glsl {
println!("{}", compilation.glsl()?)
}
if show_hlsl {
println!("{}", compilation.hlsl()?)
}
if show_msl {
println!("{}", compilation.msl()?)
}
return Ok(());
}