Skip to content

Commit

Permalink
- added support for a single variable to the calculator
Browse files Browse the repository at this point in the history
- added support for pre-compiling calculator expressions and substituting in values later
  • Loading branch information
FantasyPvP committed Mar 23, 2024
1 parent c4067fa commit 15a8a6a
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 56 deletions.
103 changes: 76 additions & 27 deletions src/user/bin/calc/calc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use core::fmt;
use alloc::{boxed::Box, string::String, vec::Vec};
use alloc::{boxed::Box, format, string::String, vec::Vec};
use alloc::string::ToString;
use alloc::borrow::ToOwned;
use crate::{println, print, mknode, std};
use crate::{println, print, mknode, std, serial_println};

use async_trait::async_trait;
use crate::std::application::{
Expand Down Expand Up @@ -35,6 +35,7 @@ impl Interpreter {
Node::Number(_) => return self.visit_number(node),
Node::Operator(_) => return self.visit_operator(node),
Node::Function(_) => return self.visit_function(node),
Node::Variable => panic!("substitution not used!"),
}
}

Expand Down Expand Up @@ -195,16 +196,6 @@ impl Interpreter {

}











impl Parser {
fn new(tokens: Vec<Token>) -> Result<Self, Error> {
let mut parser = Self { tokens, idx: -1, current: Token::Null };
Expand All @@ -217,9 +208,7 @@ impl Parser {
let result = self.expr();
result
}




fn advance(&mut self) -> Result<Option<Token>, Error> {
self.idx += 1;
if self.idx < self.tokens.len() as i32 {
Expand All @@ -240,7 +229,10 @@ impl Parser {
self.advance()?;
return Ok(Node::Number(x))
},

Token::Variable => {
self.advance()?;
return Ok(Node::Variable)
},
Token::Bracket('(') => {
self.advance()?;
let expr = self.expr()?;
Expand Down Expand Up @@ -381,7 +373,7 @@ impl Application for Calculator {
match self.calculate_and_format(inp) {
Ok(_) => (),
Err(e) => {
println!("your input must be a valid mathematical expression contaning only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
println!("your input must be a valid mathematical expression containing only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
println!("{:?}", e);
return Err(ShellError::CommandFailed(String::from("failed")))
},
Expand All @@ -391,7 +383,7 @@ impl Application for Calculator {
match self.calculate_and_format(args.into_iter().collect()) {
Ok(x) => x,
Err(e) => {
println!("your input must be a valid mathematical expression contaning only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
println!("your input must be a valid mathematical expression containing only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
println!("{:?}", e);
return Err(ShellError::CommandFailed(String::from("failed")))
},
Expand All @@ -417,7 +409,51 @@ impl Calculator {
{}", equation, res);
Ok(res)
}


pub fn get_expr(&self, mut equation: String) -> Result<Node, String> {
equation.push('\n');
let mut neweq = equation.clone();
neweq.pop();

let tokens = tokenise(&equation).map_err(|e| format!(
"failed to tokenise: {:?}",
e
))?;

serial_println!("{:?}", tokens);

let mut parser = Parser::new(tokens).unwrap();
parser.parse().map_err(|e| format!("{:?}", e))
}

pub fn substitute(&self, equation: &mut Node, value: f64) {
match equation {
Node::BinaryOperation(x) => {
self.substitute(&mut x.left, value);
self.substitute(&mut x.right, value);
},
Node::UnaryOperation(x) => {
self.substitute(&mut x.other, value);
},
Node::Function(x) => {
self.substitute(&mut x.arg, value);
},
Node::Variable => {
*equation = Node::Number(value);
}
_ => ()
}
}

pub fn evaluate(&self, equation: &Node) -> Result<f64, String> {
let mut interpreter = Interpreter::new().unwrap();
let result = interpreter.visit(equation.clone()).unwrap();
let return_res = if let Value::Number(x) = result {
x
} else { panic!("the value returned was not a float! THIS IS A BUG") };
Ok(return_res)
}

fn calculate_inner(&self, mut equation: String) -> Result<f64, Error> {
equation.push('\n');
let mut neweq = equation.clone();
Expand All @@ -436,6 +472,7 @@ impl Calculator {
}
}


fn tokenise(equation: &str) -> Result<Vec<Token>, Error> {
let mut tokens = Vec::new();
let mut current_num = "".to_string();
Expand All @@ -446,6 +483,16 @@ fn tokenise(equation: &str) -> Result<Vec<Token>, Error> {
'mainloop: for (x, character) in equation.chars().enumerate() {

match character {
'x' => {
if is_var {
tokens.push(Token::Func(current_string.clone()));
}
is_var = false;
current_string = "".to_string();
tokens.push(Token::Variable);
continue;
}

'a'..='z' => {
is_var = true;
current_string.push(character);
Expand All @@ -468,7 +515,6 @@ fn tokenise(equation: &str) -> Result<Vec<Token>, Error> {
tokens.push(Token::Number(current_num.parse::<f64>().unwrap()));
current_num = "".to_string();
} else if current_string.len() != 0 {

} match character {
'+' => tokens.push(Token::Operator(Operator::Add)),
'-' => tokens.push(Token::Operator(Operator::Sub)),
Expand All @@ -495,7 +541,7 @@ fn tokenise(equation: &str) -> Result<Vec<Token>, Error> {
'\n' => break 'mainloop,
' ' => (),
_ => {
return Err(Error::InvalidCharacter(x))
return Err(Error::InvalidCharacter(character))
},
}
}
Expand All @@ -522,11 +568,12 @@ enum Token {
Bracket(char),
Null,
Func(String),
Variable,
}


#[derive(Copy, Debug, Clone, PartialEq)]
enum Operator {
pub enum Operator {
Add,
Sub,
Mul,
Expand All @@ -539,7 +586,7 @@ enum Operator {
#[derive(Debug)]
enum Error {
InvalidSyntax(usize),
InvalidCharacter(usize),
InvalidCharacter(char),
LogicalError(String),
Eof,
Other(String),
Expand All @@ -548,8 +595,9 @@ enum Error {


#[derive(Debug, Clone, PartialEq)]
enum Node {
pub enum Node {
Number(f64),
Variable,
Operator(Operator),
Function(Box<FunctionCall>),
BinaryOperation(Box<BinaryOperation>),
Expand All @@ -558,20 +606,20 @@ enum Node {


#[derive(Debug, Clone, PartialEq)]
struct BinaryOperation {
pub struct BinaryOperation {
left: Node,
operator: Node,
right: Node,
}

#[derive(Debug, Clone, PartialEq)]
struct UnaryOperation {
pub struct UnaryOperation {
operator: Node,
other: Node,
}

#[derive(Debug, Clone, PartialEq)]
struct FunctionCall {
pub struct FunctionCall {
name: String,
arg: Node,
}
Expand Down Expand Up @@ -612,6 +660,7 @@ impl fmt::Display for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Node::Number(x) => write!(f, "{}", x),
Node::Variable => write!(f, "x"),
Node::Operator(x) => write!(f, "{}", x),
Node::BinaryOperation(x) => {
let inner = *x.clone();
Expand Down
3 changes: 2 additions & 1 deletion src/user/bin/calc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod calc;
//pub mod calc;
mod functions;
pub mod calc;

pub use calc::*;
68 changes: 43 additions & 25 deletions src/user/bin/grapher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const OFFSET_Y: i64 = 10;

use core::f64::consts::E;
use core::f64::consts::PI;
use crate::serial_println;

#[derive(Clone)]
pub struct Grapher {
Expand Down Expand Up @@ -89,14 +90,14 @@ impl Application for Grapher {
let mut offset_x: i64 = 0;
let mut offset_y: i64 = 0;

let mut rerender = true;
let mut redraw_graph = true;

while let c = Stdin::keystroke().await {

let entry_widget = container.elements.get("entry_box").unwrap();
let mut entry = entry_widget.fetch::<CgLineEdit>().unwrap();

rerender = true;
redraw_graph = true;
match c {
KeyStroke::Char('\n') => {
commandresult = entry.text.iter().collect();
Expand All @@ -105,24 +106,27 @@ impl Application for Grapher {
offset_y = 0;
},
KeyStroke::Char(Stdin::BACKSPACE) => {
rerender = false;
redraw_graph = false;
entry.backspace()
},
KeyStroke::Char('`') => {
break;
}
KeyStroke::Char(c) => entry.write_char(c),
KeyStroke::Char(c) => {
redraw_graph = false;
entry.write_char(c)
},
KeyStroke::Left => offset_x -= 1,
KeyStroke::Right => offset_x += 1,
KeyStroke::Up => offset_y -= 1,
KeyStroke::Down => offset_y += 1,
KeyStroke::Alt => break,
_ => {
rerender = false;
redraw_graph = false;
}
}

if commandresult.len() > 0 && rerender {
if commandresult.len() > 0 && redraw_graph {
self.reset_frame();
self.graph_equation(commandresult.clone(), (offset_x, offset_y));
let self_widget = container.elements.get("grapher").unwrap();
Expand Down Expand Up @@ -153,26 +157,40 @@ impl Grapher {
fn graph_equation(&mut self, equation: String, offsets: (i64, i64)) {

let cal = calc::Calculator::new();
for x in -4000..4000 {
let x = x as f64 / 100.0;

let new_eq = equation.chars().map(|c| {
match c {
'x' => format!("({})", x + offsets.0 as f64),
'e' => format!("({})", E),
'π' => format!("({})", PI),
_ => c.to_string(),
}
}).collect::<String>();

let fx = cal.calculate(new_eq);
if let Ok(y) = fx {
self.render_point(PointF64 {
x,
y: y + offsets.1 as f64,
})
let ast = cal.get_expr(equation.chars().map(|c| {
match c {
'e' => format!("({})", E),
'π' => format!("({})", PI),
_ => c.to_string(),
}
};
}).collect::<String>());

if let Ok(ast) = ast {
for x in -4000..4000 {
let x = x as f64 / 100.0;

let mut cmd = ast.clone();
cal.substitute(&mut cmd, x + offsets.0 as f64);

//
// let new_eq = equation.chars().map(|c| {
// match c {
// 'x' => format!("({})", x + offsets.0 as f64),
// 'e' => format!("({})", E),
// 'π' => format!("({})", PI),
// _ => c.to_string(),
// }
// }).collect::<String>();

let fx = cal.evaluate(&cmd);
if let Ok(y) = fx {
self.render_point(PointF64 {
x,
y: y + offsets.1 as f64,
})
}
};
}
}


Expand Down
4 changes: 2 additions & 2 deletions src/user/bin/pong.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ impl Ball {
(self.pos.y as i32 + self.vy) as usize
);
for i in 0..5 {
if player1.pos.y + i == pos_next.y && player1.pos.x == pos_next.x {
if player1.pos.y + i - 2 == pos_next.y && player1.pos.x == pos_next.x {
self.vx = -self.vx;
break;
} else if player2.pos.y + i == pos_next.y && player2.pos.x == pos_next.x {
} else if player2.pos.y + i - 2 == pos_next.y && player2.pos.x == pos_next.x {
self.vx = -self.vx;
break;
}
Expand Down
2 changes: 1 addition & 1 deletion src/user/bin/snake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ impl Game {
false => ColorCode::new(Color::LightGreen, Color::Black),
};
for point in s.tail.iter() {
frame[24 - point.y as usize][point.x as usize] = ColouredChar::coloured('@', curr_colour);
frame[24 - point.y as usize][point.x as usize] = ColouredChar::coloured('', curr_colour);
}
}

Expand Down

0 comments on commit 15a8a6a

Please sign in to comment.