Skip to content
Myr

execute.c

This file

Path

src/execute.c

1,346 lines · 35.9 KiB · C

Last changed by

Fix reduce to preserve its input across init backtracking (#3633)itchynybefore adoptiondf24981

History of this file

Take it

1#include <assert.h>2#include <errno.h>3#include <stdarg.h>4#include <stdio.h>5#include <stdlib.h>6#include <stdint.h>7#include <sys/stat.h>89#include "exec_stack.h"10#include "bytecode.h"1112#include "jv_alloc.h"13#include "locfile.h"14#include "jv.h"15#include "jq.h"16#include "builtin.h"17#include "linker.h"1819struct jq_state {20  void (*nomem_handler)(void *);21  void *nomem_handler_data;22  struct bytecode* bc;2324  jq_msg_cb err_cb;25  void *err_cb_data;26  jv error;2728  struct stack stk;29  stack_ptr curr_frame;30  stack_ptr stk_top;31  stack_ptr fork_top;3233  jv path;34  jv value_at_path;35  int subexp_nest;36  int debug_trace_enabled;37  int initial_execution;38  unsigned next_label;3940  int halted;41  jv exit_code;42  jv error_message;4344  jv attrs;45  jq_input_cb input_cb;46  void *input_cb_data;47  jq_msg_cb debug_cb;48  void *debug_cb_data;49  jq_msg_cb stderr_cb;50  void *stderr_cb_data;51};5253struct closure {54  struct bytecode* bc;  // jq bytecode55  stack_ptr env;        // jq stack address of closed frame56};5758// locals for any function called: either a closure or a local variable59union frame_entry {60  struct closure closure;61  jv localvar;62};6364// jq function call frame65struct frame {66  struct bytecode* bc;      // jq bytecode for callee67  stack_ptr env;            // jq stack address of frame to return to68  stack_ptr retdata;        // jq stack address to unwind to on RET69  uint16_t* retaddr;        // jq bytecode return address70  union frame_entry entries[]; // nclosures + nlocals71};7273static int frame_size(struct bytecode* bc) {74  return sizeof(struct frame) + sizeof(union frame_entry) * (bc->nclosures + bc->nlocals);75}7677static struct frame* frame_current(struct jq_state* jq) {78  struct frame* fp = stack_block(&jq->stk, jq->curr_frame);7980  stack_ptr next = *stack_block_next(&jq->stk, jq->curr_frame);81  if (next) {82    struct frame* fpnext = stack_block(&jq->stk, next);83    struct bytecode* bc = fpnext->bc;84    assert(fp->retaddr >= bc->code && fp->retaddr < bc->code + bc->codelen);85  } else {86    assert(fp->retaddr == 0);87  }88  return fp;89}9091static stack_ptr frame_get_level(struct jq_state* jq, int level) {92  stack_ptr fr = jq->curr_frame;93  for (int i=0; i<level; i++) {94    struct frame* fp = stack_block(&jq->stk, fr);95    fr = fp->env;96  }97  return fr;98}99100static jv* frame_local_var(struct jq_state* jq, int var, int level) {101  struct frame* fr = stack_block(&jq->stk, frame_get_level(jq, level));102  assert(var >= 0);103  assert(var < fr->bc->nlocals);104  return &fr->entries[fr->bc->nclosures + var].localvar;105}106107static struct closure make_closure(struct jq_state* jq, uint16_t* pc) {108  uint16_t level = *pc++;109  uint16_t idx = *pc++;110  stack_ptr fridx = frame_get_level(jq, level);111  struct frame* fr = stack_block(&jq->stk, fridx);112  if (idx & ARG_NEWCLOSURE) {113    // A new closure closing the frame identified by level, and with114    // the bytecode body of the idx'th subfunction of that frame115    int subfn_idx = idx & ~ARG_NEWCLOSURE;116    assert(subfn_idx < fr->bc->nsubfunctions);117    struct closure cl = {fr->bc->subfunctions[subfn_idx],118                         fridx};119    return cl;120  } else {121    // A reference to a closure from the frame identified by level; copy122    // it as-is123    int closure = idx;124    assert(closure >= 0);125    assert(closure < fr->bc->nclosures);126    return fr->entries[closure].closure;127  }128}129130static struct frame* frame_push(struct jq_state* jq, struct closure callee,131                                uint16_t* argdef, int nargs) {132  stack_ptr new_frame_idx = stack_push_block(&jq->stk, jq->curr_frame, frame_size(callee.bc));133  struct frame* new_frame = stack_block(&jq->stk, new_frame_idx);134  new_frame->bc = callee.bc;135  new_frame->env = callee.env;136  assert(nargs == new_frame->bc->nclosures);137  union frame_entry* entries = new_frame->entries;138  for (int i=0; i<nargs; i++) {139    entries->closure = make_closure(jq, argdef + i * 2);140    entries++;141  }142  for (int i=0; i<callee.bc->nlocals; i++) {143    entries->localvar = jv_invalid();144    entries++;145  }146  jq->curr_frame = new_frame_idx;147  return new_frame;148}149150static void frame_pop(struct jq_state* jq) {151  assert(jq->curr_frame);152  struct frame* fp = frame_current(jq);153  if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {154    int nlocals = fp->bc->nlocals;155    for (int i=0; i<nlocals; i++) {156      jv_free(*frame_local_var(jq, i, 0));157    }158  }159  jq->curr_frame = stack_pop_block(&jq->stk, jq->curr_frame, frame_size(fp->bc));160}161162void stack_push(jq_state *jq, jv val) {163  assert(jv_is_valid(val));164  jq->stk_top = stack_push_block(&jq->stk, jq->stk_top, sizeof(jv));165  jv* sval = stack_block(&jq->stk, jq->stk_top);166  *sval = val;167}168169jv stack_pop(jq_state *jq) {170  jv* sval = stack_block(&jq->stk, jq->stk_top);171  jv val = *sval;172  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {173    val = jv_copy(val);174  }175  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));176  assert(jv_is_valid(val));177  return val;178}179180// Like stack_pop(), but assert !stack_pop_will_free() and replace with181// jv_null() on the stack.182jv stack_popn(jq_state *jq) {183  jv* sval = stack_block(&jq->stk, jq->stk_top);184  jv val = *sval;185  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {186    *sval = jv_null();187  }188  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));189  assert(jv_is_valid(val));190  return val;191}192193194struct forkpoint {195  stack_ptr saved_data_stack;196  stack_ptr saved_curr_frame;197  int path_len, subexp_nest;198  jv value_at_path;199  uint16_t* return_address;200};201202struct stack_pos {203  stack_ptr saved_data_stack, saved_curr_frame;204};205206struct stack_pos stack_get_pos(jq_state* jq) {207  struct stack_pos sp = {jq->stk_top, jq->curr_frame};208  return sp;209}210211void stack_save(jq_state *jq, uint16_t* retaddr, struct stack_pos sp){212  jq->fork_top = stack_push_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));213  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);214  fork->saved_data_stack = jq->stk_top;215  fork->saved_curr_frame = jq->curr_frame;216  fork->path_len =217    jv_get_kind(jq->path) == JV_KIND_ARRAY ? jv_array_length(jv_copy(jq->path)) : 0;218  fork->value_at_path = jv_copy(jq->value_at_path);219  fork->subexp_nest = jq->subexp_nest;220  fork->return_address = retaddr;221  jq->stk_top = sp.saved_data_stack;222  jq->curr_frame = sp.saved_curr_frame;223}224225static int path_intact(jq_state *jq, jv curr) {226  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {227    return jv_identical(curr, jv_copy(jq->value_at_path));228  } else {229    jv_free(curr);230    return 1;231  }232}233234static void path_append(jq_state* jq, jv component, jv value_at_path) {235  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {236    int n1 = jv_array_length(jv_copy(jq->path));237    jq->path = jv_array_append(jq->path, component);238    int n2 = jv_array_length(jv_copy(jq->path));239    assert(n2 == n1 + 1);240    jv_free(jq->value_at_path);241    jq->value_at_path = value_at_path;242  } else {243    jv_free(component);244    jv_free(value_at_path);245  }246}247248/* For f_getpath() */249jv250_jq_path_append(jq_state *jq, jv v, jv p, jv value_at_path) {251  if (jq->subexp_nest != 0 ||252      jv_get_kind(jq->path) != JV_KIND_ARRAY ||253      !jv_is_valid(value_at_path)) {254    jv_free(v);255    jv_free(p);256    return value_at_path;257  }258  if (!jv_identical(v, jv_copy(jq->value_at_path))) {259    jv_free(p);260    return value_at_path;261  }262  if (jv_get_kind(p) == JV_KIND_ARRAY)263    jq->path = jv_array_concat(jq->path, p);264  else265    jq->path = jv_array_append(jq->path, p);266  jv_free(jq->value_at_path);267  return jv_copy(jq->value_at_path = value_at_path);268}269270uint16_t* stack_restore(jq_state *jq){271  while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {272    if (stack_pop_will_free(&jq->stk, jq->stk_top)) {273      jv_free(stack_pop(jq));274    } else if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {275      frame_pop(jq);276    } else {277      assert(0);278    }279  }280281  if (jq->fork_top == 0) {282    return 0;283  }284285  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);286  uint16_t* retaddr = fork->return_address;287  jq->stk_top = fork->saved_data_stack;288  jq->curr_frame = fork->saved_curr_frame;289  int path_len = fork->path_len;290  if (jv_get_kind(jq->path) == JV_KIND_ARRAY) {291    assert(path_len >= 0);292    jq->path = jv_array_slice(jq->path, 0, path_len);293  } else {294    fork->path_len = 0;295  }296  jv_free(jq->value_at_path);297  jq->value_at_path = fork->value_at_path;298  jq->subexp_nest = fork->subexp_nest;299  jq->fork_top = stack_pop_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));300  return retaddr;301}302303static void jq_reset(jq_state *jq) {304  while (stack_restore(jq)) {}305306  assert(jq->stk_top == 0);307  assert(jq->fork_top == 0);308  assert(jq->curr_frame == 0);309  stack_reset(&jq->stk);310  jv_free(jq->error);311  jq->error = jv_null();312313  jq->halted = 0;314  jv_free(jq->exit_code);315  jq->exit_code = jv_invalid();316  jv_free(jq->error_message);317  jq->error_message = jv_invalid();318  if (jv_get_kind(jq->path) != JV_KIND_INVALID)319    jv_free(jq->path);320  jq->path = jv_null();321  jv_free(jq->value_at_path);322  jq->value_at_path = jv_null();323  jq->subexp_nest = 0;324}325326void jq_report_error(jq_state *jq, jv value) {327  assert(jq->err_cb);328  // callback must jv_free() its jv argument329  jq->err_cb(jq->err_cb_data, value);330}331332static void set_error(jq_state *jq, jv value) {333  // Record so try/catch can find it.334  jv_free(jq->error);335  jq->error = value;336}337338#define ON_BACKTRACK(op) ((op)+NUM_OPCODES)339340jv jq_next(jq_state *jq) {341  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);342343  uint16_t* pc = stack_restore(jq);344  assert(pc);345346  int raising;347  int backtracking = !jq->initial_execution;348349  jq->initial_execution = 0;350  assert(jv_get_kind(jq->error) == JV_KIND_NULL);351  while (1) {352    if (jq->halted) {353      if (jq->debug_trace_enabled)354        printf("\t<halted>\n");355      return jv_invalid();356    }357    uint16_t opcode = *pc;358    raising = 0;359360    if (jq->debug_trace_enabled) {361      dump_operation(frame_current(jq)->bc, pc);362      printf("\t");363      const struct opcode_description* opdesc = opcode_describe(opcode);364      stack_ptr param = 0;365      if (!backtracking) {366        int stack_in = opdesc->stack_in;367        if (stack_in == -1) stack_in = pc[1];368        param = jq->stk_top;369        for (int i=0; i<stack_in; i++) {370          if (i != 0) {371            printf(" | ");372            param = *stack_block_next(&jq->stk, param);373          }374          if (!param) break;375          jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);376          //printf("<%d>", jv_get_refcnt(param->val));377          //printf(" -- ");378          //jv_dump(jv_copy(jq->path), 0);379        }380        if (jq->debug_trace_enabled & JQ_DEBUG_TRACE_DETAIL) {381          while ((param = *stack_block_next(&jq->stk, param))) {382            printf(" || ");383            jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);384          }385        }386      } else {387        printf("\t<backtracking>");388      }389390      printf("\n");391    }392393    if (backtracking) {394      opcode = ON_BACKTRACK(opcode);395      backtracking = 0;396      raising = !jv_is_valid(jq->error);397    }398    pc++;399400    switch (opcode) {401    default: assert(0 && "invalid instruction");402403    case TOP: break;404405    case ERRORK: {406      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);407      set_error(jq, jv_invalid_with_msg(v));408      goto do_backtrack;409    }410411    case LOADK: {412      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);413      assert(jv_is_valid(v));414      jv_free(stack_pop(jq));415      stack_push(jq, v);416      break;417    }418419    case GENLABEL: {420      stack_push(jq, JV_OBJECT(jv_string("__jq"), jv_number(jq->next_label++)));421      break;422    }423424    case DUP: {425      jv v = stack_pop(jq);426      stack_push(jq, jv_copy(v));427      stack_push(jq, v);428      break;429    }430431    case DUP2: {432      jv keep = stack_pop(jq);433      jv v = stack_pop(jq);434      stack_push(jq, jv_copy(v));435      stack_push(jq, keep);436      stack_push(jq, v);437      break;438    }439440    case SUBEXP_BEGIN: {441      jv v = stack_pop(jq);442      stack_push(jq, jv_copy(v));443      stack_push(jq, v);444      jq->subexp_nest++;445      break;446    }447448    case SUBEXP_END: {449      assert(jq->subexp_nest > 0);450      jq->subexp_nest--;451      jv a = stack_pop(jq);452      jv b = stack_pop(jq);453      stack_push(jq, a);454      stack_push(jq, b);455      break;456    }457458    case PUSHK_UNDER: {459      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);460      assert(jv_is_valid(v));461      jv v2 = stack_pop(jq);462      stack_push(jq, v);463      stack_push(jq, v2);464      break;465    }466467    case POP: {468      jv_free(stack_pop(jq));469      break;470    }471472    case APPEND: {473      jv v = stack_pop(jq);474      uint16_t level = *pc++;475      uint16_t vidx = *pc++;476      jv* var = frame_local_var(jq, vidx, level);477      assert(jv_get_kind(*var) == JV_KIND_ARRAY);478      *var = jv_array_append(*var, v);479      break;480    }481482    case INSERT: {483      jv stktop = stack_pop(jq);484      jv v = stack_pop(jq);485      jv k = stack_pop(jq);486      jv objv = stack_pop(jq);487      assert(jv_get_kind(objv) == JV_KIND_OBJECT);488      if (jv_get_kind(k) == JV_KIND_STRING) {489        stack_push(jq, jv_object_set(objv, k, v));490        stack_push(jq, stktop);491      } else {492        char errbuf[30];493        set_error(jq, jv_invalid_with_msg(jv_string_fmt(494                "Cannot use %s (%s) as object key",495                jv_kind_name(jv_get_kind(k)),496                jv_dump_string_trunc(jv_copy(k), errbuf, sizeof(errbuf)))));497        jv_free(stktop);498        jv_free(v);499        jv_free(k);500        jv_free(objv);501        goto do_backtrack;502      }503      break;504    }505506    case ON_BACKTRACK(RANGE):507    case RANGE: {508      uint16_t level = *pc++;509      uint16_t v = *pc++;510      jv* var = frame_local_var(jq, v, level);511      jv max = stack_pop(jq);512      jv step = stack_pop(jq);513      if (raising) {514        jv_free(max);515        jv_free(step);516        goto do_backtrack;517      }518519      if (jv_get_kind(*var) != JV_KIND_NUMBER || jv_get_kind(max) != JV_KIND_NUMBER ||520          jv_get_kind(step) != JV_KIND_NUMBER) {521        set_error(jq, jv_invalid_with_msg(jv_string("Range bounds and step must be numeric")));522        jv_free(max);523        jv_free(step);524        goto do_backtrack;525      } else if (jv_cmp(jv_copy(*var), jv_copy(max)) * jv_cmp(jv_copy(step), jv_number(0)) >= 0) {526        jv_free(max);527        jv_free(step);528        goto do_backtrack;529      } else {530        jv curr = *var;531        *var = jv_number(jv_number_value(curr) + jv_number_value(step));532533        struct stack_pos spos = stack_get_pos(jq);534        stack_push(jq, step);535        stack_push(jq, max);536        stack_save(jq, pc - 3, spos);537538        stack_push(jq, curr);539      }540      break;541    }542543      // FIXME: loadv/storev may do too much copying/freeing544    case LOADV: {545      uint16_t level = *pc++;546      uint16_t v = *pc++;547      jv* var = frame_local_var(jq, v, level);548      if (jq->debug_trace_enabled) {549        printf("V%d = ", v);550        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);551        printf("\n");552      }553      jv_free(stack_pop(jq));554      stack_push(jq, jv_copy(*var));555      break;556    }557558      // Does a load but replaces the variable with null559    case LOADVN: {560      uint16_t level = *pc++;561      uint16_t v = *pc++;562      jv* var = frame_local_var(jq, v, level);563      if (jq->debug_trace_enabled) {564        printf("V%d = ", v);565        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);566        printf("\n");567      }568      jv_free(stack_popn(jq));569570      // This `stack_push()` invalidates the `var` reference, so571      stack_push(jq, *var);572      // we have to re-resolve `var` before we can set it to null573      var = frame_local_var(jq, v, level);574      *var = jv_null();575      break;576    }577578    case STOREVN:579        stack_save(jq, pc - 1, stack_get_pos(jq));580        JQ_FALLTHROUGH;581    case STOREV: {582      uint16_t level = *pc++;583      uint16_t v = *pc++;584      jv* var = frame_local_var(jq, v, level);585      jv val = stack_pop(jq);586      if (jq->debug_trace_enabled) {587        printf("V%d = ", v);588        jv_dump(jv_copy(val), 0);589        printf(" (%d)\n", jv_get_refcnt(val));590      }591      jv_free(*var);592      *var = val;593      break;594    }595596    case ON_BACKTRACK(STOREVN): {597      uint16_t level = *pc++;598      uint16_t v = *pc++;599      jv* var = frame_local_var(jq, v, level);600      jv_free(*var);601      *var = jv_null();602      goto do_backtrack;603      break;604    }605606    case STORE_GLOBAL: {607      // Get the constant608      jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);609      assert(jv_is_valid(val));610611      // Store the var612      uint16_t level = *pc++;613      uint16_t v = *pc++;614      jv* var = frame_local_var(jq, v, level);615      if (jq->debug_trace_enabled) {616        printf("V%d = ", v);617        jv_dump(jv_copy(val), 0);618        printf(" (%d)\n", jv_get_refcnt(val));619      }620      jv_free(*var);621      *var = val;622      break;623    }624625    case PATH_BEGIN: {626      jv v = stack_pop(jq);627      stack_push(jq, jq->path);628629      stack_save(jq, pc - 1, stack_get_pos(jq));630631      stack_push(jq, jv_number(jq->subexp_nest));632      stack_push(jq, jq->value_at_path);633      stack_push(jq, jv_copy(v));634635      jq->path = jv_array();636      jq->value_at_path = v; // next INDEX operation must index into v637      jq->subexp_nest = 0;638      break;639    }640641    case PATH_END: {642      jv v = stack_pop(jq);643      // detect invalid path expression like path(.a | reverse)644      if (!path_intact(jq, jv_copy(v))) {645        char errbuf[30];646        jv msg = jv_string_fmt(647            "Invalid path expression with result %s",648            jv_dump_string_trunc(v, errbuf, sizeof(errbuf)));649        set_error(jq, jv_invalid_with_msg(msg));650        goto do_backtrack;651      }652      jv_free(v); // discard value, only keep path653654      jv old_value_at_path = stack_pop(jq);655      int old_subexp_nest = (int)jv_number_value(stack_pop(jq));656657      jv path = jq->path;658      jq->path = stack_pop(jq);659660      struct stack_pos spos = stack_get_pos(jq);661      stack_push(jq, jv_copy(path));662      stack_save(jq, pc - 1, spos);663664      stack_push(jq, path);665      jq->subexp_nest = old_subexp_nest;666      jv_free(jq->value_at_path);667      jq->value_at_path = old_value_at_path;668      break;669    }670671    case ON_BACKTRACK(PATH_BEGIN):672    case ON_BACKTRACK(PATH_END): {673      jv_free(jq->path);674      jq->path = stack_pop(jq);675      goto do_backtrack;676    }677678    case INDEX:679    case INDEX_OPT: {680      jv t = stack_pop(jq);681      jv k = stack_pop(jq);682      // detect invalid path expression like path(reverse | .a)683      if (!path_intact(jq, jv_copy(t))) {684        char keybuf[30];685        char objbuf[30];686        jv msg = jv_string_fmt(687            "Invalid path expression near attempt to access element %s of %s",688            jv_dump_string_trunc(k, keybuf, sizeof(keybuf)),689            jv_dump_string_trunc(t, objbuf, sizeof(objbuf)));690        set_error(jq, jv_invalid_with_msg(msg));691        goto do_backtrack;692      }693      jv v = jv_get(t, jv_copy(k));694      if (jv_is_valid(v)) {695        path_append(jq, k, jv_copy(v));696        stack_push(jq, v);697      } else {698        jv_free(k);699        if (opcode == INDEX)700          set_error(jq, v);701        else702          jv_free(v);703        goto do_backtrack;704      }705      break;706    }707708709    case JUMP: {710      uint16_t offset = *pc++;711      pc += offset;712      break;713    }714715    case JUMP_F: {716      uint16_t offset = *pc++;717      jv t = stack_pop(jq);718      jv_kind kind = jv_get_kind(t);719      if (kind == JV_KIND_FALSE || kind == JV_KIND_NULL) {720        pc += offset;721      }722      stack_push(jq, t); // FIXME do this better723      break;724    }725726    case EACH:727    case EACH_OPT: {728      jv container = stack_pop(jq);729      // detect invalid path expression like path(reverse | .[])730      if (!path_intact(jq, jv_copy(container))) {731        char errbuf[30];732        jv msg = jv_string_fmt(733            "Invalid path expression near attempt to iterate through %s",734            jv_dump_string_trunc(container, errbuf, sizeof(errbuf)));735        set_error(jq, jv_invalid_with_msg(msg));736        goto do_backtrack;737      }738      stack_push(jq, container);739      stack_push(jq, jv_number(-1));740      JQ_FALLTHROUGH;741    }742    case ON_BACKTRACK(EACH):743    case ON_BACKTRACK(EACH_OPT): {744      int idx = jv_number_value(stack_pop(jq));745      jv container = stack_pop(jq);746747      int keep_going, is_last = 0;748      jv key, value;749      if (jv_get_kind(container) == JV_KIND_ARRAY) {750        if (opcode == EACH || opcode == EACH_OPT) idx = 0;751        else idx = idx + 1;752        int len = jv_array_length(jv_copy(container));753        keep_going = idx < len;754        is_last = idx == len - 1;755        if (keep_going) {756          key = jv_number(idx);757          value = jv_array_get(jv_copy(container), idx);758        }759      } else if (jv_get_kind(container) == JV_KIND_OBJECT) {760        if (opcode == EACH || opcode == EACH_OPT) idx = jv_object_iter(container);761        else idx = jv_object_iter_next(container, idx);762        keep_going = jv_object_iter_valid(container, idx);763        if (keep_going) {764          key = jv_object_iter_key(container, idx);765          value = jv_object_iter_value(container, idx);766        }767      } else {768        assert(opcode == EACH || opcode == EACH_OPT);769        if (opcode == EACH) {770          char errbuf[30];771          set_error(jq, jv_invalid_with_msg(jv_string_fmt(772                  "Cannot iterate over %s (%s)",773                  jv_kind_name(jv_get_kind(container)),774                  jv_dump_string_trunc(jv_copy(container), errbuf, sizeof(errbuf)))));775        }776        keep_going = 0;777      }778779      if (!keep_going || raising) {780        if (keep_going) {781          jv_free(key);782          jv_free(value);783        }784        jv_free(container);785        goto do_backtrack;786      } else if (is_last) {787        // we don't need to make a backtrack point788        jv_free(container);789        path_append(jq, key, jv_copy(value));790        stack_push(jq, value);791      } else {792        struct stack_pos spos = stack_get_pos(jq);793        stack_push(jq, container);794        stack_push(jq, jv_number(idx));795        stack_save(jq, pc - 1, spos);796        path_append(jq, key, jv_copy(value));797        stack_push(jq, value);798      }799      break;800    }801802    do_backtrack:803    case BACKTRACK: {804      pc = stack_restore(jq);805      if (!pc) {806        if (!jv_is_valid(jq->error)) {807          jv error = jq->error;808          jq->error = jv_null();809          return error;810        }811        return jv_invalid();812      }813      backtracking = 1;814      break;815    }816817    case TRY_BEGIN:818      stack_save(jq, pc - 1, stack_get_pos(jq));819      pc++; // skip handler offset this time820      break;821822    case TRY_END:823      stack_save(jq, pc - 1, stack_get_pos(jq));824      break;825826    case ON_BACKTRACK(TRY_BEGIN): {827      if (!raising) {828        /*829         * `try EXP ...` -- EXP backtracked (e.g., EXP was `empty`), so we830         * backtrack more:831         */832        jv_free(stack_pop(jq));833        goto do_backtrack;834      }835836      /*837       * Else `(try EXP ... ) | EXP2` raised an error.838       *839       * If the error was wrapped in another error, then that means EXP2 raised840       * the error.  We unwrap it and re-raise it as it wasn't raised by EXP.841       *842       * See commentary in gen_try().843       */844      jv e = jv_invalid_get_msg(jv_copy(jq->error));845      if (!jv_is_valid(e) && jv_invalid_has_msg(jv_copy(e))) {846        set_error(jq, e);847        goto do_backtrack;848      }849      jv_free(e);850851      /*852       * Else we caught an error containing a non-error value, so we jump to853       * the handler.854       *855       * See commentary in gen_try().856       */857      uint16_t offset = *pc++;858      jv_free(stack_pop(jq)); // free the input859      stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message860      jq->error = jv_null();861      pc += offset;862      break;863    }864    case ON_BACKTRACK(TRY_END):865      // Wrap the error so the matching TRY_BEGIN doesn't catch it866      if (raising)867        set_error(jq, jv_invalid_with_msg(jv_copy(jq->error)));868      goto do_backtrack;869870    case DESTRUCTURE_ALT:871    case FORK: {872      stack_save(jq, pc - 1, stack_get_pos(jq));873      pc++; // skip offset this time874      break;875    }876877    case ON_BACKTRACK(DESTRUCTURE_ALT): {878      if (jv_is_valid(jq->error)) {879        // `try EXP ...` backtracked here (no value, `empty`), so we backtrack more880        jv_free(stack_pop(jq));881        goto do_backtrack;882      }883      // `try EXP ...` exception caught in EXP884      // DESTRUCTURE_ALT doesn't want the error message on the stack,885      // as we would just want to throw it away anyway.886      if (opcode != ON_BACKTRACK(DESTRUCTURE_ALT)) {887        jv_free(stack_pop(jq)); // free the input888        stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message889      } else {890        jv_free(jq->error);891      }892      jq->error = jv_null();893      uint16_t offset = *pc++;894      pc += offset;895      break;896    }897    case ON_BACKTRACK(FORK): {898      if (raising) goto do_backtrack;899      uint16_t offset = *pc++;900      pc += offset;901      break;902    }903904    case CALL_BUILTIN: {905      int nargs = *pc++;906      struct cfunction* function = &frame_current(jq)->bc->globals->cfunctions[*pc++];907      jv in[MAX_CFUNCTION_ARGS];908      for (int i = 0; i < nargs; ++i)909        in[i] = stack_pop(jq);910911      jv top;912      switch (function->nargs) {913      case 1: top = function->fptr.a1(jq, in[0]); break;914      case 2: top = function->fptr.a2(jq, in[0], in[1]); break;915      case 3: top = function->fptr.a3(jq, in[0], in[1], in[2]); break;916      case 4: top = function->fptr.a4(jq, in[0], in[1], in[2], in[3]); break;917      default: assert(0 && "Invalid number of arguments");918      }919920      if (!jv_is_valid(top)) {921        if (jv_invalid_has_msg(jv_copy(top)))922          set_error(jq, top);923        else924          jv_free(top);925        goto do_backtrack;926      }927928      stack_push(jq, top);929      break;930    }931932    case TAIL_CALL_JQ:933    case CALL_JQ: {934      /*935       * Bytecode layout here:936       *937       *  CALL_JQ938       *  <nclosures>                       (i.e., number of call arguments)939       *  <callee closure>                  (what we're calling)940       *  <nclosures' worth of closures>    (frame reference + code pointer)941       *942       *  <next instruction (to return to)>943       *944       * Each closure consists of two uint16_t values: a "level"945       * identifying the frame to be closed over, and an index.946       *947       * The level is a relative number of call frames reachable from948       * the currently one; 0 -> current frame, 1 -> previous frame, and949       * so on.950       *951       * The index is either an index of the closed frame's subfunctions952       * or of the closed frame's parameter closures.  If the latter,953       * that closure will be passed, else the closed frame's pointer954       * and the subfunction's code will form the closure to be passed.955       *956       * See make_closure() for more information.957       */958      jv input = stack_pop(jq);959      uint16_t nclosures = *pc++;960      uint16_t* retaddr = pc + 2 + nclosures*2;961      stack_ptr retdata = jq->stk_top;962      struct frame* new_frame;963      struct closure cl = make_closure(jq, pc);964      if (opcode == TAIL_CALL_JQ) {965        retaddr = frame_current(jq)->retaddr;966        retdata = frame_current(jq)->retdata;967        frame_pop(jq);968      }969      new_frame = frame_push(jq, cl, pc + 2, nclosures);970      new_frame->retdata = retdata;971      new_frame->retaddr = retaddr;972      pc = new_frame->bc->code;973      stack_push(jq, input);974      break;975    }976977    case RET: {978      jv value = stack_pop(jq);979      assert(jq->stk_top == frame_current(jq)->retdata);980      uint16_t* retaddr = frame_current(jq)->retaddr;981      if (retaddr) {982        // function return983        pc = retaddr;984        frame_pop(jq);985      } else {986        // top-level return, yielding value987        struct stack_pos spos = stack_get_pos(jq);988        stack_push(jq, jv_null());989        stack_save(jq, pc - 1, spos);990        return value;991      }992      stack_push(jq, value);993      break;994    }995    case ON_BACKTRACK(RET): {996      // resumed after top-level return997      goto do_backtrack;998    }999    }1000  }1001}10021003jv jq_format_error(jv msg) {1004  if (jv_get_kind(msg) == JV_KIND_NULL ||1005      (jv_get_kind(msg) == JV_KIND_INVALID && !jv_invalid_has_msg(jv_copy(msg)))) {1006    jv_free(msg);1007    fprintf(stderr, "jq: error: out of memory\n");1008    return jv_null();1009  }10101011  if (jv_get_kind(msg) == JV_KIND_STRING)1012    return msg;                         // expected to already be formatted10131014  if (jv_get_kind(msg) == JV_KIND_INVALID)1015    msg = jv_invalid_get_msg(msg);10161017  if (jv_get_kind(msg) == JV_KIND_NULL)1018    return jq_format_error(msg);        // ENOMEM10191020  // Invalid with msg; prefix with "jq: error: "10211022  if (jv_get_kind(msg) != JV_KIND_INVALID) {1023    if (jv_get_kind(msg) == JV_KIND_STRING) {1024      jv r = jv_string_fmt("jq: error: %s", jv_string_value(msg));1025      jv_free(msg);1026      return r;1027    }10281029    msg = jv_dump_string(msg, JV_PRINT_INVALID);1030    if (jv_get_kind(msg) == JV_KIND_STRING) {1031      jv r = jv_string_fmt("jq: error: %s", jv_string_value(msg));1032      jv_free(msg);1033      return r;1034    }1035    jv_free(msg);1036    return jq_format_error(jv_null());  // ENOMEM1037  }10381039  // An invalid inside an invalid!1040  return jq_format_error(jv_invalid_get_msg(msg));1041}10421043// XXX Refactor into a utility function that returns a jv and one that1044// uses it and then prints that jv's string as the complete error1045// message.1046static void default_err_cb(void *data, jv msg) {1047  msg = jq_format_error(msg);1048  fprintf((FILE *)data, "%s\n", jv_string_value(msg));1049  jv_free(msg);1050}10511052jq_state *jq_init(void) {1053  jq_state *jq;1054  jq = jv_mem_alloc_unguarded(sizeof(*jq));1055  if (jq == NULL)1056    return NULL;10571058  jq->bc = 0;1059  jq->next_label = 0;10601061  stack_init(&jq->stk);1062  jq->stk_top = 0;1063  jq->fork_top = 0;1064  jq->curr_frame = 0;1065  jq->error = jv_null();10661067  jq->halted = 0;1068  jq->exit_code = jv_invalid();1069  jq->error_message = jv_invalid();10701071  jq->input_cb = NULL;1072  jq->input_cb_data = NULL;10731074  jq->debug_cb = NULL;1075  jq->debug_cb_data = NULL;10761077  jq->stderr_cb = NULL;1078  jq->stderr_cb_data = NULL;10791080  jq->err_cb = default_err_cb;1081  jq->err_cb_data = stderr;10821083  jq->attrs = jv_object();1084  jq->path = jv_null();1085  jq->value_at_path = jv_null();10861087  jq->nomem_handler = NULL;1088  jq->nomem_handler_data = NULL;1089  return jq;1090}10911092void jq_set_error_cb(jq_state *jq, jq_msg_cb cb, void *data) {1093  if (cb == NULL) {1094    jq->err_cb = default_err_cb;1095    jq->err_cb_data = stderr;1096  } else {1097    jq->err_cb = cb;1098    jq->err_cb_data = data;1099  }1100}11011102void jq_get_error_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1103  *cb = jq->err_cb;1104  *data = jq->err_cb_data;1105}11061107void jq_set_nomem_handler(jq_state *jq, void (*nomem_handler)(void *), void *data) {1108  jv_nomem_handler(nomem_handler, data);1109  jq->nomem_handler = nomem_handler;1110  jq->nomem_handler_data = data;1111}111211131114void jq_start(jq_state *jq, jv input, int flags) {1115  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1116  jq_reset(jq);11171118  struct closure top = {jq->bc, -1};1119  struct frame* top_frame = frame_push(jq, top, 0, 0);1120  top_frame->retdata = 0;1121  top_frame->retaddr = 0;11221123  stack_push(jq, input);1124  stack_save(jq, jq->bc->code, stack_get_pos(jq));1125  jq->debug_trace_enabled = flags & JQ_DEBUG_TRACE_ALL;1126  jq->initial_execution = 1;1127}11281129void jq_teardown(jq_state **jq) {1130  jq_state *old_jq = *jq;1131  if (old_jq == NULL)1132    return;1133  *jq = NULL;11341135  jq_reset(old_jq);1136  bytecode_free(old_jq->bc);1137  old_jq->bc = 0;1138  jv_free(old_jq->attrs);11391140  jv_mem_free(old_jq);1141}11421143static int ret_follows(uint16_t *pc) {1144  if (*pc == RET)1145    return 1;1146  if (*pc++ != JUMP)1147    return 0;1148  return ret_follows(pc + *pc + 1); // FIXME, might be ironic1149}11501151/*1152 * Look for tail calls that can be optimized: tail calls with no1153 * references left to the current frame.1154 *1155 * We're staring at this bytecode layout:1156 *1157 *   CALL_JQ1158 *   <nclosures>1159 *   <callee closure>       (2 units)1160 *   <nclosures closures>   (2 units each)1161 *   <next instruction>1162 *1163 * A closure is:1164 *1165 *   <level>    (a relative frame count chased via the current frame's env)1166 *   <index>    (an index of a subfunction or closure in that frame)1167 *1168 * We're looking for:1169 *1170 * a) the next instruction is a RET or a chain of unconditional JUMPs1171 * that ends in a RET, and1172 *1173 * b) none of the closures -callee included- have level == 0.1174 */1175static uint16_t tail_call_analyze(uint16_t *pc) {1176  assert(*pc == CALL_JQ);1177  pc++;1178  // + 1 for the callee closure1179  for (uint16_t nclosures = *pc++ + 1; nclosures > 0; pc++, nclosures--) {1180    if (*pc++ == 0)1181      return CALL_JQ;1182  }1183  if (ret_follows(pc))1184    return TAIL_CALL_JQ;1185  return CALL_JQ;1186}11871188static struct bytecode *optimize_code(struct bytecode *bc) {1189  uint16_t *pc = bc->code;1190  // FIXME: Don't mutate bc->code...1191  while (pc < bc->code + bc->codelen) {1192    switch (*pc) {1193    case CALL_JQ:1194      *pc = tail_call_analyze(pc);1195      break;11961197    // Other bytecode optimizations here.  A peephole optimizer would1198    // fit right in.1199    default: break;1200    }1201    pc += bytecode_operation_length(pc);1202  }1203  return bc;1204}12051206static struct bytecode *optimize(struct bytecode *bc) {1207  for (int i=0; i<bc->nsubfunctions; i++) {1208    bc->subfunctions[i] = optimize(bc->subfunctions[i]);1209  }1210  return optimize_code(bc);1211}12121213static jv1214args2obj(jv args)1215{1216  if (jv_get_kind(args) == JV_KIND_OBJECT)1217    return args;1218  assert(jv_get_kind(args) == JV_KIND_ARRAY);1219  jv r = jv_object();1220  jv kk = jv_string("name");1221  jv vk = jv_string("value");1222  jv_array_foreach(args, i, v)1223    r = jv_object_set(r, jv_object_get(jv_copy(v), jv_copy(kk)), jv_object_get(v, jv_copy(vk)));1224  jv_free(args);1225  jv_free(kk);1226  jv_free(vk);1227  return r;1228}12291230int jq_compile_args(jq_state *jq, const char* str, jv args) {1231  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1232  assert(jv_get_kind(args) == JV_KIND_ARRAY || jv_get_kind(args) == JV_KIND_OBJECT);1233  struct locfile* locations;1234  locations = locfile_init(jq, "<top-level>", str, strlen(str));1235  block program;1236  jq_reset(jq);1237  if (jq->bc) {1238    bytecode_free(jq->bc);1239    jq->bc = 0;1240  }1241  int nerrors = load_program(jq, locations, &program);1242  if (nerrors == 0) {1243    nerrors = builtins_bind(jq, &program);1244    if (nerrors == 0)1245      nerrors = block_compile(program, &jq->bc, locations, args2obj(args));1246    else1247      jv_free(args);1248  } else1249    jv_free(args);1250  if (nerrors)1251    jq_report_error(jq, jv_string_fmt("jq: %d compile %s", nerrors, nerrors > 1 ? "errors" : "error"));1252  if (jq->bc)1253    jq->bc = optimize(jq->bc);1254  locfile_free(locations);1255  return jq->bc != NULL;1256}12571258int jq_compile(jq_state *jq, const char* str) {1259  return jq_compile_args(jq, str, jv_object());1260}12611262jv jq_get_jq_origin(jq_state *jq) {1263  return jq_get_attr(jq, jv_string("JQ_ORIGIN"));1264}12651266jv jq_get_prog_origin(jq_state *jq) {1267  return jq_get_attr(jq, jv_string("PROGRAM_ORIGIN"));1268}12691270jv jq_get_lib_dirs(jq_state *jq) {1271  jv lib_dirs = jq_get_attr(jq, jv_string("JQ_LIBRARY_PATH"));1272  return jv_is_valid(lib_dirs) ? lib_dirs : jv_array();1273}12741275void jq_set_attrs(jq_state *jq, jv attrs) {1276  assert(jv_get_kind(attrs) == JV_KIND_OBJECT);1277  jv_free(jq->attrs);1278  jq->attrs = attrs;1279}12801281void jq_set_attr(jq_state *jq, jv attr, jv val) {1282  jq->attrs = jv_object_set(jq->attrs, attr, val);1283}12841285jv jq_get_attr(jq_state *jq, jv attr) {1286  return jv_object_get(jv_copy(jq->attrs), attr);1287}12881289void jq_dump_disassembly(jq_state *jq, int indent) {1290  dump_disassembly(indent, jq->bc);1291}12921293void jq_set_input_cb(jq_state *jq, jq_input_cb cb, void *data) {1294  jq->input_cb = cb;1295  jq->input_cb_data = data;1296}12971298void jq_get_input_cb(jq_state *jq, jq_input_cb *cb, void **data) {1299  *cb = jq->input_cb;1300  *data = jq->input_cb_data;1301}13021303void jq_set_debug_cb(jq_state *jq, jq_msg_cb cb, void *data) {1304  jq->debug_cb = cb;1305  jq->debug_cb_data = data;1306}13071308void jq_get_debug_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1309  *cb = jq->debug_cb;1310  *data = jq->debug_cb_data;1311}13121313void jq_set_stderr_cb(jq_state *jq, jq_msg_cb cb, void *data) {1314  jq->stderr_cb = cb;1315  jq->stderr_cb_data = data;1316}13171318void jq_get_stderr_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1319  *cb = jq->stderr_cb;1320  *data = jq->stderr_cb_data;1321}13221323void1324jq_halt(jq_state *jq, jv exit_code, jv error_message)1325{1326  assert(!jq->halted);1327  jq->halted = 1;1328  jq->exit_code = exit_code;1329  jq->error_message = error_message;1330}13311332int1333jq_halted(jq_state *jq)1334{1335  return jq->halted;1336}13371338jv jq_get_exit_code(jq_state *jq)1339{1340  return jv_copy(jq->exit_code);1341}13421343jv jq_get_error_message(jq_state *jq)1344{1345  return jv_copy(jq->error_message);1346}