Skip to content

Commit

Permalink
parser/runtime: Implement Power infix operator as **
Browse files Browse the repository at this point in the history
  • Loading branch information
shesek committed Nov 7, 2024
1 parent ca7c4e9 commit 4688298
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/parser/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ pub enum InfixOp {
Add,
Subtract,
Multiply,
Power,
Mod,
Eq,
NotEq,
Expand Down
1 change: 1 addition & 0 deletions src/parser/grammar.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ InfixOpScriptSafe: ast::InfixOp = {
"+" => ast::InfixOp::Add,
"-" => ast::InfixOp::Subtract,
"*" => ast::InfixOp::Multiply,
"**" => ast::InfixOp::Power,
"%" => ast::InfixOp::Mod,
"==" => ast::InfixOp::Eq,
"!=" => ast::InfixOp::NotEq,
Expand Down
6 changes: 5 additions & 1 deletion src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,18 +306,22 @@ impl ast::InfixOp {
(Gte, Num(Float(a)), Num(Float(b))) => (a >= b).into(),
(Lte, Num(Float(a)), Num(Float(b))) => (a <= b).into(),

// + - * / % for numbers (integers and floats cannot be mixed)
// + - * / % ** for numbers (integers and floats cannot be mixed)
(Add, Num(Int(a)), Num(Int(b))) => a.checked_add(b).ok_or(Error::Overflow)?.into(),
(Subtract, Num(Int(a)), Num(Int(b))) => a.checked_sub(b).ok_or(Error::Overflow)?.into(),
(Multiply, Num(Int(a)), Num(Int(b))) => a.checked_mul(b).ok_or(Error::Overflow)?.into(),
(Divide, Num(Int(a)), Num(Int(b))) => a.checked_div(b).ok_or(Error::Overflow)?.into(),
(Mod, Num(Int(a)), Num(Int(b))) => (a % b).into(),
(Power, Num(Int(a)), Num(Int(b))) => {
a.checked_pow(b.try_into()?).ok_or(Error::Overflow)?.into()
}

(Add, Num(Float(a)), Num(Float(b))) => (a + b).into(),
(Subtract, Num(Float(a)), Num(Float(b))) => (a - b).into(),
(Multiply, Num(Float(a)), Num(Float(b))) => (a * b).into(),
(Divide, Num(Float(a)), Num(Float(b))) => (a / b).into(),
(Mod, Num(Float(a)), Num(Float(b))) => (a % b).into(),
(Power, Num(Float(a)), Num(Float(b))) => a.powf(b).into(),

// + for arrays, bytes and strings
(Add, Array(a), Array(b)) => [a.0, b.0].concat().into(),
Expand Down

0 comments on commit 4688298

Please sign in to comment.