From 5668a05227204f35247fcc81649e85cbdb7647d7 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Tue, 9 Jun 2020 14:20:40 +0200 Subject: [PATCH] Made it possible to load an input file (with variables and functions). --- kalk_cli/src/main.rs | 45 +++++++++++++++++++++++++++++++++++------- kalk_cli/src/output.rs | 8 ++++---- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/kalk_cli/src/main.rs b/kalk_cli/src/main.rs index c5e2124..e070b16 100644 --- a/kalk_cli/src/main.rs +++ b/kalk_cli/src/main.rs @@ -1,21 +1,52 @@ mod output; mod repl; +use kalk::parser; use kalk::parser::Unit; -use kalk::parser::{self}; use std::env; +use std::fs::File; +use std::io::Read; fn main() { - let mut parser = parser::Context::new().set_angle_unit(get_angle_unit()); + let mut parser_context = parser::Context::new().set_angle_unit(get_angle_unit()); // Command line argument input, execute it and exit. - if let Some(expr) = env::args().skip(1).next() { - output::eval(&mut parser, &expr); - return; + let mut args = env::args().skip(1); + let mut expr_input: Option = None; + loop { + // Get the next argument if possible, otherwise break the loop. + let arg = if let Some(arg) = args.next() { + arg + } else { + break; + }; + + if arg == "-i" { + let file_name = &args.next().expect("Expected input file."); // The next argument will be the file name. + let mut file_content = String::new(); + File::open(&file_name) + .expect("Couldn't find file.") + .read_to_string(&mut file_content) + .expect("Failed to read input file."); + + // Parse the input file content, resulting in the symbol table being filled out. + // Output is not needed here. + parser::parse(&mut parser_context, &file_content, 53) + .expect("Failed to parse input file."); + } else { + // Main argument. This is expected to be a maths expression. + // After the loop is finished, this will be parsed and outputted. + expr_input = Some(arg); + } } - // REPL - repl::start(&mut parser); + if let Some(input) = expr_input { + // Direct output + output::eval(&mut parser_context, &input); + } else { + // REPL + repl::start(&mut parser_context); + } } fn get_angle_unit() -> Unit { diff --git a/kalk_cli/src/output.rs b/kalk_cli/src/output.rs index 76e7537..6f48147 100644 --- a/kalk_cli/src/output.rs +++ b/kalk_cli/src/output.rs @@ -39,6 +39,10 @@ pub fn eval(parser: &mut parser::Context, input: &str) { } } +pub fn print_err(msg: &str) { + println!("{}", Red.paint(msg)); +} + fn print_calc_err(err: CalcError) { print_err(&match err { IncorrectAmountOfArguments(expected, func, got) => format!( @@ -54,7 +58,3 @@ fn print_calc_err(err: CalcError) { Unknown => format!("Unknown error."), }); } - -fn print_err(msg: &str) { - println!("{}", Red.paint(msg)); -}