Fix constant folding of division and reminder with zero divisor
Previously constant folding of zero division (e.x. 1/0) produces a compile error. This was incorrectly implemented by checking if the division result is infinite, so produces wrong results compared to the query where no constant folding is processed (e.x. 1e308/0.1). This patch delays the operation when the divisor is zero. This makes the results more consistent, but changes the exit code on zero division from 3 to 5. Also 0/0 now produces the zero division error, not NaN. This patch also fixes the modulo operation. Previously constant folding logic does not take care of the % operator, but now it folds if the both dividend and divisor are safe numbers to cast to the integer type, and the divisor is not zero. This patch also fixes some code that relies on undefined cast behaviors in C. The modulo operation produces NaN if either the dividend or divisor is NaN.
This commit is contained in:
1 parent
6716e23ae6
commit
0f80921268
7 files changed
+488
-449
No files matched your search
+10
-5
@@ -230,7 +230,16 @@ static block constant_fold(block a, block b, int op) {
|
||||
case '+': res = jv_number(na + nb); break;
|
||||
case '-': res = jv_number(na - nb); break;
|
||||
case '*': res = jv_number(na * nb); break;
|
||||
case '/': res = jv_number(na / nb); break;
|
||||
case '/':
|
||||
if (nb == 0.0) return gen_noop();
|
||||
res = jv_number(na / nb);
|
||||
break;
|
||||
case '%':
|
||||
#define is_unsafe_to_int_cast(n) (isnan(n) || (n) < INTMAX_MIN || -(n) < INTMAX_MIN)
|
||||
if (is_unsafe_to_int_cast(na) || is_unsafe_to_int_cast(nb) || (intmax_t)nb == 0) return gen_noop();
|
||||
#undef is_unsafe_to_int_cast
|
||||
res = jv_number((intmax_t)na % (intmax_t)nb);
|
||||
break;
|
||||
case EQ: res = (cmp == 0 ? jv_true() : jv_false()); break;
|
||||
case NEQ: res = (cmp != 0 ? jv_true() : jv_false()); break;
|
||||
case '<': res = (cmp < 0 ? jv_true() : jv_false()); break;
|
||||
@@ -463,14 +472,10 @@ Exp "*=" Exp {
|
||||
|
||||
Exp '/' Exp {
|
||||
$$ = gen_binop($1, $3, '/');
|
||||
if (block_is_const_inf($$))
|
||||
FAIL(@$, "Division by zero?");
|
||||
} |
|
||||
|
||||
Exp '%' Exp {
|
||||
$$ = gen_binop($1, $3, '%');
|
||||
if (block_is_const_inf($$))
|
||||
FAIL(@$, "Remainder by zero?");
|
||||
} |
|
||||
|
||||
Exp "/=" Exp {
|
||||
|
||||
Reference in new issue
Block a user