~davbo/ubuntu/trusty/jq/merge-debian-changes

« back to all changes in this revision

Viewing changes to execute.c

  • Committer: David King
  • Date: 2017-04-12 15:47:07 UTC
  • mto: This revision was merged to the branch mainline in revision 6.
  • Revision ID: dave@davbo.org-20170412154707-qq74qifqttlcqb3r
Tags: upstream-1.4
ImportĀ upstreamĀ versionĀ 1.4

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#include <assert.h>
 
2
#include <errno.h>
 
3
#include <stdarg.h>
2
4
#include <stdio.h>
3
5
#include <stdlib.h>
4
6
#include <stdint.h>
5
7
 
6
 
#include "execute.h"
7
 
 
8
 
#include "opcode.h"
 
8
#include "exec_stack.h"
9
9
#include "bytecode.h"
10
10
 
11
 
#include "forkable_stack.h"
12
 
#include "frame_layout.h"
13
 
 
14
11
#include "jv_alloc.h"
15
12
#include "jq_parser.h"
16
13
#include "locfile.h"
17
14
#include "jv.h"
18
 
#include "jv_aux.h"
 
15
#include "jq.h"
19
16
#include "parser.h"
20
17
#include "builtin.h"
21
18
 
22
19
struct jq_state {
23
 
  struct forkable_stack data_stk;
24
 
  struct forkable_stack frame_stk;
25
 
  struct forkable_stack fork_stk;
 
20
  void (*nomem_handler)(void *);
 
21
  void *nomem_handler_data;
 
22
  struct bytecode* bc;
 
23
 
 
24
  jq_err_cb err_cb;
 
25
  void *err_cb_data;
 
26
 
 
27
  struct stack stk;
 
28
  stack_ptr curr_frame;
 
29
  stack_ptr stk_top;
 
30
  stack_ptr fork_top;
 
31
 
26
32
  jv path;
27
33
  int subexp_nest;
28
34
  int debug_trace_enabled;
29
35
  int initial_execution;
30
36
};
31
37
 
32
 
typedef struct {
33
 
  FORKABLE_STACK_HEADER;
34
 
  jv val;
35
 
} data_stk_elem;
 
38
struct closure {
 
39
  struct bytecode* bc;
 
40
  stack_ptr env;
 
41
};
 
42
 
 
43
union frame_entry {
 
44
  struct closure closure;
 
45
  jv localvar;
 
46
};
 
47
 
 
48
struct frame {
 
49
  struct bytecode* bc;
 
50
  stack_ptr env;
 
51
  stack_ptr retdata;
 
52
  uint16_t* retaddr;
 
53
  /* bc->nclosures closures followed by bc->nlocals local variables */
 
54
  union frame_entry entries[0]; 
 
55
};
 
56
 
 
57
static int frame_size(struct bytecode* bc) {
 
58
  return sizeof(struct frame) + sizeof(union frame_entry) * (bc->nclosures + bc->nlocals);
 
59
}
 
60
 
 
61
static struct frame* frame_current(struct jq_state* jq) {
 
62
  struct frame* fp = stack_block(&jq->stk, jq->curr_frame);
 
63
 
 
64
  stack_ptr next = *stack_block_next(&jq->stk, jq->curr_frame);
 
65
  if (next) {
 
66
    struct frame* fpnext = stack_block(&jq->stk, next);
 
67
    struct bytecode* bc = fpnext->bc;
 
68
    assert(fp->retaddr >= bc->code && fp->retaddr < bc->code + bc->codelen);
 
69
  } else {
 
70
    assert(fp->retaddr == 0);
 
71
  }
 
72
  return fp;
 
73
}
 
74
 
 
75
static stack_ptr frame_get_level(struct jq_state* jq, int level) {
 
76
  stack_ptr fr = jq->curr_frame;
 
77
  for (int i=0; i<level; i++) {
 
78
    struct frame* fp = stack_block(&jq->stk, fr);
 
79
    fr = fp->env;
 
80
  }
 
81
  return fr;
 
82
}
 
83
 
 
84
static jv* frame_local_var(struct jq_state* jq, int var, int level) {
 
85
  struct frame* fr = stack_block(&jq->stk, frame_get_level(jq, level));
 
86
  assert(var >= 0);
 
87
  assert(var < fr->bc->nlocals);
 
88
  return &fr->entries[fr->bc->nclosures + var].localvar;
 
89
}
 
90
 
 
91
static struct closure make_closure(struct jq_state* jq, uint16_t* pc) {
 
92
  uint16_t level = *pc++;
 
93
  uint16_t idx = *pc++;
 
94
  stack_ptr fridx = frame_get_level(jq, level);
 
95
  struct frame* fr = stack_block(&jq->stk, fridx);
 
96
  if (idx & ARG_NEWCLOSURE) {
 
97
    int subfn_idx = idx & ~ARG_NEWCLOSURE;
 
98
    assert(subfn_idx < fr->bc->nsubfunctions);
 
99
    struct closure cl = {fr->bc->subfunctions[subfn_idx],
 
100
                         fridx};
 
101
    return cl;
 
102
  } else {
 
103
    int closure = idx;
 
104
    assert(closure >= 0);
 
105
    assert(closure < fr->bc->nclosures);
 
106
    return fr->entries[closure].closure;
 
107
  }
 
108
}
 
109
 
 
110
static struct frame* frame_push(struct jq_state* jq, struct closure callee, 
 
111
                                uint16_t* argdef, int nargs) {
 
112
  stack_ptr new_frame_idx = stack_push_block(&jq->stk, jq->curr_frame, frame_size(callee.bc));
 
113
  struct frame* new_frame = stack_block(&jq->stk, new_frame_idx);
 
114
  new_frame->bc = callee.bc;
 
115
  new_frame->env = callee.env;
 
116
  assert(nargs == new_frame->bc->nclosures);
 
117
  union frame_entry* entries = new_frame->entries;
 
118
  for (int i=0; i<nargs; i++) {
 
119
    entries->closure = make_closure(jq, argdef + i * 2);
 
120
    entries++;
 
121
  }
 
122
  for (int i=0; i<callee.bc->nlocals; i++) {
 
123
    entries->localvar = jv_invalid();
 
124
    entries++;
 
125
  }
 
126
  jq->curr_frame = new_frame_idx;
 
127
  return new_frame;
 
128
}
 
129
 
 
130
static void frame_pop(struct jq_state* jq) {
 
131
  assert(jq->curr_frame);
 
132
  struct frame* fp = frame_current(jq);
 
133
  if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {
 
134
    int nlocals = fp->bc->nlocals;
 
135
    for (int i=0; i<nlocals; i++) {
 
136
      jv_free(*frame_local_var(jq, i, 0));
 
137
    }
 
138
  }
 
139
  jq->curr_frame = stack_pop_block(&jq->stk, jq->curr_frame, frame_size(fp->bc));
 
140
}
36
141
 
37
142
void stack_push(jq_state *jq, jv val) {
38
143
  assert(jv_is_valid(val));
39
 
  data_stk_elem* s = forkable_stack_push(&jq->data_stk, sizeof(data_stk_elem));
40
 
  s->val = val;
 
144
  jq->stk_top = stack_push_block(&jq->stk, jq->stk_top, sizeof(jv));
 
145
  jv* sval = stack_block(&jq->stk, jq->stk_top);
 
146
  *sval = val;
41
147
}
42
148
 
43
149
jv stack_pop(jq_state *jq) {
44
 
  data_stk_elem* s = forkable_stack_peek(&jq->data_stk);
45
 
  jv val = s->val;
46
 
  if (!forkable_stack_pop_will_free(&jq->data_stk)) {
 
150
  jv* sval = stack_block(&jq->stk, jq->stk_top);
 
151
  jv val = *sval;
 
152
  if (!stack_pop_will_free(&jq->stk, jq->stk_top)) {
47
153
    val = jv_copy(val);
48
154
  }
49
 
  forkable_stack_pop(&jq->data_stk);
 
155
  jq->stk_top = stack_pop_block(&jq->stk, jq->stk_top, sizeof(jv));
50
156
  assert(jv_is_valid(val));
51
157
  return val;
52
158
}
53
159
 
54
160
 
55
161
struct forkpoint {
56
 
  FORKABLE_STACK_HEADER;
57
 
  struct forkable_stack_state saved_data_stack;
58
 
  struct forkable_stack_state saved_call_stack;
 
162
  stack_ptr saved_data_stack;
 
163
  stack_ptr saved_curr_frame;
59
164
  int path_len, subexp_nest;
60
165
  uint16_t* return_address;
61
166
};
62
167
 
63
 
 
64
 
void stack_save(jq_state *jq, uint16_t* retaddr){
65
 
  struct forkpoint* fork = forkable_stack_push(&jq->fork_stk, sizeof(struct forkpoint));
66
 
  forkable_stack_save(&jq->data_stk, &fork->saved_data_stack);
67
 
  forkable_stack_save(&jq->frame_stk, &fork->saved_call_stack);
 
168
struct stack_pos {
 
169
  stack_ptr saved_data_stack, saved_curr_frame;
 
170
};
 
171
 
 
172
struct stack_pos stack_get_pos(jq_state* jq) {
 
173
  struct stack_pos sp = {jq->stk_top, jq->curr_frame};
 
174
  return sp;
 
175
}
 
176
 
 
177
void stack_save(jq_state *jq, uint16_t* retaddr, struct stack_pos sp){
 
178
  jq->fork_top = stack_push_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));
 
179
  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);
 
180
  fork->saved_data_stack = jq->stk_top;
 
181
  fork->saved_curr_frame = jq->curr_frame;
68
182
  fork->path_len = 
69
183
    jv_get_kind(jq->path) == JV_KIND_ARRAY ? jv_array_length(jv_copy(jq->path)) : 0;
70
184
  fork->subexp_nest = jq->subexp_nest;
71
185
  fork->return_address = retaddr;
72
 
}
73
 
 
74
 
void stack_switch(jq_state *jq) {
75
 
  struct forkpoint* fork = forkable_stack_peek(&jq->fork_stk);
76
 
  forkable_stack_switch(&jq->data_stk, &fork->saved_data_stack);
77
 
  forkable_stack_switch(&jq->frame_stk, &fork->saved_call_stack);
 
186
  jq->stk_top = sp.saved_data_stack;
 
187
  jq->curr_frame = sp.saved_curr_frame;
78
188
}
79
189
 
80
190
void path_append(jq_state* jq, jv component) {
89
199
}
90
200
 
91
201
uint16_t* stack_restore(jq_state *jq){
92
 
  while (!forkable_stack_empty(&jq->data_stk) && 
93
 
         forkable_stack_pop_will_free(&jq->data_stk)) {
94
 
    jv_free(stack_pop(jq));
95
 
  }
96
 
  while (!forkable_stack_empty(&jq->frame_stk) && 
97
 
         forkable_stack_pop_will_free(&jq->frame_stk)) {
98
 
    frame_pop(&jq->frame_stk);
 
202
  while (!stack_pop_will_free(&jq->stk, jq->fork_top)) {
 
203
    if (stack_pop_will_free(&jq->stk, jq->stk_top)) {
 
204
      jv_free(stack_pop(jq));
 
205
    } else if (stack_pop_will_free(&jq->stk, jq->curr_frame)) {
 
206
      frame_pop(jq);
 
207
    } else {
 
208
      assert(0);
 
209
    }
99
210
  }
100
211
 
101
 
  if (forkable_stack_empty(&jq->fork_stk)) {
 
212
  if (jq->fork_top == 0) {
102
213
    return 0;
103
214
  }
104
215
 
105
 
  struct forkpoint* fork = forkable_stack_peek(&jq->fork_stk);
 
216
  struct forkpoint* fork = stack_block(&jq->stk, jq->fork_top);
106
217
  uint16_t* retaddr = fork->return_address;
107
 
  forkable_stack_restore(&jq->data_stk, &fork->saved_data_stack);
108
 
  forkable_stack_restore(&jq->frame_stk, &fork->saved_call_stack);
 
218
  jq->stk_top = fork->saved_data_stack;
 
219
  jq->curr_frame = fork->saved_curr_frame;
109
220
  int path_len = fork->path_len;
110
221
  if (jv_get_kind(jq->path) == JV_KIND_ARRAY) {
111
222
    assert(path_len >= 0);
114
225
    assert(path_len == 0);
115
226
  }
116
227
  jq->subexp_nest = fork->subexp_nest;
117
 
  forkable_stack_pop(&jq->fork_stk);
 
228
  jq->fork_top = stack_pop_block(&jq->stk, jq->fork_top, sizeof(struct forkpoint));
118
229
  return retaddr;
119
230
}
120
231
 
121
 
 
122
 
static struct closure make_closure(struct forkable_stack* stk, frame_ptr fr, uint16_t* pc) {
123
 
  uint16_t level = *pc++;
124
 
  uint16_t idx = *pc++;
125
 
  fr = frame_get_level(stk, fr, level);
126
 
  if (idx & ARG_NEWCLOSURE) {
127
 
    int subfn_idx = idx & ~ARG_NEWCLOSURE;
128
 
    assert(subfn_idx < frame_self(fr)->bc->nsubfunctions);
129
 
    struct closure cl = {frame_self(fr)->bc->subfunctions[subfn_idx],
130
 
                         forkable_stack_to_idx(stk, fr)};
131
 
    return cl;
132
 
  } else {
133
 
    return *frame_closure_arg(fr, idx);
134
 
  }
 
232
static void jq_reset(jq_state *jq) {
 
233
  while (stack_restore(jq)) {}
 
234
 
 
235
  assert(jq->stk_top == 0);
 
236
  assert(jq->fork_top == 0);
 
237
  assert(jq->curr_frame == 0);
 
238
  stack_reset(&jq->stk);
 
239
 
 
240
  if (jv_get_kind(jq->path) != JV_KIND_INVALID)
 
241
    jv_free(jq->path);
 
242
  jq->path = jv_null();
 
243
  jq->subexp_nest = 0;
135
244
}
136
245
 
137
 
void print_error(jv value) {
 
246
static void print_error(jq_state *jq, jv value) {
138
247
  assert(!jv_is_valid(value));
139
248
  jv msg = jv_invalid_get_msg(value);
140
 
  if (jv_get_kind(msg) == JV_KIND_STRING) {
141
 
    fprintf(stderr, "jq: error: %s\n", jv_string_value(msg));
142
 
  }
 
249
  jv msg2;
 
250
  if (jv_get_kind(msg) == JV_KIND_STRING)
 
251
    msg2 = jv_string_fmt("jq: error: %s", jv_string_value(msg));
 
252
  else
 
253
    msg2 = jv_string_fmt("jq: error: <unknown>");
143
254
  jv_free(msg);
 
255
 
 
256
  if (jq->err_cb)
 
257
    jq->err_cb(jq->err_cb_data, msg2);
 
258
  else if (jv_get_kind(msg2) == JV_KIND_STRING)
 
259
    fprintf(stderr, "%s\n", jv_string_value(msg2));
 
260
  else
 
261
    fprintf(stderr, "jq: error: %s\n", strerror(ENOMEM));
 
262
  jv_free(msg2);
144
263
}
145
264
#define ON_BACKTRACK(op) ((op)+NUM_OPCODES)
146
265
 
147
266
jv jq_next(jq_state *jq) {
148
267
  jv cfunc_input[MAX_CFUNCTION_ARGS];
149
268
 
 
269
  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);
 
270
 
150
271
  uint16_t* pc = stack_restore(jq);
151
272
  assert(pc);
152
273
 
156
277
    uint16_t opcode = *pc;
157
278
 
158
279
    if (jq->debug_trace_enabled) {
159
 
      dump_operation(frame_current_bytecode(&jq->frame_stk), pc);
 
280
      dump_operation(frame_current(jq)->bc, pc);
160
281
      printf("\t");
161
282
      const struct opcode_description* opdesc = opcode_describe(opcode);
162
 
      data_stk_elem* param = 0;
163
 
      int stack_in = opdesc->stack_in;
164
 
      if (stack_in == -1) stack_in = pc[1];
165
 
      for (int i=0; i<stack_in; i++) {
166
 
        if (i == 0) {
167
 
          param = forkable_stack_peek(&jq->data_stk);
168
 
        } else {
169
 
          printf(" | ");
170
 
          param = forkable_stack_peek_next(&jq->data_stk, param);
 
283
      stack_ptr param = 0;
 
284
      if (!backtracking) {
 
285
        int stack_in = opdesc->stack_in;
 
286
        if (stack_in == -1) stack_in = pc[1];
 
287
        for (int i=0; i<stack_in; i++) {
 
288
          if (i == 0) {
 
289
            param = jq->stk_top;
 
290
          } else {
 
291
            printf(" | ");
 
292
            param = *stack_block_next(&jq->stk, param);
 
293
          }
 
294
          if (!param) break;
 
295
          jv_dump(jv_copy(*(jv*)stack_block(&jq->stk, param)), 0);
 
296
          //printf("<%d>", jv_get_refcnt(param->val));
 
297
          //printf(" -- ");
 
298
          //jv_dump(jv_copy(jq->path), 0);
171
299
        }
172
 
        if (!param) break;
173
 
        jv_dump(jv_copy(param->val), 0);
174
 
        //printf("<%d>", jv_get_refcnt(param->val));
175
 
        //printf(" -- ");
176
 
        //jv_dump(jv_copy(jq->path), 0);
 
300
      } else {
 
301
        printf("\t<backtracking>");
177
302
      }
178
303
 
179
 
      if (backtracking) printf("\t<backtracking>");
180
 
 
181
304
      printf("\n");
182
305
    }
 
306
 
183
307
    if (backtracking) {
184
308
      opcode = ON_BACKTRACK(opcode);
185
309
      backtracking = 0;
190
314
    default: assert(0 && "invalid instruction");
191
315
 
192
316
    case LOADK: {
193
 
      jv v = jv_array_get(jv_copy(frame_current_bytecode(&jq->frame_stk)->constants), *pc++);
 
317
      jv v = jv_array_get(jv_copy(frame_current(jq)->bc->constants), *pc++);
194
318
      assert(jv_is_valid(v));
195
319
      jv_free(stack_pop(jq));
196
320
      stack_push(jq, v);
240
364
      jv v = stack_pop(jq);
241
365
      uint16_t level = *pc++;
242
366
      uint16_t vidx = *pc++;
243
 
      frame_ptr fp = frame_get_level(&jq->frame_stk, frame_current(&jq->frame_stk), level);
244
 
      jv* var = frame_local_var(fp, vidx);
 
367
      jv* var = frame_local_var(jq, vidx, level);
245
368
      assert(jv_get_kind(*var) == JV_KIND_ARRAY);
246
369
      *var = jv_array_append(*var, v);
247
370
      break;
257
380
        stack_push(jq, jv_object_set(objv, k, v));
258
381
        stack_push(jq, stktop);
259
382
      } else {
260
 
        print_error(jv_invalid_with_msg(jv_string_fmt("Cannot use %s as object key",
261
 
                                                      jv_kind_name(jv_get_kind(k)))));
 
383
        print_error(jq, jv_invalid_with_msg(jv_string_fmt("Cannot use %s as object key",
 
384
                                                          jv_kind_name(jv_get_kind(k)))));
262
385
        jv_free(stktop);
263
386
        jv_free(v);
264
387
        jv_free(k);
272
395
    case RANGE: {
273
396
      uint16_t level = *pc++;
274
397
      uint16_t v = *pc++;
275
 
      frame_ptr fp = frame_get_level(&jq->frame_stk, frame_current(&jq->frame_stk), level);
276
 
      jv* var = frame_local_var(fp, v);
 
398
      jv* var = frame_local_var(jq, v, level);
277
399
      jv max = stack_pop(jq);
278
400
      if (jv_get_kind(*var) != JV_KIND_NUMBER ||
279
401
          jv_get_kind(max) != JV_KIND_NUMBER) {
280
 
        print_error(jv_invalid_with_msg(jv_string_fmt("Range bounds must be numeric")));
 
402
        print_error(jq, jv_invalid_with_msg(jv_string_fmt("Range bounds must be numeric")));
281
403
        jv_free(max);
282
404
        goto do_backtrack;
283
405
      } else if (jv_number_value(jv_copy(*var)) >= jv_number_value(jv_copy(max))) {
287
409
        jv curr = jv_copy(*var);
288
410
        *var = jv_number(jv_number_value(*var) + 1);
289
411
 
290
 
        stack_save(jq, pc - 3);
 
412
        struct stack_pos spos = stack_get_pos(jq);
291
413
        stack_push(jq, jv_copy(max));
292
 
        stack_switch(jq);
 
414
        stack_save(jq, pc - 3, spos);
 
415
 
293
416
        stack_push(jq, curr);
294
417
      }
295
418
      break;
299
422
    case LOADV: {
300
423
      uint16_t level = *pc++;
301
424
      uint16_t v = *pc++;
302
 
      frame_ptr fp = frame_get_level(&jq->frame_stk, frame_current(&jq->frame_stk), level);
303
 
      jv* var = frame_local_var(fp, v);
 
425
      jv* var = frame_local_var(jq, v, level);
304
426
      if (jq->debug_trace_enabled) {
305
427
        printf("V%d = ", v);
306
428
        jv_dump(jv_copy(*var), 0);
315
437
    case LOADVN: {
316
438
      uint16_t level = *pc++;
317
439
      uint16_t v = *pc++;
318
 
      frame_ptr fp = frame_get_level(&jq->frame_stk, frame_current(&jq->frame_stk), level);
319
 
      jv* var = frame_local_var(fp, v);
 
440
      jv* var = frame_local_var(jq, v, level);
320
441
      if (jq->debug_trace_enabled) {
321
442
        printf("V%d = ", v);
322
443
        jv_dump(jv_copy(*var), 0);
331
452
    case STOREV: {
332
453
      uint16_t level = *pc++;
333
454
      uint16_t v = *pc++;
334
 
      frame_ptr fp = frame_get_level(&jq->frame_stk, frame_current(&jq->frame_stk), level);
335
 
      jv* var = frame_local_var(fp, v);
 
455
      jv* var = frame_local_var(jq, v, level);
336
456
      jv val = stack_pop(jq);
337
457
      if (jq->debug_trace_enabled) {
338
458
        printf("V%d = ", v);
348
468
      jv v = stack_pop(jq);
349
469
      stack_push(jq, jq->path);
350
470
 
351
 
      stack_save(jq, pc - 1);
352
 
      stack_switch(jq);
 
471
      stack_save(jq, pc - 1, stack_get_pos(jq));
353
472
 
354
473
      stack_push(jq, jv_number(jq->subexp_nest));
355
474
      stack_push(jq, v);
368
487
      jv path = jq->path;
369
488
      jq->path = stack_pop(jq);
370
489
 
371
 
      stack_save(jq, pc - 1);
 
490
      struct stack_pos spos = stack_get_pos(jq);
372
491
      stack_push(jq, jv_copy(path));
373
 
      stack_switch(jq);
 
492
      stack_save(jq, pc - 1, spos);
374
493
 
375
494
      stack_push(jq, path);
376
495
      jq->subexp_nest = old_subexp_nest;
384
503
      goto do_backtrack;
385
504
    }
386
505
 
387
 
    case INDEX: {
 
506
    case INDEX:
 
507
    case INDEX_OPT: {
388
508
      jv t = stack_pop(jq);
389
509
      jv k = stack_pop(jq);
390
510
      path_append(jq, jv_copy(k));
392
512
      if (jv_is_valid(v)) {
393
513
        stack_push(jq, v);
394
514
      } else {
395
 
        print_error(v);
 
515
        if (opcode == INDEX)
 
516
          print_error(jq, v);
 
517
        else
 
518
          jv_free(v);
396
519
        goto do_backtrack;
397
520
      }
398
521
      break;
417
540
    }
418
541
 
419
542
    case EACH: 
 
543
    case EACH_OPT: 
420
544
      stack_push(jq, jv_number(-1));
421
545
      // fallthrough
422
 
    case ON_BACKTRACK(EACH): {
 
546
    case ON_BACKTRACK(EACH):
 
547
    case ON_BACKTRACK(EACH_OPT): {
423
548
      int idx = jv_number_value(stack_pop(jq));
424
549
      jv container = stack_pop(jq);
425
550
 
426
551
      int keep_going, is_last = 0;
427
552
      jv key, value;
428
553
      if (jv_get_kind(container) == JV_KIND_ARRAY) {
429
 
        if (opcode == EACH) idx = 0;
 
554
        if (opcode == EACH || opcode == EACH_OPT) idx = 0;
430
555
        else idx = idx + 1;
431
556
        int len = jv_array_length(jv_copy(container));
432
557
        keep_going = idx < len;
436
561
          value = jv_array_get(jv_copy(container), idx);
437
562
        }
438
563
      } else if (jv_get_kind(container) == JV_KIND_OBJECT) {
439
 
        if (opcode == EACH) idx = jv_object_iter(container);
 
564
        if (opcode == EACH || opcode == EACH_OPT) idx = jv_object_iter(container);
440
565
        else idx = jv_object_iter_next(container, idx);
441
566
        keep_going = jv_object_iter_valid(container, idx);
442
567
        if (keep_going) {
444
569
          value = jv_object_iter_value(container, idx);
445
570
        }
446
571
      } else {
447
 
        assert(opcode == EACH);
448
 
        print_error(jv_invalid_with_msg(jv_string_fmt("Cannot iterate over %s",
449
 
                                                      jv_kind_name(jv_get_kind(container)))));
 
572
        assert(opcode == EACH || opcode == EACH_OPT);
 
573
        if (opcode == EACH) {
 
574
          print_error(jq,
 
575
                      jv_invalid_with_msg(jv_string_fmt("Cannot iterate over %s",
 
576
                                                        jv_kind_name(jv_get_kind(container)))));
 
577
        }
450
578
        keep_going = 0;
451
579
      }
452
580
 
459
587
        path_append(jq, key);
460
588
        stack_push(jq, value);
461
589
      } else {
462
 
        stack_save(jq, pc - 1);
 
590
        struct stack_pos spos = stack_get_pos(jq);
463
591
        stack_push(jq, container);
464
592
        stack_push(jq, jv_number(idx));
465
 
        stack_switch(jq);
 
593
        stack_save(jq, pc - 1, spos);
466
594
        path_append(jq, key);
467
595
        stack_push(jq, value);
468
596
      }
480
608
    }
481
609
 
482
610
    case FORK: {
483
 
      stack_save(jq, pc - 1);
484
 
      stack_switch(jq);
 
611
      stack_save(jq, pc - 1, stack_get_pos(jq));
485
612
      pc++; // skip offset this time
486
613
      break;
487
614
    }
495
622
    case CALL_BUILTIN: {
496
623
      int nargs = *pc++;
497
624
      jv top = stack_pop(jq);
498
 
      cfunc_input[0] = top;
 
625
      jv* in = cfunc_input;
 
626
      in[0] = top;
499
627
      for (int i = 1; i < nargs; i++) {
500
 
        cfunc_input[i] = stack_pop(jq);
501
 
      }
502
 
      struct cfunction* func = &frame_current_bytecode(&jq->frame_stk)->globals->cfunctions[*pc++];
503
 
      top = cfunction_invoke(func, cfunc_input);
 
628
        in[i] = stack_pop(jq);
 
629
      }
 
630
      struct cfunction* function = &frame_current(jq)->bc->globals->cfunctions[*pc++];
 
631
      typedef jv (*func_1)(jv);
 
632
      typedef jv (*func_2)(jv,jv);
 
633
      typedef jv (*func_3)(jv,jv,jv);
 
634
      typedef jv (*func_4)(jv,jv,jv,jv);
 
635
      typedef jv (*func_5)(jv,jv,jv,jv,jv);
 
636
      switch (function->nargs) {
 
637
      case 1: top = ((func_1)function->fptr)(in[0]); break;
 
638
      case 2: top = ((func_2)function->fptr)(in[0], in[1]); break;
 
639
      case 3: top = ((func_3)function->fptr)(in[0], in[1], in[2]); break;
 
640
      case 4: top = ((func_4)function->fptr)(in[0], in[1], in[2], in[3]); break;
 
641
      case 5: top = ((func_5)function->fptr)(in[0], in[1], in[2], in[3], in[4]); break;
 
642
      default: return jv_invalid_with_msg(jv_string("Function takes too many arguments"));
 
643
      }
 
644
      
504
645
      if (jv_is_valid(top)) {
505
646
        stack_push(jq, top);
506
647
      } else {
507
 
        print_error(top);
 
648
        print_error(jq, top);
508
649
        goto do_backtrack;
509
650
      }
510
651
      break;
511
652
    }
512
653
 
513
654
    case CALL_JQ: {
 
655
      jv input = stack_pop(jq);
514
656
      uint16_t nclosures = *pc++;
515
657
      uint16_t* retaddr = pc + 2 + nclosures*2;
516
 
      frame_ptr new_frame = frame_push(&jq->frame_stk, 
517
 
                                       make_closure(&jq->frame_stk, frame_current(&jq->frame_stk), pc),
518
 
                                       retaddr);
519
 
      pc += 2;
520
 
      frame_ptr old_frame = forkable_stack_peek_next(&jq->frame_stk, new_frame);
521
 
      assert(nclosures == frame_self(new_frame)->bc->nclosures);
522
 
      for (int i=0; i<nclosures; i++) {
523
 
        *frame_closure_arg(new_frame, i) = make_closure(&jq->frame_stk, old_frame, pc);
524
 
        pc += 2;
525
 
      }
526
 
 
527
 
      pc = frame_current_bytecode(&jq->frame_stk)->code;
 
658
      struct frame* new_frame = frame_push(jq, make_closure(jq, pc),
 
659
                                           pc + 2, nclosures);
 
660
      new_frame->retdata = jq->stk_top;
 
661
      new_frame->retaddr = retaddr;
 
662
      pc = new_frame->bc->code;
 
663
      stack_push(jq, input);
528
664
      break;
529
665
    }
530
666
 
531
667
    case RET: {
532
 
      uint16_t* retaddr = *frame_current_retaddr(&jq->frame_stk);
 
668
      jv value = stack_pop(jq);
 
669
      assert(jq->stk_top == frame_current(jq)->retdata);
 
670
      uint16_t* retaddr = frame_current(jq)->retaddr;
533
671
      if (retaddr) {
534
672
        // function return
535
673
        pc = retaddr;
536
 
        frame_pop(&jq->frame_stk);
 
674
        frame_pop(jq);
537
675
      } else {
538
676
        // top-level return, yielding value
539
 
        jv value = stack_pop(jq);
540
 
        stack_save(jq, pc - 1);
 
677
        struct stack_pos spos = stack_get_pos(jq);
541
678
        stack_push(jq, jv_null());
542
 
        stack_switch(jq);
 
679
        stack_save(jq, pc - 1, spos);
543
680
        return value;
544
681
      }
 
682
      stack_push(jq, value);
545
683
      break;
546
684
    }
547
685
    case ON_BACKTRACK(RET): {
552
690
  }
553
691
}
554
692
 
555
 
 
556
 
void jq_init(struct bytecode* bc, jv input, jq_state **jq, int flags) {
557
 
  jq_state *new_jq;
558
 
  new_jq = jv_mem_alloc(sizeof(*new_jq));
559
 
  memset(new_jq, 0, sizeof(*new_jq));
560
 
  new_jq->path = jv_null();
561
 
  forkable_stack_init(&new_jq->data_stk, sizeof(data_stk_elem) * 100);
562
 
  forkable_stack_init(&new_jq->frame_stk, 1024);
563
 
  forkable_stack_init(&new_jq->fork_stk, 1024);
 
693
jq_state *jq_init(void) {
 
694
  jq_state *jq;
 
695
  jq = jv_mem_alloc_unguarded(sizeof(*jq));
 
696
  if (jq == NULL)
 
697
    return NULL;
 
698
 
 
699
  jq->bc = 0;
 
700
 
 
701
  stack_init(&jq->stk);
 
702
  jq->stk_top = 0;
 
703
  jq->fork_top = 0;
 
704
  jq->curr_frame = 0;
 
705
 
 
706
  jq->err_cb = NULL;
 
707
  jq->err_cb_data = NULL;
 
708
 
 
709
  jq->path = jv_null();
 
710
  return jq;
 
711
}
 
712
 
 
713
void jq_set_error_cb(jq_state *jq, jq_err_cb cb, void *data) {
 
714
  jq->err_cb = cb;
 
715
  jq->err_cb_data = data;
 
716
}
 
717
 
 
718
void jq_get_error_cb(jq_state *jq, jq_err_cb *cb, void **data) {
 
719
  *cb = jq->err_cb;
 
720
  *data = jq->err_cb_data;
 
721
}
 
722
 
 
723
void jq_set_nomem_handler(jq_state *jq, void (*nomem_handler)(void *), void *data) {
 
724
  jv_nomem_handler(nomem_handler, data);
 
725
  jq->nomem_handler = nomem_handler;
 
726
  jq->nomem_handler_data = data;
 
727
}
 
728
 
 
729
 
 
730
void jq_start(jq_state *jq, jv input, int flags) {
 
731
  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);
 
732
  jq_reset(jq);
564
733
  
565
 
  stack_push(new_jq, input);
566
 
  struct closure top = {bc, -1};
567
 
  frame_push(&new_jq->frame_stk, top, 0);
568
 
  stack_save(new_jq, bc->code);
569
 
  stack_switch(new_jq);
 
734
  struct closure top = {jq->bc, -1};
 
735
  struct frame* top_frame = frame_push(jq, top, 0, 0);
 
736
  top_frame->retdata = 0;
 
737
  top_frame->retaddr = 0;
 
738
 
 
739
  stack_push(jq, input);
 
740
  stack_save(jq, jq->bc->code, stack_get_pos(jq));
570
741
  if (flags & JQ_DEBUG_TRACE) {
571
 
    new_jq->debug_trace_enabled = 1;
 
742
    jq->debug_trace_enabled = 1;
572
743
  } else {
573
 
    new_jq->debug_trace_enabled = 0;
 
744
    jq->debug_trace_enabled = 0;
574
745
  }
575
 
  new_jq->initial_execution = 1;
576
 
  *jq = new_jq;
 
746
  jq->initial_execution = 1;
577
747
}
578
748
 
579
749
void jq_teardown(jq_state **jq) {
582
752
    return;
583
753
  *jq = NULL;
584
754
 
585
 
  while (stack_restore(old_jq)) {}
586
 
 
587
 
  assert(forkable_stack_empty(&old_jq->fork_stk));
588
 
  assert(forkable_stack_empty(&old_jq->data_stk));
589
 
  assert(forkable_stack_empty(&old_jq->frame_stk));
590
 
  forkable_stack_free(&old_jq->fork_stk);
591
 
  forkable_stack_free(&old_jq->data_stk);
592
 
  forkable_stack_free(&old_jq->frame_stk);
593
 
 
594
 
  jv_free(old_jq->path);
 
755
  jq_reset(old_jq);
 
756
  bytecode_free(old_jq->bc);
 
757
  old_jq->bc = 0;
 
758
 
595
759
  jv_mem_free(old_jq);
596
760
}
597
761
 
598
 
struct bytecode* jq_compile_args(const char* str, jv args) {
 
762
int jq_compile_args(jq_state *jq, const char* str, jv args) {
 
763
  jv_nomem_handler(jq->nomem_handler, jq->nomem_handler_data);
599
764
  assert(jv_get_kind(args) == JV_KIND_ARRAY);
600
765
  struct locfile locations;
601
 
  locfile_init(&locations, str, strlen(str));
 
766
  locfile_init(&locations, jq, str, strlen(str));
602
767
  block program;
603
 
  struct bytecode* bc = 0;
 
768
  jq_reset(jq);
 
769
  if (jq->bc) {
 
770
    bytecode_free(jq->bc);
 
771
    jq->bc = 0;
 
772
  }
604
773
  int nerrors = jq_parse(&locations, &program);
605
774
  if (nerrors == 0) {
606
775
    for (int i=0; i<jv_array_length(jv_copy(args)); i++) {
610
779
      program = gen_var_binding(gen_const(value), jv_string_value(name), program);
611
780
      jv_free(name);
612
781
    }
613
 
    jv_free(args);
614
 
    program = builtins_bind(program);
615
 
    nerrors = block_compile(program, &locations, &bc);
 
782
    nerrors = builtins_bind(jq, &program);
 
783
    if (nerrors == 0) {
 
784
      nerrors = block_compile(program, &locations, &jq->bc);
 
785
    }
616
786
  }
 
787
  jv_free(args);
617
788
  if (nerrors) {
618
 
    fprintf(stderr, "%d compile %s\n", nerrors, nerrors > 1 ? "errors" : "error");
 
789
    jv s = jv_string_fmt("%d compile %s", nerrors,
 
790
                         nerrors > 1 ? "errors" : "error");
 
791
    if (jq->err_cb != NULL)
 
792
      jq->err_cb(jq->err_cb_data, s);
 
793
    else if (!jv_is_valid(s))
 
794
      fprintf(stderr, "Error formatting jq compilation errors: %s\n", strerror(errno));
 
795
    else
 
796
      fprintf(stderr, "%s\n", jv_string_value(s));
 
797
    jv_free(s);
619
798
  }
620
799
  locfile_free(&locations);
621
 
  return bc;
622
 
}
623
 
 
624
 
struct bytecode* jq_compile(const char* str) {
625
 
  return jq_compile_args(str, jv_array());
 
800
  return jq->bc != NULL;
 
801
}
 
802
 
 
803
int jq_compile(jq_state *jq, const char* str) {
 
804
  return jq_compile_args(jq, str, jv_array());
 
805
}
 
806
 
 
807
void jq_dump_disassembly(jq_state *jq, int indent) {
 
808
  dump_disassembly(indent, jq->bc);
626
809
}