changed some calculator stuff idk

idk
This commit is contained in:
FantasyPvP
2023-10-04 00:40:18 +01:00
parent f5cc41c132
commit 4a7cf2a634
8 changed files with 117 additions and 83 deletions
+21 -17
View File
@@ -13,7 +13,7 @@
"state": { "state": {
"type": "markdown", "type": "markdown",
"state": { "state": {
"file": "docs/crystal-api.md", "file": "docs/standard library docs/random.rs.md",
"mode": "source", "mode": "source",
"source": false "source": false
} }
@@ -85,7 +85,7 @@
"state": { "state": {
"type": "backlink", "type": "backlink",
"state": { "state": {
"file": "docs/crystal-api.md", "file": "docs/standard library docs/random.rs.md",
"collapseAll": false, "collapseAll": false,
"extraContext": false, "extraContext": false,
"sortOrder": "alphabetical", "sortOrder": "alphabetical",
@@ -102,7 +102,7 @@
"state": { "state": {
"type": "outgoing-link", "type": "outgoing-link",
"state": { "state": {
"file": "docs/crystal-api.md", "file": "docs/standard library docs/random.rs.md",
"linksCollapsed": false, "linksCollapsed": false,
"unlinkedCollapsed": true "unlinkedCollapsed": true
} }
@@ -125,7 +125,7 @@
"state": { "state": {
"type": "outline", "type": "outline",
"state": { "state": {
"file": "docs/crystal-api.md" "file": "docs/standard library docs/random.rs.md"
} }
} }
} }
@@ -148,19 +148,23 @@
}, },
"active": "66a91bbf10023e7b", "active": "66a91bbf10023e7b",
"lastOpenFiles": [ "lastOpenFiles": [
"target/x86_64-CrystalOS/debug/bootimage-CrystalOS.bin.temp-stream-669ebd", "src/system/std/random.rs~",
"target/x86_64-CrystalOS/debug/bootimage-CrystalOS.bin.temp-stream-9e0e9c", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/dep-graph.part.bin",
"target/x86_64-CrystalOS/debug/bootimage-CrystalOS.bin.temp-stream-d5e1e2", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/zul1rjeojuld5ix.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/zypku2ljqkwe2t9.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/zfnrqaw0f711j75.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/x6aoth2ydi59hrm.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/zbpiidqfbcoo2ic.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/work-products.bin", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/ybbue6yegr9wklq.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/wl6c5klbro0lehu.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/y5gexnutwichxn7.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/vrj0gel9n5vxmd1.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/xt0etcnzycl3z0h.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/uoqvrm3l2w095ln.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/xaip1tz6tun888.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/uhkf8uzx25q6zkn.o", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/wv8eny5rk6dji78.o",
"target/x86_64-CrystalOS/debug/incremental/CrystalOS-2s2eto1gmy107/s-gpa8tfuu7j-zjn7o7-au49h4b9abxljhlinnweh4wh/query-cache.bin", "target/x86_64-CrystalOS/debug/incremental/CrystalOS-3u2m7vf43mho9/s-gpbbzwrvu5-1u8ini4-working/work-products.bin",
"docs/standard library docs/application.rs.md",
"docs/standard library docs/random.rs.md",
"docs/standard library docs/io.rs.md",
"docs/main.md", "docs/main.md",
"README.md", "docs/crystal-api.md",
"docs/crystal-api.md" "docs/Untitled.md",
"README.md"
] ]
} }
@@ -0,0 +1,18 @@
- provides a simple trait to standardise the way applications are called and run from the shell or other applications.
```rust
use async_trait::async_trait;
// all applications should implment this trait and be started by using simlar to:
let res = ImplementsApplication.run(args).await?;
#[async_trait]
pub trait Application {
fn new -> Self;
async fn run(&mut self, _: Vec<String>) -> Result<(), Error>;
}
```
## important:
- the async_trait crate must be in scope in the file or else an error about trait bounds will be displayed at compile time.
+27
View File
@@ -0,0 +1,27 @@
- provides structs and functions for input and output
provided features:
```rust
print() // prints a formatted string to the screen
println!() // print with a newline appended
print_log!() // prints a formatted log string in yellow
println_log!() // print_log with newline appended
printerr!() // prints formatted error in yellow with appended newline, this is called when the OS panics.
impl Screen {
pub fn terminal_mode(); // changes the display mode of the kernel to terminal mode, meaning text can be inputted line by line as commands.
pub fn application_mode(); // changes the display mode of the kernel to application mode, meaning applications are responsible for generating their own frames and rendering them.
pub fn switch(); // toggles the current display mode
pub fn clear(); // clears the screen
}
impl Stdin {
pub async fn readline() -> String; // reads a line of input in terminal mode
pub async fn keystroke() -> char; // waits for the user to enter a keystroke
pub fn try_keystroke() -> Option<char>; // immediately returns a keystroke if an unread one has been received by the kernel
}
```
+6
View File
@@ -0,0 +1,6 @@
```rust
impl Random {
pub fn int(lower: usize, upper: usize) -> usize; // returns random number in range
pub fn selection<T: Clone>(ls: &Vec<T>)
}
```
+4 -3
View File
@@ -1,5 +1,5 @@
use alloc::{string::{String, ToString}, vec::Vec}; use alloc::{string::{String, ToString}, vec::Vec};
use core::ops::Index;
use rand::{Rng, SeedableRng, rngs::SmallRng, RngCore}; use rand::{Rng, SeedableRng, rngs::SmallRng, RngCore};
use spin::Mutex; use spin::Mutex;
use lazy_static::lazy_static; use lazy_static::lazy_static;
@@ -30,8 +30,9 @@ impl Random {
} }
} }
pub fn selection<T: Clone>(ls: &Vec<T>) -> &T {
let range = Random::int(0, ls.len() - 1); pub fn selection<T>(ls: &Vec<T>) -> &T {
let range = Random::int(0, ls.iter().len() - 1);
&ls[range as usize] &ls[range as usize]
} }
} }
+15 -34
View File
@@ -385,7 +385,7 @@ impl Application for Calculator {
if inp == String::from("exit\n") { if inp == String::from("exit\n") {
return Ok(()); return Ok(());
} }
match calculate_inner(inp) { match self.calculate_and_format(inp) {
Ok(_) => (), Ok(_) => (),
Err(e) => { 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 contaning only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
@@ -395,7 +395,7 @@ impl Application for Calculator {
}; };
} }
} else { } else {
match calculate_inner(args.into_iter().collect()) { match self.calculate_and_format(args.into_iter().collect()) {
Ok(x) => x, Ok(x) => x,
Err(e) => { 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 contaning only numbers (including floats) and the operators: [ +, -, *, **, /, //, % ]");
@@ -410,40 +410,22 @@ impl Application for Calculator {
} }
} }
pub fn calc_outer(mut equation: String) -> Result<f64, String> { impl Calculator {
calculate_inner2(equation).map_err(|_| String::from("failed to calculate")) pub fn calculate(&self, equation: String) -> Result<f64, String> {
} self.calculate_inner(equation).map_err(|_| String::from("failed to calculate"))
}
fn calculate_inner(mut equation: String) -> Result<f64, Error> {
equation.push('\n');
let mut neweq = equation.clone();
neweq.pop();
let tokens = tokenise(&equation)?;
let mut parser = Parser::new(tokens)?;
let ast = parser.parse()?;
let mut interpreter = Interpreter::new()?;
let result = interpreter.visit(ast)?;
let return_res = if let Value::Number(x) = result {
x
} else { panic!("the value returned was not a float! THIS IS A BUG") };
pub fn calculate_and_format(&self, equation: String) -> Result<f64, String> {
let res = self.calculate_inner(equation.clone()).map_err(|_| String::from("failed to calculate"))?;
println!(" println!("
Calculating...
[ EXPRESSION ]
{} {}
Result:
{}", equation, res);
Ok(res)
}
[ RESULT ] fn calculate_inner(&self, mut equation: String) -> Result<f64, Error> {
{}
", neweq, return_res);
Ok(return_res)
}
fn calculate_inner2(mut equation: String) -> Result<f64, Error> {
equation.push('\n'); equation.push('\n');
let mut neweq = equation.clone(); let mut neweq = equation.clone();
neweq.pop(); neweq.pop();
@@ -458,10 +440,9 @@ fn calculate_inner2(mut equation: String) -> Result<f64, Error> {
} else { panic!("the value returned was not a float! THIS IS A BUG") }; } else { panic!("the value returned was not a float! THIS IS A BUG") };
Ok(return_res) Ok(return_res)
}
} }
fn tokenise(equation: &str) -> Result<Vec<Token>, Error> { fn tokenise(equation: &str) -> Result<Vec<Token>, Error> {
let mut tokens = Vec::new(); let mut tokens = Vec::new();
let mut current_num = "".to_string(); let mut current_num = "".to_string();
+3 -2
View File
@@ -39,6 +39,8 @@ impl Application for Grapher {
let mut equation: String = args.into_iter().collect(); let mut equation: String = args.into_iter().collect();
use super::calc; use super::calc;
let cal = calc::Calculator::new();
for x in -4000..4000 { for x in -4000..4000 {
let x = x as f64 / 100.0; let x = x as f64 / 100.0;
@@ -46,7 +48,7 @@ impl Application for Grapher {
if c == 'x' { format!("({})", x) } else { c.to_string() } if c == 'x' { format!("({})", x) } else { c.to_string() }
}).collect::<String>(); }).collect::<String>();
let fx = calc::calc_outer(new_eq).map_err(|_| Error::ApplicationError(String::from("failed to calculate"))); let fx = cal.calculate(new_eq).map_err(|_| Error::ApplicationError(String::from("failed to calculate")));
if let Ok(y) = fx { if let Ok(y) = fx {
self.render_point(PointF64 { self.render_point(PointF64 {
@@ -54,7 +56,6 @@ impl Application for Grapher {
y, y,
}) })
} }
}; };
Screen::application_mode(); Screen::application_mode();
+10 -14
View File
@@ -3,11 +3,7 @@ use lazy_static::lazy_static;
use spin::Mutex; use spin::Mutex;
use x86_64::instructions::interrupts; use x86_64::instructions::interrupts;
use alloc::{ use alloc::{boxed::Box, string::{String, ToString}, vec, vec::Vec};
boxed::Box,
string::{String, ToString},
vec::Vec,
};
use vga::writers::{GraphicsWriter, PrimitiveDrawing}; use vga::writers::{GraphicsWriter, PrimitiveDrawing};
use crate::{ use crate::{
@@ -16,6 +12,7 @@ use crate::{
user::bin::*, user::bin::*,
}; };
use crate::std::io::{Color, write, Screen}; use crate::std::io::{Color, write, Screen};
use crate::std::random::Random;
use crate::user::bin::gigachad_detector::GigachadDetector; use crate::user::bin::gigachad_detector::GigachadDetector;
use crate::user::bin::grapher::Grapher; use crate::user::bin::grapher::Grapher;
@@ -117,6 +114,14 @@ async fn exec() -> Result<(), Error> {
let mut grapher = Grapher::new(); let mut grapher = Grapher::new();
grapher.run(args).await?; grapher.run(args).await?;
} }
"snake" => {
let mut game = snake::Game::new();
game.run(Vec::new()).await;
}
"gigachad?" => {
let mut gigachad_detector = GigachadDetector::new();
gigachad_detector.run(args).await?;
}
// direct OS functions (not applications) // direct OS functions (not applications)
"echo" => { "echo" => {
@@ -130,7 +135,6 @@ async fn exec() -> Result<(), Error> {
.collect::<String>() .collect::<String>()
) )
} }
"clear" => { "clear" => {
Screen::clear(); Screen::clear();
// not sure why this code was here but leaving it in case weird bugs happen so i remember to add it back if so // not sure why this code was here but leaving it in case weird bugs happen so i remember to add it back if so
@@ -145,14 +149,6 @@ async fn exec() -> Result<(), Error> {
"switch" => { "switch" => {
Screen::switch(); Screen::switch();
} }
"snake" => {
let mut game = snake::Game::new();
game.run(Vec::new()).await;
}
"gigachad?" => {
let mut gigachad_detector = GigachadDetector::new();
gigachad_detector.run(args).await?;
}
"time" => { "time" => {
use crate::std::time::timer; use crate::std::time::timer;
timer(); timer();