aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/jq/execute.zig
blob: 380e5bedd10c8856a5420df807938107dff3688d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
const std = @import("std");
const jv = @import("../jv.zig");
const tokenize = @import("./tokenize.zig").tokenize;
const parse = @import("./parse.zig").parse;
const Instr = @import("./compile.zig").Instr;
const compile = @import("./compile.zig").compile;

pub const ExecuteError = error{
    Unimplemented,
    InvalidType,
    InternalError,
};

const SaveableStack = @import("./saveable_stack.zig").SaveableStack;

const ValueStack = struct {
    const Self = @This();
    const Stack = SaveableStack(jv.Value);

    stack: Stack,

    pub fn init(allocator: std.mem.Allocator) !Self {
        return .{
            .stack = try Stack.init(allocator),
        };
    }

    pub fn deinit(self: *Self) void {
        self.stack.deinit();
    }

    pub fn push(self: *Self, value: jv.Value) !void {
        try self.stack.push(value);
    }

    pub fn pop(self: *Self) jv.Value {
        return self.stack.pop();
    }

    pub fn popInteger(self: *Self) ExecuteError!i64 {
        const value = self.pop();
        return switch (value) {
            .integer => |i| i,
            else => error.InvalidType,
        };
    }

    pub fn popNumber(self: *Self) ExecuteError!f64 {
        const value = self.pop();
        return switch (value) {
            .integer => |i| @floatFromInt(i),
            .float => |f| f,
            else => error.InvalidType,
        };
    }

    pub fn popString(self: *Self) ExecuteError![]const u8 {
        const value = self.pop();
        return switch (value) {
            .string => |s| s,
            else => error.InvalidType,
        };
    }

    pub fn popArray(self: *Self) ExecuteError!jv.Array {
        const value = self.pop();
        return switch (value) {
            .array => |a| a,
            else => error.InvalidType,
        };
    }

    pub fn popObject(self: *Self) ExecuteError!jv.Object {
        const value = self.pop();
        return switch (value) {
            .object => |o| o,
            else => error.InvalidType,
        };
    }

    pub fn dup(self: *Self) !void {
        const top = self.stack.top().*;
        try self.push(top);
    }

    pub fn swap(self: *Self) !void {
        std.debug.assert(self.ensureSize(2));

        const a = self.pop();
        const b = self.pop();
        try self.push(a);
        try self.push(b);
    }

    pub fn save(self: *Self) !void {
        try self.stack.save();
    }

    pub fn restore(self: *Self) void {
        self.stack.restore();
    }

    pub fn ensureSize(self: *Self, n: usize) bool {
        return self.stack.ensureSize(n);
    }
};

pub const Runtime = struct {
    const Self = @This();

    allocator: std.mem.Allocator,
    values: ValueStack,
    forks: std.ArrayList(usize),
    instrs: []const Instr,
    pc: usize,

    pub fn init(allocator: std.mem.Allocator) !Self {
        return .{
            .allocator = allocator,
            .values = try ValueStack.init(allocator),
            .forks = .{},
            .instrs = &[_]Instr{},
            .pc = 0,
        };
    }

    pub fn deinit(self: *Self) void {
        for (self.instrs) |instr| {
            instr.deinit(self.allocator);
        }
        self.allocator.free(self.instrs);

        self.values.deinit();
        self.forks.deinit(self.allocator);
    }

    pub fn compileFromReader(self: *Self, reader: *std.Io.Reader) !void {
        std.debug.assert(self.instrs.len == 0);

        var compile_allocator = std.heap.ArenaAllocator.init(self.allocator);
        defer compile_allocator.deinit();
        const tokens = try tokenize(compile_allocator.allocator(), reader);
        const ast = try parse(self.allocator, compile_allocator.allocator(), tokens);
        const instrs = try compile(self.allocator, compile_allocator.allocator(), ast);
        self.instrs = instrs;
        // std.debug.print("BEGIN\n", .{});
        // for (self.instrs) |instr| {
        //     std.debug.print("{}\n", .{instr});
        // }
        // std.debug.print("END\n", .{});
    }

    pub fn compileFromSlice(self: *Self, query: []const u8) !void {
        var reader = std.Io.Reader.fixed(query);
        return self.compileFromReader(&reader);
    }

    pub fn start(self: *Self, input: jv.Value) !void {
        try self.values.push(input);
    }

    pub fn next(self: *Self) !?jv.Value {
        std.debug.assert(self.instrs.len > 0);

        self.restore_stack();

        while (self.pc < self.instrs.len) : (self.pc += 1) {
            const cur = self.instrs[self.pc];
            // std.debug.print("{}\n", .{cur});
            switch (cur) {
                .nop => {},
                .ret => {
                    self.pc += 1;
                    return self.values.pop();
                },
                .jump => |offset| {
                    self.pc += offset - 1;
                },
                .fork => |offset| {
                    try self.save_stack(self.pc + offset);
                },
                .subexp_begin => try self.values.dup(),
                .subexp_end => try self.values.swap(),
                .array_index => {
                    std.debug.assert(self.values.ensureSize(2));

                    const array = try self.values.popArray();
                    const index: usize = @intCast(try self.values.popInteger());
                    const result = if (index < array.items.len) array.items[index] else .null;
                    try self.values.push(result);
                },
                .add => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = try self.values.popInteger();
                    const rhs = try self.values.popInteger();
                    const result = lhs + rhs;
                    try self.values.push(.{ .integer = result });
                },
                .sub => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = try self.values.popInteger();
                    const rhs = try self.values.popInteger();
                    const result = lhs - rhs;
                    try self.values.push(.{ .integer = result });
                },
                .mul => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = try self.values.popInteger();
                    const rhs = try self.values.popInteger();
                    const result = lhs * rhs;
                    try self.values.push(.{ .integer = result });
                },
                .div => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = try self.values.popInteger();
                    const rhs = try self.values.popInteger();
                    const result = @divTrunc(lhs, rhs);
                    try self.values.push(.{ .integer = result });
                },
                .mod => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = try self.values.popInteger();
                    const rhs = try self.values.popInteger();
                    const result = @mod(lhs, rhs);
                    try self.values.push(.{ .integer = result });
                },
                .eq => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .eq);
                    try self.values.push(.{ .bool = result });
                },
                .ne => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .ne);
                    try self.values.push(.{ .bool = result });
                },
                .lt => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .lt);
                    try self.values.push(.{ .bool = result });
                },
                .gt => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .gt);
                    try self.values.push(.{ .bool = result });
                },
                .le => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .le);
                    try self.values.push(.{ .bool = result });
                },
                .ge => {
                    std.debug.assert(self.values.ensureSize(3));

                    _ = self.values.pop();
                    const lhs = self.values.pop();
                    const rhs = self.values.pop();
                    const result = try compareValues(lhs, rhs, .ge);
                    try self.values.push(.{ .bool = result });
                },
                .object_key => |key| {
                    std.debug.assert(self.values.ensureSize(1));

                    const obj = try self.values.popObject();
                    const result = obj.get(key) orelse .null;
                    try self.values.push(result);
                },
                .literal => |value| {
                    std.debug.assert(self.values.ensureSize(1));

                    _ = self.values.pop();
                    try self.values.push(value.*);
                },
            }
        }

        return null;
    }

    fn save_stack(self: *Self, target_pc: usize) !void {
        try self.forks.append(self.allocator, target_pc);
        try self.values.save();
    }

    fn restore_stack(self: *Self) void {
        if (self.forks.pop()) |target_pc| {
            self.pc = target_pc;
            self.values.restore();
        }
    }
};

const CompareOp = enum { eq, ne, lt, gt, le, ge };

fn compareValues(lhs: jv.Value, rhs: jv.Value, op: CompareOp) ExecuteError!bool {
    const lhs_tag = std.meta.activeTag(lhs);
    const rhs_tag = std.meta.activeTag(rhs);

    if (lhs_tag != rhs_tag) {
        const lhs_is_number = lhs_tag == .integer or lhs_tag == .float;
        const rhs_is_number = rhs_tag == .integer or rhs_tag == .float;
        if (lhs_is_number and rhs_is_number) {
            return compareNumbers(lhs, rhs, op);
        }
        return error.InvalidType;
    }

    return switch (lhs) {
        .null => switch (op) {
            .eq => true,
            .ne => false,
            .lt, .gt, .le, .ge => error.Unimplemented,
        },
        .bool => |lhs_bool| {
            const rhs_bool = rhs.bool;
            return switch (op) {
                .eq => lhs_bool == rhs_bool,
                .ne => lhs_bool != rhs_bool,
                .lt, .gt, .le, .ge => error.Unimplemented,
            };
        },
        .integer, .float => compareNumbers(lhs, rhs, op),
        .string => |lhs_str| {
            const rhs_str = rhs.string;
            const order = std.mem.order(u8, lhs_str, rhs_str);
            return switch (op) {
                .eq => order == .eq,
                .ne => order != .eq,
                .lt => order == .lt,
                .gt => order == .gt,
                .le => order == .lt or order == .eq,
                .ge => order == .gt or order == .eq,
            };
        },
        .array => switch (op) {
            .eq, .ne => error.Unimplemented,
            .lt, .gt, .le, .ge => error.Unimplemented,
        },
        .object => switch (op) {
            .eq, .ne => error.Unimplemented,
            .lt, .gt, .le, .ge => error.Unimplemented,
        },
        .number_string => error.Unimplemented,
    };
}

fn compareNumbers(lhs: jv.Value, rhs: jv.Value, op: CompareOp) bool {
    const lhs_f: f64 = switch (lhs) {
        .integer => |i| @floatFromInt(i),
        .float => |f| f,
        else => unreachable,
    };
    const rhs_f: f64 = switch (rhs) {
        .integer => |i| @floatFromInt(i),
        .float => |f| f,
        else => unreachable,
    };
    return switch (op) {
        .eq => lhs_f == rhs_f,
        .ne => lhs_f != rhs_f,
        .lt => lhs_f < rhs_f,
        .gt => lhs_f > rhs_f,
        .le => lhs_f <= rhs_f,
        .ge => lhs_f >= rhs_f,
    };
}