Skip to content

Commit

Permalink
Fix + Format
Browse files Browse the repository at this point in the history
  • Loading branch information
ImpossibleReality committed Jan 22, 2024
1 parent 7de4041 commit 5e3d420
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 74 deletions.
25 changes: 6 additions & 19 deletions src-tauri/src/evaluation/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
mod state;
pub use state::*;

use pest::Parser;
pub use state::SiffraState;

use crate::grammar::representation::ParsedLine;
use crate::grammar::{parse_line, Rule, SiffraParser};
use crate::representations::{Expression, Value, Float, Dimension};

const PI_STRING: &str = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230";
const E_STRING: &str = "2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059";

use crate::representations::{Dimension, Expression, Float, Value};
pub type EvaluationResult = Result<Option<Value>, ()>;

pub fn evaluate_line(line: &str, state: &mut SiffraState) -> EvaluationResult {
Expand Down Expand Up @@ -48,18 +43,8 @@ pub fn evaluate_expr(expr: &Expression, state: &SiffraState) -> Result<Value, ()
Ok(v.clone())
} else {
match name.as_str() {
"pi" => Ok(Value::new(
{
Float::pi()
},
None,
)),
"e" => Ok(Value::new(
{
Float::e()
},
None,
)),
"pi" => Ok(Value::new(Float::pi(), None)),
"e" => Ok(Value::new(Float::e(), None)),
_ => Err(()),
}
}
Expand Down Expand Up @@ -95,7 +80,9 @@ pub fn evaluate_expr(expr: &Expression, state: &SiffraState) -> Result<Value, ()
}
"sqrt" => {
if args.len() == 1 {
Ok(args[0].try_pow(&Value::new(Float::from(0.5), None)).ok_or(())?)
Ok(args[0]
.try_pow(&Value::new(Float::from(0.5), None))
.ok_or(())?)
} else {
Err(())
}
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/grammar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ mod tests {

#[test]
fn test_parse_expr() {
let expr = parse_expr(SiffraParser::parse(Rule::expr, "log2(5(x)(y)) as mol %").unwrap());
let _expr = parse_expr(SiffraParser::parse(Rule::expr, "log2(5(x)(y)) as mol %").unwrap());
}

#[test]
Expand All @@ -326,6 +326,6 @@ mod tests {

#[test]
fn test_ungrouped_functions() {
let expr = parse_expr(SiffraParser::parse(Rule::expr, "log 5a").unwrap());
let _expr = parse_expr(SiffraParser::parse(Rule::expr, "log 5a").unwrap());
}
}
12 changes: 3 additions & 9 deletions src-tauri/src/grammar/representation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::representations::{Dimension, Quantity};
use crate::representations::{Expression, Float, Value};
use std::str::FromStr;
use crate::representations::{Dimension, Quantity};

#[derive(Debug)]
pub enum ParsedLine {
Expand Down Expand Up @@ -79,19 +79,13 @@ impl TryFrom<ParsedDimension> for Dimension {

for (unit, power) in dimension.numerator {
if !(unit.name == "unitless" || unit.name == "number") {
quantities.push((
Quantity::from_str(unit.name.as_str())?,
Float::from(power),
));
quantities.push((Quantity::from_str(unit.name.as_str())?, Float::from(power)));
}
}

for (unit, power) in dimension.denominator {
if !(unit.name == "unitless" || unit.name == "number") {
quantities.push((
Quantity::from_str(unit.name.as_str())?,
Float::from(-power),
));
quantities.push((Quantity::from_str(unit.name.as_str())?, Float::from(-power)));
}
}

Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ struct SiffraLineOutput {
}

fn display_value(val: Value) -> String {
let (mut val, dim) = val.into_parts();
let (val, dim) = val.into_parts();

let mut output = String::new();

Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/representations/expression.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::representations::Value;
use crate::representations::Dimension;
use crate::representations::Value;

#[derive(Debug, Clone)]
pub enum Expression {
Expand Down
4 changes: 2 additions & 2 deletions src-tauri/src/representations/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod value;
mod expression;
mod value;

pub use value::*;
pub use expression::*;
pub use value::*;
17 changes: 4 additions & 13 deletions src-tauri/src/representations/value/dimension/angle.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,24 @@
use crate::{quantity, ratio};



quantity!(
Angle,
[
(
Radian,
ratio!(1 / 1),
"rad",
"radian",
"radians",
"rads"
),
(Radian, ratio!(1 / 1), "rad", "radian", "radians", "rads"),
(
Degree,
ratio!( 1783366216531 / 102179357533440),
ratio!(1783366216531 / 102179357533440),
"deg",
"degree",
"degs",
"degrees"
),
(
Revolution,
ratio!( 1783366216531 / 567663097408 ),
ratio!(1783366216531 / 567663097408),
"rev",
"revolution",
"revs",
"revolutions"
)
]
);
);
14 changes: 7 additions & 7 deletions src-tauri/src/representations/value/dimension/mod.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
mod amount;
mod angle;
mod chemical;
mod length;
mod macros;
mod mass;
mod time;
mod angle;

use std::str::FromStr;
use crate::representations::Float;
use std::collections::BTreeMap;
use std::fmt::Display;
use std::ops::Neg;
use crate::representations::Float;
use std::str::FromStr;

pub use {
amount::Amount,
chemical::{ Compound, Element },
angle::Angle,
chemical::{Compound, Element},
length::Length,
mass::Mass,
time::Time,
angle::Angle,
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
Expand Down Expand Up @@ -119,15 +119,15 @@ impl Display for Dimension {

if *power > Float::from(0) {
if !numerator.is_empty() {
quantity_shorthand = format!("*{}", quantity_shorthand);
quantity_shorthand = format!("*{}", quantity_shorthand);
}
numerator.push_str(&*quantity_shorthand);
if *power > Float::from(1) {
numerator.push_str(&format!("^{}", power));
}
} else if *power < Float::from(0) {
if !denominator.is_empty() {
quantity_shorthand = format!("*{}", quantity_shorthand);
quantity_shorthand = format!("*{}", quantity_shorthand);
}
denominator.push_str(&*quantity_shorthand);
if *power != Float::from(-1) {
Expand Down
40 changes: 27 additions & 13 deletions src-tauri/src/representations/value/float.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use std::fmt::Display;
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::sync::{Arc, Mutex};
use astro_float::{BigFloat, Radix};
use astro_float::Consts;
use astro_float::RoundingMode;
use astro_float::{BigFloat, Radix};
use lazy_static::lazy_static;
use std::fmt::Display;
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::sync::{Arc, Mutex};

lazy_static! {
static ref CONST_CACHE: Arc<Mutex<Consts>> = Arc::new(Mutex::new(Consts::new().expect("Failed to initialize constants")));
static ref CONST_CACHE: Arc<Mutex<Consts>> = Arc::new(Mutex::new(
Consts::new().expect("Failed to initialize constants")
));
}

const PRECISION: usize = 256;
Expand Down Expand Up @@ -103,13 +105,16 @@ impl Float {
impl Display for Float {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut cache = CONST_CACHE.lock().unwrap();
let string = self.0.format(Radix::Dec, ROUNDING_MODE, &mut *cache).unwrap();
let string = self
.0
.format(Radix::Dec, ROUNDING_MODE, &mut *cache)
.unwrap();

// In scientific notation
let string = string.split('e').collect::<Vec<&str>>();
let (Some(mantissa), Some(exponent)) = (string.get(0), string.get(1)) else {
write!(f, "{}", string[0])?;
return Ok(())
return Ok(());
};

let mut exponent = exponent.parse::<i32>().unwrap();
Expand Down Expand Up @@ -263,8 +268,6 @@ impl PartialOrd for Float {
}
}



impl<T> From<T> for Float
where
T: Into<BigFloat>,
Expand All @@ -282,8 +285,14 @@ mod tests {
fn test_parse() {
assert_eq!(Float::parse("1.00").unwrap(), Float::from(1));
assert_eq!(Float::parse("1.0E1").unwrap(), Float::from(10));
assert!((&Float::parse("1.0E-1").unwrap() - &Float::from(0.1)).abs() < Float::from(0.0000000001));
assert!((&Float::parse("15.03E+3").unwrap() - &Float::from(15030)).abs() < Float::from(0.0000000001));
assert!(
(&Float::parse("1.0E-1").unwrap() - &Float::from(0.1)).abs()
< Float::from(0.0000000001)
);
assert!(
(&Float::parse("15.03E+3").unwrap() - &Float::from(15030)).abs()
< Float::from(0.0000000001)
);
}

#[test]
Expand All @@ -292,12 +301,17 @@ mod tests {
assert_eq!(Float::parse("001.00").unwrap().to_string(), "1");
assert_eq!(Float::parse("5e-20").unwrap().to_string(), "5E-20");
assert_eq!(Float::parse("999").unwrap().to_string(), "999");
assert_eq!(Float::parse(".01123410918273418734182374").unwrap().to_string(), "0.01123410918273418734182374");
assert_eq!(
Float::parse(".01123410918273418734182374")
.unwrap()
.to_string(),
"0.01123410918273418734182374"
);
assert_eq!(Float::parse("0").unwrap().to_string(), "0.0");
assert_eq!(Float::from(0).to_string(), "0.0");
assert_eq!(Float::from(-1).to_string(), "-1");
assert_eq!(Float::from(f64::NAN).to_string(), "NaN");
assert_eq!(Float::from(f64::INFINITY).to_string(), "Inf");
assert_eq!(Float::from(f64::NEG_INFINITY).to_string(), "-Inf");
}
}
}
8 changes: 1 addition & 7 deletions src-tauri/src/representations/value/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::fmt::Display;
use std::ops::{Add, Div, Mul, Neg, Sub};
use std::str::FromStr;

mod dimension;
pub use dimension::*;
Expand Down Expand Up @@ -96,11 +94,7 @@ impl Value {
self.dimension
.0
.iter()
.map(|(quantity, power)| {
(quantity.clone(), {
power.clone().neg()
})
})
.map(|(quantity, power)| (quantity.clone(), { power.clone().neg() }))
.collect(),
),
value: self.value.clone().recip(),
Expand Down

0 comments on commit 5e3d420

Please sign in to comment.