aboutsummaryrefslogtreecommitdiff
path: root/src/pointer.zig
blob: dcbca46edb6c614d94e9f3d8f85731b79ed4a753 (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
const std = @import("std");
const defaultIO = @import("defaultIO.zig");
const field = @import("field.zig");
const stackStack = @import("stackStack.zig");

const vector = std.meta.Vector(2, i64);

const pointerErrorType = error{ EmptyFieldError, IOError, NotImplemented, OutOfMemory };

const pointerReturn = struct {
    code: ?i64 = null,
};

pub const IOFunctions = struct {
    characterInput: fn () defaultIO.IOErrors!i64 = defaultIO.characterInput,
    decimalInput: fn () defaultIO.IOErrors!i64 = defaultIO.decimalInput,
    characterOutput: fn (i64) defaultIO.IOErrors!void = defaultIO.characterOutput,
    decimalOutput: fn (i64) defaultIO.IOErrors!void = defaultIO.decimalOutput,
};

pub const Pointer = struct {
    allocator: std.mem.Allocator,
    field: *field.Field,
    x: i64 = 0, // The position
    y: i64 = 0,
    dx: i64 = 1, // The traveling delta
    dy: i64 = 0,
    sox: i64 = 0, // The storage offset
    soy: i64 = 0,
    stringMode: bool = false, // string mode flags
    lastCharWasSpace: bool = false,
    ss: *stackStack.StackStack,
    ioFunctions: IOFunctions,
    argv: []const []const u8,
    rand: *std.rand.Random,

    pub fn deinit(self: *Pointer) void {
        self.ss.deinit();
        self.allocator.destroy(self);
    }
    fn eval(p: *Pointer, c: i64) pointerErrorType!?pointerReturn {
        // Returns non nil if the pointer terminated, and a return code if
        // the program should terminate completely
        switch (c) {
            '@' => return pointerReturn{},
            'z' => {},
            '#' => p.step(),
            'j' => {
                var n = p.ss.toss.pop();
                var j: usize = 0;
                if (n > 0) {
                    while (j < n) : (j += 1) {
                        p.step();
                    }
                } else {
                    p.reverse();
                    while (j < -n) : (j += 1) {
                        p.step();
                    }
                    p.reverse();
                }
            },
            'q' => return pointerReturn{ .code = p.ss.toss.pop() },
            'k' => {
                const x = p.x;
                const y = p.y;
                const n = p.ss.toss.pop();
                var v = p.stepAndGet();
                var jumpingMode = false;
                while (jumpingMode or v == ' ' or v == ';') : (v = p.stepAndGet()) {
                    if (v == ';') jumpingMode = !jumpingMode;
                }
                if (n > 0) {
                    p.x = x;
                    p.y = y;
                    if (v != ' ' and v != ';') {
                        if (v == 'q' or v == '@') return try p.eval(v);
                        var i: usize = 0;
                        while (i < n) : (i += 1) _ = try p.eval(v);
                    }
                }
            },
            '!' => {
                if (p.ss.toss.pop() == 0) {
                    try p.ss.toss.push(1);
                } else {
                    try p.ss.toss.push(0);
                }
            },
            '`' => {
                const v = p.ss.toss.popVector();
                if (v[0] > v[1]) {
                    try p.ss.toss.push(1);
                } else {
                    try p.ss.toss.push(0);
                }
            },
            '_' => {
                if (p.ss.toss.pop() == 0) {
                    p.dx = 1;
                } else {
                    p.dx = -1;
                }
                p.dy = 0;
            },
            '|' => {
                p.dx = 0;
                if (p.ss.toss.pop() == 0) {
                    p.dy = 1;
                } else {
                    p.dy = -1;
                }
            },
            'w' => {
                const v = p.ss.toss.popVector();
                const dx = p.dx;
                if (v[0] < v[1]) {
                    p.dx = p.dy;
                    p.dy = -dx;
                } else if (v[0] > v[1]) {
                    p.dx = -p.dy;
                    p.dy = dx;
                }
            },
            '+' => {
                const v = p.ss.toss.popVector();
                try p.ss.toss.push(v[0] + v[1]);
            },
            '*' => {
                const v = p.ss.toss.popVector();
                try p.ss.toss.push(v[0] * v[1]);
            },
            '-' => {
                const v = p.ss.toss.popVector();
                try p.ss.toss.push(v[0] - v[1]);
            },
            '/' => {
                const v = p.ss.toss.popVector();
                if (v[1] == 0) {
                    try p.ss.toss.push(0);
                } else {
                    try p.ss.toss.push(@divFloor(v[0], v[1]));
                }
            },
            '%' => {
                const v = p.ss.toss.popVector();
                if (v[1] == 0) {
                    try p.ss.toss.push(0);
                } else {
                    try p.ss.toss.push(@mod(v[0], v[1]));
                }
            },
            '"' => p.stringMode = true,
            '\'' => try p.ss.toss.push(p.stepAndGet()),
            's' => {
                p.step();
                try p.field.set(p.x, p.y, p.ss.toss.pop());
            },
            '$' => _ = p.ss.toss.pop(),
            ':' => try p.ss.toss.duplicate(),
            '\\' => try p.ss.toss.swap(),
            'n' => p.ss.toss.clear(),
            // TODO
            '{' => return error.NotImplemented,
            // TODO
            '}' => return error.NotImplemented,
            // TODO
            'u' => return error.NotImplemented,
            'g' => {
                const v = p.ss.toss.popVector();
                try p.ss.toss.push(p.field.get(v[0] + p.sox, v[1] + p.soy));
            },
            'p' => {
                const v = p.ss.toss.popVector();
                const n = p.ss.toss.pop();
                try p.field.set(v[0] + p.sox, v[1] + p.soy, n);
            },
            '.' => try p.ioFunctions.decimalOutput(p.ss.toss.pop()),
            ',' => try p.ioFunctions.characterOutput(p.ss.toss.pop()),
            '&' => try p.ss.toss.push(try p.ioFunctions.decimalInput()),
            '~' => try p.ss.toss.push(try p.ioFunctions.characterInput()),
            // TODO
            'y' => return error.NotImplemented,
            '(' => {
                const n = p.ss.toss.pop();
                var v: i64 = 0;
                var i: usize = 0;
                while (i < n) : (i += 1) {
                    v = v * 256 + p.ss.toss.pop();
                }
                p.reverse(); // no fingerprints supported for now
            },
            ')' => {
                const n = p.ss.toss.pop();
                var v: i64 = 0;
                var i: usize = 0;
                while (i < n) : (i += 1) {
                    v = v * 256 + p.ss.toss.pop();
                }
                p.reverse(); // no fingerprints supported for now
            },
            'i' => return error.NotImplemented,
            'o' => return error.NotImplemented,
            '=' => return error.NotImplemented,
            't' => return error.NotImplemented,
            else => return error.NotImplemented,
        }
        return null;
    }
    fn exec(self: *Pointer) !?pointerReturn {
        // Advances to the next instruction of the field and executes it
        // Returns non nil if the pointer terminated, and a return code if
        // the program should terminate completely
        var result: ?pointerReturn = null;
        var c = self.field.get(self.x, self.y);
        if (self.stringMode) {
            if (self.lastCharWasSpace) {
                while (c == ' ') {
                    c = self.stepAndGet();
                }
                self.lastCharWasSpace = false;
            }
            if (c == '"') {
                self.stringMode = false;
            } else {
                if (c == ' ') self.lastCharWasSpace = true;
                try self.ss.toss.push(c);
            }
        } else {
            var jumpingMode = false;
            while (jumpingMode or c == ' ' or c == ';') {
                if (c == ';') jumpingMode = !jumpingMode;
                c = self.stepAndGet();
            }
            result = try self.eval(c);
        }
        self.step();
        return result;
    }
    pub fn init(allocator: std.mem.Allocator, f: *field.Field, ioFunctions: ?IOFunctions, argv: []const []const u8) !*Pointer {
        var p = try allocator.create(Pointer);
        errdefer allocator.destroy(p);
        p.allocator = allocator;
        p.field = f;
        p.ss = try stackStack.StackStack.init(allocator);
        p.ioFunctions = if (ioFunctions) |i| i else IOFunctions{};
        p.argv = argv;
        p.x = 0;
        p.y = 0;
        p.dx = 1;
        p.dy = 0;
        p.sox = 0;
        p.soy = 0;
        p.stringMode = false;
        p.lastCharWasSpace = false;
        // Initializing the random number generator
        var seed: u64 = undefined;
        try std.os.getrandom(std.mem.asBytes(&seed));
        var prng = std.rand.DefaultPrng.init(seed);
        p.rand = &prng.random();
        return p;
    }
    inline fn redirect(p: *Pointer, c: i64) bool {
        switch (c) {
            '^' => {
                p.dx = 0;
                p.dy = -1;
            },
            '>' => {
                p.dx = 1;
                p.dy = 0;
            },
            'v' => {
                p.dx = 0;
                p.dy = 1;
            },
            '<' => {
                p.dx = -1;
                p.dy = 0;
            },
            '?' => {
                const directions = []i8{ 0, -1, 1, 0, 0, 1, -1, 0 };
                const r = 2 * p.rand.intRangeAtMost(u8, 0, 3);
                p.dx = directions[r];
                p.dy = directions[r + 1];
            },
            '[' => {
                const dx = p.dx;
                p.dx = p.dy;
                p.dy = -dx;
            },
            ']' => {
                const dx = p.dx;
                p.dx = -p.dy;
                p.dy = dx;
            },
            'r' => p.reverse(),
            'x' => {
                const v = p.ss.toss.popVector();
                p.dx = v[0];
                p.dy = v[1];
            },
            else => return false,
        }
        return true;
    }
    inline fn reverse(p: *Pointer) void {
        p.dx = -p.dx;
        p.dy = -p.dy;
    }
    inline fn step(self: *Pointer) void {
        const v = self.field.step(self.x, self.y, self.dx, self.dy);
        self.x = v.x;
        self.y = v.y;
    }
    inline fn stepAndGet(self: *Pointer) i64 {
        self.step();
        return self.field.get(self.x, self.y);
    }
};

test "all" {
    std.testing.refAllDecls(@This());
}
test "minimal" {
    const minimal = std.io.fixedBufferStream("@").reader();
    var f = try field.Field.init(std.testing.allocator);
    defer f.deinit();
    try f.load(minimal);
    const argv = [_][]const u8{"minimal"};
    var p = try Pointer.init(std.testing.allocator, f, null, argv[0..]);
    defer p.deinit();
    try std.testing.expectEqual(p.exec(), pointerReturn{});
}
test "almost minimal" {
    const minimal = std.io.fixedBufferStream(" @").reader();
    var f = try field.Field.init(std.testing.allocator);
    defer f.deinit();
    try f.load(minimal);
    const argv = [_][]const u8{"minimal"};
    var p = try Pointer.init(std.testing.allocator, f, null, argv[0..]);
    defer p.deinit();
    try std.testing.expectEqual(p.exec(), pointerReturn{});
}