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
use itertools::Either;
use itertools::Either::{Left, Right};
use ux::{u12, u4};

/// One of the 16 CHIP-8 variable registers `V0`–`VF`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Register(pub u4);

impl From<Register> for usize {
    fn from(register: Register) -> Self {
        usize::try_from(register.0).unwrap()
    }
}

/// The possible byte operands in a CHIP-8 opcode: A nibble representing a [`Register`] holding a byte, or an immediate byte value.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Byte {
    Register(Register),
    Immediate(u8),
}

impl From<Byte> for u8 {
    fn from(byte: Byte) -> Self {
        match byte {
            Byte::Register(Register(x)) => u8::from(x),
            Byte::Immediate(x) => x,
        }
    }
}

/// CHIP-8 instructions.
///
/// This instruction set is mostly based on what Octo supports, which comprises the specifications for CHIP-8, SUPER-CHIP and XO-CHIP.
///
/// However, there is also support for some more esoteric instructions, especially where there are no collisions in the opcode space.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Instruction {
    /// Halt the CHIP-8 interpreter.
    ///
    /// Based on Octo's behavior when encountering `0000`.
    Halt,
    /// Exit the CHIP-8 interpreter with an optional exit code.
    ///
    /// Based on the following opcodes:
    /// * `00FD`: Exit interpreter (from SUPER-CHIP 1.1)
    /// * `001N`: Exit with exit code `N` (from [`chip8run`](http://chip8.sourceforge.net/))
    Exit(Option<u8>),
    /// Scroll the display up.
    ///
    /// Based on the following opcodes:
    /// * `00BN`: Scroll up by N pixels (from [Massung's SUPER-CHIP interpreter](https://chip-8.github.io/extensions/#super-chip-with-scroll-up) and Mega-Chip)
    /// * `00DN`: Scroll up by N pixels (from [XO-CHIP](http://johnearnest.github.io/Octo/docs/XO-ChipSpecification.html))
    ScrollUp(u4),
    /// Scroll the display down.
    ///
    /// Based on the following opcode:
    /// * `00CN`: Scroll down by N pixels
    ScrollDown(u4),
    /// Scroll the display right.
    ScrollRight,
    /// Scroll the display left.
    ScrollLeft,
    /// Clear the display.
    Clear,
    /// Return from subroutine.
    Return,
    /// Toggle the behavior of `Instruction::Load` and `Instruction::Store`
    ToggleLoadStoreQuirk,
    /// Change display to low resolution ("lores") mode, 64x32 pixels
    LoRes,
    /// Change display to high resolution ("hires") mode, 128x64 pixels
    HiRes,
    /// Call machine code routine.
    CallMachineCode(u12),
    /// Jump to memory address
    Jump(u12),
    /// Call subroutine
    Call(u12),
    /// Skip the next instruction if
    SkipIfEqual(Register, Byte),
    SkipIfNotEqual(Register, Byte),
    Add(Register, Byte),
    Set(Register, Byte),
    Or(Register, Register),
    And(Register, Register),
    Xor(Register, Register),
    Sub(Register, Register),
    ShiftRight(Register, Register),
    ShiftLeft(Register, Register),
    SubReverse(Register, Register),
    SetIndex(u16),
    JumpRelative(u16),
    Random(Register, u8),
    /// Draw a sprite on the display.
    ///
    ///
    Draw(Register, Register, u4),
    SkipKey(Register),
    SkipNotKey(Register),
    SetIndexLong,
    LoadAudio,
    LoadDelay(Register),
    BlockKey(Register),
    SelectPlane(u4),
    SetPitch(Register),
    SetDelay(Register),
    SetSound(Register),
    AddRegisterToIndex(Register),
    FontCharacter(Register),
    BigFontCharacter(Register),
    Bcd(Register),
    Store(Register),
    Load(Register),
    StoreRange(Register, Register),
    LoadRange(Register, Register),
    StoreFlags(Register),
    LoadFlags(Register),
}

impl From<Instruction> for Either<u16, u32> {
    fn from(instruction: Instruction) -> Either<u16, u32> {
        match instruction {
            Instruction::Halt => Left(0x0000),
            Instruction::Exit(None) => Left(0x00FD),
            Instruction::Exit(Some(n)) => Left(0x0010 + u16::from(n)),
            Instruction::ScrollUp(_) => todo!(),
            Instruction::ScrollDown(_) => todo!(),
            Instruction::ScrollRight => todo!(),
            Instruction::ScrollLeft => todo!(),
            Instruction::Clear => Left(0x00E0),
            Instruction::Return => Left(0x00EE),
            Instruction::ToggleLoadStoreQuirk => todo!(),
            Instruction::LoRes => todo!(),
            Instruction::HiRes => todo!(),
            Instruction::CallMachineCode(_) => todo!(),
            Instruction::Jump(_) => todo!(),
            Instruction::Call(_) => todo!(),
            Instruction::SkipIfEqual(_, _) => todo!(),
            Instruction::SkipIfNotEqual(_, _) => todo!(),
            Instruction::Add(_, _) => todo!(),
            Instruction::Set(_, _) => todo!(),
            Instruction::Or(_, _) => todo!(),
            Instruction::And(_, _) => todo!(),
            Instruction::Xor(_, _) => todo!(),
            Instruction::Sub(_, _) => todo!(),
            Instruction::ShiftRight(_, _) => todo!(),
            Instruction::ShiftLeft(_, _) => todo!(),
            Instruction::SubReverse(_, _) => todo!(),
            Instruction::SetIndex(n) => {
                if n <= 0xFFF {
                    Left(0xA000 + n)
                } else {
                    Right(0xF000_0000 + u32::from(n))
                }
            }
            Instruction::JumpRelative(_) => todo!(),
            Instruction::Random(_, _) => todo!(),
            Instruction::Draw(_, _, _) => todo!(),
            Instruction::SkipKey(_) => todo!(),
            Instruction::SkipNotKey(_) => todo!(),
            Instruction::SetIndexLong => Left(0xF000),
            Instruction::LoadAudio => todo!(),
            Instruction::LoadDelay(_) => todo!(),
            Instruction::BlockKey(_) => todo!(),
            Instruction::SelectPlane(_) => todo!(),
            Instruction::SetPitch(_) => todo!(),
            Instruction::SetDelay(_) => todo!(),
            Instruction::SetSound(_) => todo!(),
            Instruction::AddRegisterToIndex(_) => todo!(),
            Instruction::FontCharacter(_) => todo!(),
            Instruction::BigFontCharacter(_) => todo!(),
            Instruction::Bcd(_) => todo!(),
            Instruction::Store(_) => todo!(),
            Instruction::Load(_) => todo!(),
            Instruction::StoreRange(_, _) => todo!(),
            Instruction::LoadRange(_, _) => todo!(),
            Instruction::StoreFlags(_) => todo!(),
            Instruction::LoadFlags(_) => todo!(),
        }
    }
}

impl TryFrom<u32> for Instruction {
    type Error = String;

    fn try_from(opcode: u32) -> Result<Self, Self::Error> {
        let prefix = u16::try_from(opcode >> 16).unwrap();
        let suffix = u16::try_from(opcode & 0x0000_FFFF).unwrap();
        if prefix == 0x0000 {
            Ok(Instruction::try_from(suffix)?)
        } else if prefix == 0xF000 {
            Ok(Instruction::SetIndex(suffix))
        } else {
            Err(format!("Unknown opcode {:#010x}", opcode))
        }
    }
}

impl TryFrom<u16> for Instruction {
    type Error = String;

    fn try_from(opcode: u16) -> Result<Self, Self::Error> {
        let x = u4::try_from((opcode & 0x0F00) >> 8).unwrap();
        let y = u4::try_from((opcode & 0x00F0) >> 4).unwrap();
        let nnn = u12::try_from(opcode & 0x0FFF).unwrap();
        let kk = (opcode & 0x00FF) as u8;
        let n = u4::try_from(opcode & 0x000F).unwrap();

        let op1 = (opcode & 0xF000) >> 12;
        let op2 = (opcode & 0x0F00) >> 8;
        let op3 = (opcode & 0x00F0) >> 4;
        let op4 = opcode & 0x000F;

        Ok(
            match (op1, op2, op3, op4) {
                #![allow(clippy::match_same_arms)]
                (0x0, 0x0, 0x0, 0x0) => Instruction::Halt,
                (0x0, 0x0, 0x1, _) => Instruction::Exit(Some(op4 as u8)),
                (0x0, 0x0, 0xB, _) => Instruction::ScrollUp(n),
                (0x0, 0x0, 0xC, _) => Instruction::ScrollDown(n),
                (0x0, 0x0, 0xD, _) => Instruction::ScrollUp(n),
                (0x0, 0x0, 0xE, 0x0) => Instruction::Clear,
                (0x0, 0x0, 0xE, 0xE) => Instruction::Return,
                (0x0, 0x0, 0xF, 0xA) => Instruction::ToggleLoadStoreQuirk,
                (0x0, 0x0, 0xF, 0xB) => Instruction::ScrollRight,
                (0x0, 0x0, 0xF, 0xC) => Instruction::ScrollLeft,
                (0x0, 0x0, 0xF, 0xD) => Instruction::Exit(None),
                (0x0, 0x0, 0xF, 0xE) => Instruction::LoRes,
                (0x0, 0x0, 0xF, 0xF) => Instruction::HiRes,
                (0x0, _, _, _) => Instruction::CallMachineCode(nnn),
                (0x1, _, _, _) => Instruction::Jump(nnn),
                (0x2, _, _, _) => Instruction::Call(nnn),
                (0x3, _, _, _) => Instruction::SkipIfEqual(Register(x), Byte::Immediate(kk)),
                (0x4, _, _, _) => Instruction::SkipIfNotEqual(Register(x), Byte::Immediate(kk)),
                (0x5, _, _, 0x0) => {
                    Instruction::SkipIfEqual(Register(x), Byte::Register(Register(y)))
                }
                (0x5, _, _, 0x2) => Instruction::StoreRange(Register(x), Register(y)),
                (0x5, _, _, 0x3) => Instruction::LoadRange(Register(x), Register(y)),
                (0x6, _, _, _) => Instruction::Set(Register(x), Byte::Immediate(kk)),
                (0x7, _, _, _) => Instruction::Add(Register(x), Byte::Immediate(kk)),
                (0x8, _, _, 0) => Instruction::Set(Register(x), Byte::Register(Register(y))),
                (0x8, _, _, 1) => Instruction::Or(Register(x), Register(y)),
                (0x8, _, _, 2) => Instruction::And(Register(x), Register(y)),
                (0x8, _, _, 3) => Instruction::Xor(Register(x), Register(y)),
                (0x8, _, _, 4) => Instruction::Add(Register(x), Byte::Register(Register(y))),
                (0x8, _, _, 5) => Instruction::Sub(Register(x), Register(y)),
                (0x8, _, _, 0x6) => Instruction::ShiftRight(Register(x), Register(y)),
                (0x8, _, _, 0x7) => Instruction::SubReverse(Register(x), Register(y)),
                (0x8, _, _, 0xE) => Instruction::ShiftLeft(Register(x), Register(y)),
                (0x9, _, _, 0x0) => {
                    Instruction::SkipIfNotEqual(Register(x), Byte::Register(Register(y)))
                }
                (0xA, _, _, _) => Instruction::SetIndex(u16::from(nnn)),
                (0xB, _, _, _) => Instruction::JumpRelative(u16::from(nnn)),
                (0xC, _x, _, _) => Instruction::Random(Register(x), kk),
                (0xD, _, _, _) => Instruction::Draw(Register(x), Register(y), n),
                (0xE, _x, 0x9, 0xE) => Instruction::SkipKey(Register(x)),
                (0xE, _x, 0xA, 0x1) => Instruction::SkipNotKey(Register(x)),
                (0xF, 0x0, 0x0, 0x0) => Instruction::SetIndexLong,
                (0xF, 0x0, 0x0, 0x2) => Instruction::LoadAudio,
                (0xF, _, 0x0, 0x7) => Instruction::LoadDelay(Register(x)),
                (0xF, _x, 0x0, 0xA) => Instruction::BlockKey(Register(x)),
                (0xF, _, 0x0, 0x1) => Instruction::SelectPlane(x),
                (0xF, _x, 0x3, 0xA) => Instruction::SetPitch(Register(x)),
                (0xF, _, 0x1, 0x5) => Instruction::SetDelay(Register(x)),
                (0xF, _, 0x1, 0x8) => Instruction::SetSound(Register(x)),
                (0xF, _, 0x1, 0xE) => Instruction::AddRegisterToIndex(Register(x)),
                (0xF, _x, 0x2, 0x9) => Instruction::FontCharacter(Register(x)),
                (0xF, _x, 0x3, 0x0) => Instruction::BigFontCharacter(Register(x)),
                (0xF, _x, 0x3, 0x3) => Instruction::Bcd(Register(x)),
                (0xF, _, 0x5, 0x5) => Instruction::Store(Register(x)),
                (0xF, _, 0x6, 0x5) => Instruction::Load(Register(x)),
                (0xF, _x, 0x7, 0x5) => Instruction::StoreFlags(Register(x)),
                (0xF, _x, 0x8, 0x5) => Instruction::LoadFlags(Register(x)),
                _ => return Err(format!("Unknown opcode {:#06x}", opcode)),
            },
        )
    }
}