added exponentials

This commit is contained in:
Lilith Schier 2026-08-18 20:36:18 +02:00
parent 074c7a10e4
commit 9b78cf2786
2 changed files with 12 additions and 1 deletions

View file

@ -17,6 +17,7 @@ pub enum Expression {
Mul(ExpBox, ExpBox), Mul(ExpBox, ExpBox),
Div(ExpBox, ExpBox), Div(ExpBox, ExpBox),
IntDiv(ExpBox, ExpBox), IntDiv(ExpBox, ExpBox),
Pow(ExpBox, ExpBox),
} }
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
@ -265,6 +266,12 @@ impl Expression {
let rhs = rhs_node.evaluate(rng, w, precedence)?; let rhs = rhs_node.evaluate(rng, w, precedence)?;
lhs.div_euclid(rhs) lhs.div_euclid(rhs)
} }
Pow(lhs_node, rhs_node) => {
let lhs = lhs_node.evaluate(rng, w, precedence)?;
write!(w, " ^ ")?;
let rhs = rhs_node.evaluate(rng, w, precedence)?;
lhs.powf(rhs)
}
}; };
if needs_parens { if needs_parens {
write!(w, ")")?; write!(w, ")")?;
@ -326,6 +333,7 @@ impl Expression {
Expression::Mul(lhs, rhs) => lhs.avg()? * rhs.avg()?, Expression::Mul(lhs, rhs) => lhs.avg()? * rhs.avg()?,
Expression::Div(lhs, rhs) => lhs.avg()? / rhs.avg()?, Expression::Div(lhs, rhs) => lhs.avg()? / rhs.avg()?,
Expression::IntDiv(lhs, rhs) => lhs.avg()?.div_euclid(rhs.avg()?), Expression::IntDiv(lhs, rhs) => lhs.avg()?.div_euclid(rhs.avg()?),
Expression::Pow(lhs, rhs) => lhs.avg()?.powf(rhs.avg()?),
}; };
Ok(result) Ok(result)
} }
@ -377,6 +385,7 @@ impl Expression {
match self { match self {
Const(_) => 1, Const(_) => 1,
Dice { .. } => 2, Dice { .. } => 2,
Pow(_, _) => 4,
Neg(_) => 5, Neg(_) => 5,
Mul(_, _) | Div(_, _) | IntDiv(_, _) => 7, Mul(_, _) | Div(_, _) | IntDiv(_, _) => 7,
Add(_, _) | Sub(_, _) => 8, Add(_, _) | Sub(_, _) => 8,

View file

@ -94,6 +94,7 @@ fn expr<'c, 'i>(
complete(unary_op(5, tag("-"))), complete(unary_op(5, tag("-"))),
fail(), fail(),
complete(alt(( complete(alt((
binary_op(4, Left, spaced_op("^")),
binary_op(7, Left, spaced_op("*")), binary_op(7, Left, spaced_op("*")),
binary_op(7, Left, spaced_op("//")), binary_op(7, Left, spaced_op("//")),
binary_op(7, Left, spaced_op("/")), binary_op(7, Left, spaced_op("/")),
@ -106,6 +107,7 @@ fn expr<'c, 'i>(
Ok(match op { Ok(match op {
Prefix("-", x) => Neg(Box::new(x)), Prefix("-", x) => Neg(Box::new(x)),
Binary(lhs, "^", rhs) => Pow(Box::new(lhs), Box::new(rhs)),
Binary(lhs, "*", rhs) => Mul(Box::new(lhs), Box::new(rhs)), Binary(lhs, "*", rhs) => Mul(Box::new(lhs), Box::new(rhs)),
Binary(lhs, "//", rhs) => IntDiv(Box::new(lhs), Box::new(rhs)), Binary(lhs, "//", rhs) => IntDiv(Box::new(lhs), Box::new(rhs)),
Binary(lhs, "/", rhs) => Div(Box::new(lhs), Box::new(rhs)), Binary(lhs, "/", rhs) => Div(Box::new(lhs), Box::new(rhs)),
@ -182,7 +184,7 @@ mod test {
#[test] #[test]
pub fn parse_math() { pub fn parse_math() {
let expression = parse("8 * 2 + 2 * 5").unwrap(); let expression = parse("8 * 2 + 2 * 5 ^ 4").unwrap();
assert_matches!(expression, Expression::Add { .. }); assert_matches!(expression, Expression::Add { .. });
} }