From a60140b2ebbf67629e7e5bc8bc6e15cf5bec3a06 Mon Sep 17 00:00:00 2001 From: itchyny Date: Sun, 4 Jun 2023 11:53:01 +0900 Subject: [PATCH] Fold modulo operator on constant values and raise zero remainder error quickly --- src/parser.c | 1 + src/parser.y | 1 + tests/jq.test | 4 ++++ 3 files changed, 6 insertions(+) diff --git a/src/parser.c b/src/parser.c index e7c6a4ea00..59f375f78d 100644 --- a/src/parser.c +++ b/src/parser.c @@ -498,6 +498,7 @@ 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((intmax_t)nb == 0 ? INFINITY : (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; diff --git a/src/parser.y b/src/parser.y index 7599d9f2f4..4ad00a6886 100644 --- a/src/parser.y +++ b/src/parser.y @@ -230,6 +230,7 @@ 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((intmax_t)nb == 0 ? INFINITY : (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; diff --git a/tests/jq.test b/tests/jq.test index 4e0b950d3c..fdcefcb436 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -1651,6 +1651,10 @@ try (1%.) catch . 1/0 jq: error: Division by zero? at , line 1: +%%FAIL +1%0 +jq: error: Remainder by zero? at , line 1: + # Basic numbers tests: integers, powers of two [range(-52;52;1)] as $powers | [$powers[]|pow(2;.)|log2|round] == $powers null