From d334411b9f23cfc4589b86c7a2e90b7de608f2aa Mon Sep 17 00:00:00 2001 From: gibkim <86421130+gibkim@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:33:36 +0900 Subject: [PATCH] Fix assignment operators copying their whole input since #3633 (#3706) Since #3633, `reduce` pushes a copy of its input before the `FORK`, and that copy stays in a slot saved by the `FORK` until the loop ends. When `init` holds `.`, as in `_assign` and `_modify`, the copy is a second reference to the accumulator, so the first `setpath` in each reduction copies the whole input. Building an object key by key with `.[$k] = $v`, `|=` or `+=` became quadratic again, the slowdown #618 reported and `DUPN` was added to fix. Store the input in a variable before the `FORK` and load it with `LOADVN` at the start of the loop instead. The slots saved by the `FORK` no longer refer to the input while the body runs, and the slot below `init` is still not popped destructively, so #3227 stays fixed. --- src/compile.c | 10 ++++++++-- tests/jq.test | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/compile.c b/src/compile.c index e1780b9a..c800ce81 100644 --- a/src/compile.c +++ b/src/compile.c @@ -832,7 +832,13 @@ static block bind_alternation_matchers(block matchers, block body) { block gen_reduce(block source, block matcher, block init, block body) { block res_var = gen_op_var_fresh(STOREV, "reduce"); - block loop = BLOCK(source, + // Keep the input in a variable rather than in a stack slot saved by the + // FORK, so that it is not referenced while `body` updates the accumulator, + // and leave the slot below `init` intact for `init` to backtrack (#3227). + block input_var = gen_op_var_fresh(STOREV, "reduce_input"); + block loop = BLOCK(gen_op_bound(LOADVN, input_var), + gen_op_simple(DUP), + source, bind_alternation_matchers(matcher, BLOCK(gen_op_bound(LOADVN, res_var), body, @@ -842,9 +848,9 @@ block gen_reduce(block source, block matcher, block init, block body) { init, res_var, gen_op_simple(DUP), + input_var, gen_op_target(FORK, loop), loop, - gen_op_simple(POP), gen_op_bound(LOADVN, res_var)); } diff --git a/tests/jq.test b/tests/jq.test index 5afb3097..06ef7f63 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -2795,6 +2795,12 @@ null 0 1 +# regression test for #3227 (reduce, non-empty source) +reduce .[] as $x (0, 10; . + $x) +[1, 2] +3 +13 + # regression test for #3227 (foreach) foreach .[] as $x (0, 1; . + $x) [1, 2]