use std::io::{self, Read, Write};
use std::path::PathBuf;
use clap::Parser;
use miette::{IntoDiagnostic, WrapErr};
use xqvm::Program;
use xqvm::disasm::Disassembly;
#[derive(Debug, Parser)]
pub(crate) struct Args {
file: Option<PathBuf>,
}
pub(crate) fn exec(args: &Args) -> miette::Result<()> {
let bytes = if let Some(path) = &args.file {
std::fs::read(path)
.into_diagnostic()
.wrap_err_with(|| format!("failed to read '{}'", path.display()))?
} else {
let mut buf = Vec::new();
let _n = io::stdin()
.read_to_end(&mut buf)
.into_diagnostic()
.wrap_err("failed to read stdin")?;
buf
};
let mut out = Vec::new();
let program = Program::decode(&bytes)
.into_diagnostic()
.wrap_err("failed to decode program")?;
Disassembly::from_program(&program)
.write_to(&mut out)
.into_diagnostic()
.wrap_err("failed to write disassembly")?;
io::stdout().write_all(&out).into_diagnostic()?;
Ok(())
}