Skip to content

fix: report "Division by zero." for modulo by zero#910

Open
He-Pin wants to merge 1 commit into
databricks:masterfrom
He-Pin:fix/modulo-division-by-zero
Open

fix: report "Division by zero." for modulo by zero#910
He-Pin wants to merge 1 commit into
databricks:masterfrom
He-Pin:fix/modulo-division-by-zero

Conversation

@He-Pin

@He-Pin He-Pin commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Add zero-divisor check for % operator across all evaluation paths, the static optimizer, and stdlib builtins (std.mod, std.modulo). Previously 42 % 0 produced NaN; now it reports "Division by zero." matching go-jsonnet.

Motivation

The modulo operator (%) did not check for zero divisor, producing NaN instead of an error. This was inconsistent with go-jsonnet which reports "Division by zero." and also inconsistent with sjsonnet's own division operator (/) which already had the check in every evaluation path.

Modification

Add zero-divisor guard for % in all evaluation paths:

  • Evaluator: tryInlineArith, evalBinaryOpNumNum, visitBinaryOpAsDouble, visitBinaryOp (polymorphic OP_% case)
  • StaticOptimizer: tryFoldBinaryOp (constant folding guard), tryFoldAsDouble (range folding sentinel)
  • stdlib: std.mod and std.modulo builtins
  • Update go_test_suite golden file for percent_mod_int5

Result

42 % 0 now reports "Division by zero." matching go-jsonnet, instead of silently producing NaN.

Test plan

  • All 143 existing test suites pass
  • Updated go_test_suite/percent_mod_int5.jsonnet.golden
  • Added new_test_suite/error.modulo_by_zero.jsonnet (constant path)
  • Added new_test_suite/error.modulo_by_zero_runtime.jsonnet (runtime path)
  • Formatting clean

Motivation:
The modulo operator (%) did not check for zero divisor, producing NaN
instead of an error. This was inconsistent with go-jsonnet which reports
"Division by zero." and also inconsistent with sjsonnet's own division
operator (/) which already had the check in every evaluation path.

Modification:
Add zero-divisor guard for % in all evaluation paths:
- Evaluator: tryInlineArith, evalBinaryOpNumNum, visitBinaryOpAsDouble,
  visitBinaryOp (polymorphic OP_% case)
- StaticOptimizer: tryFoldBinaryOp (constant folding guard),
  tryFoldAsDouble (range folding sentinel)
- stdlib: std.mod and std.modulo builtins
- Update go_test_suite golden file for percent_mod_int5

Result:
`42 % 0` now reports "Division by zero." matching go-jsonnet,
instead of silently producing NaN.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant