Skip to content

Commit 96e8d89

Browse files
authored
fix: reduce/foreach state variable should not be reset each iteration (#3205)
When the UPDATE query in a reduce or foreach syntax does not emit a value, it should simply skip updating the state variable. But currently it resets the state variable to null.
1 parent 8619f8a commit 96e8d89

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/compile.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -832,7 +832,7 @@ block gen_reduce(block source, block matcher, block init, block body) {
832832
block loop = BLOCK(gen_op_simple(DUPN),
833833
source,
834834
bind_alternation_matchers(matcher,
835-
BLOCK(gen_op_bound(LOADVN, res_var),
835+
BLOCK(gen_op_bound(LOADV, res_var),
836836
body,
837837
gen_op_bound(STOREV, res_var))),
838838
gen_op_simple(BACKTRACK));
@@ -854,7 +854,7 @@ block gen_foreach(block source, block matcher, block init, block update, block e
854854
// in the body to see
855855
bind_alternation_matchers(matcher,
856856
// load the loop state variable
857-
BLOCK(gen_op_bound(LOADVN, state_var),
857+
BLOCK(gen_op_bound(LOADV, state_var),
858858
// generate updated state
859859
update,
860860
// save the updated state for value extraction

tests/jq.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,10 @@ null
322322
[{"a":1}, {"b":2}, {"a":3, "b":4}]
323323
[-1, -1, -4]
324324

325+
[foreach range(5) as $x (0; .+$x | select($x!=2); [$x,.])]
326+
null
327+
[[0,0],[1,1],[3,4],[4,8]]
328+
325329
[limit(3; .[])]
326330
[11,22,33,44,55,66,77,88,99]
327331
[11,22,33]
@@ -825,6 +829,10 @@ reduce . as $n (.; .)
825829
null
826830
null
827831

832+
reduce range(5) as $x (0; .+$x | select($x!=2))
833+
null
834+
8
835+
828836
# Destructuring
829837
. as {$a, b: [$c, {$d}]} | [$a, $c, $d]
830838
{"a":1, "b":[2,{"d":3}]}

0 commit comments

Comments
 (0)