From 7b76c697bd9f733aa242e12a01df4dc3a065a9e0 Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Sun, 25 Sep 2022 00:04:18 +0200 Subject: allow to run program from file, add ch5 example programs --- src/main.rs | 47 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index b660416..868706d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -130,17 +130,10 @@ where module.dump(); } -fn main() { - println!("Parse stdin."); - println!("ENTER to parse current input."); - println!("C-d to exit."); - - // Create lexer over stdin. - let lexer = Lexer::new(std::io::stdin().bytes().filter_map(|v| { - let v = v.ok()?; - Some(v.into()) - })); - +fn run_kaleidoscope(lexer: Lexer) +where + I: Iterator, +{ // Create parser for kaleidoscope. let mut parser = Parser::new(lexer); @@ -155,3 +148,35 @@ fn main() { // De-allocate managed static LLVM data. llvm::shutdown(); } + +fn main() { + match std::env::args().nth(1) { + Some(file) => { + println!("Parse {}.", file); + + // Create lexer over file. + let lexer = Lexer::new( + std::fs::File::open(&file) + .expect(&format!("Failed to open file {}!", file)) + .bytes() + .filter_map(|v| { + let v = v.ok()?; + Some(v.into()) + }), + ); + run_kaleidoscope(lexer); + } + None => { + println!("Parse stdin."); + println!("ENTER to parse current input."); + println!("C-d to exit."); + + // Create lexer over stdin. + let lexer = Lexer::new(std::io::stdin().bytes().filter_map(|v| { + let v = v.ok()?; + Some(v.into()) + })); + run_kaleidoscope(lexer); + } + } +} -- cgit v1.2.3