Path: blob/main/cranelift/serde/src/clif-json.rs
1691 views
//! Utility for `cranelift_serde`.12#![deny(missing_docs)]34use clap::Parser;5use cranelift_codegen::ir::Function;6use cranelift_reader::parse_functions;7use std::fs::File;8use std::io;9use std::io::prelude::*;10use std::process;1112fn call_ser(file: &str, pretty: bool) -> Result<(), String> {13let ret_of_parse = parse_functions(file);14match ret_of_parse {15Ok(funcs) => {16let ser_str = if pretty {17serde_json::to_string_pretty(&funcs).unwrap()18} else {19serde_json::to_string(&funcs).unwrap()20};21println!("{ser_str}");22Ok(())23}24Err(_pe) => Err("There was a parsing error".to_string()),25}26}2728fn call_de(file: &File) -> Result<(), String> {29let de: Vec<Function> = match serde_json::from_reader(file) {30Result::Ok(val) => val,31Result::Err(err) => panic!("{}", err),32};33println!("{de:?}");34Ok(())35}3637/// Cranelift JSON serializer/deserializer utility38#[derive(Parser, Debug)]39#[command(about)]40enum Args {41/// Serializes Cranelift IR into JSON42Serialize {43/// Generate pretty json44#[arg(long, short)]45pretty: bool,4647/// Input file for serialization48file: String,49},50/// Deserializes Cranelift IR into JSON51Deserialize {52/// Input file for deserialization53file: String,54},55}5657fn main() {58let res_serde = match Args::parse() {59Args::Serialize { pretty, file } => {60let mut contents = String::new();61let mut file = File::open(file).expect("Unable to open the file");62file.read_to_string(&mut contents)63.expect("Unable to read the file");6465call_ser(&contents, pretty)66}67Args::Deserialize { file } => {68let file = File::open(file).expect("Unable to open the file");69call_de(&file)70}71};7273if let Err(mut msg) = res_serde {74if !msg.ends_with('\n') {75msg.push('\n');76}77io::stdout().flush().expect("flushing stdout");78io::stderr().write_all(msg.as_bytes()).unwrap();79process::exit(1);80}81}828384