mod codegen;
mod parser;
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;
#[derive(Debug, Clone)]
pub struct GeneratorOptions {
pub endian: String,
pub allow_attr: Option<String>,
pub constant_type_aliases: HashMap<String, String>,
}
impl Default for GeneratorOptions {
fn default() -> Self {
Self {
endian: "little".into(),
allow_attr: None,
constant_type_aliases: HashMap::new(),
}
}
}
#[derive(Debug, Error)]
pub enum GeneratorError {
#[error("failed to parse schema: {0}")]
Parse(#[from] parser::ParseError),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
}
pub fn generate(
schema_xml: &str,
opts: &GeneratorOptions,
) -> Result<Vec<(String, String)>, GeneratorError> {
let schema = parser::parse_schema(schema_xml)?;
Ok(codegen::generate(&schema, opts))
}
pub fn generate_to<P: AsRef<Path>>(
schema_xml: &str,
out_dir: P,
opts: &GeneratorOptions,
) -> Result<(), GeneratorError> {
use std::fs;
use std::fs::File;
use std::io::Write;
let modules = generate(schema_xml, opts)?;
let out_dir = out_dir.as_ref();
if !out_dir.exists() {
fs::create_dir_all(out_dir)?;
}
for (fname, contents) in modules {
let path = out_dir.join(&fname);
let mut f = File::create(&path)?;
f.write_all(contents.as_bytes())?;
}
Ok(())
}