diff --git a/hblang/src/fs.rs b/hblang/src/fs.rs index 0bc3901..2539b04 100644 --- a/hblang/src/fs.rs +++ b/hblang/src/fs.rs @@ -4,7 +4,7 @@ use { parser::{self, Ast}, }, alloc::{string::String, vec::Vec}, - core::fmt::Write, + core::{fmt::Write, num::NonZeroUsize}, hashbrown::hash_map, std::{ collections::VecDeque, @@ -39,6 +39,33 @@ pub struct Options { pub extra_threads: usize, } +impl Options { + pub fn from_args(args: &[&str]) -> std::io::Result { + if args.contains(&"--help") || args.contains(&"-h") { + log::error!("Usage: hbc [OPTIONS...] "); + log::error!(include_str!("../command-help.txt")); + return Err(std::io::ErrorKind::Other.into()); + } + + Ok(Options { + fmt: args.contains(&"--fmt"), + fmt_stdout: args.contains(&"--fmt-stdout"), + dump_asm: args.contains(&"--dump-asm"), + extra_threads: args + .iter() + .position(|&a| a == "--threads") + .map(|i| { + args[i + 1].parse::().map_err(|e| { + std::io::Error::other(format!("--threads expects non zero integer: {e}")) + }) + }) + .transpose()? + .map_or(1, NonZeroUsize::get) + - 1, + }) + } +} + pub fn format_to(ast: &parser::Ast, source: &str, out: &mut String) -> core::fmt::Result { for (i, expr) in ast.exprs().iter().enumerate() { parser::Formatter::new(&ast.file).fmt(expr, out)?; diff --git a/hblang/src/main.rs b/hblang/src/main.rs index 802e536..8f86d03 100644 --- a/hblang/src/main.rs +++ b/hblang/src/main.rs @@ -1,33 +1,15 @@ #[cfg(feature = "std")] fn main() -> std::io::Result<()> { - use std::{io::Write, num::NonZeroUsize}; + use std::io::Write; log::set_logger(&hblang::Logger).unwrap(); let args = std::env::args().collect::>(); let args = args.iter().map(String::as_str).collect::>(); - - if args.contains(&"--help") || args.contains(&"-h") { - println!("Usage: hbc [OPTIONS...] "); - println!(include_str!("../command-help.txt")); - return Err(std::io::ErrorKind::Other.into()); - } + let opts = hblang::Options::from_args(&args)?; + let file = args.iter().filter(|a| !a.starts_with('-')).nth(1).copied().unwrap_or("main.hb"); let mut out = Vec::new(); - hblang::run_compiler( - args.iter().filter(|a| !a.starts_with('-')).nth(1).copied().unwrap_or("main.hb"), - hblang::Options { - fmt: args.contains(&"--fmt"), - fmt_stdout: args.contains(&"--fmt-stdout"), - dump_asm: args.contains(&"--dump-asm"), - extra_threads: args - .iter() - .position(|&a| a == "--threads") - .map(|i| args[i + 1].parse::().expect("--threads expects integer")) - .map_or(1, NonZeroUsize::get) - - 1, - }, - &mut out, - )?; + hblang::run_compiler(file, opts, &mut out)?; std::io::stdout().write_all(&out) }