baryuxn 0.3.0

An implementation of the Uxn stack machine as a no_std library.
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! # BaryUxn: the baremetal Uxn stack machine
//! An implementation of the [Uxn stack machine](https://wiki.xxiivv.com/site/uxn.html)
//! designed to not rely on `std`.
//!
//! This means it can run on baremetal, and is thoroughly adaptable to any plateform.
//!
//! The source is also designed to be as readable as possible, while compiling
//! down to efficient code regardless of the target plateform.
//!
//! # STATUS
//! BaryUxn is still in early development, and as such is not thoroughly tested on
//! real world examples. The API may change drastically to ease up implementation.
//!
//! The stack machine itself is well tested, however.
//!
//! Put simply, the library is in a usable state, but I would not be surprised that
//! some things are missing or unergonomic.
//!
//! # Features
//! As of now, there is a single feature, `pretty_print`, which includes string representations
//! of Uxn opcodes for help debugging. It is disabled by default as it induces a huge increase in
//! binary size.
//!
//! # Quick start
//! To spin up a Uxn emulator, simply load a ROM by opening up a file and loading
//! its byte contents into a form of storage that implements the [`UxnMemory`] trait.
//! Rust's slices implement this trait automatically.
//!
//! ```rust
//! # use baryuxn::*;
//! # struct NullDevices;
//! # impl UxnDeviceBus for NullDevices {
//! # fn read(&mut self, _machine: &mut UxnMachineState, _address: u8) -> u8 { 0 }
//! # fn write(&mut self, _machine: &mut UxnMachineState, _address: u8, _byte: u8) {}
//! # }
//! # fn main() {
//! let mut memory = [0; 0x10000];
//! // Examples devices that always read/write zeros
//! let mut devices = NullDevices;
//!
//! // Creates a new machine state (stacks).
//! let mut machine = UxnMachineState::new();
//! // Vectors are the main way to execute code, they hold a mutable reference
//! // to everything needed, and keep running from the starting address until
//! // a BRK instruction is executed.
//! UxnVector::new(0x100, &mut machine, &mut memory, &mut devices).execute_till_end();
//! # }
//! ```
//!
//! # Vectors
//! Uxn code is executed using vectors, a continuous stream of Uxn operations ending
//! when it executes the `BRK` instruction.
//!
//! Vectors in BaryUxn are implemented as iterators to allow flexibility. You can then:
//! - log instruction counters
//! - execute a vector step-by-step
//! - or anything you can do with a standard iterator
//!
//! Creating a [`UxnVector`] is as simple as:
//! ```rust
//! # use baryuxn::*;
//! # struct NullDevices;
//! # impl UxnDeviceBus for NullDevices {
//! # fn read(&mut self, _machine: &mut UxnMachineState, _address: u8) -> u8 { 0 }
//! # fn write(&mut self, _machine: &mut UxnMachineState, _address: u8, _byte: u8) {}
//! # }
//! # fn main() {
//! # let mut memory = [0; 0x10000];
//! # let mut devices = NullDevices;
//! # let mut machine = UxnMachineState::new();
//! // Creates an execution vector starting at address 0x110 and going until it
//! // executes a BRK instruction.
//! UxnVector::new(0x110, &mut machine, &mut memory, &mut devices).execute_till_end();
//! # }
//! ```
//! ## Multiple vectors
//! Note that [`UxnVector`] takes ownership through a mutable reference to a [`UxnMachineState`]
//! as well as memory and devices. If you need to keep track of multiple vectors (which
//! can be needed to implement interrupt-like behaviors, like the [Varvara computer](https://wiki.xxiivv.com/site/varvara.html)
//! does), you can use [`UxnVector::release`]:.
//!
//! ```rust
//! # use baryuxn::*;
//! # struct NullDevices;
//! # impl UxnDeviceBus for NullDevices {
//! # fn read(&mut self, _machine: &mut UxnMachineState, _address: u8) -> u8 { 0 }
//! # fn write(&mut self, _machine: &mut UxnMachineState, _address: u8, _byte: u8) {}
//! # }
//! # fn main() {
//! # let mut mem = [0; 0x10000];
//! # let mut dev = NullDevices;
//! # let mut machine = UxnMachineState::new();
//! // Do stuff with the original vector...
//! let mut vector = UxnVector::new(0x100, &mut machine, &mut mem, &mut dev);
//!
//! // Releasing the vector returns the current program counter
//! let next_instruction = vector.release();
//!
//! // Do stuff with the other vector...
//! let mut second_vector = UxnVector::new(0x234, &mut machine, &mut mem, &mut dev);
//!
//! // Once done, release it and recreate a new vector starting where the previous one
//! // ended
//! second_vector.release();
//! let mut vector = UxnVector::new(next_instruction, &mut machine, &mut mem, &mut dev);
//! # }
//! ```
//!
//! # Memory
//! Due to wildly different possible memory implementations (shared memory, parallel access, etc),
//! the implementation for memory components is user-defined. Anything implementing
//! the [`UxnMemory`] trait, which allows you to access the storage using 16 bit
//! integers, works.
//!
//! A blanket implementation for usual arrays, slices, vectors and else is implemented.
//!
//! # Devices
//! Uxn CPUs can interract with the outside world using devices. To execute instructions,
//! a [`UxnMachineState`] requires a mutable reference to a value implementing the [`UxnDeviceBus`]
//! trait.
//!
//! This trait defines two methods: one to read bytes, and another to write them, all
//! addressed by [`u8`]. Writing or reading from a so-called port can trigger specific
//! behavior from your devices, like printing a character to the console or logging some
//! information.
//! ```rust
//! # use baryuxn::*;
//! /// Simplified implementation of a CLI Varvara machine.
//! struct CliDeviceBus {
//!     storage: [u8; 0x100],
//!     debug: bool,
//!     should_quit: bool,
//! }
//! impl UxnDeviceBus for CliDeviceBus {
//!     fn read(&mut self, machine: &mut UxnMachineState, address: u8) -> u8 {
//!         let page = address & 0xf0;
//!         let port = address & 0x0f;
//!         match page {
//!             0x00 => match port {
//!                 // System
//!                 0x04 => machine.work_stack.pointer,
//!                 0x05 => machine.return_stack.pointer,
//!                 _ => self.storage[address as usize],
//!             },
//!             _ => self.storage[address as usize],
//!         }
//!     }
//!     fn write(&mut self, machine: &mut UxnMachineState, address: u8, byte: u8) {
//!         let page = address & 0xf0;
//!         let port = address & 0x0f;
//!         self.storage[address as usize] = byte;
//!         match page {
//!             0x00 => match port {
//!                 // System
//!                 0x04 => machine.work_stack.pointer = byte,
//!                 0x05 => machine.return_stack.pointer = byte,
//!                 0x0e if byte != 0 && self.debug => {
//!                     println!(
//!                         "WST ( {:?} )\nRST ( {:?} )",
//!                         machine.work_stack, machine.return_stack
//!                     );
//!                 }
//!                 0x0f if byte != 0 => self.should_quit = true,
//!                 _ => {}
//!             },
//!             0x10 => match port {
//!                 // Console
//!                 0x08 => print!("{}", byte as char),
//!                 0x09 => eprint!("{}", byte as char),
//!                 _ => {}
//!             },
//!             _ => {}
//!         }
//!     }
//! }
//! ```

#![no_std]

mod bus;
mod machine;
mod memory;
#[cfg(feature = "pretty_print")]
mod pretty_print;
mod stack;

pub use bus::*;
pub use machine::*;
pub use memory::*;
pub use stack::*;

#[cfg(feature = "pretty_print")]
pub use pretty_print::*;

#[cfg(test)]
mod test;

/// An instruction vector, implemented as an iterator that executes instructions
/// in sequence until it encounters a `BRK` instruction.
///
/// Using an iterator for this allows users of the API to execute instructions step
/// by step if they so wish.
///
/// # Queuing vectors
/// The design of some implementations, notably the Varvara ordinator, require
/// their emulator to break evaluation to run a vector when some event happens
/// on a device, akin to interrupts. To allow for this, vectors can release their
/// mutable reference to the UxnMachine, memory and device bus while returning their
/// current program counter to resume progress later.
///
/// # [`FusedIterator`](core::iter::FusedIterator)
/// Note that this cannot implement [`FusedIterator`](core::iter::FusedIterator).
/// Since Uxn does not forbid self modifying code, it is possible to read a `BRK`
/// instruction once, returning `None`, then reading a different instruction at the
/// same location in memory later on.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UxnVector<'a, M, B> {
    pub machine: &'a mut UxnMachineState,
    pub program_counter: u16,
    pub memory: &'a mut M,
    pub device_bus: &'a mut B,
}
impl<'a, M, B> UxnVector<'a, M, B>
where
    M: UxnMemory,
    B: UxnDeviceBus,
{
    /// Creates a new UxnVector starting at the given program counter.
    pub fn new(
        program_counter: u16,
        machine: &'a mut UxnMachineState,
        memory: &'a mut M,
        device_bus: &'a mut B,
    ) -> Self {
        Self {
            machine,
            program_counter,
            memory,
            device_bus,
        }
    }

    /// Executes this vector until it encounters a BRK instruction.
    pub fn execute_till_end(self) {
        self.for_each(|_| {})
    }

    /// Releases the vector, returning its current program counter in order to continue
    /// execution later.
    pub fn release(self) -> u16 {
        self.program_counter
    }
}
impl<M, B> Iterator for UxnVector<'_, M, B>
where
    M: UxnMemory,
    B: UxnDeviceBus,
{
    type Item = (u8, u16);

    /// Steps through the next instruction to execute. Returns `Some((instruction, program_counter))`
    /// until the executed instruction is `BRK` (`0x00`)
    fn next(&mut self) -> Option<Self::Item> {
        let (instruction, next_program_counter) = execute_operation(
            self.machine,
            self.program_counter,
            self.memory,
            self.device_bus,
        );
        if let Some(pc) = next_program_counter {
            let old_pc = self.program_counter;
            self.program_counter = pc;
            Some((instruction, old_pc))
        } else {
            None
        }
    }
}

/// Executes a single UxnTal operation given a program counter, RAM and devices.
///
/// Returns the instruction executed as well as the next value of the program counter after this operation.
pub fn execute_operation<M: UxnMemory, B: UxnDeviceBus>(
    machine_state: &mut UxnMachineState,
    program_counter: u16,
    memory: &mut M,
    device_bus: &mut B,
) -> (u8, Option<u16>) {
    let instruction = memory.get(program_counter);
    let operation = instruction & 0x1f;

    // Select the right function to call depending on mode flags
    (
        instruction,
        match instruction & 0xe0 {
            0x00 => execute_operation_generic::<false, false, false, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0x20 => execute_operation_generic::<true, false, false, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0x40 => execute_operation_generic::<false, true, false, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0x60 => execute_operation_generic::<true, true, false, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0x80 => execute_operation_generic::<false, false, true, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0xa0 => execute_operation_generic::<true, false, true, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0xc0 => execute_operation_generic::<false, true, true, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            0xe0 => execute_operation_generic::<true, true, true, M, B>(
                machine_state,
                operation,
                program_counter,
                memory,
                device_bus,
            ),
            _ => unreachable!("You managed to enter a set of modes that does not exist... huh?"),
        },
    )
}

/// Executes a UxnTal operation using modes defined using const generics.
///
/// This allows this crucial function to be monomorphized into 8 mode specific
/// functions that are optimized individually.
///
/// Returns the next value of the program counter after this operation.
fn execute_operation_generic<
    const SHORT: bool,
    const RETURN: bool,
    const KEEP: bool,
    M: UxnMemory,
    B: UxnDeviceBus,
>(
    machine_state: &mut UxnMachineState,
    operation: u8,
    mut program_counter: u16,
    memory: &mut M,
    device_bus: &mut B,
) -> Option<u16> {
    macro_rules! stack {
        () => {
            if RETURN {
                &mut machine_state.return_stack
            } else {
                &mut machine_state.work_stack
            }
        };
    }
    macro_rules! return_stack {
        () => {
            if RETURN {
                &mut machine_state.work_stack
            } else {
                &mut machine_state.return_stack
            }
        };
    }

    let mut popped = 0;
    fn pop<const KEEP: bool>(stack: &mut UxnStack, popped: &mut i8) -> u8 {
        if KEEP {
            *popped -= 1;
            stack.get(*popped + 1)
        } else {
            stack.pop()
        }
    }
    fn pop_short<const KEEP: bool>(stack: &mut UxnStack, popped: &mut i8) -> u16 {
        if KEEP {
            *popped -= 2;
            stack.get_short(*popped + 2)
        } else {
            stack.pop_short()
        }
    }

    program_counter = program_counter.wrapping_add(1);
    match operation {
        0x00 => {
            // Immediate opcodes depend simply on which modes are set.
            match (SHORT, RETURN, KEEP) {
                (false, false, false) => return None, // BRK
                (true, false, false) => {
                    // JCI
                    if machine_state.work_stack.pop() != 0 {
                        program_counter =
                            program_counter.wrapping_add(memory.get_short(program_counter))
                    }
                    program_counter = program_counter.wrapping_add(2)
                }
                (false, true, false) => {
                    // JMI
                    program_counter = program_counter
                        .wrapping_add(memory.get_short(program_counter))
                        .wrapping_add(2);
                }
                (true, true, false) => {
                    // JSI
                    machine_state
                        .return_stack
                        .push_short(program_counter.wrapping_add(2));
                    program_counter = program_counter
                        .wrapping_add(memory.get_short(program_counter))
                        .wrapping_add(2)
                }
                (false, _, true) => {
                    // LIT
                    let value = memory.get(program_counter);
                    stack!().push(value);
                    program_counter = program_counter.wrapping_add(1);
                }
                (true, _, true) => {
                    // LIT2
                    let value = memory.get_short(program_counter);
                    stack!().push_short(value);
                    program_counter = program_counter.wrapping_add(2)
                }
            }
        }

        // General opcodes
        0x01 => {
            // INC
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped).wrapping_add(1);
                stack!().push_short(v)
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped).wrapping_add(1);
                stack!().push(v)
            }
        }
        0x02 => {
            // POP
            if SHORT {
                pop_short::<KEEP>(stack!(), &mut popped);
            } else {
                pop::<KEEP>(stack!(), &mut popped);
            }
        }
        0x03 => {
            // NIP
            if SHORT {
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let _ = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(b);
            } else {
                let b = pop::<KEEP>(stack!(), &mut popped);
                let _ = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(b);
            }
        }
        0x04 => {
            // SWP
            if SHORT {
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(b);
                stack!().push_short(a);
            } else {
                let b = pop::<KEEP>(stack!(), &mut popped);
                let a = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(b);
                stack!().push(a);
            }
        }
        0x05 => {
            // ROT
            if SHORT {
                let c = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(b);
                stack!().push_short(c);
                stack!().push_short(a);
            } else {
                let c = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                let a = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(b);
                stack!().push(c);
                stack!().push(a);
            }
        }
        0x06 => {
            // DUP
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(v);
                stack!().push_short(v);
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(v);
                stack!().push(v);
            }
        }
        0x07 => {
            // OVR
            if SHORT {
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a);
                stack!().push_short(b);
                stack!().push_short(a);
            } else {
                let b = pop::<KEEP>(stack!(), &mut popped);
                let a = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a);
                stack!().push(b);
                stack!().push(a);
            }
        }
        0x08 => {
            // EQU
            let res = if SHORT {
                pop_short::<KEEP>(stack!(), &mut popped) == pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                pop::<KEEP>(stack!(), &mut popped) == pop::<KEEP>(stack!(), &mut popped)
            } as u8;
            stack!().push(res);
        }
        0x09 => {
            // NEQ
            let res = if SHORT {
                pop_short::<KEEP>(stack!(), &mut popped) != pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                pop::<KEEP>(stack!(), &mut popped) != pop::<KEEP>(stack!(), &mut popped)
            } as u8;
            stack!().push(res);
        }
        0x0a => {
            // GTH
            let res = if SHORT {
                pop_short::<KEEP>(stack!(), &mut popped) < pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                pop::<KEEP>(stack!(), &mut popped) < pop::<KEEP>(stack!(), &mut popped)
            } as u8;
            stack!().push(res);
        }
        0x0b => {
            // LTH
            let res = if SHORT {
                pop_short::<KEEP>(stack!(), &mut popped) > pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                pop::<KEEP>(stack!(), &mut popped) > pop::<KEEP>(stack!(), &mut popped)
            } as u8;
            stack!().push(res);
        }
        0x0c => {
            // JMP
            if SHORT {
                program_counter = pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                program_counter =
                    program_counter.wrapping_add((pop::<KEEP>(stack!(), &mut popped) as i8) as u16)
            }
        }
        0x0d => {
            // JCN
            if pop::<KEEP>(stack!(), &mut popped) != 0 {
                if SHORT {
                    program_counter = pop_short::<KEEP>(stack!(), &mut popped)
                } else {
                    program_counter = program_counter
                        .wrapping_add((pop::<KEEP>(stack!(), &mut popped) as i8) as u16)
                }
            }
        }
        0x0e => {
            // JSR
            machine_state.return_stack.push_short(program_counter);
            if SHORT {
                program_counter = pop_short::<KEEP>(stack!(), &mut popped)
            } else {
                program_counter =
                    program_counter.wrapping_add((pop::<KEEP>(stack!(), &mut popped) as i8) as u16)
            }
        }
        0x0f => {
            // STH
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                return_stack!().push_short(v);
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                return_stack!().push(v);
            }
        }
        0x10 => {
            // LDZ
            let address = pop::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let value = memory.get_short(address as u16);
                stack!().push_short(value)
            } else {
                let value = memory.get(address as u16);
                stack!().push(value)
            }
        }
        0x11 => {
            // STZ
            let address = pop::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                memory.set_short(address as u16, v)
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                *memory.get_mut(address as u16) = v
            }
        }
        0x12 => {
            // LDR
            let address = program_counter
                .wrapping_add_signed((pop::<KEEP>(stack!(), &mut popped) as i8) as i16);
            if SHORT {
                let value = memory.get_short(address as u16);
                stack!().push_short(value)
            } else {
                let value = memory.get(address as u16);
                stack!().push(value)
            }
        }
        0x13 => {
            // STR
            let address =
                program_counter.wrapping_add((pop::<KEEP>(stack!(), &mut popped) as i8) as u16);
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                memory.set_short(address as u16, v)
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                *memory.get_mut(address as u16) = v
            }
        }
        0x14 => {
            // LDA
            let address = pop_short::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let value = memory.get_short(address);
                stack!().push_short(value)
            } else {
                let value = memory.get(address);
                stack!().push(value)
            }
        }
        0x15 => {
            // STA
            let address = pop_short::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                memory.set_short(address, v);
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                *memory.get_mut(address) = v
            }
        }
        0x16 => {
            // DEI
            let address = pop::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let v = device_bus.read_short(machine_state, address);
                stack!().push_short(v)
            } else {
                let v = device_bus.read(machine_state, address);
                stack!().push(v)
            }
        }
        0x17 => {
            // DEO
            let address = pop::<KEEP>(stack!(), &mut popped);
            if SHORT {
                let value = pop_short::<KEEP>(stack!(), &mut popped);
                device_bus.write_short(machine_state, address, value);
            } else {
                let value = pop::<KEEP>(stack!(), &mut popped);
                device_bus.write(machine_state, address, value);
            }
        }
        0x18 => {
            // ADD
            if SHORT {
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a.wrapping_add(b));
            } else {
                let a = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a.wrapping_add(b));
            }
        }
        0x19 => {
            // SUB
            if SHORT {
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a.wrapping_sub(b));
            } else {
                let b = pop::<KEEP>(stack!(), &mut popped);
                let a = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a.wrapping_sub(b));
            }
        }
        0x1a => {
            // MUL
            if SHORT {
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a.wrapping_mul(b));
            } else {
                let a = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a.wrapping_mul(b));
            }
        }
        0x1b => {
            // DIV
            if SHORT {
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                if b == 0 {
                    stack!().push_short(0)
                } else {
                    stack!().push_short(a.wrapping_div(b));
                }
            } else {
                let b = pop::<KEEP>(stack!(), &mut popped);
                let a = pop::<KEEP>(stack!(), &mut popped);
                if b == 0 {
                    stack!().push(0)
                } else {
                    stack!().push(a.wrapping_div(b));
                }
            }
        }
        0x1c => {
            // AND
            if SHORT {
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a & b);
            } else {
                let a = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a & b);
            }
        }
        0x1d => {
            // ORA
            if SHORT {
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a | b);
            } else {
                let a = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a | b);
            }
        }
        0x1e => {
            // EOR
            if SHORT {
                let a = pop_short::<KEEP>(stack!(), &mut popped);
                let b = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short(a ^ b);
            } else {
                let a = pop::<KEEP>(stack!(), &mut popped);
                let b = pop::<KEEP>(stack!(), &mut popped);
                stack!().push(a ^ b);
            }
        }
        0x1f => {
            // SFT
            let shift = pop::<KEEP>(stack!(), &mut popped);
            let shift_right = 0x0f & shift;
            let shift_left = (0xf0 & shift) >> 4;
            if SHORT {
                let v = pop_short::<KEEP>(stack!(), &mut popped);
                stack!().push_short((v >> shift_right) << shift_left)
            } else {
                let v = pop::<KEEP>(stack!(), &mut popped);
                stack!().push((v >> shift_right) << shift_left)
            }
        }
        _ => {}
    }

    Some(program_counter)
}