diff --git a/src/main.rs b/src/main.rs index 7e0f87e..2548b55 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,99 @@ pub mod codegen; pub mod errors; pub mod parser; +use std::fs; +use std::path::PathBuf; +use std::process; + fn main() { - println!("Hello, world!"); + let args: Vec = std::env::args().collect(); + + if args.len() < 2 { + print_usage(); + process::exit(1); + } + + match args[1].as_str() { + "build" => { + if args.len() < 3 { + eprintln!("error: expected a file path\n usage: mist build "); + process::exit(1); + } + cmd_build(&args[2]); + } + "check" => { + if args.len() < 3 { + eprintln!("error: expected a file path\n usage: mist check "); + process::exit(1); + } + cmd_check(&args[2]); + } + "version" | "--version" | "-v" => { + println!("mist {}", env!("CARGO_PKG_VERSION")); + } + "help" | "--help" | "-h" => { + print_usage(); + } + unknown => { + eprintln!("error: unknown command '{}'\n", unknown); + print_usage(); + process::exit(1); + } + } +} + +fn cmd_build(path: &str) { + let source = read_ms_file(path); + match parser::parse(&source) { + Ok(ast) => { + println!("parsed {} top-level items", ast.statements.len()); + // codegen will go here + } + Err(e) => { + eprintln!("parse error:\n{}", e); + process::exit(1); + } + } +} + +fn cmd_check(path: &str) { + let source = read_ms_file(path); + match parser::parse(&source) { + Ok(_) => { + println!("ok"); + } + Err(e) => { + eprintln!("parse error:\n{}", e); + process::exit(1); + } + } +} + +fn read_ms_file(path: &str) -> String { + let pb = PathBuf::from(path); + + if !pb.exists() { + eprintln!("error: file '{}' not found", path); + process::exit(1); + } + + if pb.extension().and_then(|e| e.to_str()) != Some("ms") { + eprintln!("error: expected a .ms file, got '{}'", path); + process::exit(1); + } + + fs::read_to_string(&pb).unwrap_or_else(|e| { + eprintln!("error: could not read '{}': {}", path, e); + process::exit(1); + }) +} + +fn print_usage() { + println!("mist - the mist compiler"); + println!(); + println!("usage:"); + println!(" mist build compile a .ms file to go"); + println!(" mist check parse and validate without compiling"); + println!(" mist version print the compiler version"); + println!(" mist help print this message"); } diff --git a/test/main.ms b/test/main.ms new file mode 100644 index 0000000..e69de29