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 --- README.md | 10 ++++++++++ ks/forloop.ks | 7 +++++++ ks/ifelse.ks | 7 +++++++ src/main.rs | 47 ++++++++++++++++++++++++++++++++++++----------- 4 files changed, 60 insertions(+), 11 deletions(-) create mode 100644 ks/forloop.ks create mode 100644 ks/ifelse.ks diff --git a/README.md b/README.md index 95981d5..816e4b9 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,16 @@ going to use the llvm `C` API and build our own safe wrapper specialized for this tutorial. The wrapper offers a similar interface as the `C++` API and is implemented in [`src/llvm/`](src/llvm/) +## Demo + +```bash +# Run kaleidoscope program from file. +cargo run ks/ + +# Run REPL loop, parsing from stdin. +cargo run +``` + ## Documentation Rustdoc for this crate is available at diff --git a/ks/forloop.ks b/ks/forloop.ks new file mode 100644 index 0000000..0efa5c3 --- /dev/null +++ b/ks/forloop.ks @@ -0,0 +1,7 @@ +extern putchard(char); +def printstar(n) + for i = 1, i < n, 1.0 in + putchard(42); # ascii 42 = '*' + +# print 100 '*' characters +printstar(100); diff --git a/ks/ifelse.ks b/ks/ifelse.ks new file mode 100644 index 0000000..3aa4778 --- /dev/null +++ b/ks/ifelse.ks @@ -0,0 +1,7 @@ +def fib(x) + if x < 3 then + 1 + else + fib(x-1)+fib(x-2); + +fib(10); 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