Add `label $name | EXP`; fix `break`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is to fix the problem where `break` is dynamic, not lexical. With this it should be possible to do this sort of thing: label $break | inputs | if ... then $break|error else . end This is a backwards-incompatible change for master, but the previous `break` hadn't shipped yet. Still needed: - testing
authored by Nicolas Williams · committed by Nicolas Williams · parent cbfc0d6 · Browse files · 11 files·+225 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+225 added−33 removed
- tests:+22 added−2 removed
- other:+203 added−31 removed
Provenance
- Commit
7dc34b9- Tree
12c5b48- Author
Nicolas Williams <nico@cryptonector.com>- Committer
Nicolas Williams <nico@cryptonector.com>- Parent
cbfc0d6
11 files changed+225 added−33 removed
modified:docs/content/3.manual/manual.yml+58 added-4 removed
1738 unmodified lines1739 - program: 'try error("some exception") catch .'1740 input: 'true'1741 output: ['"some exception"']1742 1743+ - title: Breaking out of control structures1744+ body: |1745+1746+ A convenient use of try/catch is to break out of control1747+ structures like `reduce`, `foreach`, `while`, and so on.1748+1749+ For example:1750+1751+ # Repeat an expression until it raises "break" as an1752+ # error, then stop repeating without re-raising the error.1753+ # But if the error caught is not "break" then re-raise it.1754+ try repeat(exp) catch .=="break" then empty else error;1755+1756+ jq has a syntax for lexical labels to "break" or "go (back) to":1757+1758+ label | ... break ...1759+1760+ The `break` builtin will cause the program to return to act as1761+ though the nearest `label` (to the left) produced `empty`.1762+1763+ The `break2` builtin will return the program to the second1764+ nearest `label`, then `empty`.1765+1766+ The `break3` builtin will return the program to the third1767+ nearest `label`, then `empty`.1768+1769+ A variation on this is named labels:1770+1771+ label $name | ... break $name1772+1773+ The `break $name` form returns to the named label and produces1774+ `empty`.1775+1776+ In all cases the relationship between the `break` and1777+ corresponding `label` is lexical: the label has to be1778+ "visible" from the break.1779+1780+ To break out of a `reduce`, for example:1781+1782+ label | reduce .[] as $item (null; if .==false then break else ... end)1783+1784+ The following jq program produces a syntax error:1785+1786+ break1787+1788+ because:1789+1790+ jq: error: break used outside labeled control structure1791+1792 - title: "`?` operator"1793 body: |1794 1795 The `?` operator, used as `EXP?`, is shorthand for `try EXP`.423 unmodified lines2219 for each new state to extract an output of `foreach`.2220 2221 This is mostly useful only for constructing `reduce`- and2222 `limit`-like functions. But it is much more general, as it2174- allows for partial reductions (see the example below), as well2175- as breaking out of the "loop" with `break`.2223+ allows for partial reductions (see the example below).2224 2225 examples:2226 - program: '[foreach .[] as $item2227 ([[],[]];18 unmodified lines2246 2247 def recurse(f): def r: ., (f | select(. != null) | r); r;2248 2249 def while(cond; update):2202- def w: if cond then ., (update | _while) else empty end;2203- try _while catch if . == "break" then empty else . end;2250+ def _while:2251+ if cond then ., (update | _while) else empty end;2252+ _while;2253 2254+ def repeat(exp):2255+ def _repeat:2256+ exp, _repeat;2257+ _repeat;2258+2259 - title: Generators and iterators2260 body: |2261 2262 Some jq operators and functions are actually generators in303 unmodified linesmodified:tests/all.test+22 added-2 removed
245 unmodified lines246 [while(.<100; .*2)]247 1248 [1,2,4,8,16,32,64]249 250-[while(.<100; .*2|if . > 10 then break else . end)]250+[label | while(.<100; .*2|if . > 10 then break else . end)]251 1252 [1,2,4,8]253 254+[(label $here | .[] | if .>1 then break $here else . end), "hi!"]255+[0,1,2]256+[0,1,"hi!"]257+258+[(label $here | .[] | if .>1 then break $here else . end), "hi!"]259+[0,2,1]260+[0,"hi!"]261+262+(label | (label | 2 | break2)), 1263+null264+1265+266+%%FAIL267+break268+jq: error: break used outside labeled control structure269+270+%%FAIL271+. as $foo | break $foo272+jq: error: *label-foo/0 is not defined273+274 [.[]|[.,1]|until(.[0] < 1; [.[0] - 1, .[1] * .[0]])|.[1]]275 [1,2,3,4,5]276 [1,2,6,24,120]277 258-[foreach .[] as $item ([3, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1])]278+[label | foreach .[] as $item ([3, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1])]279 [11,22,33,44,55,66,77,88,99]280 [11,22,33]281 282 [foreach range(5) as $item (0; $item)]844 unmodified linesmodified:builtin.c+8 added-9 removed
987 unmodified lines988 #define LIBM_DD(name) "def " #name ": _" #name ";",989 990 static const char* const jq_builtins[] = {991 "def error: error(.);",992- "def break: error(\"break\");",992 "def map(f): [.[] | f];",993 "def map_values(f): .[] |= f;",994 "def select(f): if f then . else empty end;",995 "def sort_by(f): _sort_by_impl(map([f]));",26 unmodified lines1022 "def rindex($i): indices($i) | .[-1:][0];", // TODO: optimize1023 "def paths: path(recurse(if (type|. == \"array\" or . == \"object\") then .[] else empty end))|select(length > 0);",1024 "def paths(node_filter): . as $dot|paths|select(. as $p|$dot|getpath($p)|node_filter);",1025 "def any(generator; condition):"1027- " [foreach generator as $i"1026+ " [label | foreach generator as $i"1027 " (false;"1028 " if . then break elif $i | condition then true else . end;"1029 " if . then . else empty end)] | length == 1;",1030 "def any(condition): any(.[]; condition);",1031 "def any: any(.);",1032 "def all(generator; condition): "1034- " [foreach generator as $i"1033+ " [label | foreach generator as $i"1034 " (true;"1035 " if .|not then break elif $i | condition then . else false end;"1036 " if .|not then . else empty end)] | length == 0;",1037 "def all(condition): all(.[]; condition);",93 unmodified lines1131 // generic iterator/generator1132 "def while(cond; update): "1133 " def _while: "1134 " if cond then ., (update | _while) else empty end; "1136- " try _while catch if .==\"break\" then empty else . end;",1135+ " _while;",1136 "def until(cond; next): "1137 " def _until: "1138 " if cond then . else (next|_until) end;"1139 " _until;",1141- "def limit($n; exp): if $n < 0 then exp else foreach exp as $item ([$n, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1]) end;",1142- "def first(g): foreach g as $item ([false, null]; if .[0]==true then break else [true, $item] end; .[1]);",1140+ "def limit($n; exp): if $n < 0 then exp else label | foreach exp as $item ([$n, null]; if .[0] < 1 then break else [.[0] -1, $item] end; .[1]) end;",1141+ "def first(g): label | foreach g as $item ([false, null]; if .[0]==true then break else [true, $item] end; .[1]);",1142 "def last(g): reduce g as $item (null; $item);",1143 "def nth($n; g): if $n < 0 then error(\"nth doesn't support negative indices\") else last(limit($n + 1; g)) end;",1144 "def first: .[0];",1145 "def last: .[-1];",9 unmodified lines1155 " ([]; . + [reduce range(0;$length) as $i ([]; . + [ $in[$i][$j] ] )] )"1156 " end;",1157 "def in(xs): . as $x | xs | has($x);",1158 "def inside(xs): . as $x | xs | contains($x);",1160- "def input: try _input catch if .==\"break\" then empty else . end;",1159+ "def input: _input;",1160 "def repeat(exp): "1161 " def _repeat: "1162 " exp, _repeat;"1164- " try _repeat catch if .==\"break\" then empty else . end;",1165- "def inputs: repeat(_input);",1163+ " _repeat;",1164+ "def inputs: try repeat(_input) catch if .==\"break\" then empty else .|error end;",1165 // # like ruby's downcase - only characters A to Z are affected1166 "def ascii_downcase:"1167 " explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;",1168 // # like ruby's upcase - only characters a to z are affected78 unmodified linesmodified:bytecode.h+3 added
23 unmodified lines24 OP_HAS_CFUNC = 32,25 OP_HAS_UFUNC = 64,26 OP_IS_CALL_PSEUDO = 128,27 OP_HAS_BINDING = 1024,28+ // NOTE: Not actually part of any op -- a pseudo-op flag for special29+ // handling of `break`.30+ OP_BIND_WILDCARD = 2048,31 };32 struct opcode_description {33 opcode op;34 const char* name;58 unmodified linesmodified:compile.c+76 added-17 removed
239 unmodified lines240 }241 242 int block_has_only_binders(block binders, int bindflags) {243 bindflags |= OP_HAS_BINDING;244+ bindflags &= ~OP_BIND_WILDCARD;245 for (inst* curr = binders.first; curr; curr = curr->next) {246 if ((opcode_describe(curr->op)->flags & bindflags) != bindflags && curr->op != MODULEMETA) {247 return 0;248 }42 unmodified lines291 }292 return nrefs;293 }294 294-static int block_bind_subblock(block binder, block body, int bindflags) {295+static int block_bind_subblock(block binder, block body, int bindflags, int break_distance) {296 assert(block_is_single(binder));296- assert((opcode_describe(binder.first->op)->flags & bindflags) == bindflags);297+ assert((opcode_describe(binder.first->op)->flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD));298 assert(binder.first->symbol);299 assert(binder.first->bound_by == 0 || binder.first->bound_by == binder.first);300+ assert(break_distance >= 0);301 302 binder.first->bound_by = binder.first;303 if (binder.first->nformals == -1)304 binder.first->nformals = block_count_formals(binder);305 int nrefs = 0;306 for (inst* i = body.first; i; i = i->next) {307 int flags = opcode_describe(i->op)->flags;306- if ((flags & bindflags) == bindflags &&307- i->bound_by == 0 &&308- !strcmp(i->symbol, binder.first->symbol)) {308+ if ((flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD) && i->bound_by == 0 &&309+ (!strcmp(i->symbol, binder.first->symbol) ||310+ // Check for break/break2/break3; see parser.y311+ ((bindflags & OP_BIND_WILDCARD) && i->symbol[0] == '*' &&312+ break_distance <= 3 && (i->symbol[1] == '1' + break_distance) &&313+ i->symbol[2] == '\0'))) {314+ if (bindflags & OP_BIND_WILDCARD) {315+ jv_mem_free(i->symbol);316+ i->symbol = strdup(binder.first->symbol);317+ }318 // bind this instruction319 if (i->op == CALL_JQ && i->nactuals == -1)320 i->nactuals = block_count_actuals(i->arglist);321 if (i->nactuals == -1 || i->nactuals == binder.first->nformals) {322 i->bound_by = binder.first;323 nrefs++;324 }325+ } else if ((flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD) && i->bound_by != 0 &&326+ !strncmp(binder.first->symbol, "*anonlabel", sizeof("*anonlabel") - 1) &&327+ !strncmp(i->symbol, "*anonlabel", sizeof("*anonlabel") - 1)) {328+ // Increment the break distance required for this binder to match329+ // a break whenever we come across a STOREV of *anonlabel...330+ break_distance++;331 }332 // binding recurses into closures318- nrefs += block_bind_subblock(binder, i->subfn, bindflags);333+ nrefs += block_bind_subblock(binder, i->subfn, bindflags, break_distance);334 // binding recurses into argument list320- nrefs += block_bind_subblock(binder, i->arglist, bindflags);335+ nrefs += block_bind_subblock(binder, i->arglist, bindflags, break_distance);336 }337 return nrefs;338 }339 1 unmodified line341 assert(block_has_only_binders(binder, bindflags));342 bindflags |= OP_HAS_BINDING;343 int nrefs = 0;344 for (inst* curr = binder.first; curr; curr = curr->next) {330- nrefs += block_bind_subblock(inst_block(curr), body, bindflags);345+ nrefs += block_bind_subblock(inst_block(curr), body, bindflags, 0);346 }347 return nrefs;348 }349 18 unmodified lines368 char* tname = malloc(strlen(curr->symbol)+matchlen+1);369 strcpy(tname, matchname);370 strcpy(tname+matchlen,cname);371 curr->symbol = tname;357- nrefs += block_bind_subblock(inst_block(curr), body, bindflags);372+ nrefs += block_bind_subblock(inst_block(curr), body, bindflags, 0);373 curr->symbol = cname;374 free(tname);375 }376 free(matchname);120 unmodified lines497 if (i->op == CLOSURE_PARAM_REGULAR) {498 i->op = CLOSURE_PARAM;499 body = gen_var_binding(gen_call(i->symbol, gen_noop()), i->symbol, body);500 }486- block_bind_subblock(inst_block(i), body, OP_IS_CALL_PSEUDO | OP_HAS_BINDING);501+ block_bind_subblock(inst_block(i), body, OP_IS_CALL_PSEUDO | OP_HAS_BINDING, 0);502 }503 i->subfn = body;504 i->symbol = strdup(name);505 i->arglist = formals;506 block b = inst_block(i);492- block_bind_subblock(b, b, OP_IS_CALL_PSEUDO | OP_HAS_BINDING);507+ block_bind_subblock(b, b, OP_IS_CALL_PSEUDO | OP_HAS_BINDING, 0);508 return b;509 }510 511 block gen_param_regular(const char* name) {209 unmodified lines721 // will be on top of the stack, and we don't722 // want to output it, so we backtrack.723 gen_op_simple(BACKTRACK));724 inst_set_target(output, foreach); // make that JUMP go bast the BACKTRACK at the end of the loop710- block handler = gen_cond(gen_call("_equal", BLOCK(gen_lambda(gen_const(jv_string("break"))), gen_lambda(gen_noop()))),711- gen_op_simple(BACKTRACK),712- gen_call("error", gen_noop()));713- return gen_try(foreach, handler);725+ return foreach;726 }727 728 block gen_definedor(block a, block b) {729 // var found := false71 unmodified lines801 block_bind(gen_op_unbound(STOREV, name),802 body, OP_HAS_VARIABLE));803 }804 805+// Like gen_var_binding(), but bind `break`'s wildcard unbound variable806+static block gen_wildvar_binding(block var, const char* name, block body) {807+ return BLOCK(gen_op_simple(DUP), var,808+ block_bind(gen_op_unbound(STOREV, name),809+ body, OP_HAS_VARIABLE | OP_BIND_WILDCARD));810+}811+812 block gen_cond(block cond, block iftrue, block iffalse) {813 return BLOCK(gen_op_simple(DUP), cond, 814 gen_condbranch(BLOCK(gen_op_simple(POP), iftrue),815 BLOCK(gen_op_simple(POP), iffalse)));816 }817 818+block gen_try_handler(block handler) {819+ // Quite a pain just to hide jq's internal errors.820+ return gen_cond(// `if type=="object" and .__jq821+ gen_and(gen_call("_equal",822+ BLOCK(gen_lambda(gen_const(jv_string("object"))),823+ gen_lambda(gen_noop()))),824+ BLOCK(gen_subexp(gen_const(jv_string("__jq"))),825+ gen_noop(),826+ gen_op_simple(INDEX))),827+ // `then error`828+ gen_call("error", gen_noop()),829+ // `else HANDLER end`830+ handler);831+}832+833 block gen_try(block exp, block handler) {834 /*801- * Produce:835+ * Produce something like:836 * FORK_OPT <address of handler>837 * <exp>838 * JUMP <end of handler>839 * <handler>840 *841+ * If this is not an internal try/catch, then catch and re-raise842+ * internal errors to prevent them from leaking.843+ *844 * The handler will only execute if we backtrack to the FORK_OPT with845 * an error (exception). If <exp> produces no value then FORK_OPT846 * will backtrack (propagate the `empty`, as it were. If <exp>847 * produces a value then we'll execute whatever bytecode follows this5 unmodified lines853 exp = BLOCK(exp, gen_op_target(JUMP, handler));854 return BLOCK(gen_op_target(FORK_OPT, exp), exp, handler);855 }856 857+block gen_label(const char *label, block exp) {858+ block cond = gen_call("_equal",859+ BLOCK(gen_lambda(gen_noop()),860+ gen_lambda(gen_op_unbound(LOADV, label))));861+ return gen_wildvar_binding(gen_op_simple(GENLABEL), label,862+ BLOCK(gen_op_simple(POP),863+ // try exp catch if . == $label864+ // then empty865+ // else error end866+ //867+ // Can't use gen_binop(), as that's firmly868+ // stuck in parser.y as it refers to things869+ // like EQ.870+ gen_try(exp,871+ gen_cond(cond,872+ gen_op_simple(BACKTRACK),873+ gen_call("error", gen_noop())))));874+}875+876 block gen_cbinding(const struct cfunction* cfunctions, int ncfunctions, block code) {877 for (int cfunc=0; cfunc<ncfunctions; cfunc++) {878 inst* i = inst_new(CLOSURE_CREATE_C);879 i->imm.cfunc = &cfunctions[cfunc];30 unmodified lines910 block ret = gen_noop();911 for (inst* curr; (curr = block_take(b));) {912 if (opcode_describe(curr->op)->flags & OP_HAS_BINDING) {913 if (!curr->bound_by) {914+ if (curr->symbol[0] == '*' && curr->symbol[1] >= '1' && curr->symbol[1] <= '3' && curr->symbol[2] == '\0')915+ locfile_locate(curr->locfile, curr->source, "jq: error: break used outside labeled control structure");916+ else858- locfile_locate(curr->locfile, curr->source, "jq: error: %s/%d is not defined", curr->symbol, block_count_actuals(curr->arglist));917+ locfile_locate(curr->locfile, curr->source, "jq: error: %s/%d is not defined", curr->symbol, block_count_actuals(curr->arglist));918 errors++;919 // don't process this instruction if it's not well-defined920 ret = BLOCK(ret, inst_block(curr));921 continue;216 unmodified linesmodified:compile.h+2 added
48 unmodified lines49 50 block gen_var_binding(block var, const char* name, block body);51 52 block gen_cond(block cond, block iftrue, block iffalse);53+block gen_try_handler(block handler);54 block gen_try(block exp, block handler);55+block gen_label(const char *label, block exp);56 57 block gen_cbinding(const struct cfunction* functions, int nfunctions, block b);58 59 void block_append(block* b, block b2);37 unmodified linesmodified:execute.c+7 added
35 unmodified lines36 jv path;37 int subexp_nest;38 int debug_trace_enabled;39 int initial_execution;40+ unsigned next_label;41 42 jv attrs;43 jq_input_cb input_cb;44 void *input_cb_data;306 unmodified lines351 stack_push(jq, v);352 break;353 }354 355+ case GENLABEL: {356+ stack_push(jq, JV_OBJECT(jv_string("__jq"), jv_number(jq->next_label++)));357+ break;358+ }359+360 case DUP: {361 jv v = stack_pop(jq);362 stack_push(jq, jv_copy(v));363 stack_push(jq, v);479 unmodified lines843 if (jq == NULL)844 return NULL;845 846 jq->bc = 0;847+ jq->next_label = 0;848 849 stack_init(&jq->stk);850 jq->stk_top = 0;851 jq->fork_top = 0;223 unmodified linesmodified:lexer.l+4 added
55 unmodified lines56 "foreach" { return FOREACH; }57 "//" { return DEFINEDOR; }58 "try" { return TRY; }59 "catch" { return CATCH; }60+"label" { return LABEL; }61+"break" { return BREAK; }62+"break2" { return BREAK2; }63+"break3" { return BREAK3; }64 "|=" { return SETPIPE; }65 "+=" { return SETPLUS; }66 "-=" { return SETMINUS; }67 "*=" { return SETMULT; }117 unmodified linesmodified:main.c+1 added
349 unmodified lines350 if (isoption(argv[i], 'e', "exit-status", &short_opts)) {351 options |= EXIT_STATUS;352 if (!short_opts) continue;353 }354+ // FIXME: For --arg* we should check that the varname is acceptable355 if (isoption(argv[i], 0, "arg", &short_opts)) {356 if (i >= argc - 2) {357 fprintf(stderr, "%s: --arg takes two parameters (e.g. -a varname value)\n", progname);358 die();268 unmodified linesmodified:opcode_list.h+1 added
38 unmodified lines39 OP(TOP, NONE, 0, 0)40 OP(CLOSURE_PARAM_REGULAR, DEFINITION, 0, 0)41 OP(DEPS, CONSTANT, 0, 0)42 OP(MODULEMETA, CONSTANT, 0, 0)43+OP(GENLABEL, NONE, 0, 1)modified:parser.y+43 added-1 removed
68 unmodified lines69 %token AND "and"70 %token OR "or"71 %token TRY "try"72 %token CATCH "catch"73+%token LABEL "label"74+%token BREAK "break"75+%token BREAK2 "break2"76+%token BREAK3 "break3"77 %token SETPIPE "|="78 %token SETPLUS "+="79 %token SETMINUS "-="80 %token SETMULT "*="71 unmodified lines152 }153 return tok;154 }155 156+static unsigned int next_label = 0;157+158 static block gen_dictpair(block k, block v) {159 return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));160 }161 178 unmodified lines340 } |341 342 "try" Exp "catch" Exp {343 //$$ = BLOCK(gen_op_target(FORK_OPT, $2), $2, $4);338- $$ = gen_try($2, $4);344+ $$ = gen_try($2, gen_try_handler($4));345 } |346 "try" Exp {347 //$$ = BLOCK(gen_op_target(FORK_OPT, $2), $2, gen_op_simple(BACKTRACK));348 $$ = gen_try($2, gen_op_simple(BACKTRACK));2 unmodified lines351 FAIL(@$, "Possibly unterminated 'try' statement");352 $$ = $2;353 } |354 355+"label" '|' Exp {356+ jv v = jv_string_fmt("*anonlabel%u", next_label++);357+ $$ = gen_location(@$, locations, gen_label(jv_string_value(v), $3));358+ jv_free(v);359+} |360+361+"label" '$' IDENT '|' Exp {362+ jv v = jv_string_fmt("*label-%s", jv_string_value($3));363+ $$ = gen_location(@$, locations, gen_label(jv_string_value(v), $5));364+ jv_free($3);365+ jv_free(v);366+} |367+368 // This rule conflicts with all the other rules using the '?' operator.369 // It doesn't matter which bison prefers: all of them result in the same370 // syntax and semantics, but the more specific rules optimize better371 // because they use opcodes specifically made for the purpose. We216 unmodified lines588 } |589 REC {590 $$ = gen_call("recurse", gen_noop());591 } |592+BREAK {593+ $$ = gen_location(@$, locations,594+ BLOCK(gen_op_unbound(LOADV, "*1"), // impossible symbol595+ gen_call("error", gen_noop())));596+} |597+BREAK2 {598+ $$ = gen_location(@$, locations,599+ BLOCK(gen_op_unbound(LOADV, "*2"), // impossible symbol600+ gen_call("error", gen_noop())));601+} |602+BREAK3 {603+ $$ = gen_location(@$, locations,604+ BLOCK(gen_op_unbound(LOADV, "*3"), // impossible symbol605+ gen_call("error", gen_noop())));606+} |607+BREAK '$' IDENT {608+ jv v = jv_string_fmt("*label-%s", jv_string_value($3)); // impossible symbol609+ $$ = gen_location(@$, locations,610+ BLOCK(gen_op_unbound(LOADV, jv_string_value(v)),611+ gen_call("error", gen_noop())));612+ jv_free(v);613+ jv_free($3);614+} |615 Term FIELD '?' {616 $$ = gen_index_opt($1, gen_const($2));617 } |618 FIELD '?' { 180 unmodified lines