Skip to content
Myr

execute.c

This file

Path

src/execute.c

1,340 lines · 35.9 KiB · C

Last changed by

jq_next: simplify CALL_BUILTIN implementationEmanuele Torrebefore adoption8bcdc93

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 "jq_parser.h"14#include "locfile.h"15#include "jv.h"16#include "jq.h"17#include "parser.h"18#include "builtin.h"19#include "util.h"20#include "linker.h"2122struct jq_state {23  void (*nomem_handler)(void *);24  void *nomem_handler_data;25  struct bytecode* bc;2627  jq_msg_cb err_cb;28  void *err_cb_data;29  jv error;3031  struct stack stk;32  stack_ptr curr_frame;33  stack_ptr stk_top;34  stack_ptr fork_top;3536  jv path;37  jv value_at_path;38  int subexp_nest;39  int debug_trace_enabled;40  int initial_execution;41  unsigned next_label;4243  int halted;44  jv exit_code;45  jv error_message;4647  jv attrs;48  jq_input_cb input_cb;49  void *input_cb_data;50  jq_msg_cb debug_cb;51  void *debug_cb_data;52  jq_msg_cb stderr_cb;53  void *stderr_cb_data;54};5556struct closure {57  struct bytecode* bc;  // jq bytecode58  stack_ptr env;        // jq stack address of closed frame59};6061// locals for any function called: either a closure or a local variable62union frame_entry {63  struct closure closure;64  jv localvar;65};6667// jq function call frame68struct frame {69  struct bytecode* bc;      // jq bytecode for callee70  stack_ptr env;            // jq stack address of frame to return to71  stack_ptr retdata;        // jq stack address to unwind to on RET72  uint16_t* retaddr;        // jq bytecode return address73  union frame_entry entries[]; // nclosures + nlocals74};7576static int frame_size(struct bytecode* bc) {77  return sizeof(struct frame) + sizeof(union frame_entry) * (bc->nclosures + bc->nlocals);78}7980static struct frame* frame_current(struct jq_state* jq) {81  struct frame* fp = stack_block(&jq->stk, jq->curr_frame);8283  stack_ptr next = *stack_block_next(&jq->stk, jq->curr_frame);84  if (next) {85    struct frame* fpnext = stack_block(&jq->stk, next);86    struct bytecode* bc = fpnext->bc;87    assert(fp->retaddr >= bc->code && fp->retaddr < bc->code + bc->codelen);88  } else {89    assert(fp->retaddr == 0);90  }91  return fp;92}9394static stack_ptr frame_get_level(struct jq_state* jq, int level) {95  stack_ptr fr = jq->curr_frame;96  for (int i=0; i<level; i++) {97    struct frame* fp = stack_block(&jq->stk, fr);98    fr = fp->env;99  }100  return fr;101}102103static jv* frame_local_var(struct jq_state* jq, int var, int level) {104  struct frame* fr = stack_block(&jq->stk, frame_get_level(jq, level));105  assert(var >= 0);106  assert(var < fr->bc->nlocals);107  return &fr->entries[fr->bc->nclosures + var].localvar;108}109110static struct closure make_closure(struct jq_state* jq, uint16_t* pc) {111  uint16_t level = *pc++;112  uint16_t idx = *pc++;113  stack_ptr fridx = frame_get_level(jq, level);114  struct frame* fr = stack_block(&jq->stk, fridx);115  if (idx & ARG_NEWCLOSURE) {116    // A new closure closing the frame identified by level, and with117    // the bytecode body of the idx'th subfunction of that frame118    int subfn_idx = idx & ~ARG_NEWCLOSURE;119    assert(subfn_idx < fr->bc->nsubfunctions);120    struct closure cl = {fr->bc->subfunctions[subfn_idx],121                         fridx};122    return cl;123  } else {124    // A reference to a closure from the frame identified by level; copy125    // it as-is126    int closure = idx;127    assert(closure >= 0);128    assert(closure < fr->bc->nclosures);129    return fr->entries[closure].closure;130  }131}132133static struct frame* frame_push(struct jq_state* jq, struct closure callee,134                                uint16_t* argdef, int nargs) {135  stack_ptr new_frame_idx = stack_push_block(&jq->stk, jq->curr_frame, frame_size(callee.bc));136  struct frame* new_frame = stack_block(&jq->stk, new_frame_idx);137  new_frame->bc = callee.bc;138  new_frame->env = callee.env;139  assert(nargs == new_frame->bc->nclosures);140  union frame_entry* entries = new_frame->entries;141  for (int i=0; i<nargs; i++) {142    entries->closure = make_closure(jq, argdef + i * 2);143    entries++;144  }145  for (int i=0; i<callee.bc->nlocals; i++) {146    entries->localvar = jv_invalid();147    entries++;148  }149  jq->curr_frame = new_frame_idx;150  return new_frame;151}152153static void frame_pop(struct jq_state* jq) {154  assert(jq->curr_frame);155  struct frame* fp = frame_current(jq);156  if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {157    int nlocals = fp->bc->nlocals;158    for (int i=0; i<nlocals; i++) {159      jv_free(*frame_local_var(jq, i, 0));160    }161  }162  jq->curr_frame = stack_pop_block(&jq->stk, jq->curr_frame, frame_size(fp->bc));163}164165void stack_push(jq_state *jq, jv val) {166  assert(jv_is_valid(val));167  jq->stk_top = stack_push_block(&jq->stk, jq->stk_top, sizeof(jv));168  jv* sval = stack_block(&jq->stk, jq->stk_top);169  *sval = val;170}171172jv stack_pop(jq_state *jq) {173  jv* sval = stack_block(&jq->stk, jq->stk_top);174  jv val = *sval;175  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {176    val = jv_copy(val);177  }178  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));179  assert(jv_is_valid(val));180  return val;181}182183// Like stack_pop(), but assert !stack_pop_will_free() and replace with184// jv_null() on the stack.185jv stack_popn(jq_state *jq) {186  jv* sval = stack_block(&jq->stk, jq->stk_top);187  jv val = *sval;188  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {189    *sval = jv_null();190  }191  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));192  assert(jv_is_valid(val));193  return val;194}195196197struct forkpoint {198  stack_ptr saved_data_stack;199  stack_ptr saved_curr_frame;200  int path_len, subexp_nest;201  jv value_at_path;202  uint16_t* return_address;203};204205struct stack_pos {206  stack_ptr saved_data_stack, saved_curr_frame;207};208209struct stack_pos stack_get_pos(jq_state* jq) {210  struct stack_pos sp = {jq->stk_top, jq->curr_frame};211  return sp;212}213214void stack_save(jq_state *jq, uint16_t* retaddr, struct stack_pos sp){215  jq->fork_top = stack_push_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));216  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);217  fork->saved_data_stack = jq->stk_top;218  fork->saved_curr_frame = jq->curr_frame;219  fork->path_len =220    jv_get_kind(jq->path) == JV_KIND_ARRAY ? jv_array_length(jv_copy(jq->path)) : 0;221  fork->value_at_path = jv_copy(jq->value_at_path);222  fork->subexp_nest = jq->subexp_nest;223  fork->return_address = retaddr;224  jq->stk_top = sp.saved_data_stack;225  jq->curr_frame = sp.saved_curr_frame;226}227228static int path_intact(jq_state *jq, jv curr) {229  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {230    return jv_identical(curr, jv_copy(jq->value_at_path));231  } else {232    jv_free(curr);233    return 1;234  }235}236237static void path_append(jq_state* jq, jv component, jv value_at_path) {238  if (jq->subexp_nest == 0 && jv_get_kind(jq->path) == JV_KIND_ARRAY) {239    int n1 = jv_array_length(jv_copy(jq->path));240    jq->path = jv_array_append(jq->path, component);241    int n2 = jv_array_length(jv_copy(jq->path));242    assert(n2 == n1 + 1);243    jv_free(jq->value_at_path);244    jq->value_at_path = value_at_path;245  } else {246    jv_free(component);247    jv_free(value_at_path);248  }249}250251/* For f_getpath() */252jv253_jq_path_append(jq_state *jq, jv v, jv p, jv value_at_path) {254  if (jq->subexp_nest != 0 ||255      jv_get_kind(jq->path) != JV_KIND_ARRAY ||256      !jv_is_valid(value_at_path)) {257    jv_free(v);258    jv_free(p);259    return value_at_path;260  }261  if (!jv_identical(v, jv_copy(jq->value_at_path))) {262    jv_free(p);263    return value_at_path;264  }265  if (jv_get_kind(p) == JV_KIND_ARRAY)266    jq->path = jv_array_concat(jq->path, p);267  else268    jq->path = jv_array_append(jq->path, p);269  jv_free(jq->value_at_path);270  return jv_copy(jq->value_at_path = value_at_path);271}272273uint16_t* stack_restore(jq_state *jq){274  while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {275    if (stack_pop_will_free(&jq->stk, jq->stk_top)) {276      jv_free(stack_pop(jq));277    } else if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {278      frame_pop(jq);279    } else {280      assert(0);281    }282  }283284  if (jq->fork_top == 0) {285    return 0;286  }287288  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);289  uint16_t* retaddr = fork->return_address;290  jq->stk_top = fork->saved_data_stack;291  jq->curr_frame = fork->saved_curr_frame;292  int path_len = fork->path_len;293  if (jv_get_kind(jq->path) == JV_KIND_ARRAY) {294    assert(path_len >= 0);295    jq->path = jv_array_slice(jq->path, 0, path_len);296  } else {297    fork->path_len = 0;298  }299  jv_free(jq->value_at_path);300  jq->value_at_path = fork->value_at_path;301  jq->subexp_nest = fork->subexp_nest;302  jq->fork_top = stack_pop_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));303  return retaddr;304}305306static void jq_reset(jq_state *jq) {307  while (stack_restore(jq)) {}308309  assert(jq->stk_top == 0);310  assert(jq->fork_top == 0);311  assert(jq->curr_frame == 0);312  stack_reset(&jq->stk);313  jv_free(jq->error);314  jq->error = jv_null();315316  jq->halted = 0;317  jv_free(jq->exit_code);318  jq->exit_code = jv_invalid();319  jv_free(jq->error_message);320  jq->error_message = jv_invalid();321  if (jv_get_kind(jq->path) != JV_KIND_INVALID)322    jv_free(jq->path);323  jq->path = jv_null();324  jv_free(jq->value_at_path);325  jq->value_at_path = jv_null();326  jq->subexp_nest = 0;327}328329void jq_report_error(jq_state *jq, jv value) {330  assert(jq->err_cb);331  // callback must jv_free() its jv argument332  jq->err_cb(jq->err_cb_data, value);333}334335static void set_error(jq_state *jq, jv value) {336  // Record so try/catch can find it.337  jv_free(jq->error);338  jq->error = value;339}340341#define ON_BACKTRACK(op) ((op)+NUM_OPCODES)342343jv jq_next(jq_state *jq) {344  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);345346  uint16_t* pc = stack_restore(jq);347  assert(pc);348349  int raising;350  int backtracking = !jq->initial_execution;351352  jq->initial_execution = 0;353  assert(jv_get_kind(jq->error) == JV_KIND_NULL);354  while (1) {355    if (jq->halted) {356      if (jq->debug_trace_enabled)357        printf("\t<halted>\n");358      return jv_invalid();359    }360    uint16_t opcode = *pc;361    raising = 0;362363    if (jq->debug_trace_enabled) {364      dump_operation(frame_current(jq)->bc, pc);365      printf("\t");366      const struct opcode_description* opdesc = opcode_describe(opcode);367      stack_ptr param = 0;368      if (!backtracking) {369        int stack_in = opdesc->stack_in;370        if (stack_in == -1) stack_in = pc[1];371        param = jq->stk_top;372        for (int i=0; i<stack_in; i++) {373          if (i != 0) {374            printf(" | ");375            param = *stack_block_next(&jq->stk, param);376          }377          if (!param) break;378          jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);379          //printf("<%d>", jv_get_refcnt(param->val));380          //printf(" -- ");381          //jv_dump(jv_copy(jq->path), 0);382        }383        if (jq->debug_trace_enabled & JQ_DEBUG_TRACE_DETAIL) {384          while ((param = *stack_block_next(&jq->stk, param))) {385            printf(" || ");386            jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), JV_PRINT_REFCOUNT);387          }388        }389      } else {390        printf("\t<backtracking>");391      }392393      printf("\n");394    }395396    if (backtracking) {397      opcode = ON_BACKTRACK(opcode);398      backtracking = 0;399      raising = !jv_is_valid(jq->error);400    }401    pc++;402403    switch (opcode) {404    default: assert(0 && "invalid instruction");405406    case TOP: break;407408    case ERRORK: {409      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);410      set_error(jq, jv_invalid_with_msg(v));411      goto do_backtrack;412    }413414    case LOADK: {415      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);416      assert(jv_is_valid(v));417      jv_free(stack_pop(jq));418      stack_push(jq, v);419      break;420    }421422    case GENLABEL: {423      stack_push(jq, JV_OBJECT(jv_string("__jq"), jv_number(jq->next_label++)));424      break;425    }426427    case DUP: {428      jv v = stack_pop(jq);429      stack_push(jq, jv_copy(v));430      stack_push(jq, v);431      break;432    }433434    case DUPN: {435      jv v = stack_popn(jq);436      stack_push(jq, jv_copy(v));437      stack_push(jq, v);438      break;439    }440441    case DUP2: {442      jv keep = stack_pop(jq);443      jv v = stack_pop(jq);444      stack_push(jq, jv_copy(v));445      stack_push(jq, keep);446      stack_push(jq, v);447      break;448    }449450    case SUBEXP_BEGIN: {451      jv v = stack_pop(jq);452      stack_push(jq, jv_copy(v));453      stack_push(jq, v);454      jq->subexp_nest++;455      break;456    }457458    case SUBEXP_END: {459      assert(jq->subexp_nest > 0);460      jq->subexp_nest--;461      jv a = stack_pop(jq);462      jv b = stack_pop(jq);463      stack_push(jq, a);464      stack_push(jq, b);465      break;466    }467468    case PUSHK_UNDER: {469      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);470      assert(jv_is_valid(v));471      jv v2 = stack_pop(jq);472      stack_push(jq, v);473      stack_push(jq, v2);474      break;475    }476477    case POP: {478      jv_free(stack_pop(jq));479      break;480    }481482    case APPEND: {483      jv v = stack_pop(jq);484      uint16_t level = *pc++;485      uint16_t vidx = *pc++;486      jv* var = frame_local_var(jq, vidx, level);487      assert(jv_get_kind(*var) == JV_KIND_ARRAY);488      *var = jv_array_append(*var, v);489      break;490    }491492    case INSERT: {493      jv stktop = stack_pop(jq);494      jv v = stack_pop(jq);495      jv k = stack_pop(jq);496      jv objv = stack_pop(jq);497      assert(jv_get_kind(objv) == JV_KIND_OBJECT);498      if (jv_get_kind(k) == JV_KIND_STRING) {499        stack_push(jq, jv_object_set(objv, k, v));500        stack_push(jq, stktop);501      } else {502        char errbuf[15];503        set_error(jq, jv_invalid_with_msg(jv_string_fmt("Cannot use %s (%s) as object key",504                                                        jv_kind_name(jv_get_kind(k)),505                                                        jv_dump_string_trunc(jv_copy(k), errbuf, sizeof(errbuf)))));506        jv_free(stktop);507        jv_free(v);508        jv_free(k);509        jv_free(objv);510        goto do_backtrack;511      }512      break;513    }514515    case ON_BACKTRACK(RANGE):516    case RANGE: {517      uint16_t level = *pc++;518      uint16_t v = *pc++;519      jv* var = frame_local_var(jq, v, level);520      jv max = stack_pop(jq);521      if (raising) {522        jv_free(max);523        goto do_backtrack;524      } 525      if (jv_get_kind(*var) != JV_KIND_NUMBER ||526          jv_get_kind(max) != JV_KIND_NUMBER) {527        set_error(jq, jv_invalid_with_msg(jv_string_fmt("Range bounds must be numeric")));528        jv_free(max);529        goto do_backtrack;530      } else if (jv_number_value(*var) >= jv_number_value(max)) {531        /* finished iterating */532        jv_free(max);533        goto do_backtrack;534      } else {535        jv curr = *var;536        *var = jv_number(jv_number_value(*var) + 1);537538        struct stack_pos spos = stack_get_pos(jq);539        stack_push(jq, max);540        stack_save(jq, pc - 3, spos);541542        stack_push(jq, curr);543      }544      break;545    }546547      // FIXME: loadv/storev may do too much copying/freeing548    case LOADV: {549      uint16_t level = *pc++;550      uint16_t v = *pc++;551      jv* var = frame_local_var(jq, v, level);552      if (jq->debug_trace_enabled) {553        printf("V%d = ", v);554        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);555        printf("\n");556      }557      jv_free(stack_pop(jq));558      stack_push(jq, jv_copy(*var));559      break;560    }561562      // Does a load but replaces the variable with null563    case LOADVN: {564      uint16_t level = *pc++;565      uint16_t v = *pc++;566      jv* var = frame_local_var(jq, v, level);567      if (jq->debug_trace_enabled) {568        printf("V%d = ", v);569        jv_dump(jv_copy(*var), JV_PRINT_REFCOUNT);570        printf("\n");571      }572      jv_free(stack_popn(jq));573574      // This `stack_push()` invalidates the `var` reference, so575      stack_push(jq, *var);576      // we have to re-resolve `var` before we can set it to null577      var = frame_local_var(jq, v, level);578      *var = jv_null();579      break;580    }581582    case STOREVN:583        stack_save(jq, pc - 1, stack_get_pos(jq));584        JQ_FALLTHROUGH;585    case STOREV: {586      uint16_t level = *pc++;587      uint16_t v = *pc++;588      jv* var = frame_local_var(jq, v, level);589      jv val = stack_pop(jq);590      if (jq->debug_trace_enabled) {591        printf("V%d = ", v);592        jv_dump(jv_copy(val), 0);593        printf(" (%d)\n", jv_get_refcnt(val));594      }595      jv_free(*var);596      *var = val;597      break;598    }599600    case ON_BACKTRACK(STOREVN): {601      uint16_t level = *pc++;602      uint16_t v = *pc++;603      jv* var = frame_local_var(jq, v, level);604      jv_free(*var);605      *var = jv_null();606      goto do_backtrack;607      break;608    }609610    case STORE_GLOBAL: {611      // Get the constant612      jv val = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);613      assert(jv_is_valid(val));614615      // Store the var616      uint16_t level = *pc++;617      uint16_t v = *pc++;618      jv* var = frame_local_var(jq, v, level);619      if (jq->debug_trace_enabled) {620        printf("V%d = ", v);621        jv_dump(jv_copy(val), 0);622        printf(" (%d)\n", jv_get_refcnt(val));623      }624      jv_free(*var);625      *var = val;626      break;627    }628629    case PATH_BEGIN: {630      jv v = stack_pop(jq);631      stack_push(jq, jq->path);632633      stack_save(jq, pc - 1, stack_get_pos(jq));634635      stack_push(jq, jv_number(jq->subexp_nest));636      stack_push(jq, jq->value_at_path);637      stack_push(jq, jv_copy(v));638639      jq->path = jv_array();640      jq->value_at_path = v; // next INDEX operation must index into v641      jq->subexp_nest = 0;642      break;643    }644645    case PATH_END: {646      jv v = stack_pop(jq);647      // detect invalid path expression like path(.a | reverse)648      if (!path_intact(jq, jv_copy(v))) {649        char errbuf[30];650        jv msg = jv_string_fmt(651            "Invalid path expression with result %s",652            jv_dump_string_trunc(v, errbuf, sizeof(errbuf)));653        set_error(jq, jv_invalid_with_msg(msg));654        goto do_backtrack;655      }656      jv_free(v); // discard value, only keep path657658      jv old_value_at_path = stack_pop(jq);659      int old_subexp_nest = (int)jv_number_value(stack_pop(jq));660661      jv path = jq->path;662      jq->path = stack_pop(jq);663664      struct stack_pos spos = stack_get_pos(jq);665      stack_push(jq, jv_copy(path));666      stack_save(jq, pc - 1, spos);667668      stack_push(jq, path);669      jq->subexp_nest = old_subexp_nest;670      jv_free(jq->value_at_path);671      jq->value_at_path = old_value_at_path;672      break;673    }674675    case ON_BACKTRACK(PATH_BEGIN):676    case ON_BACKTRACK(PATH_END): {677      jv_free(jq->path);678      jq->path = stack_pop(jq);679      goto do_backtrack;680    }681682    case INDEX:683    case INDEX_OPT: {684      jv t = stack_pop(jq);685      jv k = stack_pop(jq);686      // detect invalid path expression like path(reverse | .a)687      if (!path_intact(jq, jv_copy(t))) {688        char keybuf[15];689        char objbuf[30];690        jv msg = jv_string_fmt(691            "Invalid path expression near attempt to access element %s of %s",692            jv_dump_string_trunc(k, keybuf, sizeof(keybuf)),693            jv_dump_string_trunc(t, objbuf, sizeof(objbuf)));694        set_error(jq, jv_invalid_with_msg(msg));695        goto do_backtrack;696      }697      jv v = jv_get(t, jv_copy(k));698      if (jv_is_valid(v)) {699        path_append(jq, k, jv_copy(v));700        stack_push(jq, v);701      } else {702        jv_free(k);703        if (opcode == INDEX)704          set_error(jq, v);705        else706          jv_free(v);707        goto do_backtrack;708      }709      break;710    }711712713    case JUMP: {714      uint16_t offset = *pc++;715      pc += offset;716      break;717    }718719    case JUMP_F: {720      uint16_t offset = *pc++;721      jv t = stack_pop(jq);722      jv_kind kind = jv_get_kind(t);723      if (kind == JV_KIND_FALSE || kind == JV_KIND_NULL) {724        pc += offset;725      }726      stack_push(jq, t); // FIXME do this better727      break;728    }729730    case EACH:731    case EACH_OPT: {732      jv container = stack_pop(jq);733      // detect invalid path expression like path(reverse | .[])734      if (!path_intact(jq, jv_copy(container))) {735        char errbuf[30];736        jv msg = jv_string_fmt(737            "Invalid path expression near attempt to iterate through %s",738            jv_dump_string_trunc(container, errbuf, sizeof(errbuf)));739        set_error(jq, jv_invalid_with_msg(msg));740        goto do_backtrack;741      }742      stack_push(jq, container);743      stack_push(jq, jv_number(-1));744      JQ_FALLTHROUGH;745    }746    case ON_BACKTRACK(EACH):747    case ON_BACKTRACK(EACH_OPT): {748      int idx = jv_number_value(stack_pop(jq));749      jv container = stack_pop(jq);750751      int keep_going, is_last = 0;752      jv key, value;753      if (jv_get_kind(container) == JV_KIND_ARRAY) {754        if (opcode == EACH || opcode == EACH_OPT) idx = 0;755        else idx = idx + 1;756        int len = jv_array_length(jv_copy(container));757        keep_going = idx < len;758        is_last = idx == len - 1;759        if (keep_going) {760          key = jv_number(idx);761          value = jv_array_get(jv_copy(container), idx);762        }763      } else if (jv_get_kind(container) == JV_KIND_OBJECT) {764        if (opcode == EACH || opcode == EACH_OPT) idx = jv_object_iter(container);765        else idx = jv_object_iter_next(container, idx);766        keep_going = jv_object_iter_valid(container, idx);767        if (keep_going) {768          key = jv_object_iter_key(container, idx);769          value = jv_object_iter_value(container, idx);770        }771      } else {772        assert(opcode == EACH || opcode == EACH_OPT);773        if (opcode == EACH) {774          char errbuf[15];775          set_error(jq,776                    jv_invalid_with_msg(jv_string_fmt("Cannot iterate over %s (%s)",777                                                      jv_kind_name(jv_get_kind(container)),778                                                      jv_dump_string_trunc(jv_copy(container), errbuf, sizeof(errbuf)))));779        }780        keep_going = 0;781      }782783      if (!keep_going || raising) {784        if (keep_going) {785          jv_free(key);786          jv_free(value);787        }788        jv_free(container);789        goto do_backtrack;790      } else if (is_last) {791        // we don't need to make a backtrack point792        jv_free(container);793        path_append(jq, key, jv_copy(value));794        stack_push(jq, value);795      } else {796        struct stack_pos spos = stack_get_pos(jq);797        stack_push(jq, container);798        stack_push(jq, jv_number(idx));799        stack_save(jq, pc - 1, spos);800        path_append(jq, key, jv_copy(value));801        stack_push(jq, value);802      }803      break;804    }805806    do_backtrack:807    case BACKTRACK: {808      pc = stack_restore(jq);809      if (!pc) {810        if (!jv_is_valid(jq->error)) {811          jv error = jq->error;812          jq->error = jv_null();813          return error;814        }815        return jv_invalid();816      }817      backtracking = 1;818      break;819    }820821    case TRY_BEGIN:822      stack_save(jq, pc - 1, stack_get_pos(jq));823      pc++; // skip handler offset this time824      break;825826    case TRY_END:827      stack_save(jq, pc - 1, stack_get_pos(jq));828      break;829830    case ON_BACKTRACK(TRY_BEGIN): {831      if (!raising) {832        /*833         * `try EXP ...` -- EXP backtracked (e.g., EXP was `empty`), so we834         * backtrack more:835         */836        jv_free(stack_pop(jq));837        goto do_backtrack;838      }839840      /*841       * Else `(try EXP ... ) | EXP2` raised an error.842       *843       * If the error was wrapped in another error, then that means EXP2 raised844       * the error.  We unwrap it and re-raise it as it wasn't raised by EXP.845       *846       * See commentary in gen_try().847       */848      jv e = jv_invalid_get_msg(jv_copy(jq->error));849      if (!jv_is_valid(e) && jv_invalid_has_msg(jv_copy(e))) {850        set_error(jq, e);851        goto do_backtrack;852      }853      jv_free(e);854855      /*856       * Else we caught an error containing a non-error value, so we jump to857       * the handler.858       *859       * See commentary in gen_try().860       */861      uint16_t offset = *pc++;862      jv_free(stack_pop(jq)); // free the input863      stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message864      jq->error = jv_null();865      pc += offset;866      break;867    }868    case ON_BACKTRACK(TRY_END):869      // Wrap the error so the matching TRY_BEGIN doesn't catch it870      if (raising)871        set_error(jq, jv_invalid_with_msg(jv_copy(jq->error)));872      goto do_backtrack;873874    case DESTRUCTURE_ALT:875    case FORK: {876      stack_save(jq, pc - 1, stack_get_pos(jq));877      pc++; // skip offset this time878      break;879    }880881    case ON_BACKTRACK(DESTRUCTURE_ALT): {882      if (jv_is_valid(jq->error)) {883        // `try EXP ...` backtracked here (no value, `empty`), so we backtrack more884        jv_free(stack_pop(jq));885        goto do_backtrack;886      }887      // `try EXP ...` exception caught in EXP888      // DESTRUCTURE_ALT doesn't want the error message on the stack,889      // as we would just want to throw it away anyway.890      if (opcode != ON_BACKTRACK(DESTRUCTURE_ALT)) {891        jv_free(stack_pop(jq)); // free the input892        stack_push(jq, jv_invalid_get_msg(jq->error));  // push the error's message893      } else {894        jv_free(jq->error);895      }896      jq->error = jv_null();897      uint16_t offset = *pc++;898      pc += offset;899      break;900    }901    case ON_BACKTRACK(FORK): {902      if (raising) goto do_backtrack;903      uint16_t offset = *pc++;904      pc += offset;905      break;906    }907908    case CALL_BUILTIN: {909      int nargs = *pc++;910      struct cfunction* function = &frame_current(jq)->bc->globals->cfunctions[*pc++];911      jv in[MAX_CFUNCTION_ARGS];912      for (int i = 0; i < nargs; ++i)913        in[i] = stack_pop(jq);914915      jv top;916      switch (function->nargs) {917      case 1: top = function->fptr.a1(jq, in[0]); break;918      case 2: top = function->fptr.a2(jq, in[0], in[1]); break;919      case 3: top = function->fptr.a3(jq, in[0], in[1], in[2]); break;920      case 4: top = function->fptr.a4(jq, in[0], in[1], in[2], in[3]); break;921      default: assert(0 && "Invalid number of arguments");922      }923924      if (!jv_is_valid(top)) {925        if (jv_invalid_has_msg(jv_copy(top)))926          set_error(jq, top);927        goto do_backtrack;928      }929930      stack_push(jq, top);931      break;932    }933934    case TAIL_CALL_JQ:935    case CALL_JQ: {936      /*937       * Bytecode layout here:938       *939       *  CALL_JQ940       *  <nclosures>                       (i.e., number of call arguments)941       *  <callee closure>                  (what we're calling)942       *  <nclosures' worth of closures>    (frame reference + code pointer)943       *944       *  <next instruction (to return to)>945       *946       * Each closure consists of two uint16_t values: a "level"947       * identifying the frame to be closed over, and an index.948       *949       * The level is a relative number of call frames reachable from950       * the currently one; 0 -> current frame, 1 -> previous frame, and951       * so on.952       *953       * The index is either an index of the closed frame's subfunctions954       * or of the closed frame's parameter closures.  If the latter,955       * that closure will be passed, else the closed frame's pointer956       * and the subfunction's code will form the closure to be passed.957       *958       * See make_closure() for more information.959       */960      jv input = stack_pop(jq);961      uint16_t nclosures = *pc++;962      uint16_t* retaddr = pc + 2 + nclosures*2;963      stack_ptr retdata = jq->stk_top;964      struct frame* new_frame;965      struct closure cl = make_closure(jq, pc);966      if (opcode == TAIL_CALL_JQ) {967        retaddr = frame_current(jq)->retaddr;968        retdata = frame_current(jq)->retdata;969        frame_pop(jq);970      }971      new_frame = frame_push(jq, cl, pc + 2, nclosures);972      new_frame->retdata = retdata;973      new_frame->retaddr = retaddr;974      pc = new_frame->bc->code;975      stack_push(jq, input);976      break;977    }978979    case RET: {980      jv value = stack_pop(jq);981      assert(jq->stk_top == frame_current(jq)->retdata);982      uint16_t* retaddr = frame_current(jq)->retaddr;983      if (retaddr) {984        // function return985        pc = retaddr;986        frame_pop(jq);987      } else {988        // top-level return, yielding value989        struct stack_pos spos = stack_get_pos(jq);990        stack_push(jq, jv_null());991        stack_save(jq, pc - 1, spos);992        return value;993      }994      stack_push(jq, value);995      break;996    }997    case ON_BACKTRACK(RET): {998      // resumed after top-level return999      goto do_backtrack;1000    }1001    }1002  }1003}10041005jv jq_format_error(jv msg) {1006  if (jv_get_kind(msg) == JV_KIND_NULL ||1007      (jv_get_kind(msg) == JV_KIND_INVALID && !jv_invalid_has_msg(jv_copy(msg)))) {1008    jv_free(msg);1009    fprintf(stderr, "jq: error: out of memory\n");1010    return jv_null();1011  }10121013  if (jv_get_kind(msg) == JV_KIND_STRING)1014    return msg;                         // expected to already be formatted10151016  if (jv_get_kind(msg) == JV_KIND_INVALID)1017    msg = jv_invalid_get_msg(msg);10181019  if (jv_get_kind(msg) == JV_KIND_NULL)1020    return jq_format_error(msg);        // ENOMEM10211022  // Invalid with msg; prefix with "jq: error: "10231024  if (jv_get_kind(msg) != JV_KIND_INVALID) {1025    if (jv_get_kind(msg) == JV_KIND_STRING)1026      return jv_string_fmt("jq: error: %s", jv_string_value(msg));10271028    msg = jv_dump_string(msg, JV_PRINT_INVALID);1029    if (jv_get_kind(msg) == JV_KIND_STRING)1030      return jv_string_fmt("jq: error: %s", jv_string_value(msg));1031    return jq_format_error(jv_null());  // ENOMEM1032  }10331034  // An invalid inside an invalid!1035  return jq_format_error(jv_invalid_get_msg(msg));1036}10371038// XXX Refactor into a utility function that returns a jv and one that1039// uses it and then prints that jv's string as the complete error1040// message.1041static void default_err_cb(void *data, jv msg) {1042  msg = jq_format_error(msg);1043  fprintf((FILE *)data, "%s\n", jv_string_value(msg));1044  jv_free(msg);1045}10461047jq_state *jq_init(void) {1048  jq_state *jq;1049  jq = jv_mem_alloc_unguarded(sizeof(*jq));1050  if (jq == NULL)1051    return NULL;10521053  jq->bc = 0;1054  jq->next_label = 0;10551056  stack_init(&jq->stk);1057  jq->stk_top = 0;1058  jq->fork_top = 0;1059  jq->curr_frame = 0;1060  jq->error = jv_null();10611062  jq->halted = 0;1063  jq->exit_code = jv_invalid();1064  jq->error_message = jv_invalid();10651066  jq->input_cb = NULL;1067  jq->input_cb_data = NULL;10681069  jq->debug_cb = NULL;1070  jq->debug_cb_data = NULL;10711072  jq->stderr_cb = NULL;1073  jq->stderr_cb_data = NULL;10741075  jq->err_cb = default_err_cb;1076  jq->err_cb_data = stderr;10771078  jq->attrs = jv_object();1079  jq->path = jv_null();1080  jq->value_at_path = jv_null();10811082  jq->nomem_handler = NULL;1083  jq->nomem_handler_data = NULL;1084  return jq;1085}10861087void jq_set_error_cb(jq_state *jq, jq_msg_cb cb, void *data) {1088  if (cb == NULL) {1089    jq->err_cb = default_err_cb;1090    jq->err_cb_data = stderr;1091  } else {1092    jq->err_cb = cb;1093    jq->err_cb_data = data;1094  }1095}10961097void jq_get_error_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1098  *cb = jq->err_cb;1099  *data = jq->err_cb_data;1100}11011102void jq_set_nomem_handler(jq_state *jq, void (*nomem_handler)(void *), void *data) {1103  jv_nomem_handler(nomem_handler, data);1104  jq->nomem_handler = nomem_handler;1105  jq->nomem_handler_data = data;1106}110711081109void jq_start(jq_state *jq, jv input, int flags) {1110  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1111  jq_reset(jq);11121113  struct closure top = {jq->bc, -1};1114  struct frame* top_frame = frame_push(jq, top, 0, 0);1115  top_frame->retdata = 0;1116  top_frame->retaddr = 0;11171118  stack_push(jq, input);1119  stack_save(jq, jq->bc->code, stack_get_pos(jq));1120  jq->debug_trace_enabled = flags & JQ_DEBUG_TRACE_ALL;1121  jq->initial_execution = 1;1122}11231124void jq_teardown(jq_state **jq) {1125  jq_state *old_jq = *jq;1126  if (old_jq == NULL)1127    return;1128  *jq = NULL;11291130  jq_reset(old_jq);1131  bytecode_free(old_jq->bc);1132  old_jq->bc = 0;1133  jv_free(old_jq->attrs);11341135  jv_mem_free(old_jq);1136}11371138static int ret_follows(uint16_t *pc) {1139  if (*pc == RET)1140    return 1;1141  if (*pc++ != JUMP)1142    return 0;1143  return ret_follows(pc + *pc + 1); // FIXME, might be ironic1144}11451146/*1147 * Look for tail calls that can be optimized: tail calls with no1148 * references left to the current frame.1149 *1150 * We're staring at this bytecode layout:1151 *1152 *   CALL_JQ1153 *   <nclosures>1154 *   <callee closure>       (2 units)1155 *   <nclosures closures>   (2 units each)1156 *   <next instruction>1157 *1158 * A closure is:1159 *1160 *   <level>    (a relative frame count chased via the current frame's env)1161 *   <index>    (an index of a subfunction or closure in that frame)1162 *1163 * We're looking for:1164 *1165 * a) the next instruction is a RET or a chain of unconditional JUMPs1166 * that ends in a RET, and1167 *1168 * b) none of the closures -callee included- have level == 0.1169 */1170static uint16_t tail_call_analyze(uint16_t *pc) {1171  assert(*pc == CALL_JQ);1172  pc++;1173  // + 1 for the callee closure1174  for (uint16_t nclosures = *pc++ + 1; nclosures > 0; pc++, nclosures--) {1175    if (*pc++ == 0)1176      return CALL_JQ;1177  }1178  if (ret_follows(pc))1179    return TAIL_CALL_JQ;1180  return CALL_JQ;1181}11821183static struct bytecode *optimize_code(struct bytecode *bc) {1184  uint16_t *pc = bc->code;1185  // FIXME: Don't mutate bc->code...1186  while (pc < bc->code + bc->codelen) {1187    switch (*pc) {1188    case CALL_JQ:1189      *pc = tail_call_analyze(pc);1190      break;11911192    // Other bytecode optimizations here.  A peephole optimizer would1193    // fit right in.1194    default: break;1195    }1196    pc += bytecode_operation_length(pc);1197  }1198  return bc;1199}12001201static struct bytecode *optimize(struct bytecode *bc) {1202  for (int i=0; i<bc->nsubfunctions; i++) {1203    bc->subfunctions[i] = optimize(bc->subfunctions[i]);1204  }1205  return optimize_code(bc);1206}12071208static jv1209args2obj(jv args)1210{1211  if (jv_get_kind(args) == JV_KIND_OBJECT)1212    return args;1213  assert(jv_get_kind(args) == JV_KIND_ARRAY);1214  jv r = jv_object();1215  jv kk = jv_string("name");1216  jv vk = jv_string("value");1217  jv_array_foreach(args, i, v)1218    r = jv_object_set(r, jv_object_get(jv_copy(v), kk), jv_object_get(v, vk));1219  jv_free(args);1220  jv_free(kk);1221  jv_free(vk);1222  return r;1223}12241225int jq_compile_args(jq_state *jq, const char* str, jv args) {1226  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);1227  assert(jv_get_kind(args) == JV_KIND_ARRAY || jv_get_kind(args) == JV_KIND_OBJECT);1228  struct locfile* locations;1229  locations = locfile_init(jq, "<top-level>", str, strlen(str));1230  block program;1231  jq_reset(jq);1232  if (jq->bc) {1233    bytecode_free(jq->bc);1234    jq->bc = 0;1235  }1236  int nerrors = load_program(jq, locations, &program);1237  if (nerrors == 0) {1238    nerrors = builtins_bind(jq, &program);1239    if (nerrors == 0) {1240      nerrors = block_compile(program, &jq->bc, locations, args2obj(args));1241    }1242  } else1243    jv_free(args);1244  if (nerrors)1245    jq_report_error(jq, jv_string_fmt("jq: %d compile %s", nerrors, nerrors > 1 ? "errors" : "error"));1246  if (jq->bc)1247    jq->bc = optimize(jq->bc);1248  locfile_free(locations);1249  return jq->bc != NULL;1250}12511252int jq_compile(jq_state *jq, const char* str) {1253  return jq_compile_args(jq, str, jv_object());1254}12551256jv jq_get_jq_origin(jq_state *jq) {1257  return jq_get_attr(jq, jv_string("JQ_ORIGIN"));1258}12591260jv jq_get_prog_origin(jq_state *jq) {1261  return jq_get_attr(jq, jv_string("PROGRAM_ORIGIN"));1262}12631264jv jq_get_lib_dirs(jq_state *jq) {1265  jv lib_dirs = jq_get_attr(jq, jv_string("JQ_LIBRARY_PATH"));1266  return jv_is_valid(lib_dirs) ? lib_dirs : jv_array();1267}12681269void jq_set_attrs(jq_state *jq, jv attrs) {1270  assert(jv_get_kind(attrs) == JV_KIND_OBJECT);1271  jv_free(jq->attrs);1272  jq->attrs = attrs;1273}12741275void jq_set_attr(jq_state *jq, jv attr, jv val) {1276  jq->attrs = jv_object_set(jq->attrs, attr, val);1277}12781279jv jq_get_attr(jq_state *jq, jv attr) {1280  return jv_object_get(jv_copy(jq->attrs), attr);1281}12821283void jq_dump_disassembly(jq_state *jq, int indent) {1284  dump_disassembly(indent, jq->bc);1285}12861287void jq_set_input_cb(jq_state *jq, jq_input_cb cb, void *data) {1288  jq->input_cb = cb;1289  jq->input_cb_data = data;1290}12911292void jq_get_input_cb(jq_state *jq, jq_input_cb *cb, void **data) {1293  *cb = jq->input_cb;1294  *data = jq->input_cb_data;1295}12961297void jq_set_debug_cb(jq_state *jq, jq_msg_cb cb, void *data) {1298  jq->debug_cb = cb;1299  jq->debug_cb_data = data;1300}13011302void jq_get_debug_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1303  *cb = jq->debug_cb;1304  *data = jq->debug_cb_data;1305}13061307void jq_set_stderr_cb(jq_state *jq, jq_msg_cb cb, void *data) {1308  jq->stderr_cb = cb;1309  jq->stderr_cb_data = data;1310}13111312void jq_get_stderr_cb(jq_state *jq, jq_msg_cb *cb, void **data) {1313  *cb = jq->stderr_cb;1314  *data = jq->stderr_cb_data;1315}13161317void1318jq_halt(jq_state *jq, jv exit_code, jv error_message)1319{1320  assert(!jq->halted);1321  jq->halted = 1;1322  jq->exit_code = exit_code;1323  jq->error_message = error_message;1324}13251326int1327jq_halted(jq_state *jq)1328{1329  return jq->halted;1330}13311332jv jq_get_exit_code(jq_state *jq)1333{1334  return jv_copy(jq->exit_code);1335}13361337jv jq_get_error_message(jq_state *jq)1338{1339  return jv_copy(jq->error_message);1340}