Files
Graphite/libraries/math-parser/src/ast.rs
urisinger 9fb494764c Add math-parser library (#2033)
* start of parser

* ops forgot

* reorder files and work on executer

* start of parser

* ops forgot

* reorder files and work on executer

* Cleanup and fix tests

* Integrate into the editor

* added unit checking at parse time

* fix tests

* fix issues

* fix editor intergration

* update pest grammer to support units

* units should be working, need to set up tests to know

* make unit type store exponants as i32

* remove scale, insted just multiply the literal by the scale

* unit now contains empty unit,remove options

* add more tests and implement almost all unary operators

* add evaluation context and variables

* function calling, api might be refined later

* add constants, change function call to not be as built into the parser
and add tests

* add function definitions

* remove meval

* remove raw-rs from workspace

* add support for numberless units

* fix unit handleing logic, add some "unit" tests(haha)

* make it so units cant do implcit mul with idents

* add bench and better tests

* fix editor api

* remove old test

* change hashmap context to use deref

* change constants to use hashmap instad of function

---------

Co-authored-by: hypercube <0hypercube@gmail.com>
Co-authored-by: Keavon Chambers <keavon@keavon.com>
2024-11-21 10:24:01 -08:00

76 lines
1.4 KiB
Rust

use crate::value::Complex;
#[derive(Debug, PartialEq, Eq)]
pub struct Unit {
// Exponent of length unit (meters)
pub length: i32,
// Exponent of mass unit (kilograms)
pub mass: i32,
// Exponent of time unit (seconds)
pub time: i32,
}
impl Default for Unit {
fn default() -> Self {
Self::BASE_UNIT
}
}
impl Unit {
pub const BASE_UNIT: Unit = Unit { length: 0, mass: 0, time: 0 };
pub const LENGTH: Unit = Unit { length: 1, mass: 0, time: 0 };
pub const MASS: Unit = Unit { length: 0, mass: 1, time: 0 };
pub const TIME: Unit = Unit { length: 0, mass: 0, time: 1 };
pub const VELOCITY: Unit = Unit { length: 1, mass: 0, time: -1 };
pub const ACCELERATION: Unit = Unit { length: 1, mass: 0, time: -2 };
pub const FORCE: Unit = Unit { length: 1, mass: 1, time: -2 };
pub fn base_unit() -> Self {
Self::BASE_UNIT
}
pub fn is_base(&self) -> bool {
*self == Self::BASE_UNIT
}
}
#[derive(Debug, PartialEq)]
pub enum Literal {
Float(f64),
Complex(Complex),
}
impl From<f64> for Literal {
fn from(value: f64) -> Self {
Self::Float(value)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Pow,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum UnaryOp {
Neg,
Sqrt,
Fac,
}
#[derive(Debug, PartialEq)]
pub enum Node {
Lit(Literal),
Var(String),
FnCall { name: String, expr: Vec<Node> },
BinOp { lhs: Box<Node>, op: BinaryOp, rhs: Box<Node> },
UnaryOp { expr: Box<Node>, op: UnaryOp },
}