Skip to content
Myr

Add `break` builtin for `foreach`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Nicolas Williams · committed by Nicolas Williams · parent 6458910 · Browse files · 4 files+7 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+7 added−4 removed

  • tests:+1 added−1 removed
  • other:+6 added−3 removed

4 files+7 added−4 removed

modified:docs/content/3.manual/manual.yml+1 added-2 removed
1842 unmodified lines
18431844 This is mostly useful only for constructing `reduce`- and1845 `limit`-like functions. But it is much more general, as it1846 allows for partial reductions (see the example below), as well1847 as breaking out of the "loop" with `empty`, or even `error(x)`1848 if there's a try/catch around the foreach.1847 as breaking out of the "loop" with `break`.18481849 examples:1850 - program: '[foreach .[] as $item1851 ([[],[]];
179 unmodified lines
modified:tests/all.test+1 added-1 removed
224 unmodified lines
225[while(.<100; .*2)]2261227[1,2,4,8,16,32,64]228229[foreach .[] as $item ([3, null]; if .[0] < 1 then empty else [.[0] -1, $item] end; .[1])]229[foreach .[] as $item ([3, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1])]230[11,22,33,44,55,66,77,88,99]231[11,22,33]232233[limit(3; .[])]
721 unmodified lines
modified:builtin.c+1 added
900 unmodified lines
901902#define LIBM_DD(name) "def " #name ": _" #name ";",903904static const char* const jq_builtins[] = {905 "def break: error(\"break\");",906 "def map(f): [.[] | f];",907 "def select(f): if f then . else empty end;",908 "def sort(f): _sort_by_impl(map([f]));",909 "def sort_by(f): sort(f);",
107 unmodified lines
modified:compile.c+4 added-1 removed
404 unmodified lines
405 // top of the stack, and we don't want to output406 // it, so we backtrack.407 gen_op_simple(BACKTRACK));408 inst_set_target(output, foreach);409 return foreach;409 block handler = gen_cond(gen_call("_equal", BLOCK(gen_lambda(gen_const(jv_string("break"))), gen_lambda(gen_noop()))),410 gen_op_simple(BACKTRACK),411 gen_call("break", gen_noop()));412 return gen_try(foreach, handler);413}414415block gen_definedor(block a, block b) {416 // var found := false
357 unmodified lines