aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock11
-rw-r--r--Cargo.toml1
-rw-r--r--src/error.rs42
-rw-r--r--src/lex.rs6
-rw-r--r--src/main.rs3
-rw-r--r--src/readline.rs2
6 files changed, 62 insertions, 3 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 8b0baa1..de51705 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -158,6 +158,7 @@ dependencies = [
158 "radix_fmt", 158 "radix_fmt",
159 "regex", 159 "regex",
160 "rustyline", 160 "rustyline",
161 "term_size",
161] 162]
162 163
163[[package]] 164[[package]]
@@ -374,6 +375,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
374checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 375checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
375 376
376[[package]] 377[[package]]
378name = "term_size"
379version = "0.3.2"
380source = "registry+https://github.com/rust-lang/crates.io-index"
381checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"
382dependencies = [
383 "libc",
384 "winapi",
385]
386
387[[package]]
377name = "textwrap" 388name = "textwrap"
378version = "0.11.0" 389version = "0.11.0"
379source = "registry+https://github.com/rust-lang/crates.io-index" 390source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index ae37294..4527862 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,3 +19,4 @@ lazy_static = "1.3.0"
19directories = "2.0.1" 19directories = "2.0.1"
20regex = "1.1.7" 20regex = "1.1.7"
21num = "0.2" 21num = "0.2"
22term_size = "0.3"
diff --git a/src/error.rs b/src/error.rs
index ec2b555..e05d4e3 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -2,11 +2,16 @@
2 * Refer to LICENCE for more information. 2 * Refer to LICENCE for more information.
3 * */ 3 * */
4 4
5use std::iter::ExactSizeIterator;
6
7use crate::lex;
8
5#[derive(Debug)] 9#[derive(Debug)]
6pub enum CalcError { 10pub enum CalcError {
7 Math(Math), 11 Math(Math),
8 Syntax(String), 12 Syntax(String),
9 Parser(String), 13 Parser(String),
14 Help,
10} 15}
11 16
12#[derive(Debug)] 17#[derive(Debug)]
@@ -25,5 +30,42 @@ pub fn handler(e: CalcError) -> String {
25 }, 30 },
26 CalcError::Syntax(details) => format!("Syntax Error: {}", details), 31 CalcError::Syntax(details) => format!("Syntax Error: {}", details),
27 CalcError::Parser(details) => format!("Parser Error: {}", details), 32 CalcError::Parser(details) => format!("Parser Error: {}", details),
33 CalcError::Help => {
34 // calculate max width but ideally this should be calculated once
35 let mut max_width = 79; // capped at 79
36 if let Some((w, _)) = term_size::dimensions() {
37 if w < max_width {
38 max_width = w;
39 }
40 }
41 let operators: Vec<_> = lex::OPERATORS.keys().map(|c| c.to_string()).collect();
42 format!(
43 "Constants\n{}\nFunctions\n{}\nOperators\n{}\n",
44 blocks(max_width, lex::CONSTANTS.keys().cloned()),
45 blocks(max_width, lex::FUNCTIONS.keys().cloned()),
46 operators.join(" ")
47 )
48 }
49 }
50}
51
52/// Convert iterator into strings of chunks of 8 right padded with space.
53fn blocks(
54 max_width: usize,
55 mut iter: impl Iterator<Item = &'static str> + ExactSizeIterator,
56) -> String {
57 // multiply by eight since we are formatting it into chunks of 8
58 let items_per_line = max_width / 8;
59 let full_bytes = (iter.len() - iter.len() % items_per_line) * 8;
60 let part_bytes = iter.len() % items_per_line * 8; // leftovers
61 let n_newlines = iter.len() / items_per_line + if part_bytes > 0 { 1 } else { 0 };
62 let mut s = String::with_capacity(full_bytes + part_bytes + n_newlines);
63 for _ in 0..n_newlines {
64 for item in iter.by_ref().take(items_per_line) {
65 s.extend(format!("{:>8}", item).chars());
66 }
67 s.push('\n');
28 } 68 }
69 debug_assert_eq!(s.capacity(), s.len()); // check capacity calculation
70 s
29} 71}
diff --git a/src/lex.rs b/src/lex.rs
index a2de98a..76f61a0 100644
--- a/src/lex.rs
+++ b/src/lex.rs
@@ -69,14 +69,14 @@ pub enum Token {
69} 69}
70 70
71lazy_static! { 71lazy_static! {
72 static ref CONSTANTS: HashMap<&'static str, Token> = { 72 pub static ref CONSTANTS: HashMap<&'static str, Token> = {
73 let mut m = HashMap::new(); 73 let mut m = HashMap::new();
74 m.insert("e", Token::Num(std::f64::consts::E)); 74 m.insert("e", Token::Num(std::f64::consts::E));
75 m.insert("pi", Token::Num(std::f64::consts::PI)); 75 m.insert("pi", Token::Num(std::f64::consts::PI));
76 m 76 m
77 }; 77 };
78 78
79 static ref FUNCTIONS: HashMap<&'static str, Token> = { 79 pub static ref FUNCTIONS: HashMap<&'static str, Token> = {
80 let mut m = HashMap::new(); 80 let mut m = HashMap::new();
81 m.insert("sin", Function::token_from_fn("sin".into(), |x| is_radian_mode(x, CONFIGURATION.radian_mode).sin())); 81 m.insert("sin", Function::token_from_fn("sin".into(), |x| is_radian_mode(x, CONFIGURATION.radian_mode).sin()));
82 m.insert("cos", Function::token_from_fn("cos".into(), |x| is_radian_mode(x, CONFIGURATION.radian_mode).cos())); 82 m.insert("cos", Function::token_from_fn("cos".into(), |x| is_radian_mode(x, CONFIGURATION.radian_mode).cos()));
@@ -105,7 +105,7 @@ lazy_static! {
105 m 105 m
106 }; 106 };
107 107
108 static ref OPERATORS: HashMap<char, Token> = { 108 pub static ref OPERATORS: HashMap<char, Token> = {
109 let mut m = HashMap::new(); 109 let mut m = HashMap::new();
110 m.insert('+', Operator::token_from_op('+', |x, y| x + y, 2, true)); 110 m.insert('+', Operator::token_from_op('+', |x, y| x + y, 2, true));
111 m.insert('-', Operator::token_from_op('-', |x, y| x - y, 2, true)); 111 m.insert('-', Operator::token_from_op('-', |x, y| x - y, 2, true));
diff --git a/src/main.rs b/src/main.rs
index 5540da9..94f4cbc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -193,6 +193,9 @@ fn parse_arguments() -> Configuration {
193 193
194pub fn eval_math_expression(input: &str, prev_ans: Option<f64>) -> Result<f64, CalcError> { 194pub fn eval_math_expression(input: &str, prev_ans: Option<f64>) -> Result<f64, CalcError> {
195 let input = input.trim().replace(" ", ""); 195 let input = input.trim().replace(" ", "");
196 if input == "help" {
197 return Err(CalcError::Help);
198 }
196 if input.is_empty() { 199 if input.is_empty() {
197 return Ok(0.); 200 return Ok(0.);
198 } 201 }
diff --git a/src/readline.rs b/src/readline.rs
index ea195ee..d689f95 100644
--- a/src/readline.rs
+++ b/src/readline.rs
@@ -12,6 +12,7 @@ use directories::ProjectDirs;
12 12
13use regex::Regex; 13use regex::Regex;
14 14
15use crate::error::CalcError;
15use crate::eval_math_expression; 16use crate::eval_math_expression;
16 17
17pub struct RLHelper { 18pub struct RLHelper {
@@ -67,6 +68,7 @@ impl Highlighter for LineHighlighter {
67 } 68 }
68 Owned(coloured) 69 Owned(coloured)
69 } 70 }
71 Err(CalcError::Help) => Owned(line.replace("help", "\x1b[36mhelp\x1b[0m")),
70 Err(_) => Owned(format!("\x1b[31m{}\x1b[0m", line)), 72 Err(_) => Owned(format!("\x1b[31m{}\x1b[0m", line)),
71 } 73 }
72 } 74 }