diff --git a/src/quantity/quantity.rs b/src/quantity/quantity.rs index dfff1b4..7bf2779 100644 --- a/src/quantity/quantity.rs +++ b/src/quantity/quantity.rs @@ -111,6 +111,7 @@ impl Quantity { pub fn is_negative(&self) -> bool { self.v.is_negative() } pub fn is_positive(&self) -> bool { self.v.is_positive() } pub fn unitless(&self) -> bool { self.u.unitless() } + pub fn unit(&self) -> &Unit { &self.u } quant_foward!(fract); quant_foward!(abs); diff --git a/src/tests.rs b/src/tests.rs index dbca87b..8c24f00 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -191,7 +191,7 @@ fn units() { //good_expr("2 m", "rt (4m^2)"); - //bad_expr("m + s"); - //bad_expr("m ^ s"); + bad_expr("m + s"); + bad_expr("m ^ s"); //bad_expr("m ^ pi"); } \ No newline at end of file diff --git a/src/tokens/function.rs b/src/tokens/function.rs index 35720c6..b958c46 100644 --- a/src/tokens/function.rs +++ b/src/tokens/function.rs @@ -70,6 +70,10 @@ impl Function { let a = args[0].as_number(); let Token::Number(q) = a else {panic!()}; + if !q.unitless() { + return Err(()); + } + match self { Function::Abs => { return Ok(Token::Number(q.abs())); }, Function::Floor => { return Ok(Token::Number(q.floor())); }, diff --git a/src/tokens/operator.rs b/src/tokens/operator.rs index 2053691..6488cd8 100644 --- a/src/tokens/operator.rs +++ b/src/tokens/operator.rs @@ -369,6 +369,11 @@ impl Operator{ while i < args.len() { let j = args[i].as_number(); if let Token::Number(v) = j { + + if sum.unit() != v.unit() { + return Err(()); + } + sum += v; } else { panic!(); @@ -399,6 +404,11 @@ impl Operator{ if let Token::Number(va) = a { if let Token::Number(vb) = b { + + if !(va.unitless() && vb.unitless()) { + return Err(()); + } + if vb <= Quantity::new_rational(1f64).unwrap() { return Err(()); } if va.fract() != Quantity::new_rational(0f64).unwrap() { return Err(()); } if vb.fract() != Quantity::new_rational(0f64).unwrap() { return Err(()); } @@ -415,6 +425,11 @@ impl Operator{ if let Token::Number(va) = a { if let Token::Number(vb) = b { + + if va.unit() != vb.unit() { + return Err(()); + } + let p = va.pow(vb); if p.is_nan() {return Err(());} return Ok(Token::Number(p)); @@ -427,6 +442,11 @@ impl Operator{ let args = args[0].as_number(); if let Token::Number(v) = args { + + if !v.unitless() { + return Err(()); + } + if !v.fract().is_zero() { return Err(()); } if v > Quantity::new_rational(50_000f64).unwrap() { return Err(()); }