///|
const MAX_EVAL_STEPS : Int32 = 4096

///|
/// Evaluate with UInt64 arithmetic and short-circuiting. Division or remainder by zero and evaluation limits raise PluralError.
/// Example: `expr.eval(21)`.
pub fn PluralExpr::eval(
  self : PluralExpr,
  n : UInt64,
) -> UInt64 raise PluralError {
  let mut steps = 0
  fn visit(node : PluralExpr, depth : Int32) -> UInt64 raise PluralError {
    check_depth(depth)
    steps += 1
    if steps > MAX_EVAL_STEPS {
      raise EvalLimitExceeded(limit=MAX_EVAL_STEPS)
    }
    match node {
      Literal(value) => value
      VarN => n
      Unary(LogicalNot, arg) => (visit(arg, depth + 1) == 0).to_uint64()
      Ternary(cond, yes, no) => {
        let branch = if visit(cond, depth + 1) != 0 { yes } else { no }
        visit(branch, depth + 1)
      }
      Binary(op, left, right) => {
        let a = visit(left, depth + 1)
        if op == LogicalOr && a != 0 {
          return 1
        }
        if op == LogicalAnd && a == 0 {
          return 0
        }
        let b = visit(right, depth + 1)
        match op {
          LogicalOr | LogicalAnd => (b != 0).to_uint64()
          Eq => (a == b).to_uint64()
          NotEq => (a != b).to_uint64()
          Lt => (a < b).to_uint64()
          LtEq => (a <= b).to_uint64()
          Gt => (a > b).to_uint64()
          GtEq => (a >= b).to_uint64()
          Add => a + b
          Sub => a - b
          Mul => a * b
          Div | Mod if b == 0 => raise DivisionByZero
          Div => a / b
          Mod => a % b
        }
      }
    }
  }
  visit(self, 0)
}

///|
/// Evaluate a count and check the resulting index against nplurals. Propagates evaluation errors and raises InvalidPluralIndex for an out-of-range result.
/// Example: `rule.eval_index(21)`.
pub fn PluralRule::eval_index(
  self : PluralRule,
  n : UInt64,
) -> Int32 raise PluralError {
  let index = self.expr.eval(n)
  if index >= self.nplurals.to_uint64() {
    raise InvalidPluralIndex(index~, nplurals=self.nplurals)
  }
  index.to_int()
}