compile.c
This file
Path
src/compile.c
1,404 lines · 43.7 KiB · C
Last changed by
Fix assertion failure on too many parameters in a nested function (#3663)itchynybefore adoptiona5323a3
History of this fileTake it
1#include <assert.h>2#include <string.h>3#include <stdlib.h>4#include <unistd.h>5#include "compile.h"6#include "bytecode.h"7#include "locfile.h"8#include "jv_alloc.h"9#include "util.h"1011/*12 The intermediate representation for jq filters is as a sequence of13 struct inst, which form a doubly-linked list via the next and prev14 pointers.1516 A "block" represents a sequence of "struct inst", which may be17 empty.1819 Blocks are generated by the parser bottom-up, so may have free20 variables (refer to things not defined). See inst.bound_by and21 inst.symbol.22 */23struct inst {24 struct inst* next;25 struct inst* prev;2627 opcode op;2829 struct {30 uint16_t intval;31 struct inst* target;32 jv constant;33 const struct cfunction* cfunc;34 } imm;3536 struct locfile* locfile;37 location source;3839 // Binding40 // An instruction requiring binding (for parameters/variables/functions)41 // is in one of three states:42 // inst->bound_by = NULL - Unbound free variable43 // inst->bound_by = inst - This instruction binds a variable44 // inst->bound_by = other - Uses variable bound by other instruction45 // Unbound instructions (references to other things that may or may not46 // exist) are created by "gen_foo_unbound", and bindings are created by47 // block_bind(definition, body), which binds all instructions in48 // body which are unbound and refer to "definition" by name.49 struct inst* bound_by;50 char* symbol;51 int any_unbound;52 int referenced;5354 int nformals;55 int nactuals;5657 block subfn; // used by CLOSURE_CREATE (body of function)58 block arglist; // used by CLOSURE_CREATE (formals) and CALL_JQ (arguments)5960 // This instruction is compiled as part of which function?61 // (only used during block_compile)62 struct bytecode* compiled;6364 int bytecode_pos; // position just after this insn65};6667static inst* inst_new(opcode op) {68 inst* i = jv_mem_alloc(sizeof(inst));69 i->next = i->prev = 0;70 i->op = op;71 i->bytecode_pos = -1;72 i->bound_by = 0;73 i->symbol = 0;74 i->any_unbound = 0;75 i->referenced = 0;76 i->nformals = -1;77 i->nactuals = -1;78 i->subfn = gen_noop();79 i->arglist = gen_noop();80 i->source = UNKNOWN_LOCATION;81 i->locfile = 0;82 return i;83}8485static void inst_free(struct inst* i) {86 jv_mem_free(i->symbol);87 block_free(i->subfn);88 block_free(i->arglist);89 if (i->locfile)90 locfile_free(i->locfile);91 if (opcode_describe(i->op)->flags & OP_HAS_CONSTANT) {92 jv_free(i->imm.constant);93 }94 jv_mem_free(i);95}9697static block inst_block(inst* i) {98 block b = {i,i};99 return b;100}101102int block_is_single(block b) {103 return b.first && b.first == b.last;104}105106static inst* block_take(block* b) {107 if (b->first == 0) return 0;108 inst* i = b->first;109 if (i->next) {110 i->next->prev = 0;111 b->first = i->next;112 i->next = 0;113 } else {114 b->first = 0;115 b->last = 0;116 }117 return i;118}119120block gen_location(location loc, struct locfile* l, block b) {121 for (inst* i = b.first; i; i = i->next) {122 if (i->source.start == UNKNOWN_LOCATION.start &&123 i->source.end == UNKNOWN_LOCATION.end) {124 i->source = loc;125 i->locfile = locfile_retain(l);126 }127 }128 return b;129}130131block gen_noop(void) {132 block b = {0,0};133 return b;134}135136int block_is_noop(block b) {137 return (b.first == 0 && b.last == 0);138}139140block gen_op_simple(opcode op) {141 assert(opcode_describe(op)->length == 1);142 return inst_block(inst_new(op));143}144145146block gen_error(jv constant) {147 assert(opcode_describe(ERRORK)->flags & OP_HAS_CONSTANT);148 inst *i = inst_new(ERRORK);149 i->imm.constant = constant;150 return inst_block(i);151}152153block gen_const(jv constant) {154 assert(opcode_describe(LOADK)->flags & OP_HAS_CONSTANT);155 inst* i = inst_new(LOADK);156 i->imm.constant = constant;157 return inst_block(i);158}159160block gen_const_global(jv constant, const char *name) {161 assert((opcode_describe(STORE_GLOBAL)->flags & (OP_HAS_CONSTANT | OP_HAS_VARIABLE | OP_HAS_BINDING)) ==162 (OP_HAS_CONSTANT | OP_HAS_VARIABLE | OP_HAS_BINDING));163 inst* i = inst_new(STORE_GLOBAL);164 i->imm.constant = constant;165 i->symbol = strdup(name);166 i->any_unbound = 0;167 return inst_block(i);168}169170block gen_op_pushk_under(jv constant) {171 assert(opcode_describe(PUSHK_UNDER)->flags & OP_HAS_CONSTANT);172 inst* i = inst_new(PUSHK_UNDER);173 i->imm.constant = constant;174 return inst_block(i);175}176177int block_is_const(block b) {178 return (block_is_single(b) && (b.first->op == LOADK || b.first->op == PUSHK_UNDER));179}180181jv_kind block_const_kind(block b) {182 assert(block_is_const(b));183 return jv_get_kind(b.first->imm.constant);184}185186jv block_const(block b) {187 assert(block_is_const(b));188 return jv_copy(b.first->imm.constant);189}190191block gen_op_target(opcode op, block target) {192 assert(opcode_describe(op)->flags & OP_HAS_BRANCH);193 assert(target.last);194 inst* i = inst_new(op);195 i->imm.target = target.last;196 return inst_block(i);197}198199block gen_op_targetlater(opcode op) {200 assert(opcode_describe(op)->flags & OP_HAS_BRANCH);201 inst* i = inst_new(op);202 i->imm.target = 0;203 return inst_block(i);204}205void inst_set_target(block b, block target) {206 assert(block_is_single(b));207 assert(opcode_describe(b.first->op)->flags & OP_HAS_BRANCH);208 assert(target.last);209 b.first->imm.target = target.last;210}211212block gen_op_unbound(opcode op, const char* name) {213 assert(opcode_describe(op)->flags & OP_HAS_BINDING);214 inst* i = inst_new(op);215 i->symbol = strdup(name);216 i->any_unbound = 1;217 return inst_block(i);218}219220block gen_op_var_fresh(opcode op, const char* name) {221 assert(opcode_describe(op)->flags & OP_HAS_VARIABLE);222 block b = gen_op_unbound(op, name);223 b.first->bound_by = b.first;224 return b;225}226227block gen_op_bound(opcode op, block binder) {228 assert(block_is_single(binder));229 block b = gen_op_unbound(op, binder.first->symbol);230 b.first->bound_by = binder.first;231 b.first->any_unbound = 0;232 return b;233}234235block gen_dictpair(block k, block v) {236 return BLOCK(gen_subexp(k), gen_subexp(v), gen_op_simple(INSERT));237}238239240static void inst_join(inst* a, inst* b) {241 assert(a && b);242 assert(!a->next);243 assert(!b->prev);244 a->next = b;245 b->prev = a;246}247248void block_append(block* b, block b2) {249 if (b2.first) {250 if (b->last) {251 inst_join(b->last, b2.first);252 } else {253 b->first = b2.first;254 }255 b->last = b2.last;256 }257}258259block block_join(block a, block b) {260 block c = a;261 block_append(&c, b);262 return c;263}264265int block_has_only_binders_and_imports(block binders, int bindflags) {266 bindflags |= OP_HAS_BINDING;267 for (inst* curr = binders.first; curr; curr = curr->next) {268 if ((opcode_describe(curr->op)->flags & bindflags) != bindflags && curr->op != DEPS && curr->op != MODULEMETA) {269 return 0;270 }271 }272 return 1;273}274275static int inst_is_binder(inst *i, int bindflags) {276 return !((opcode_describe(i->op)->flags & bindflags) != bindflags && i->op != MODULEMETA);277}278279int block_has_only_binders(block binders, int bindflags) {280 bindflags |= OP_HAS_BINDING;281 bindflags &= ~OP_BIND_WILDCARD;282 for (inst* curr = binders.first; curr; curr = curr->next) {283 if ((opcode_describe(curr->op)->flags & bindflags) != bindflags && curr->op != MODULEMETA) {284 return 0;285 }286 }287 return 1;288}289290// Count a call site's actual params291static int block_count_actuals(block b) {292 int args = 0;293 for (inst* i = b.first; i; i = i->next) {294 switch (i->op) {295 default: assert(0 && "Unknown function type"); break;296 case CLOSURE_CREATE:297 case CLOSURE_PARAM:298 case CLOSURE_CREATE_C:299 args++;300 break;301 }302 }303 return args;304}305306static int block_bind_subblock_inner(int* any_unbound, block binder, block body, int bindflags, int break_distance) {307 assert(block_is_single(binder));308 assert((opcode_describe(binder.first->op)->flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD));309 assert(binder.first->symbol);310 assert(binder.first->bound_by == 0 || binder.first->bound_by == binder.first);311 assert(break_distance >= 0);312313 binder.first->bound_by = binder.first;314 int nrefs = 0;315 for (inst* i = body.first; i; i = i->next) {316 if (i->any_unbound == 0)317 continue;318319 int flags = opcode_describe(i->op)->flags;320 if ((flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD) && i->bound_by == 0 &&321 (!strcmp(i->symbol, binder.first->symbol) ||322 // Check for break/break2/break3; see parser.y323 ((bindflags & OP_BIND_WILDCARD) && i->symbol[0] == '*' &&324 break_distance <= 3 && (i->symbol[1] == '1' + break_distance) &&325 i->symbol[2] == '\0'))) {326 // bind this instruction327 if (i->nactuals == -1 || i->nactuals == binder.first->nformals) {328 i->bound_by = binder.first;329 nrefs++;330 }331 } else if ((flags & bindflags) == (bindflags & ~OP_BIND_WILDCARD) && i->bound_by != 0 &&332 !strncmp(binder.first->symbol, "*anonlabel", sizeof("*anonlabel") - 1) &&333 !strncmp(i->symbol, "*anonlabel", sizeof("*anonlabel") - 1)) {334 // Increment the break distance required for this binder to match335 // a break whenever we come across a STOREV of *anonlabel...336 break_distance++;337 }338339 i->any_unbound = (i->symbol && !i->bound_by);340341 // binding recurses into closures342 nrefs += block_bind_subblock_inner(&i->any_unbound, binder, i->subfn, bindflags, break_distance);343 // binding recurses into argument list344 nrefs += block_bind_subblock_inner(&i->any_unbound, binder, i->arglist, bindflags, break_distance);345346 if (i->any_unbound)347 *any_unbound = 1;348 }349 return nrefs;350}351352static int block_bind_subblock(block binder, block body, int bindflags, int break_distance) {353 int any_unbound;354 return block_bind_subblock_inner(&any_unbound, binder, body, bindflags, break_distance);355}356357static int block_bind_each(block binder, block body, int bindflags) {358 assert(block_has_only_binders(binder, bindflags));359 bindflags |= OP_HAS_BINDING;360 int nrefs = 0;361 for (inst* curr = binder.first; curr; curr = curr->next) {362 nrefs += block_bind_subblock(inst_block(curr), body, bindflags, 0);363 }364 return nrefs;365}366367static block block_bind(block binder, block body, int bindflags) {368 block_bind_each(binder, body, bindflags);369 return block_join(binder, body);370}371372block block_bind_library(block binder, block body, int bindflags, const char *libname) {373 bindflags |= OP_HAS_BINDING;374 int matchlen = (libname == NULL) ? 0 : strlen(libname);375 char *matchname = jv_mem_alloc(matchlen+2+1);376 matchname[0] = '\0';377 if (libname != NULL && libname[0] != '\0') {378 strcpy(matchname,libname);379 strcpy(matchname+matchlen, "::");380 matchlen += 2;381 }382 assert(block_has_only_binders(binder, bindflags));383 for (inst *curr = binder.last; curr; curr = curr->prev) {384 int bindflags2 = bindflags;385 char* cname = curr->symbol;386 char* tname = jv_mem_alloc(strlen(curr->symbol)+matchlen+1);387 strcpy(tname, matchname);388 strcpy(tname+matchlen, curr->symbol);389390 // Ew391 if ((opcode_describe(curr->op)->flags & (OP_HAS_VARIABLE | OP_HAS_CONSTANT)))392 bindflags2 = OP_HAS_VARIABLE | OP_HAS_BINDING;393394 // This mutation is ugly, even if we undo it395 curr->symbol = tname;396 block_bind_subblock(inst_block(curr), body, bindflags2, 0);397 curr->symbol = cname;398 free(tname);399 }400 free(matchname);401 return body; // We don't return a join because we don't want those sticking around...402}403404static inst* block_take_last(block* b) {405 inst* i = b->last;406 if (i == 0)407 return 0;408 if (i->prev) {409 i->prev->next = i->next;410 b->last = i->prev;411 i->prev = 0;412 } else {413 b->first = 0;414 b->last = 0;415 }416 return i;417}418419// Binds a sequence of binders, which *must not* already be bound to each other,420// to body, throwing away unreferenced defs421block block_bind_referenced(block binder, block body, int bindflags) {422 assert(block_has_only_binders(binder, bindflags));423 bindflags |= OP_HAS_BINDING;424425 inst* curr;426 while ((curr = block_take_last(&binder))) {427 block b = inst_block(curr);428 if (block_bind_subblock(b, body, bindflags, 0) == 0) {429 block_free(b);430 } else {431 body = BLOCK(b, body);432 }433 }434 return body;435}436437block block_bind_self(block binder, int bindflags) {438 assert(block_has_only_binders(binder, bindflags));439 bindflags |= OP_HAS_BINDING;440 block body = gen_noop();441442 inst* curr;443 while ((curr = block_take_last(&binder))) {444 block b = inst_block(curr);445 block_bind_subblock(b, body, bindflags, 0);446 body = BLOCK(b, body);447 }448 return body;449}450451static void block_mark_referenced(block body) {452 int saw_top = 0;453 for (inst* i = body.last; i; i = i->prev) {454 if (saw_top && i->bound_by == i && !i->referenced)455 continue;456 if (i->op == TOP) {457 saw_top = 1;458 }459 if (i->bound_by) {460 i->bound_by->referenced = 1;461 }462463 block_mark_referenced(i->arglist);464 block_mark_referenced(i->subfn);465 }466}467468block block_drop_unreferenced(block body) {469 block_mark_referenced(body);470471 block refd = gen_noop();472 inst* curr;473 while ((curr = block_take(&body))) {474 if (curr->bound_by == curr && !curr->referenced) {475 inst_free(curr);476 } else {477 refd = BLOCK(refd, inst_block(curr));478 }479 }480 return refd;481}482483jv block_take_imports(block* body) {484 jv imports = jv_array();485486 /* Parser should never generate TOP before imports */487 assert(!(body->first && body->first->op == TOP && body->first->next &&488 (body->first->next->op == MODULEMETA || body->first->next->op == DEPS)));489490 while (body->first && (body->first->op == MODULEMETA || body->first->op == DEPS)) {491 inst* dep = block_take(body);492 if (dep->op == DEPS) {493 imports = jv_array_append(imports, jv_copy(dep->imm.constant));494 }495 inst_free(dep);496 }497 return imports;498}499500jv block_list_funcs(block body, int omit_underscores) {501 jv funcs = jv_object(); // Use the keys for set semantics.502 for (inst *pos = body.first; pos != NULL; pos = pos->next) {503 if (pos->op == CLOSURE_CREATE || pos->op == CLOSURE_CREATE_C) {504 if (pos->symbol != NULL && (!omit_underscores || pos->symbol[0] != '_')) {505 funcs = jv_object_set(funcs, jv_string_fmt("%s/%i", pos->symbol, pos->nformals), jv_null());506 }507 }508 }509 return jv_keys_unsorted(funcs);510}511512block gen_module(block metadata) {513 assert(block_is_const(metadata) && block_const_kind(metadata) == JV_KIND_OBJECT);514 inst* i = inst_new(MODULEMETA);515 i->imm.constant = block_const(metadata);516 if (jv_get_kind(i->imm.constant) != JV_KIND_OBJECT)517 i->imm.constant = jv_object_set(jv_object(), jv_string("metadata"), i->imm.constant);518 block_free(metadata);519 return inst_block(i);520}521522jv block_module_meta(block b) {523 if (b.first != NULL && b.first->op == MODULEMETA)524 return jv_copy(b.first->imm.constant);525 return jv_null();526}527528block gen_import(jv name, jv as, int is_data) {529 assert(jv_get_kind(name) == JV_KIND_STRING);530 assert(!jv_is_valid(as) || jv_get_kind(as) == JV_KIND_STRING);531 inst* i = inst_new(DEPS);532 jv meta = jv_object();533 if (jv_is_valid(as))534 meta = jv_object_set(meta, jv_string("as"), as);535 else536 jv_free(as);537 meta = jv_object_set(meta, jv_string("is_data"), is_data ? jv_true() : jv_false());538 meta = jv_object_set(meta, jv_string("relpath"), name);539 i->imm.constant = meta;540 return inst_block(i);541}542543block gen_import_meta(block import, block metadata) {544 assert(block_is_single(import) && import.first->op == DEPS);545 assert(block_is_const(metadata) && block_const_kind(metadata) == JV_KIND_OBJECT);546 inst *i = import.first;547 i->imm.constant = jv_object_merge(block_const(metadata), i->imm.constant);548 block_free(metadata);549 return import;550}551552block gen_function(const char* name, block formals, block body) {553 inst* i = inst_new(CLOSURE_CREATE);554 int nformals = 0;555 for (inst* i = formals.last; i; i = i->prev) {556 nformals++;557 i->nformals = 0;558 if (i->op == CLOSURE_PARAM_REGULAR) {559 i->op = CLOSURE_PARAM;560 body = gen_var_binding(gen_call(i->symbol, gen_noop()), i->symbol, body);561 }562 block_bind_subblock(inst_block(i), body, OP_IS_CALL_PSEUDO | OP_HAS_BINDING, 0);563 }564 i->subfn = body;565 i->symbol = strdup(name);566 i->any_unbound = -1;567 i->nformals = nformals;568 i->arglist = formals;569 block b = inst_block(i);570 block_bind_subblock(b, b, OP_IS_CALL_PSEUDO | OP_HAS_BINDING, 0);571 return b;572}573574block gen_param_regular(const char* name) {575 return gen_op_unbound(CLOSURE_PARAM_REGULAR, name);576}577578block gen_param(const char* name) {579 return gen_op_unbound(CLOSURE_PARAM, name);580}581582block gen_lambda(block body) {583 return gen_function("@lambda", gen_noop(), body);584}585586block gen_call(const char* name, block args) {587 block b = gen_op_unbound(CALL_JQ, name);588 b.first->arglist = args;589 b.first->nactuals = block_count_actuals(b.first->arglist);590 return b;591}592593block gen_subexp(block a) {594 if (block_is_noop(a)) {595 return gen_op_simple(DUP);596 }597 if (block_is_single(a) && a.first->op == LOADK) {598 jv c = block_const(a);599 block_free(a);600 return gen_op_pushk_under(c);601 }602 return BLOCK(gen_op_simple(SUBEXP_BEGIN), a, gen_op_simple(SUBEXP_END));603}604605block gen_both(block a, block b) {606 block jump = gen_op_targetlater(JUMP);607 block fork = gen_op_target(FORK, jump);608 block c = BLOCK(fork, a, jump, b);609 inst_set_target(jump, c);610 return c;611}612613block gen_const_object(block expr) {614 int is_const = 1;615 jv o = jv_object();616 jv k = jv_null();617 jv v = jv_null();618 for (inst *i = expr.first; i; i = i->next) {619 if (i->op == PUSHK_UNDER) {620 k = jv_copy(i->imm.constant);621 i = i->next;622 } else if (i->op != SUBEXP_BEGIN ||623 i->next == NULL ||624 i->next->op != LOADK ||625 i->next->next == NULL ||626 i->next->next->op != SUBEXP_END) {627 is_const = 0;628 break;629 } else {630 k = jv_copy(i->next->imm.constant);631 i = i->next->next->next;632 }633 if (i != NULL && i->op == PUSHK_UNDER) {634 v = jv_copy(i->imm.constant);635 i = i->next;636 } else if (i == NULL ||637 i->op != SUBEXP_BEGIN ||638 i->next == NULL ||639 i->next->op != LOADK ||640 i->next->next == NULL ||641 i->next->next->op != SUBEXP_END) {642 is_const = 0;643 break;644 } else {645 v = jv_copy(i->next->imm.constant);646 i = i->next->next->next;647 }648 if (i == NULL || i->op != INSERT) {649 is_const = 0;650 break;651 }652 if (jv_get_kind(k) != JV_KIND_STRING) {653 is_const = 0;654 break;655 }656 o = jv_object_set(o, k, v);657 k = jv_null();658 v = jv_null();659 }660 if (!is_const) {661 jv_free(o);662 jv_free(k);663 jv_free(v);664 block b = {0,0};665 return b;666 }667 block_free(expr);668 return gen_const(o);669}670671static block gen_const_array(block expr) {672 /*673 * An expr of all constant elements looks like this:674 *675 * 0009 FORK 0027676 * 0011 FORK 0023677 * 0013 FORK 0019678 * 0015 LOADK 1679 * 0017 JUMP 0021680 * 0019 LOADK 2681 * 0021 JUMP 0025682 * 0023 LOADK 3683 * 0025 JUMP 0029684 * 0027 LOADK 4685 *686 * That's: N-1 commas for N elements, N LOADKs, and a JUMP between687 * every LOADK. The sequence ends in a LOADK. Any deviation and it's688 * not a list of constants.689 *690 * Here we check for this pattern almost exactly. We don't check that691 * the targets of the FORK and JUMP instructions are in the right692 * sequence.693 */694 int all_const = 1;695 int commas = 0;696 int normal = 1;697 jv a = jv_array();698 for (inst *i = expr.first; i; i = i->next) {699 if (i->op == FORK) {700 commas++;701 if (i->imm.target == NULL || i->imm.target->op != JUMP ||702 jv_array_length(jv_copy(a)) > 0) {703 normal = 0;704 break;705 }706 } else if (all_const && i->op == LOADK) {707 if (i->next != NULL && i->next->op != JUMP) {708 normal = 0;709 break;710 }711 a = jv_array_append(a, jv_copy(i->imm.constant));712 } else if (i->op != JUMP || i->imm.target == NULL ||713 i->imm.target->op != LOADK) {714 all_const = 0;715 }716 }717718 if (all_const && normal &&719 (expr.last == NULL || expr.last->op == LOADK) &&720 jv_array_length(jv_copy(a)) == commas + 1) {721 block_free(expr);722 return gen_const(a);723 }724725 jv_free(a);726 block b = {0,0};727 return b;728}729730block gen_collect(block expr) {731 block const_array = gen_const_array(expr);732 if (const_array.first != NULL)733 return const_array;734735 block array_var = gen_op_var_fresh(STOREV, "collect");736 block c = BLOCK(gen_op_simple(DUP), gen_const(jv_array()), array_var);737738 block tail = BLOCK(gen_op_bound(APPEND, array_var),739 gen_op_simple(BACKTRACK));740741 return BLOCK(c,742 gen_op_target(FORK, tail),743 expr,744 tail,745 gen_op_bound(LOADVN, array_var));746}747748static block bind_matcher(block matcher, block body) {749 // cannot call block_bind(matcher, body) because that requires750 // block_has_only_binders(matcher), which is not true here as matchers751 // may also contain code to extract the correct elements752 for (inst* i = matcher.first; i; i = i->next) {753 if ((i->op == STOREV || i->op == STOREVN) && !i->bound_by)754 block_bind_subblock(inst_block(i), body, OP_HAS_VARIABLE, 0);755 }756 return BLOCK(matcher, body);757}758759760// Extract destructuring var names from the block761// *vars should be a jv_object (for set semantics)762static void block_get_unbound_vars(block b, jv *vars) {763 assert(vars != NULL);764 assert(jv_get_kind(*vars) == JV_KIND_OBJECT);765 for (inst* i = b.first; i; i = i->next) {766 if (i->subfn.first) {767 block_get_unbound_vars(i->subfn, vars);768 continue;769 }770 if ((i->op == STOREV || i->op == STOREVN) && i->bound_by == NULL) {771 *vars = jv_object_set(*vars, jv_string(i->symbol), jv_true());772 }773 }774}775776/* Build wrappers around destructuring matchers so that we can chain them777 * when we have errors. The approach is as follows:778 * DESTRUCTURE_ALT NEXT_MATCHER (unless last matcher)779 * existing_matcher_block780 * JUMP BODY781 */782static block bind_alternation_matchers(block matchers, block body) {783 block preamble = {0};784 block altmatchers = {0};785 block mb = {0};786 block final_matcher = matchers;787788 // Pass through the matchers to find all destructured names.789 while (final_matcher.first && final_matcher.first->op == DESTRUCTURE_ALT) {790 block_append(&altmatchers, inst_block(block_take(&final_matcher)));791 }792793 // We don't have any alternations here, so we can use the simplest case.794 if (altmatchers.first == NULL) {795 return bind_matcher(final_matcher, body);796 }797798 // Collect var names799 jv all_vars = jv_object();800 block_get_unbound_vars(altmatchers, &all_vars);801 block_get_unbound_vars(final_matcher, &all_vars);802803 // We need a preamble of STOREVs to which to bind the matchers and the body.804 jv_object_keys_foreach(all_vars, key) {805 preamble = BLOCK(preamble,806 gen_op_simple(DUP),807 gen_const(jv_null()),808 gen_op_unbound(STOREV, jv_string_value(key)));809 jv_free(key);810 }811 jv_free(all_vars);812813 // Now we build each matcher in turn814 for (inst *i = altmatchers.first; i; i = i->next) {815 block submatcher = i->subfn;816817 // If we're successful, jump to the end of the matchers818 submatcher = BLOCK(submatcher, gen_op_target(JUMP, final_matcher));819820 // DESTRUCTURE_ALT to the end of this submatcher so we can skip to the next one on error821 mb = BLOCK(mb, gen_op_target(DESTRUCTURE_ALT, submatcher), submatcher);822823 // We're done with this inst and we don't want it anymore824 // But we can't let it free the submatcher block.825 i->subfn.first = i->subfn.last = NULL;826 }827 // We're done with these insts now.828 block_free(altmatchers);829830 return bind_matcher(preamble, BLOCK(mb, final_matcher, body));831}832833block gen_reduce(block source, block matcher, block init, block body) {834 block res_var = gen_op_var_fresh(STOREV, "reduce");835 block loop = BLOCK(source,836 bind_alternation_matchers(matcher,837 BLOCK(gen_op_bound(LOADVN, res_var),838 body,839 gen_op_bound(STOREV, res_var))),840 gen_op_simple(BACKTRACK));841 return BLOCK(gen_op_simple(DUP),842 init,843 res_var,844 gen_op_simple(DUP),845 gen_op_target(FORK, loop),846 loop,847 gen_op_simple(POP),848 gen_op_bound(LOADVN, res_var));849}850851block gen_foreach(block source, block matcher, block init, block update, block extract) {852 block state_var = gen_op_var_fresh(STOREV, "foreach");853 return BLOCK(gen_op_simple(DUP),854 init,855 state_var,856 gen_op_simple(DUP),857 // get a value from the source expression:858 source,859 // destructure the value into variable(s) for all the code860 // in the body to see861 bind_alternation_matchers(matcher,862 // load the loop state variable863 BLOCK(gen_op_bound(LOADVN, state_var),864 // generate updated state865 update,866 // save the updated state for value extraction867 gen_op_simple(DUP),868 // save new state869 gen_op_bound(STOREV, state_var),870 // extract an output...871 extract)));872}873874block gen_definedor(block a, block b) {875 // var found := false876 block found_var = gen_op_var_fresh(STOREV, "found");877 block init = BLOCK(gen_op_simple(DUP), gen_const(jv_false()), found_var);878879 // if found, backtrack. Otherwise execute b880 block backtrack = gen_op_simple(BACKTRACK);881 block tail = BLOCK(gen_op_simple(DUP),882 gen_op_bound(LOADV, found_var),883 gen_op_target(JUMP_F, backtrack),884 backtrack,885 gen_op_simple(POP),886 b);887888 // try again889 block if_notfound = gen_op_simple(BACKTRACK);890891 // found := true, produce result892 block if_found = BLOCK(gen_op_simple(DUP),893 gen_const(jv_true()),894 gen_op_bound(STOREV, found_var),895 gen_op_target(JUMP, tail));896897 return BLOCK(init,898 gen_op_target(FORK, if_notfound),899 a,900 gen_op_target(JUMP_F, if_found),901 if_found,902 if_notfound,903 tail);904}905906int block_has_main(block top) {907 for (inst *c = top.first; c; c = c->next) {908 if (c->op == TOP)909 return 1;910 }911 return 0;912}913914int block_is_funcdef(block b) {915 if (b.first != NULL && b.first->op == CLOSURE_CREATE)916 return 1;917 return 0;918}919920block gen_condbranch(block iftrue, block iffalse) {921 iftrue = BLOCK(iftrue, gen_op_target(JUMP, iffalse));922 return BLOCK(gen_op_target(JUMP_F, iftrue), iftrue, iffalse);923}924925block gen_and(block a, block b) {926 // a and b = if a then (if b then true else false) else false927 return BLOCK(gen_op_simple(DUP), a,928 gen_condbranch(BLOCK(gen_op_simple(POP),929 b,930 gen_condbranch(gen_const(jv_true()),931 gen_const(jv_false()))),932 BLOCK(gen_op_simple(POP), gen_const(jv_false()))));933}934935block gen_or(block a, block b) {936 // a or b = if a then true else (if b then true else false)937 return BLOCK(gen_op_simple(DUP), a,938 gen_condbranch(BLOCK(gen_op_simple(POP), gen_const(jv_true())),939 BLOCK(gen_op_simple(POP),940 b,941 gen_condbranch(gen_const(jv_true()),942 gen_const(jv_false())))));943}944945block gen_destructure_alt(block matcher) {946 for (inst *i = matcher.first; i; i = i->next) {947 if (i->op == STOREV) {948 i->op = STOREVN;949 }950 }951 inst* i = inst_new(DESTRUCTURE_ALT);952 i->subfn = matcher;953 return inst_block(i);954}955956block gen_var_binding(block var, const char* name, block body) {957 return gen_destructure(var, gen_op_unbound(STOREV, name), body);958}959960block gen_array_matcher(block left, block curr) {961 int index;962 if (block_is_noop(left))963 index = 0;964 else {965 // `left` was returned by this function, so the third inst is the966 // constant containing the previously used index967 assert(left.first->op == DUP);968 assert(left.first->next != NULL);969 inst *i = NULL;970 if (left.first->next->op == PUSHK_UNDER) {971 i = left.first->next;972 } else {973 assert(left.first->next->op == SUBEXP_BEGIN);974 assert(left.first->next->next->op == LOADK);975 i = left.first->next->next;976 }977 index = 1 + (int) jv_number_value(i->imm.constant);978 }979980 // `left` goes at the end so that the const index is in a predictable place981 return BLOCK(gen_op_simple(DUP), gen_subexp(gen_const(jv_number(index))),982 gen_op_simple(INDEX), curr, left);983}984985block gen_object_matcher(block name, block curr) {986 return BLOCK(gen_op_simple(DUP), gen_subexp(name), gen_op_simple(INDEX),987 curr);988}989990block gen_destructure(block var, block matchers, block body) {991 // var bindings can be added after coding the program; leave the TOP first.992 block top = gen_noop();993 if (body.first && body.first->op == TOP)994 top = inst_block(block_take(&body));995996 if (matchers.first && matchers.first->op == DESTRUCTURE_ALT) {997 block_append(&var, gen_op_simple(DUP));998 } else {999 top = BLOCK(top, gen_op_simple(DUP));1000 }10011002 return BLOCK(top, gen_subexp(var), gen_op_simple(POP), bind_alternation_matchers(matchers, body));1003}10041005// Like gen_var_binding(), but bind `break`'s wildcard unbound variable1006static block gen_wildvar_binding(block var, const char* name, block body) {1007 return BLOCK(gen_op_simple(DUP), var,1008 block_bind(gen_op_unbound(STOREV, name),1009 body, OP_HAS_VARIABLE | OP_BIND_WILDCARD));1010}10111012block gen_cond(block cond, block iftrue, block iffalse) {1013 return BLOCK(gen_op_simple(DUP), BLOCK(gen_subexp(cond), gen_op_simple(POP)),1014 gen_condbranch(BLOCK(gen_op_simple(POP), iftrue),1015 BLOCK(gen_op_simple(POP), iffalse)));1016}10171018block gen_try(block exp, block handler) {1019 /*1020 * Produce:1021 *1022 * TRY_BEGIN handler1023 * <exp>1024 * TRY_END1025 * JUMP past_handler1026 * handler: <handler>1027 * past_handler:1028 *1029 * If <exp> backtracks then TRY_BEGIN will backtrack.1030 *1031 * If <exp> produces a value then we'll execute whatever bytecode follows1032 * this sequence. If that code raises an exception, then TRY_END will wrap1033 * and re-raise that exception, and TRY_BEGIN will unwrap and re-raise the1034 * exception (see jq_next()).1035 *1036 * If <exp> raises then the TRY_BEGIN will see a non-wrapped exception and1037 * will jump to the handler (note the TRY_END will not execute in this case),1038 * and if the handler produces any values, then we'll execute whatever1039 * bytecode follows this sequence. Note that TRY_END will not execute in1040 * this case, so if the handler raises an exception, or code past the handler1041 * raises an exception, then that exception won't be wrapped and re-raised,1042 * and the TRY_BEGIN will not catch it because it does not stack_save() when1043 * it branches to the handler.1044 */10451046 if (block_is_noop(handler))1047 handler = BLOCK(gen_op_simple(DUP), gen_op_simple(POP));10481049 block jump = gen_op_target(JUMP, handler);1050 return BLOCK(gen_op_target(TRY_BEGIN, jump), exp, gen_op_simple(TRY_END),1051 jump, handler);1052}10531054block gen_label(const char *label, block exp) {1055 block cond = gen_call("_equal",1056 BLOCK(gen_lambda(gen_noop()),1057 gen_lambda(gen_op_unbound(LOADV, label))));1058 return gen_wildvar_binding(gen_op_simple(GENLABEL), label,1059 BLOCK(gen_op_simple(POP),1060 // try exp catch if . == $label1061 // then empty1062 // else error end1063 //1064 // Can't use gen_binop(), as that's firmly1065 // stuck in parser.y as it refers to things1066 // like EQ.1067 gen_try(exp,1068 gen_cond(cond,1069 gen_op_simple(BACKTRACK),1070 gen_call("error", gen_noop())))));1071}10721073block gen_cbinding(const struct cfunction* cfunctions, int ncfunctions, block code) {1074 for (int cfunc=0; cfunc<ncfunctions; cfunc++) {1075 inst* i = inst_new(CLOSURE_CREATE_C);1076 i->imm.cfunc = &cfunctions[cfunc];1077 i->symbol = strdup(cfunctions[cfunc].name);1078 i->nformals = cfunctions[cfunc].nargs - 1;1079 i->any_unbound = 0;1080 code = BLOCK(inst_block(i), code);1081 }1082 return code;1083}10841085static uint16_t nesting_level(struct bytecode* bc, inst* target) {1086 uint16_t level = 0;1087 assert(bc && target && target->compiled);1088 while (bc && target->compiled != bc) {1089 level++;1090 bc = bc->parent;1091 }1092 assert(bc && bc == target->compiled);1093 return level;1094}10951096static int count_cfunctions(block b) {1097 int n = 0;1098 for (inst* i = b.first; i; i = i->next) {1099 if (i->op == CLOSURE_CREATE_C) n++;1100 n += count_cfunctions(i->subfn);1101 }1102 return n;1103}11041105#ifndef WIN321106extern char **environ;1107#endif11081109static jv1110make_env(jv env)1111{1112 if (jv_is_valid(env))1113 return jv_copy(env);1114 jv r = jv_object();1115 if (environ == NULL)1116 return r;1117 for (size_t i = 0; environ[i] != NULL; i++) {1118 const char *eq;11191120 if ((eq = strchr(environ[i], '=')) == NULL)1121 r = jv_object_delete(r, jv_string(environ[i]));1122 else1123 r = jv_object_set(r, jv_string_sized(environ[i], eq - environ[i]), jv_string(eq + 1));1124 }1125 return jv_copy(r);1126}11271128// Expands call instructions into a calling sequence1129static int expand_call_arglist(block* b, jv args, jv *env) {1130 int errors = 0;1131 block ret = gen_noop();1132 for (inst* curr; (curr = block_take(b));) {1133 if (opcode_describe(curr->op)->flags & OP_HAS_BINDING) {1134 if (!curr->bound_by && curr->op == LOADV && strcmp(curr->symbol, "ENV") == 0) {1135 curr->op = LOADK;1136 *env = curr->imm.constant = make_env(*env);1137 } else if (!curr->bound_by && curr->op == LOADV && jv_object_has(jv_copy(args), jv_string(curr->symbol))) {1138 curr->op = LOADK;1139 curr->imm.constant = jv_object_get(jv_copy(args), jv_string(curr->symbol));1140 } else if (!curr->bound_by) {1141 if (curr->symbol[0] == '*' && curr->symbol[1] >= '1' && curr->symbol[1] <= '3' && curr->symbol[2] == '\0')1142 locfile_locate(curr->locfile, curr->source, "jq: error: break used outside labeled control structure");1143 else if (curr->op == LOADV)1144 locfile_locate(curr->locfile, curr->source, "jq: error: $%s is not defined", curr->symbol);1145 else1146 locfile_locate(curr->locfile, curr->source, "jq: error: %s/%d is not defined", curr->symbol, curr->nactuals);1147 errors++;1148 // don't process this instruction if it's not well-defined1149 ret = BLOCK(ret, inst_block(curr));1150 continue;1151 }1152 }11531154 block prelude = gen_noop();1155 if (curr->op == CALL_JQ) {1156 int actual_args = 0, desired_args = 0;1157 // We expand the argument list as a series of instructions1158 switch (curr->bound_by->op) {1159 default: assert(0 && "Unknown function type"); break;1160 case CLOSURE_CREATE:1161 case CLOSURE_PARAM: {1162 block callargs = gen_noop();1163 for (inst* i; (i = block_take(&curr->arglist));) {1164 assert(opcode_describe(i->op)->flags & OP_IS_CALL_PSEUDO);1165 block b = inst_block(i);1166 switch (i->op) {1167 default: assert(0 && "Unknown type of parameter"); break;1168 case CLOSURE_REF:1169 block_append(&callargs, b);1170 break;1171 case CLOSURE_CREATE:1172 block_append(&prelude, b);1173 block_append(&callargs, gen_op_bound(CLOSURE_REF, b));1174 break;1175 }1176 actual_args++;1177 }1178 curr->imm.intval = actual_args;1179 curr->arglist = callargs;11801181 if (curr->bound_by->op == CLOSURE_CREATE) {1182 for (inst* i = curr->bound_by->arglist.first; i; i = i->next) {1183 assert(i->op == CLOSURE_PARAM);1184 desired_args++;1185 }1186 }1187 break;1188 }11891190 case CLOSURE_CREATE_C: {1191 for (inst* i; (i = block_take(&curr->arglist)); ) {1192 assert(i->op == CLOSURE_CREATE); // FIXME1193 block body = i->subfn;1194 i->subfn = gen_noop();1195 inst_free(i);1196 // arguments should be pushed in reverse order, prepend them to prelude1197 errors += expand_call_arglist(&body, args, env);1198 prelude = BLOCK(gen_subexp(body), prelude);1199 actual_args++;1200 }1201 assert(curr->op == CALL_JQ);1202 curr->op = CALL_BUILTIN;1203 curr->imm.intval = actual_args + 1 /* include the implicit input in arg count */;1204 assert(curr->bound_by->op == CLOSURE_CREATE_C);1205 desired_args = curr->bound_by->imm.cfunc->nargs - 1;1206 assert(!curr->arglist.first);1207 break;1208 }1209 }12101211 assert(actual_args == desired_args); // because now handle this above1212 }1213 ret = BLOCK(ret, prelude, inst_block(curr));1214 }1215 *b = ret;1216 return errors;1217}12181219static int compile(struct bytecode* bc, block b, struct locfile* lf, jv args, jv *env) {1220 int errors = 0;1221 int pos = 0;1222 int var_frame_idx = 0;1223 bc->nsubfunctions = 0;1224 errors += expand_call_arglist(&b, args, env);1225 b = BLOCK(b, gen_op_simple(RET));1226 jv localnames = jv_array();1227 for (inst* curr = b.first; curr; curr = curr->next) {1228 if (!curr->next) assert(curr == b.last);1229 int length = opcode_describe(curr->op)->length;1230 if (curr->op == CALL_JQ) {1231 for (inst* arg = curr->arglist.first; arg; arg = arg->next) {1232 length += 2;1233 }1234 }1235 pos += length;1236 curr->bytecode_pos = pos;1237 curr->compiled = bc;12381239 assert(curr->op != CLOSURE_REF && curr->op != CLOSURE_PARAM);12401241 if ((opcode_describe(curr->op)->flags & OP_HAS_VARIABLE) &&1242 curr->bound_by == curr) {1243 curr->imm.intval = var_frame_idx++;1244 localnames = jv_array_append(localnames, jv_string(curr->symbol));1245 }12461247 if (curr->op == CLOSURE_CREATE) {1248 assert(curr->bound_by == curr);1249 // Prevent subfunction index from overflowing into ARG_NEWCLOSURE flag1250 if (bc->nsubfunctions >= ARG_NEWCLOSURE) {1251 locfile_locate(lf, curr->source,1252 "too many function parameters or local function definitions (max %d)", ARG_NEWCLOSURE - 1);1253 errors++;1254 break;1255 }1256 curr->imm.intval = bc->nsubfunctions++;1257 }1258 if (curr->op == CLOSURE_CREATE_C) {1259 assert(curr->bound_by == curr);1260 int idx = bc->globals->ncfunctions++;1261 bc->globals->cfunc_names = jv_array_append(bc->globals->cfunc_names,1262 jv_string(curr->symbol));1263 bc->globals->cfunctions[idx] = *curr->imm.cfunc;1264 curr->imm.intval = idx;1265 }1266 }1267 if (pos > 0xFFFF) {1268 // too long for program counter to fit in uint16_t1269 locfile_locate(lf, UNKNOWN_LOCATION,1270 "function compiled to %d bytes which is too long", pos);1271 errors++;1272 }1273 bc->codelen = pos;1274 bc->debuginfo = jv_object_set(bc->debuginfo, jv_string("locals"), localnames);1275 if (bc->nsubfunctions && !errors) {1276 bc->subfunctions = jv_mem_calloc(bc->nsubfunctions, sizeof(struct bytecode*));1277 for (inst* curr = b.first; curr; curr = curr->next) {1278 if (curr->op == CLOSURE_CREATE) {1279 struct bytecode* subfn = jv_mem_alloc(sizeof(struct bytecode));1280 bc->subfunctions[curr->imm.intval] = subfn;1281 subfn->globals = bc->globals;1282 subfn->parent = bc;1283 subfn->nclosures = 0;1284 subfn->debuginfo = jv_object_set(jv_object(), jv_string("name"), jv_string(curr->symbol));1285 jv params = jv_array();1286 for (inst* param = curr->arglist.first; param; param = param->next) {1287 assert(param->op == CLOSURE_PARAM);1288 assert(param->bound_by == param);1289 // Prevent closure index from overflowing into ARG_NEWCLOSURE flag1290 if (subfn->nclosures >= ARG_NEWCLOSURE) {1291 locfile_locate(lf, curr->source,1292 "function has too many parameters (max %d)", ARG_NEWCLOSURE - 1);1293 errors++;1294 break;1295 }1296 param->imm.intval = subfn->nclosures++;1297 param->compiled = subfn;1298 params = jv_array_append(params, jv_string(param->symbol));1299 }1300 subfn->debuginfo = jv_object_set(subfn->debuginfo, jv_string("params"), params);1301 errors += compile(subfn, curr->subfn, lf, args, env);1302 curr->subfn = gen_noop();1303 }1304 }1305 } else {1306 bc->nsubfunctions = 0;1307 bc->subfunctions = 0;1308 }1309 if (errors) {1310 bc->code = 0;1311 bc->constants = jv_invalid();1312 block_free(b);1313 return errors;1314 }1315 uint16_t* code = jv_mem_calloc(bc->codelen, sizeof(uint16_t));1316 bc->code = code;1317 pos = 0;1318 jv constant_pool = jv_array();1319 int maxvar = -1;1320 for (inst* curr = b.first; curr; curr = curr->next) {1321 const struct opcode_description* op = opcode_describe(curr->op);1322 if (op->length == 0)1323 continue;1324 code[pos++] = curr->op;1325 assert(curr->op != CLOSURE_REF && curr->op != CLOSURE_PARAM);1326 if (curr->op == CALL_BUILTIN) {1327 assert(curr->bound_by->op == CLOSURE_CREATE_C);1328 assert(!curr->arglist.first);1329 code[pos++] = (uint16_t)curr->imm.intval;1330 code[pos++] = curr->bound_by->imm.intval;1331 } else if (curr->op == CALL_JQ) {1332 assert(curr->bound_by->op == CLOSURE_CREATE ||1333 curr->bound_by->op == CLOSURE_PARAM);1334 code[pos++] = (uint16_t)curr->imm.intval;1335 code[pos++] = nesting_level(bc, curr->bound_by);1336 code[pos++] = curr->bound_by->imm.intval |1337 (curr->bound_by->op == CLOSURE_CREATE ? ARG_NEWCLOSURE : 0);1338 for (inst* arg = curr->arglist.first; arg; arg = arg->next) {1339 assert(arg->op == CLOSURE_REF && arg->bound_by->op == CLOSURE_CREATE);1340 code[pos++] = nesting_level(bc, arg->bound_by);1341 code[pos++] = arg->bound_by->imm.intval | ARG_NEWCLOSURE;1342 }1343 } else if ((op->flags & OP_HAS_CONSTANT) && (op->flags & OP_HAS_VARIABLE)) {1344 // STORE_GLOBAL: constant global, basically1345 code[pos++] = jv_array_length(jv_copy(constant_pool));1346 constant_pool = jv_array_append(constant_pool, jv_copy(curr->imm.constant));1347 code[pos++] = nesting_level(bc, curr->bound_by);1348 uint16_t var = (uint16_t)curr->bound_by->imm.intval;1349 code[pos++] = var;1350 if (var > maxvar) maxvar = var;1351 } else if (op->flags & OP_HAS_CONSTANT) {1352 code[pos++] = jv_array_length(jv_copy(constant_pool));1353 constant_pool = jv_array_append(constant_pool, jv_copy(curr->imm.constant));1354 } else if (op->flags & OP_HAS_VARIABLE) {1355 code[pos++] = nesting_level(bc, curr->bound_by);1356 uint16_t var = (uint16_t)curr->bound_by->imm.intval;1357 code[pos++] = var;1358 if (var > maxvar) maxvar = var;1359 } else if (op->flags & OP_HAS_BRANCH) {1360 assert(curr->imm.target->bytecode_pos != -1);1361 assert(curr->imm.target->bytecode_pos > pos); // only forward branches1362 code[pos] = curr->imm.target->bytecode_pos - (pos + 1);1363 pos++;1364 } else if (op->length > 1) {1365 assert(0 && "codegen not implemented for this operation");1366 }1367 }1368 bc->constants = constant_pool;1369 bc->nlocals = maxvar + 2; // FIXME: frames of size zero?1370 block_free(b);1371 return errors;1372}13731374int block_compile(block b, struct bytecode** out, struct locfile* lf, jv args) {1375 struct bytecode* bc = jv_mem_alloc(sizeof(struct bytecode));1376 bc->parent = 0;1377 bc->nclosures = 0;1378 bc->globals = jv_mem_alloc(sizeof(struct symbol_table));1379 int ncfunc = count_cfunctions(b);1380 bc->globals->ncfunctions = 0;1381 bc->globals->cfunctions = jv_mem_calloc(MAX(ncfunc, 1), sizeof(struct cfunction));1382 bc->globals->cfunc_names = jv_array();1383 bc->debuginfo = jv_object_set(jv_object(), jv_string("name"), jv_null());1384 jv env = jv_invalid();1385 int nerrors = compile(bc, b, lf, args, &env);1386 jv_free(args);1387 jv_free(env);1388 assert(bc->globals->ncfunctions == ncfunc);1389 if (nerrors > 0) {1390 bytecode_free(bc);1391 *out = 0;1392 } else {1393 *out = bc;1394 }1395 return nerrors;1396}13971398void block_free(block b) {1399 struct inst* next;1400 for (struct inst* curr = b.first; curr; curr = next) {1401 next = curr->next;1402 inst_free(curr);1403 }1404}