quilt-lang 0.1.1

A programming language
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use anyhow::{anyhow, Result};
use std::io::{self, Write};

use crate::{Condition, Instruction, Pixel};
use crate::{Matrix, MatrixPoint};

const TAPE_SIZE: usize = 360;

pub struct VM<T: Write> {
    stack: Vec<i64>,
    register_a: u16,
    tape: [i64; TAPE_SIZE],
    direction: Direction,
    instructions: Matrix<Pixel>,
    pc: MatrixPoint,
    out: T,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Direction {
    North,
    East,
    South,
    West,
}

impl Direction {
    pub fn clockwise(&self) -> Direction {
        match self {
            Direction::North => Direction::East,
            Direction::East => Direction::South,
            Direction::South => Direction::West,
            Direction::West => Direction::North,
        }
    }

    #[inline]
    pub fn opposite(&self) -> Direction {
        self.clockwise().clockwise()
    }

    #[inline]
    pub fn counter_clockwise(&self) -> Direction {
        self.opposite().clockwise()
    }
}

impl Default for VM<io::Stdout> {
    fn default() -> VM<io::Stdout> {
        VM {
            stack: vec![],
            register_a: 0,
            tape: [0; TAPE_SIZE],
            direction: Direction::East,
            instructions: Matrix::new(vec![]),
            pc: MatrixPoint(0, 0),
            out: io::stdout(),
        }
    }
}

impl<T: Write> VM<T> {
    pub fn new(out: T) -> VM<T> {
        VM {
            stack: vec![],
            register_a: 0,
            tape: [0; TAPE_SIZE],
            direction: Direction::East,
            instructions: Matrix::new(vec![]),
            pc: MatrixPoint(0, 0),
            out,
        }
    }

    pub fn execute(&mut self, instructions: Matrix<Pixel>) {
        self.instructions = instructions;
        self.pc = self.find_start();

        loop {
            let pixel = self.get_next_instruction();
            self.pc = pixel.point;

            let instruction = pixel.as_instruction();

            let condition = if instruction.is_conditional() {
                self.get_condition()
            } else {
                Condition::Equal
            };

            let arg = if instruction.takes_arg() {
                let arg_pixel = self.get_next_instruction();
                self.pc = arg_pixel.point;
                Some(arg_pixel)
            } else {
                None
            };

            // execute the instruction
            if let Err(e) = self.execute_instruction(instruction, arg, condition) {
                eprintln!("{}", e);
                break;
            }
        }
    }

    #[allow(clippy::unit_arg)]
    fn execute_instruction(
        &mut self,
        instruction: Instruction,
        arg: Option<Pixel>,
        condition: Condition,
    ) -> Result<()> {
        if instruction.takes_arg() && arg.is_none() {
            return Err(anyhow!("no arg supplied"));
        }

        match instruction {
            Instruction::Road | Instruction::Start | Instruction::None => Ok(()),
            Instruction::Push => Ok(self.push(arg.unwrap().value as i64)),
            Instruction::Add => self.infix(|a, b| a + b),
            Instruction::Sub => self.infix(|a, b| a - b),
            Instruction::Mult => self.infix(|a, b| a * b),
            Instruction::Div => self.infix(|a, b| a / b),
            Instruction::Modulo => self.infix(|a, b| a % b),
            Instruction::LeftShift => self.unary_infix(|a| a << 1),
            Instruction::RightShift => self.unary_infix(|a| a >> 1),
            Instruction::Output => self.output(),
            Instruction::OutputUntil => self.output_until(condition),
            Instruction::PushA => Ok(self.push(self.tape[self.register_a as usize])),
            Instruction::PopUntil => self.pop_until(condition),
            Instruction::Save => {
                Ok(self.tape[self.register_a as usize] = arg.unwrap().value as i64)
            }
            Instruction::PopA => Ok(self.tape[self.register_a as usize] = self.pop()?),
            Instruction::MovA => Ok(self.register_a = arg.unwrap().value),
            Instruction::And => self.infix(|a, b| a & b),
            Instruction::Or => self.infix(|a, b| a | b),
            Instruction::Xor => self.infix(|a, b| a ^ b),
            Instruction::Not => self.unary_infix(|a| !a),
        }
    }

    fn push(&mut self, arg: i64) {
        self.stack.push(arg)
    }

    fn pop(&mut self) -> Result<i64> {
        self.stack.pop().ok_or(anyhow!("stack is empty"))
    }

    // infix operations (add, sub, mult, div, modulo)
    fn infix(&mut self, f: fn(i64, i64) -> i64) -> Result<()> {
        let b = self.pop()?;
        let a = self.pop()?;
        self.stack.push(f(a, b));
        Ok(())
    }

    // infix operations that use a constant (and subsequently only pops once)
    fn unary_infix(&mut self, f: fn(i64) -> i64) -> Result<()> {
        let a = self.pop()?;
        self.stack.push(f(a));
        Ok(())
    }

    fn output_until(&mut self, condition: Condition) -> Result<()> {
        // TODO: switch exit direction as we keep popping.
        let mut c = self.pop()?;

        while !condition.compare(c) {
            write!(self.out, "{}", c as u8 as char)?;
            c = self.pop()?;
        }

        // TODO maybe push c back on the stack here
        Ok(())
    }

    fn pop_until(&mut self, condition: Condition) -> Result<()> {
        // TODO: switch exit direction as we keep popping.
        let mut c = self.pop()?;

        while !condition.compare(c) {
            c = self.pop()?;
        }

        Ok(())
    }

    fn output(&mut self) -> Result<()> {
        let c = self.pop()?;
        write!(self.out, "{}", c as u8 as char)?;

        Ok(())
    }

    // prioritize roads over all other instructions besides the one in front of us
    pub fn get_next_instruction(&mut self) -> Pixel {
        let next_pixels = self.get_next_pixels();
        let (first_dir, first_pixel) = next_pixels[0];
        let first_road = next_pixels
            .iter()
            .find(|(_dir, pixel)| matches!(pixel.as_instruction(), Instruction::Road));

        // take the first road available, unless it's in the opposite direction
        // only take the opposite road if there are no other options
        if let Some((dir, road)) = first_road {
            if *dir != self.direction.opposite() {
                self.direction = *dir;
                return *road;
            }
        }

        // if there are no roads that don't lead backwards & there is an
        // instruction in front, take it
        if first_dir == self.direction {
            first_pixel
        } else if let Some((opp_dir, pixel)) = next_pixels.last() {
            // otherwise - if there are no roads to the left or right & nothing in front -
            // we go backwards (no matter if it's a road or not)
            self.direction = *opp_dir;
            *pixel
        } else {
            // it should be impossible for there to be nothing in front of or behind
            unreachable!()
        }
    }

    // try the pixel ahead of us. If that doesn't exist,
    // try the pixel to the 'right' (counter-clockwise & opposite). If that doesn't exist,
    // try the pixel to the 'left' (counter-clockwise). If that doesn't exist,
    // go back the way we came
    fn get_next_pixels(&self) -> Vec<(Direction, Pixel)> {
        let ins = &self.instructions;
        let mut next_pixels = vec![];

        let directions = [
            self.direction,                     // forward
            self.direction.clockwise(),         // right
            self.direction.counter_clockwise(), // left
            self.direction.opposite(),          // back
        ];

        for dir in directions {
            if let Some(point) = ins.go(self.pc, dir) {
                next_pixels.push((dir, point));
            }
        }

        next_pixels
    }

    // this is called when the program counter is _at_ the conditional (roundabout).
    // to get the correct condition (traffic light) we need to move one pixel back
    // to where we came from and check on the right-hand side.
    fn get_condition(&self) -> Condition {
        let back = self.direction.opposite();
        let right = self.direction.clockwise();
        if let Some(point) = self.instructions.corner(self.pc, back, right) {
            point.as_condition()
        } else {
            Condition::Equal
        }
    }

    fn find_start(&self) -> MatrixPoint {
        for (row_idx, row) in self.instructions.matrix.iter().enumerate() {
            for (col_idx, pixel) in row.iter().enumerate() {
                if pixel.as_instruction() == Instruction::Start {
                    return MatrixPoint(col_idx, row_idx);
                }
            }
        }

        // default start coordinates
        MatrixPoint(0, 0)
    }
}

#[cfg(test)]
mod test {
    use super::{Direction, VM};
    use crate::pixel::START;
    use crate::vm::Direction::{East, North, South, West};
    use crate::{Matrix, MatrixPoint, Pixel};
    use std::io;

    fn init_vm(matrix: Vec<Vec<u16>>) -> VM<io::Stdout> {
        // we aren't checking the output in these tests, so it's okay
        // to return io::Stdout
        let mut vm = VM::default();
        vm.instructions = init_matrix(matrix);
        vm.pc = vm.find_start();
        vm
    }

    fn init_matrix(pixels: Vec<Vec<u16>>) -> Matrix<Pixel> {
        let mut v = vec![];

        for (row_idx, row) in pixels.iter().enumerate() {
            let mut row_vec = vec![];
            for (col_idx, pixel) in row.iter().enumerate() {
                row_vec.push(Pixel::new(*pixel, MatrixPoint(col_idx, row_idx)));
            }
            v.push(row_vec);
        }

        Matrix::new(v)
    }

    #[test]
    fn test_start_one_d() {
        let vm = init_vm(vec![vec![
            START, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306,
        ]]);

        assert_eq!(vm.pc, MatrixPoint(0, 0));
    }

    #[test]
    fn test_start_two_d() {
        let vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, START, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        assert_eq!(vm.pc, MatrixPoint(5, 1));
    }

    #[test]
    fn test_start_bounds() {
        let vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, 3, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, START],
        ]);

        assert_eq!(vm.pc, MatrixPoint(11, 2));
    }

    fn compare_pixels(actual: Vec<(Direction, Pixel)>, expected: Vec<(Direction, u16)>) {
        assert_eq!(actual.len(), expected.len());

        for (idx, (dir, pixel)) in actual.iter().enumerate() {
            let (expected_dir, expected_pixel) = expected[idx];
            assert_eq!(*dir, expected_dir);
            assert_eq!(pixel.value, expected_pixel);
        }
    }

    #[test]
    fn test_get_next_pixels_east() {
        let vm = init_vm(vec![vec![
            START, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306,
        ]]);

        let actual = vm.get_next_pixels();
        let expected = vec![(East, 180)];
        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_east_middle() {
        let vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, START, 2, 108, 36, 48, 108, 306],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        assert_eq!(vm.pc, MatrixPoint(5, 1));
        let pixels = vm.get_next_pixels();

        let expected = vec![(East, 2), (South, 36), (North, 37), (West, 1)];

        compare_pixels(pixels, expected);
    }

    #[test]
    fn test_get_next_pixels_east_bound() {
        let vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 36, 48, 108, 310],
            vec![0, 180, 180, 36, 1, 108, 2, 108, 36, 48, 108, START],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        assert_eq!(vm.pc, MatrixPoint(11, 1));
        let actual = vm.get_next_pixels();

        let expected = vec![(South, 306), (North, 310), (West, 108)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_north() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 36, 48, 108, 310],
            vec![0, 180, 180, 36, 1, 108, 2, 108, 36, START, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = North;

        assert_eq!(vm.pc, MatrixPoint(9, 1));
        let actual = vm.get_next_pixels();

        let expected = vec![(North, 48), (East, 108), (West, 36), (South, 48)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_north_bound() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, START, 48, 108, 310],
            vec![0, 180, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = North;

        assert_eq!(vm.pc, MatrixPoint(8, 0));
        let actual = vm.get_next_pixels();

        let expected = vec![(East, 48), (West, 108), (South, 36)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_west() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![0, 180, START, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = West;

        assert_eq!(vm.pc, MatrixPoint(2, 1));
        let actual = vm.get_next_pixels();

        let expected = vec![(West, 180), (North, 180), (South, 180), (East, 36)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_south_bound() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![0, 180, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![START, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = South;

        assert_eq!(vm.pc, MatrixPoint(0, 2));
        let actual = vm.get_next_pixels();

        let expected = vec![(East, 180), (North, 0)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_south() {
        let mut vm = init_vm(vec![
            vec![0, 180, START, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![0, 180, 100, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = South;

        assert_eq!(vm.pc, MatrixPoint(2, 0));
        let actual = vm.get_next_pixels();

        let expected = vec![(South, 100), (West, 180), (East, 36)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_pixels_west_bound() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![START, 180, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = West;

        assert_eq!(vm.pc, MatrixPoint(0, 1));
        let actual = vm.get_next_pixels();

        let expected = vec![(North, 0), (South, 0), (East, 180)];

        compare_pixels(actual, expected);
    }

    #[test]
    fn test_get_next_instruction() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![START, 180, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = East;

        assert_eq!(vm.pc, MatrixPoint(0, 1));
        let pixel = vm.get_next_instruction();

        assert_eq!(pixel.value, 180);
    }

    #[test]
    fn test_get_next_instruction1() {
        let mut vm = init_vm(vec![
            vec![0, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![START, 1, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![0, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = East;

        let pixel = vm.get_next_instruction();

        assert_eq!(pixel.value, 1);
    }

    #[test]
    fn test_get_next_instruction2() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![START, 1, 180, 36, 1, 18, 2, 108, 36, 42, 108, 314],
            vec![180, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = East;

        let pixel = vm.get_next_instruction();

        // take the road to the 'right' (south)
        assert_eq!(pixel.value, 180);
    }

    #[test]
    fn test_get_next_instruction3() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![180, 180, 180, 36, 1, 18, 2, 108, 36, 42, 180, START],
            vec![180, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = East;

        let pixel = vm.get_next_instruction();

        // turn around
        assert_eq!(pixel.value, 180);
    }

    #[test]
    fn test_get_next_instruction4() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![180, 180, 180, 36, 180, START, 2, 108, 36, 42, 180, 200],
            vec![180, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = North;

        let pixel = vm.get_next_instruction();

        // go 'left'
        assert_eq!(pixel.value, 180);
    }

    #[test]
    fn test_get_next_instruction5() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 310],
            vec![180, 180, 180, 36, 1, START, 2, 108, 36, 42, 180, 200],
            vec![180, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = North;

        let pixel = vm.get_next_instruction();

        assert_eq!(pixel.value, 37);
    }

    #[test]
    fn test_get_next_instruction6() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 180],
            vec![180, 180, 180, 36, 1, 18, 2, 108, 36, 42, 180, START],
            vec![180, 180, 180, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = East;

        let pixel = vm.get_next_instruction();

        // don't turn around if there's another road available
        assert_eq!(pixel.value, 180);
    }

    #[test]
    fn test_get_next_instruction7() {
        let mut vm = init_vm(vec![
            vec![180, 180, 180, 36, 1, 37, 2, 108, 70, 48, 108, 180],
            vec![180, 180, 180, 36, 1, 18, 2, 108, 36, 42, 180, 180],
            vec![180, 1, START, 36, 1, 36, 2, 108, 36, 48, 108, 306],
        ]);

        vm.direction = North;

        let pixel = vm.get_next_instruction();

        // go north
        assert_eq!(pixel.value, 180);
    }
}