From 22a5faa6be04a29a4f0246656fcd2195ff2f5bd0 Mon Sep 17 00:00:00 2001 From: Kasper Date: Tue, 14 Jan 2020 02:50:10 +0100 Subject: [PATCH] Ignoring operators at the end (with option to disable) --- src/lexer.rs | 14 ++++++++++++-- src/main.rs | 12 +++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/lexer.rs b/src/lexer.rs index 8b41c96..821fad8 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -9,9 +9,19 @@ use crate::LexerKeyword::{In, PercentChar, Per, Mercury, Hg, PoundForce, PoundWo use crate::FunctionIdentifier::{Cbrt, Ceil, Cos, Exp, Abs, Floor, Ln, Log, Round, Sin, Sqrt, Tan}; use crate::units::Unit::*; -pub fn lex(input: &str) -> Result { +pub fn lex(input: &str, allow_trailing_operators: bool) -> Result { + + let mut input = input.replace(",", ""); // ignore commas + + if allow_trailing_operators { + match &input.chars().last().unwrap_or('x') { + '+' | '-' | '*' | '/' | '%' | '^' | '(' => { + input.pop(); + }, + _ => {}, + } + } - let input = input.replace(",", ""); let mut chars = input.chars().peekable(); let mut tokens: TokenVector = vec![]; let max_word_length = 30; diff --git a/src/main.rs b/src/main.rs index 2ebb2d4..be85b8b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -88,14 +88,20 @@ mod evaluator; mod lookup; fn main() { - use std::env; let args: Vec = env::args().collect(); - let s = if args.len() >= 2 { &args[1] } else { "0.1" }; + if args.len() >= 2 { + eval(&args[1], true); + } else { + println!("No argument supplied"); + } +} + +pub fn eval(input: &str, allow_trailing_operators: bool) { let lex_start = Instant::now(); - match lexer::lex(s) { + match lexer::lex(input, allow_trailing_operators) { Ok(tokens) => { let lex_time = Instant::now().duration_since(lex_start).as_nanos() as f32;