Merge branch 'imperative-rs'
Rewrote the disassembler and `cpu::tick()` for code concision and massive speed improvements. Turns out, getting the current time takes AGES, so if we don't need it, we don't get it.
This commit is contained in:
commit
a744fa08c7
22
Cargo.lock
generated
22
Cargo.lock
generated
@ -182,6 +182,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"gumdrop",
|
"gumdrop",
|
||||||
"iced",
|
"iced",
|
||||||
|
"imperative-rs",
|
||||||
"minifb",
|
"minifb",
|
||||||
"owo-colors",
|
"owo-colors",
|
||||||
"rand",
|
"rand",
|
||||||
@ -1086,6 +1087,27 @@ version = "1.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "imperative-rs"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fed4f0a3a8fe169e919b74f6ba77c473d356ef05d0d65da06467b8836e508aa3"
|
||||||
|
dependencies = [
|
||||||
|
"imperative-rs-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "imperative-rs-derive"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "02b842fd8a24b2b715ac0baffae4aa72aa59ecb8e90d3de175180dbb5b1caaab"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 1.0.109",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "indexmap"
|
name = "indexmap"
|
||||||
version = "1.9.3"
|
version = "1.9.3"
|
||||||
|
@ -28,6 +28,7 @@ overflow-checks = false
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
gumdrop = "^0.8.1"
|
gumdrop = "^0.8.1"
|
||||||
iced = {version = "0.8.0", optional = true}
|
iced = {version = "0.8.0", optional = true}
|
||||||
|
imperative-rs = "0.3.1"
|
||||||
minifb = { version = "^0.24.0", features = ["wayland"] }
|
minifb = { version = "^0.24.0", features = ["wayland"] }
|
||||||
owo-colors = "^3"
|
owo-colors = "^3"
|
||||||
rand = "^0.8.5"
|
rand = "^0.8.5"
|
||||||
|
2
justfile
2
justfile
@ -4,7 +4,7 @@ test:
|
|||||||
cargo test --doc && cargo nextest run
|
cargo test --doc && cargo nextest run
|
||||||
|
|
||||||
chirp:
|
chirp:
|
||||||
cargo run --bin chirp -- tests/chip8-test-suite/bin/chip8-test-suite.ch8
|
cargo run --bin chirp-minifb -- tests/chip8-test-suite/bin/chip8-test-suite.ch8
|
||||||
|
|
||||||
cover:
|
cover:
|
||||||
cargo llvm-cov --open --doctests
|
cargo llvm-cov --open --doctests
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use chirp::{error::Result, prelude::*};
|
use chirp::{cpu::Disassembler, error::Result, prelude::*};
|
||||||
use gumdrop::*;
|
use gumdrop::*;
|
||||||
use std::{fs::read, path::PathBuf};
|
|
||||||
use owo_colors::OwoColorize;
|
use owo_colors::OwoColorize;
|
||||||
|
use std::{fs::read, path::PathBuf};
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Options, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Options, Hash)]
|
||||||
struct Arguments {
|
struct Arguments {
|
||||||
@ -22,18 +22,20 @@ fn parse_hex(value: &str) -> std::result::Result<u16, std::num::ParseIntError> {
|
|||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let options = Arguments::parse_args_default_or_exit();
|
let options = Arguments::parse_args_default_or_exit();
|
||||||
let contents = &read(&options.file)?;
|
let contents = &read(&options.file)?;
|
||||||
let disassembler = Disassemble::default();
|
let disassembler = Dis::default();
|
||||||
for (addr, insn) in contents[options.offset..].chunks_exact(2).enumerate() {
|
for (addr, insn) in contents[options.offset..].chunks_exact(2).enumerate() {
|
||||||
let insn = u16::from_be_bytes(
|
let insn = u16::from_be_bytes(
|
||||||
insn.try_into()
|
insn.try_into()
|
||||||
.expect("Iterated over 2-byte chunks, got <2 bytes"),
|
.expect("Iterated over 2-byte chunks, got <2 bytes"),
|
||||||
);
|
);
|
||||||
println!(
|
println!(
|
||||||
"{:03x}: {} {:04x}",
|
"{}",
|
||||||
2 * addr + 0x200 + options.offset,
|
format_args!(
|
||||||
disassembler.instruction(insn),
|
"{:03x}: {} {:04x}",
|
||||||
insn.bright_black(),
|
2 * addr + 0x200 + options.offset,
|
||||||
|
disassembler.once(insn),
|
||||||
|
insn.bright_black(),
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
use chirp::{error::Result, prelude::*};
|
use chirp::{error::Result, prelude::*};
|
||||||
use gumdrop::*;
|
use gumdrop::*;
|
||||||
|
use owo_colors::OwoColorize;
|
||||||
use std::fs::read;
|
use std::fs::read;
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
@ -23,11 +24,12 @@ struct Arguments {
|
|||||||
#[options(help = "Enable pause mode at startup.")]
|
#[options(help = "Enable pause mode at startup.")]
|
||||||
pub pause: bool,
|
pub pause: bool,
|
||||||
|
|
||||||
#[options(help = "Set the instructions-per-frame rate.")]
|
#[options(help = "Set the instructions-per-delay rate, or use realtime.")]
|
||||||
pub speed: Option<usize>,
|
pub speed: Option<usize>,
|
||||||
#[options(help = "Run the emulator as fast as possible for `step` instructions.")]
|
#[options(help = "Set the instructions-per-frame rate.")]
|
||||||
pub step: Option<usize>,
|
pub step: Option<usize>,
|
||||||
|
#[options(help = "Enable performance benchmarking on stderr (requires -S)")]
|
||||||
|
pub perf: bool,
|
||||||
#[options(
|
#[options(
|
||||||
short = "z",
|
short = "z",
|
||||||
help = "Disable setting vF to 0 after a bitwise operation."
|
help = "Disable setting vF to 0 after a bitwise operation."
|
||||||
@ -77,6 +79,7 @@ struct State {
|
|||||||
pub speed: usize,
|
pub speed: usize,
|
||||||
pub step: Option<usize>,
|
pub step: Option<usize>,
|
||||||
pub rate: u64,
|
pub rate: u64,
|
||||||
|
pub perf: bool,
|
||||||
pub ch8: Chip8,
|
pub ch8: Chip8,
|
||||||
pub ui: UI,
|
pub ui: UI,
|
||||||
pub ft: Instant,
|
pub ft: Instant,
|
||||||
@ -88,6 +91,7 @@ impl State {
|
|||||||
speed: options.speed.unwrap_or(8),
|
speed: options.speed.unwrap_or(8),
|
||||||
step: options.step,
|
step: options.step,
|
||||||
rate: options.frame_rate,
|
rate: options.frame_rate,
|
||||||
|
perf: options.perf,
|
||||||
ch8: Chip8 {
|
ch8: Chip8 {
|
||||||
bus: bus! {
|
bus: bus! {
|
||||||
// Load the charset into ROM
|
// Load the charset into ROM
|
||||||
@ -104,7 +108,7 @@ impl State {
|
|||||||
0x50,
|
0x50,
|
||||||
0x200,
|
0x200,
|
||||||
0xefe,
|
0xefe,
|
||||||
Disassemble::default(),
|
Dis::default(),
|
||||||
options.breakpoints,
|
options.breakpoints,
|
||||||
ControlFlags {
|
ControlFlags {
|
||||||
quirks: chirp::cpu::Quirks {
|
quirks: chirp::cpu::Quirks {
|
||||||
@ -127,27 +131,35 @@ impl State {
|
|||||||
state.ch8.bus.write(0x1feu16, options.data);
|
state.ch8.bus.write(0x1feu16, options.data);
|
||||||
Ok(state)
|
Ok(state)
|
||||||
}
|
}
|
||||||
fn keys(&mut self) -> Option<()> {
|
fn keys(&mut self) -> Result<Option<()>> {
|
||||||
self.ui.keys(&mut self.ch8)
|
self.ui.keys(&mut self.ch8)
|
||||||
}
|
}
|
||||||
fn frame(&mut self) -> Option<()> {
|
fn frame(&mut self) -> Option<()> {
|
||||||
self.ui.frame(&mut self.ch8)
|
self.ui.frame(&mut self.ch8)
|
||||||
}
|
}
|
||||||
fn tick_cpu(&mut self) {
|
fn tick_cpu(&mut self) -> Result<()> {
|
||||||
if !self.ch8.cpu.flags.pause {
|
if !self.ch8.cpu.flags.pause {
|
||||||
let rate = self.speed;
|
let rate = self.speed;
|
||||||
match self.step {
|
match self.step {
|
||||||
Some(ticks) => {
|
Some(ticks) => {
|
||||||
self.ch8.cpu.multistep(&mut self.ch8.bus, ticks);
|
let time = Instant::now();
|
||||||
// Pause the CPU and clear step
|
self.ch8.cpu.multistep(&mut self.ch8.bus, ticks)?;
|
||||||
self.ch8.cpu.flags.pause = true;
|
if self.perf {
|
||||||
self.step = None;
|
let time = time.elapsed();
|
||||||
|
let nspt = time.as_secs_f64() / ticks as f64;
|
||||||
|
eprintln!(
|
||||||
|
"{ticks},\t{time:.05?},\t{:.4}nspt,\t{}ipf",
|
||||||
|
nspt * 1_000_000_000.0,
|
||||||
|
((1.0 / 60.0f64) / nspt).trunc(),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
self.ch8.cpu.multistep(&mut self.ch8.bus, rate);
|
self.ch8.cpu.multistep(&mut self.ch8.bus, rate)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
fn wait_for_next_frame(&mut self) {
|
fn wait_for_next_frame(&mut self) {
|
||||||
let rate = 1_000_000_000 / self.rate + 1;
|
let rate = 1_000_000_000 / self.rate + 1;
|
||||||
@ -157,21 +169,34 @@ impl State {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Iterator for State {
|
impl Iterator for State {
|
||||||
type Item = ();
|
type Item = Result<()>;
|
||||||
|
|
||||||
|
/// Pretty heavily abusing iterators here, in an annoying way
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
self.wait_for_next_frame();
|
self.wait_for_next_frame();
|
||||||
self.keys()?;
|
match self.keys() {
|
||||||
self.tick_cpu();
|
Ok(opt) => opt?,
|
||||||
self.frame();
|
Err(e) => return Some(Err(e)), // summary
|
||||||
Some(())
|
}
|
||||||
|
self.keys().unwrap_or(None)?;
|
||||||
|
if let Err(e) = self.tick_cpu() {
|
||||||
|
return Some(Err(e));
|
||||||
|
}
|
||||||
|
self.frame()?;
|
||||||
|
Some(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let options = Arguments::parse_args_default_or_exit();
|
let options = Arguments::parse_args_default_or_exit();
|
||||||
let state = State::new(options)?;
|
let state = State::new(options)?;
|
||||||
Ok(for _ in state {})
|
for result in state {
|
||||||
|
if let Err(e) = result {
|
||||||
|
eprintln!("{}", e.bold().red());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a hexadecimal string into a u16
|
/// Parses a hexadecimal string into a u16
|
||||||
|
385
src/cpu.rs
385
src/cpu.rs
@ -6,10 +6,20 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
||||||
pub mod disassemble;
|
/// Disassembles Chip-8 instructions
|
||||||
|
pub trait Disassembler {
|
||||||
|
/// Disassemble a single instruction
|
||||||
|
fn once(&self, insn: u16) -> String;
|
||||||
|
}
|
||||||
|
|
||||||
use self::disassemble::Disassemble;
|
pub mod disassembler;
|
||||||
use crate::bus::{Bus, Read, Region, Write};
|
|
||||||
|
use self::disassembler::{Dis, Insn};
|
||||||
|
use crate::{
|
||||||
|
bus::{Bus, Read, Region, Write},
|
||||||
|
error::Result,
|
||||||
|
};
|
||||||
|
use imperative_rs::InstructionSet;
|
||||||
use owo_colors::OwoColorize;
|
use owo_colors::OwoColorize;
|
||||||
use rand::random;
|
use rand::random;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
@ -116,6 +126,22 @@ impl ControlFlags {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
struct Timers {
|
||||||
|
frame: Instant,
|
||||||
|
insn: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Timers {
|
||||||
|
fn default() -> Self {
|
||||||
|
let now = Instant::now();
|
||||||
|
Self {
|
||||||
|
frame: now,
|
||||||
|
insn: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Represents the internal state of the CPU interpreter
|
/// Represents the internal state of the CPU interpreter
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub struct CPU {
|
pub struct CPU {
|
||||||
@ -135,10 +161,10 @@ pub struct CPU {
|
|||||||
// I/O
|
// I/O
|
||||||
keys: [bool; 16],
|
keys: [bool; 16],
|
||||||
// Execution data
|
// Execution data
|
||||||
timer: Instant,
|
timers: Timers,
|
||||||
cycle: usize,
|
cycle: usize,
|
||||||
breakpoints: Vec<Adr>,
|
breakpoints: Vec<Adr>,
|
||||||
disassembler: Disassemble,
|
disassembler: Dis,
|
||||||
}
|
}
|
||||||
|
|
||||||
// public interface
|
// public interface
|
||||||
@ -153,7 +179,7 @@ impl CPU {
|
|||||||
/// 0x50, // font location
|
/// 0x50, // font location
|
||||||
/// 0x200, // start of program
|
/// 0x200, // start of program
|
||||||
/// 0xefe, // top of stack
|
/// 0xefe, // top of stack
|
||||||
/// Disassemble::default(),
|
/// Dis::default(),
|
||||||
/// vec![], // Breakpoints
|
/// vec![], // Breakpoints
|
||||||
/// ControlFlags::default()
|
/// ControlFlags::default()
|
||||||
/// );
|
/// );
|
||||||
@ -164,7 +190,7 @@ impl CPU {
|
|||||||
font: Adr,
|
font: Adr,
|
||||||
pc: Adr,
|
pc: Adr,
|
||||||
sp: Adr,
|
sp: Adr,
|
||||||
disassembler: Disassemble,
|
disassembler: Dis,
|
||||||
breakpoints: Vec<Adr>,
|
breakpoints: Vec<Adr>,
|
||||||
flags: ControlFlags,
|
flags: ControlFlags,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
@ -336,7 +362,7 @@ impl CPU {
|
|||||||
/// 0x50,
|
/// 0x50,
|
||||||
/// 0x340,
|
/// 0x340,
|
||||||
/// 0xefe,
|
/// 0xefe,
|
||||||
/// Disassemble::default(),
|
/// Dis::default(),
|
||||||
/// vec![],
|
/// vec![],
|
||||||
/// ControlFlags::default()
|
/// ControlFlags::default()
|
||||||
/// );
|
/// );
|
||||||
@ -368,7 +394,7 @@ impl CPU {
|
|||||||
/// Unset a breakpoint
|
/// Unset a breakpoint
|
||||||
// TODO: Unit test this
|
// TODO: Unit test this
|
||||||
pub fn unset_break(&mut self, point: Adr) -> &mut Self {
|
pub fn unset_break(&mut self, point: Adr) -> &mut Self {
|
||||||
fn linear_find(needle: Adr, haystack: &Vec<Adr>) -> Option<usize> {
|
fn linear_find(needle: Adr, haystack: &[Adr]) -> Option<usize> {
|
||||||
for (i, v) in haystack.iter().enumerate() {
|
for (i, v) in haystack.iter().enumerate() {
|
||||||
if *v == needle {
|
if *v == needle {
|
||||||
return Some(i);
|
return Some(i);
|
||||||
@ -376,7 +402,7 @@ impl CPU {
|
|||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
if let Some(idx) = linear_find(point, &self.breakpoints) {
|
if let Some(idx) = linear_find(point, self.breakpoints.as_slice()) {
|
||||||
assert_eq!(point, self.breakpoints.swap_remove(idx));
|
assert_eq!(point, self.breakpoints.swap_remove(idx));
|
||||||
}
|
}
|
||||||
self
|
self
|
||||||
@ -393,7 +419,7 @@ impl CPU {
|
|||||||
///# }
|
///# }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn breakpoints(&self) -> &[Adr] {
|
pub fn breakpoints(&self) -> &[Adr] {
|
||||||
&self.breakpoints.as_slice()
|
self.breakpoints.as_slice()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unpauses the emulator for a single tick,
|
/// Unpauses the emulator for a single tick,
|
||||||
@ -412,18 +438,18 @@ impl CPU {
|
|||||||
/// ],
|
/// ],
|
||||||
/// Screen [0x0f00..0x1000],
|
/// Screen [0x0f00..0x1000],
|
||||||
/// };
|
/// };
|
||||||
/// cpu.singlestep(&mut bus);
|
/// cpu.singlestep(&mut bus)?;
|
||||||
/// assert_eq!(0x202, cpu.pc());
|
/// assert_eq!(0x202, cpu.pc());
|
||||||
/// assert_eq!(1, cpu.cycle());
|
/// assert_eq!(1, cpu.cycle());
|
||||||
///# Ok(())
|
///# Ok(())
|
||||||
///# }
|
///# }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn singlestep(&mut self, bus: &mut Bus) -> &mut Self {
|
pub fn singlestep(&mut self, bus: &mut Bus) -> Result<&mut Self> {
|
||||||
self.flags.pause = false;
|
self.flags.pause = false;
|
||||||
self.tick(bus);
|
self.tick(bus)?;
|
||||||
self.flags.vbi_wait = false;
|
self.flags.vbi_wait = false;
|
||||||
self.flags.pause = true;
|
self.flags.pause = true;
|
||||||
self
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unpauses the emulator for `steps` ticks
|
/// Unpauses the emulator for `steps` ticks
|
||||||
@ -441,18 +467,18 @@ impl CPU {
|
|||||||
/// ],
|
/// ],
|
||||||
/// Screen [0x0f00..0x1000],
|
/// Screen [0x0f00..0x1000],
|
||||||
/// };
|
/// };
|
||||||
/// cpu.multistep(&mut bus, 0x20);
|
/// cpu.multistep(&mut bus, 0x20)?;
|
||||||
/// assert_eq!(0x202, cpu.pc());
|
/// assert_eq!(0x202, cpu.pc());
|
||||||
/// assert_eq!(0x20, cpu.cycle());
|
/// assert_eq!(0x20, cpu.cycle());
|
||||||
///# Ok(())
|
///# Ok(())
|
||||||
///# }
|
///# }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn multistep(&mut self, bus: &mut Bus, steps: usize) -> &mut Self {
|
pub fn multistep(&mut self, bus: &mut Bus, steps: usize) -> Result<&mut Self> {
|
||||||
for _ in 0..steps {
|
for _ in 0..steps {
|
||||||
self.tick(bus);
|
self.tick(bus)?;
|
||||||
self.vertical_blank();
|
self.vertical_blank();
|
||||||
}
|
}
|
||||||
self
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Simulates vertical blanking
|
/// Simulates vertical blanking
|
||||||
@ -464,6 +490,7 @@ impl CPU {
|
|||||||
/// - Subtracts the elapsed time in fractions of a frame
|
/// - Subtracts the elapsed time in fractions of a frame
|
||||||
/// from st/dt
|
/// from st/dt
|
||||||
/// - Disables framepause if the duration exceeds that of a frame
|
/// - Disables framepause if the duration exceeds that of a frame
|
||||||
|
#[inline(always)]
|
||||||
pub fn vertical_blank(&mut self) -> &mut Self {
|
pub fn vertical_blank(&mut self) -> &mut Self {
|
||||||
if self.flags.pause {
|
if self.flags.pause {
|
||||||
return self;
|
return self;
|
||||||
@ -471,16 +498,17 @@ impl CPU {
|
|||||||
// Use a monotonic counter when testing
|
// Use a monotonic counter when testing
|
||||||
if let Some(speed) = self.flags.monotonic {
|
if let Some(speed) = self.flags.monotonic {
|
||||||
if self.flags.vbi_wait {
|
if self.flags.vbi_wait {
|
||||||
self.flags.vbi_wait = !(self.cycle % speed == 0);
|
self.flags.vbi_wait = self.cycle % speed != 0;
|
||||||
}
|
}
|
||||||
self.delay -= 1.0 / speed as f64;
|
let speed = 1.0 / speed as f64;
|
||||||
self.sound -= 1.0 / speed as f64;
|
self.delay -= speed;
|
||||||
|
self.sound -= speed;
|
||||||
return self;
|
return self;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Convert the elapsed time to 60ths of a second
|
// Convert the elapsed time to 60ths of a second
|
||||||
let time = self.timer.elapsed().as_secs_f64() * 60.0;
|
let time = self.timers.frame.elapsed().as_secs_f64() * 60.0;
|
||||||
self.timer = Instant::now();
|
self.timers.frame = Instant::now();
|
||||||
if time > 1.0 {
|
if time > 1.0 {
|
||||||
self.flags.vbi_wait = false;
|
self.flags.vbi_wait = false;
|
||||||
}
|
}
|
||||||
@ -506,7 +534,7 @@ impl CPU {
|
|||||||
/// ],
|
/// ],
|
||||||
/// Screen [0x0f00..0x1000],
|
/// Screen [0x0f00..0x1000],
|
||||||
/// };
|
/// };
|
||||||
/// cpu.tick(&mut bus);
|
/// cpu.tick(&mut bus)?;
|
||||||
/// assert_eq!(0x202, cpu.pc());
|
/// assert_eq!(0x202, cpu.pc());
|
||||||
/// assert_eq!(1, cpu.cycle());
|
/// assert_eq!(1, cpu.cycle());
|
||||||
///# Ok(())
|
///# Ok(())
|
||||||
@ -527,162 +555,92 @@ impl CPU {
|
|||||||
/// ],
|
/// ],
|
||||||
/// Screen [0x0f00..0x1000],
|
/// Screen [0x0f00..0x1000],
|
||||||
/// };
|
/// };
|
||||||
/// cpu.multistep(&mut bus, 0x10); // panics!
|
/// cpu.tick(&mut bus)?; // panics!
|
||||||
///# Ok(())
|
///# Ok(())
|
||||||
///# }
|
///# }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn tick(&mut self, bus: &mut Bus) -> &mut Self {
|
pub fn tick(&mut self, bus: &mut Bus) -> Result<&mut Self> {
|
||||||
// Do nothing if paused
|
// Do nothing if paused
|
||||||
if self.flags.pause || self.flags.vbi_wait || self.flags.keypause {
|
if self.flags.pause || self.flags.vbi_wait || self.flags.keypause {
|
||||||
// always tick in test mode
|
// always tick in test mode
|
||||||
if self.flags.monotonic.is_some() {
|
if self.flags.monotonic.is_some() {
|
||||||
self.cycle += 1;
|
self.cycle += 1;
|
||||||
}
|
}
|
||||||
return self;
|
return Ok(self);
|
||||||
}
|
}
|
||||||
self.cycle += 1;
|
self.cycle += 1;
|
||||||
// fetch opcode
|
// fetch opcode
|
||||||
let opcode: u16 = bus.read(self.pc);
|
let opcode: &[u8; 2] = if let Some(slice) = bus.get(self.pc as usize..self.pc as usize + 2)
|
||||||
let pc = self.pc;
|
{
|
||||||
|
slice.try_into()?
|
||||||
|
} else {
|
||||||
|
return Err(crate::error::Error::InvalidBusRange {
|
||||||
|
range: self.pc as usize..self.pc as usize + 2,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
// DINC pc
|
|
||||||
self.pc = self.pc.wrapping_add(2);
|
|
||||||
// decode opcode
|
|
||||||
|
|
||||||
use disassemble::{a, b, i, n, x, y};
|
|
||||||
let (i, x, y, n, b, a) = (
|
|
||||||
i(opcode),
|
|
||||||
x(opcode),
|
|
||||||
y(opcode),
|
|
||||||
n(opcode),
|
|
||||||
b(opcode),
|
|
||||||
a(opcode),
|
|
||||||
);
|
|
||||||
match i {
|
|
||||||
// # Issue a system call
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 00e0 | Clear screen memory to all 0 |
|
|
||||||
// | 00ee | Return from subroutine |
|
|
||||||
0x0 => match a {
|
|
||||||
0x0e0 => self.clear_screen(bus),
|
|
||||||
0x0ee => self.ret(bus),
|
|
||||||
_ => self.sys(a),
|
|
||||||
},
|
|
||||||
// | 1aaa | Sets pc to an absolute address
|
|
||||||
0x1 => self.jump(a),
|
|
||||||
// | 2aaa | Pushes pc onto the stack, then jumps to a
|
|
||||||
0x2 => self.call(a, bus),
|
|
||||||
// | 3xbb | Skips next instruction if register X == b
|
|
||||||
0x3 => self.skip_equals_immediate(x, b),
|
|
||||||
// | 4xbb | Skips next instruction if register X != b
|
|
||||||
0x4 => self.skip_not_equals_immediate(x, b),
|
|
||||||
// # Performs a register-register comparison
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 9XY0 | Skip next instruction if vX == vY |
|
|
||||||
0x5 => match n {
|
|
||||||
0x0 => self.skip_equals(x, y),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// 6xbb: Loads immediate byte b into register vX
|
|
||||||
0x6 => self.load_immediate(x, b),
|
|
||||||
// 7xbb: Adds immediate byte b to register vX
|
|
||||||
0x7 => self.add_immediate(x, b),
|
|
||||||
// # Performs ALU operation
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 8xy0 | Y = X |
|
|
||||||
// | 8xy1 | X = X | Y |
|
|
||||||
// | 8xy2 | X = X & Y |
|
|
||||||
// | 8xy3 | X = X ^ Y |
|
|
||||||
// | 8xy4 | X = X + Y; Set vF=carry |
|
|
||||||
// | 8xy5 | X = X - Y; Set vF=carry |
|
|
||||||
// | 8xy6 | X = X >> 1 |
|
|
||||||
// | 8xy7 | X = Y - X; Set vF=carry |
|
|
||||||
// | 8xyE | X = X << 1 |
|
|
||||||
0x8 => match n {
|
|
||||||
0x0 => self.load(x, y),
|
|
||||||
0x1 => self.or(x, y),
|
|
||||||
0x2 => self.and(x, y),
|
|
||||||
0x3 => self.xor(x, y),
|
|
||||||
0x4 => self.add(x, y),
|
|
||||||
0x5 => self.sub(x, y),
|
|
||||||
0x6 => self.shift_right(x, y),
|
|
||||||
0x7 => self.backwards_sub(x, y),
|
|
||||||
0xE => self.shift_left(x, y),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// # Performs a register-register comparison
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 9XY0 | Skip next instruction if vX != vY |
|
|
||||||
0x9 => match n {
|
|
||||||
0 => self.skip_not_equals(x, y),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// Aaaa: Load address #a into register I
|
|
||||||
0xa => self.load_i_immediate(a),
|
|
||||||
// Baaa: Jump to &adr + v0
|
|
||||||
0xb => self.jump_indexed(a),
|
|
||||||
// Cxbb: Stores a random number + the provided byte into vX
|
|
||||||
0xc => self.rand(x, b),
|
|
||||||
// Dxyn: Draws n-byte sprite to the screen at coordinates (vX, vY)
|
|
||||||
0xd => self.draw(x, y, n, bus),
|
|
||||||
|
|
||||||
// # Skips instruction on value of keypress
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | eX9e | Skip next instruction if key == vX |
|
|
||||||
// | eXa1 | Skip next instruction if key != vX |
|
|
||||||
0xe => match b {
|
|
||||||
0x9e => self.skip_key_equals(x),
|
|
||||||
0xa1 => self.skip_key_not_equals(x),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
|
|
||||||
// # Performs IO
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | fX07 | Set vX to value in delay timer |
|
|
||||||
// | fX0a | Wait for input, store in vX m |
|
|
||||||
// | fX15 | Set sound timer to the value in vX |
|
|
||||||
// | fX18 | set delay timer to the value in vX |
|
|
||||||
// | fX1e | Add x to I |
|
|
||||||
// | fX29 | Load sprite for character x into I |
|
|
||||||
// | fX33 | BCD convert X into I[0..3] |
|
|
||||||
// | fX55 | DMA Stor from I to registers 0..X |
|
|
||||||
// | fX65 | DMA Load from I to registers 0..X |
|
|
||||||
0xf => match b {
|
|
||||||
0x07 => self.load_delay_timer(x),
|
|
||||||
0x0A => self.wait_for_key(x),
|
|
||||||
0x15 => self.store_delay_timer(x),
|
|
||||||
0x18 => self.store_sound_timer(x),
|
|
||||||
0x1E => self.add_i(x),
|
|
||||||
0x29 => self.load_sprite(x),
|
|
||||||
0x33 => self.bcd_convert(x, bus),
|
|
||||||
0x55 => self.store_dma(x, bus),
|
|
||||||
0x65 => self.load_dma(x, bus),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
_ => unreachable!("Extracted nibble from byte, got >nibble?"),
|
|
||||||
}
|
|
||||||
let elapsed = self.timer.elapsed();
|
|
||||||
// Print opcode disassembly:
|
// Print opcode disassembly:
|
||||||
if self.flags.debug {
|
if self.flags.debug {
|
||||||
std::println!(
|
println!("{:?}", self.timers.insn.elapsed().bright_black());
|
||||||
"{:3} {:03x}: {:<36}{:?}",
|
self.timers.insn = Instant::now();
|
||||||
|
std::print!(
|
||||||
|
"{:3} {:03x}: {:<36}",
|
||||||
self.cycle.bright_black(),
|
self.cycle.bright_black(),
|
||||||
pc,
|
self.pc,
|
||||||
self.disassembler.instruction(opcode),
|
self.disassembler.once(u16::from_be_bytes(*opcode))
|
||||||
elapsed.dimmed()
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// decode opcode
|
||||||
|
if let Ok((inc, insn)) = Insn::decode(opcode) {
|
||||||
|
self.pc = self.pc.wrapping_add(inc as u16);
|
||||||
|
match insn {
|
||||||
|
Insn::cls => self.clear_screen(bus),
|
||||||
|
Insn::ret => self.ret(bus),
|
||||||
|
Insn::jmp { A } => self.jump(A),
|
||||||
|
Insn::call { A } => self.call(A, bus),
|
||||||
|
Insn::seb { B, x } => self.skip_equals_immediate(x, B),
|
||||||
|
Insn::sneb { B, x } => self.skip_not_equals_immediate(x, B),
|
||||||
|
Insn::se { y, x } => self.skip_equals(x, y),
|
||||||
|
Insn::movb { B, x } => self.load_immediate(x, B),
|
||||||
|
Insn::addb { B, x } => self.add_immediate(x, B),
|
||||||
|
Insn::mov { x, y } => self.load(x, y),
|
||||||
|
Insn::or { y, x } => self.or(x, y),
|
||||||
|
Insn::and { y, x } => self.and(x, y),
|
||||||
|
Insn::xor { y, x } => self.xor(x, y),
|
||||||
|
Insn::add { y, x } => self.add(x, y),
|
||||||
|
Insn::sub { y, x } => self.sub(x, y),
|
||||||
|
Insn::shr { y, x } => self.shift_right(x, y),
|
||||||
|
Insn::bsub { y, x } => self.backwards_sub(x, y),
|
||||||
|
Insn::shl { y, x } => self.shift_left(x, y),
|
||||||
|
Insn::sne { y, x } => self.skip_not_equals(x, y),
|
||||||
|
Insn::movI { A } => self.load_i_immediate(A),
|
||||||
|
Insn::jmpr { A } => self.jump_indexed(A),
|
||||||
|
Insn::rand { B, x } => self.rand(x, B),
|
||||||
|
Insn::draw { x, y, n } => self.draw(x, y, n, bus),
|
||||||
|
Insn::sek { x } => self.skip_key_equals(x),
|
||||||
|
Insn::snek { x } => self.skip_key_not_equals(x),
|
||||||
|
Insn::getdt { x } => self.load_delay_timer(x),
|
||||||
|
Insn::waitk { x } => self.wait_for_key(x),
|
||||||
|
Insn::setdt { x } => self.store_delay_timer(x),
|
||||||
|
Insn::movst { x } => self.store_sound_timer(x),
|
||||||
|
Insn::addI { x } => self.add_i(x),
|
||||||
|
Insn::font { x } => self.load_sprite(x),
|
||||||
|
Insn::bcd { x } => self.bcd_convert(x, bus),
|
||||||
|
Insn::dmao { x } => self.store_dma(x, bus),
|
||||||
|
Insn::dmai { x } => self.load_dma(x, bus),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err(crate::error::Error::UnimplementedInstruction {
|
||||||
|
word: u16::from_be_bytes(*opcode),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// process breakpoints
|
// process breakpoints
|
||||||
if self.breakpoints.contains(&self.pc) {
|
if !self.breakpoints.is_empty() && self.breakpoints.contains(&self.pc) {
|
||||||
self.flags.pause = true;
|
self.flags.pause = true;
|
||||||
}
|
}
|
||||||
self
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dumps the current state of all CPU registers, and the cycle count
|
/// Dumps the current state of all CPU registers, and the cycle count
|
||||||
@ -763,9 +721,9 @@ impl Default for CPU {
|
|||||||
debug: true,
|
debug: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
timer: Instant::now(),
|
timers: Default::default(),
|
||||||
breakpoints: vec![],
|
breakpoints: vec![],
|
||||||
disassembler: Disassemble::default(),
|
disassembler: Dis::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -780,18 +738,8 @@ impl Default for CPU {
|
|||||||
// | 00e0 | Clear screen memory to all 0 |
|
// | 00e0 | Clear screen memory to all 0 |
|
||||||
// | 00ee | Return from subroutine |
|
// | 00ee | Return from subroutine |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// Unused instructions
|
|
||||||
#[inline]
|
|
||||||
fn unimplemented(&self, opcode: u16) {
|
|
||||||
unimplemented!("Opcode: {opcode:04x}")
|
|
||||||
}
|
|
||||||
/// 0aaa: Handles a "machine language function call" (lmao)
|
|
||||||
#[inline]
|
|
||||||
fn sys(&mut self, a: Adr) {
|
|
||||||
unimplemented!("SYS\t{a:03x}");
|
|
||||||
}
|
|
||||||
/// 00e0: Clears the screen memory to 0
|
/// 00e0: Clears the screen memory to 0
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn clear_screen(&mut self, bus: &mut Bus) {
|
fn clear_screen(&mut self, bus: &mut Bus) {
|
||||||
if let Some(screen) = bus.get_region_mut(Region::Screen) {
|
if let Some(screen) = bus.get_region_mut(Region::Screen) {
|
||||||
for byte in screen {
|
for byte in screen {
|
||||||
@ -800,7 +748,7 @@ impl CPU {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// 00ee: Returns from subroutine
|
/// 00ee: Returns from subroutine
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn ret(&mut self, bus: &impl Read<u16>) {
|
fn ret(&mut self, bus: &impl Read<u16>) {
|
||||||
self.sp = self.sp.wrapping_add(2);
|
self.sp = self.sp.wrapping_add(2);
|
||||||
self.pc = bus.read(self.sp);
|
self.pc = bus.read(self.sp);
|
||||||
@ -810,7 +758,7 @@ impl CPU {
|
|||||||
// | 1aaa | Sets pc to an absolute address
|
// | 1aaa | Sets pc to an absolute address
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 1aaa: Sets the program counter to an absolute address
|
/// 1aaa: Sets the program counter to an absolute address
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn jump(&mut self, a: Adr) {
|
fn jump(&mut self, a: Adr) {
|
||||||
// jump to self == halt
|
// jump to self == halt
|
||||||
if a.wrapping_add(2) == self.pc {
|
if a.wrapping_add(2) == self.pc {
|
||||||
@ -823,7 +771,7 @@ impl CPU {
|
|||||||
// | 2aaa | Pushes pc onto the stack, then jumps to a
|
// | 2aaa | Pushes pc onto the stack, then jumps to a
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 2aaa: Pushes pc onto the stack, then jumps to a
|
/// 2aaa: Pushes pc onto the stack, then jumps to a
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn call(&mut self, a: Adr, bus: &mut impl Write<u16>) {
|
fn call(&mut self, a: Adr, bus: &mut impl Write<u16>) {
|
||||||
bus.write(self.sp, self.pc);
|
bus.write(self.sp, self.pc);
|
||||||
self.sp = self.sp.wrapping_sub(2);
|
self.sp = self.sp.wrapping_sub(2);
|
||||||
@ -834,7 +782,7 @@ impl CPU {
|
|||||||
// | 3xbb | Skips next instruction if register X == b
|
// | 3xbb | Skips next instruction if register X == b
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 3xbb: Skips the next instruction if register X == b
|
/// 3xbb: Skips the next instruction if register X == b
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_equals_immediate(&mut self, x: Reg, b: u8) {
|
fn skip_equals_immediate(&mut self, x: Reg, b: u8) {
|
||||||
if self.v[x] == b {
|
if self.v[x] == b {
|
||||||
self.pc = self.pc.wrapping_add(2);
|
self.pc = self.pc.wrapping_add(2);
|
||||||
@ -845,7 +793,7 @@ impl CPU {
|
|||||||
// | 4xbb | Skips next instruction if register X != b
|
// | 4xbb | Skips next instruction if register X != b
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 4xbb: Skips the next instruction if register X != b
|
/// 4xbb: Skips the next instruction if register X != b
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_not_equals_immediate(&mut self, x: Reg, b: u8) {
|
fn skip_not_equals_immediate(&mut self, x: Reg, b: u8) {
|
||||||
if self.v[x] != b {
|
if self.v[x] != b {
|
||||||
self.pc = self.pc.wrapping_add(2);
|
self.pc = self.pc.wrapping_add(2);
|
||||||
@ -860,7 +808,7 @@ impl CPU {
|
|||||||
// | 5XY0 | Skip next instruction if vX == vY |
|
// | 5XY0 | Skip next instruction if vX == vY |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 5xy0: Skips the next instruction if register X != register Y
|
/// 5xy0: Skips the next instruction if register X != register Y
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_equals(&mut self, x: Reg, y: Reg) {
|
fn skip_equals(&mut self, x: Reg, y: Reg) {
|
||||||
if self.v[x] == self.v[y] {
|
if self.v[x] == self.v[y] {
|
||||||
self.pc = self.pc.wrapping_add(2);
|
self.pc = self.pc.wrapping_add(2);
|
||||||
@ -871,7 +819,7 @@ impl CPU {
|
|||||||
// | 6xbb | Loads immediate byte b into register vX
|
// | 6xbb | Loads immediate byte b into register vX
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 6xbb: Loads immediate byte b into register vX
|
/// 6xbb: Loads immediate byte b into register vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load_immediate(&mut self, x: Reg, b: u8) {
|
fn load_immediate(&mut self, x: Reg, b: u8) {
|
||||||
self.v[x] = b;
|
self.v[x] = b;
|
||||||
}
|
}
|
||||||
@ -880,7 +828,7 @@ impl CPU {
|
|||||||
// | 7xbb | Adds immediate byte b to register vX
|
// | 7xbb | Adds immediate byte b to register vX
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 7xbb: Adds immediate byte b to register vX
|
/// 7xbb: Adds immediate byte b to register vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn add_immediate(&mut self, x: Reg, b: u8) {
|
fn add_immediate(&mut self, x: Reg, b: u8) {
|
||||||
self.v[x] = self.v[x].wrapping_add(b);
|
self.v[x] = self.v[x].wrapping_add(b);
|
||||||
}
|
}
|
||||||
@ -901,7 +849,7 @@ impl CPU {
|
|||||||
// | 8xyE | X = X << 1 |
|
// | 8xyE | X = X << 1 |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 8xy0: Loads the value of y into x
|
/// 8xy0: Loads the value of y into x
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load(&mut self, x: Reg, y: Reg) {
|
fn load(&mut self, x: Reg, y: Reg) {
|
||||||
self.v[x] = self.v[y];
|
self.v[x] = self.v[y];
|
||||||
}
|
}
|
||||||
@ -909,7 +857,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn or(&mut self, x: Reg, y: Reg) {
|
fn or(&mut self, x: Reg, y: Reg) {
|
||||||
self.v[x] |= self.v[y];
|
self.v[x] |= self.v[y];
|
||||||
if self.flags.quirks.bin_ops {
|
if self.flags.quirks.bin_ops {
|
||||||
@ -920,7 +868,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn and(&mut self, x: Reg, y: Reg) {
|
fn and(&mut self, x: Reg, y: Reg) {
|
||||||
self.v[x] &= self.v[y];
|
self.v[x] &= self.v[y];
|
||||||
if self.flags.quirks.bin_ops {
|
if self.flags.quirks.bin_ops {
|
||||||
@ -931,7 +879,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
/// The original chip-8 interpreter will clobber vF for any 8-series instruction
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn xor(&mut self, x: Reg, y: Reg) {
|
fn xor(&mut self, x: Reg, y: Reg) {
|
||||||
self.v[x] ^= self.v[y];
|
self.v[x] ^= self.v[y];
|
||||||
if self.flags.quirks.bin_ops {
|
if self.flags.quirks.bin_ops {
|
||||||
@ -939,14 +887,14 @@ impl CPU {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// 8xy4: Performs addition of vX and vY, and stores the result in vX
|
/// 8xy4: Performs addition of vX and vY, and stores the result in vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn add(&mut self, x: Reg, y: Reg) {
|
fn add(&mut self, x: Reg, y: Reg) {
|
||||||
let carry;
|
let carry;
|
||||||
(self.v[x], carry) = self.v[x].overflowing_add(self.v[y]);
|
(self.v[x], carry) = self.v[x].overflowing_add(self.v[y]);
|
||||||
self.v[0xf] = carry.into();
|
self.v[0xf] = carry.into();
|
||||||
}
|
}
|
||||||
/// 8xy5: Performs subtraction of vX and vY, and stores the result in vX
|
/// 8xy5: Performs subtraction of vX and vY, and stores the result in vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn sub(&mut self, x: Reg, y: Reg) {
|
fn sub(&mut self, x: Reg, y: Reg) {
|
||||||
let carry;
|
let carry;
|
||||||
(self.v[x], carry) = self.v[x].overflowing_sub(self.v[y]);
|
(self.v[x], carry) = self.v[x].overflowing_sub(self.v[y]);
|
||||||
@ -956,7 +904,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// On the original chip-8 interpreter, this shifts vY and stores the result in vX
|
/// On the original chip-8 interpreter, this shifts vY and stores the result in vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn shift_right(&mut self, x: Reg, y: Reg) {
|
fn shift_right(&mut self, x: Reg, y: Reg) {
|
||||||
let src: Reg = if self.flags.quirks.shift { y } else { x };
|
let src: Reg = if self.flags.quirks.shift { y } else { x };
|
||||||
let shift_out = self.v[src] & 1;
|
let shift_out = self.v[src] & 1;
|
||||||
@ -964,7 +912,7 @@ impl CPU {
|
|||||||
self.v[0xf] = shift_out;
|
self.v[0xf] = shift_out;
|
||||||
}
|
}
|
||||||
/// 8xy7: Performs subtraction of vY and vX, and stores the result in vX
|
/// 8xy7: Performs subtraction of vY and vX, and stores the result in vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn backwards_sub(&mut self, x: Reg, y: Reg) {
|
fn backwards_sub(&mut self, x: Reg, y: Reg) {
|
||||||
let carry;
|
let carry;
|
||||||
(self.v[x], carry) = self.v[y].overflowing_sub(self.v[x]);
|
(self.v[x], carry) = self.v[y].overflowing_sub(self.v[x]);
|
||||||
@ -975,7 +923,7 @@ impl CPU {
|
|||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// On the original chip-8 interpreter, this would perform the operation on vY
|
/// On the original chip-8 interpreter, this would perform the operation on vY
|
||||||
/// and store the result in vX. This behavior was left out, for now.
|
/// and store the result in vX. This behavior was left out, for now.
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn shift_left(&mut self, x: Reg, y: Reg) {
|
fn shift_left(&mut self, x: Reg, y: Reg) {
|
||||||
let src: Reg = if self.flags.quirks.shift { y } else { x };
|
let src: Reg = if self.flags.quirks.shift { y } else { x };
|
||||||
let shift_out: u8 = self.v[src] >> 7;
|
let shift_out: u8 = self.v[src] >> 7;
|
||||||
@ -991,7 +939,7 @@ impl CPU {
|
|||||||
// | 9XY0 | Skip next instruction if vX != vY |
|
// | 9XY0 | Skip next instruction if vX != vY |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// 9xy0: Skip next instruction if X != y
|
/// 9xy0: Skip next instruction if X != y
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_not_equals(&mut self, x: Reg, y: Reg) {
|
fn skip_not_equals(&mut self, x: Reg, y: Reg) {
|
||||||
if self.v[x] != self.v[y] {
|
if self.v[x] != self.v[y] {
|
||||||
self.pc = self.pc.wrapping_add(2);
|
self.pc = self.pc.wrapping_add(2);
|
||||||
@ -1002,7 +950,7 @@ impl CPU {
|
|||||||
// | Aaaa | Load address #a into register I
|
// | Aaaa | Load address #a into register I
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// Aadr: Load address #adr into register I
|
/// Aadr: Load address #adr into register I
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load_i_immediate(&mut self, a: Adr) {
|
fn load_i_immediate(&mut self, a: Adr) {
|
||||||
self.i = a;
|
self.i = a;
|
||||||
}
|
}
|
||||||
@ -1014,7 +962,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// Quirk:
|
/// Quirk:
|
||||||
/// On the Super-Chip, this does stupid shit
|
/// On the Super-Chip, this does stupid shit
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn jump_indexed(&mut self, a: Adr) {
|
fn jump_indexed(&mut self, a: Adr) {
|
||||||
let reg = if self.flags.quirks.stupid_jumps {
|
let reg = if self.flags.quirks.stupid_jumps {
|
||||||
a as usize >> 8
|
a as usize >> 8
|
||||||
@ -1025,10 +973,10 @@ impl CPU {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// | Cxbb | Stores a random number + the provided byte into vX
|
// | Cxbb | Stores a random number & the provided byte into vX
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// Cxbb: Stores a random number & the provided byte into vX
|
/// Cxbb: Stores a random number & the provided byte into vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn rand(&mut self, x: Reg, b: u8) {
|
fn rand(&mut self, x: Reg, b: u8) {
|
||||||
self.v[x] = random::<u8>() & b;
|
self.v[x] = random::<u8>() & b;
|
||||||
}
|
}
|
||||||
@ -1040,6 +988,7 @@ impl CPU {
|
|||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// On the original chip-8 interpreter, this will wait for a VBI
|
/// On the original chip-8 interpreter, this will wait for a VBI
|
||||||
|
#[inline(always)]
|
||||||
fn draw(&mut self, x: Reg, y: Reg, n: Nib, bus: &mut Bus) {
|
fn draw(&mut self, x: Reg, y: Reg, n: Nib, bus: &mut Bus) {
|
||||||
let (x, y) = (self.v[x] as u16 % 64, self.v[y] as u16 % 32);
|
let (x, y) = (self.v[x] as u16 % 64, self.v[y] as u16 % 32);
|
||||||
if self.flags.quirks.draw_wait {
|
if self.flags.quirks.draw_wait {
|
||||||
@ -1054,7 +1003,7 @@ impl CPU {
|
|||||||
let addr = (y + byte) * 8 + (x & 0x3f) / 8 + self.screen;
|
let addr = (y + byte) * 8 + (x & 0x3f) / 8 + self.screen;
|
||||||
// Read a byte of sprite data into a u16, and shift it x % 8 bits
|
// Read a byte of sprite data into a u16, and shift it x % 8 bits
|
||||||
let sprite: u8 = bus.read(self.i + byte);
|
let sprite: u8 = bus.read(self.i + byte);
|
||||||
let sprite = (sprite as u16) << 8 - (x & 7) & if x % 64 > 56 { 0xff00 } else { 0xffff };
|
let sprite = (sprite as u16) << (8 - (x & 7)) & if x % 64 > 56 { 0xff00 } else { 0xffff };
|
||||||
// Read a u16 from the bus containing the two bytes which might need to be updated
|
// Read a u16 from the bus containing the two bytes which might need to be updated
|
||||||
let mut screen: u16 = bus.read(addr);
|
let mut screen: u16 = bus.read(addr);
|
||||||
// Save the bits-toggled-off flag if necessary
|
// Save the bits-toggled-off flag if necessary
|
||||||
@ -1073,19 +1022,19 @@ impl CPU {
|
|||||||
//
|
//
|
||||||
// |opcode| effect |
|
// |opcode| effect |
|
||||||
// |------|------------------------------------|
|
// |------|------------------------------------|
|
||||||
// | eX9e | Skip next instruction if key == #X |
|
// | eX9e | Skip next instruction if key == vX |
|
||||||
// | eXa1 | Skip next instruction if key != #X |
|
// | eXa1 | Skip next instruction if key != vX |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// Ex9E: Skip next instruction if key == #X
|
/// Ex9E: Skip next instruction if key == vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_key_equals(&mut self, x: Reg) {
|
fn skip_key_equals(&mut self, x: Reg) {
|
||||||
let x = self.v[x] as usize;
|
let x = self.v[x] as usize;
|
||||||
if self.keys[x] {
|
if self.keys[x] {
|
||||||
self.pc += 2;
|
self.pc += 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// ExaE: Skip next instruction if key != #X
|
/// ExaE: Skip next instruction if key != vX
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn skip_key_not_equals(&mut self, x: Reg) {
|
fn skip_key_not_equals(&mut self, x: Reg) {
|
||||||
let x = self.v[x] as usize;
|
let x = self.v[x] as usize;
|
||||||
if !self.keys[x] {
|
if !self.keys[x] {
|
||||||
@ -1099,25 +1048,25 @@ impl CPU {
|
|||||||
// |opcode| effect |
|
// |opcode| effect |
|
||||||
// |------|------------------------------------|
|
// |------|------------------------------------|
|
||||||
// | fX07 | Set vX to value in delay timer |
|
// | fX07 | Set vX to value in delay timer |
|
||||||
// | fX0a | Wait for input, store in vX m |
|
// | fX0a | Wait for input, store key in vX |
|
||||||
// | fX15 | Set sound timer to the value in vX |
|
// | fX15 | Set sound timer to the value in vX |
|
||||||
// | fX18 | set delay timer to the value in vX |
|
// | fX18 | set delay timer to the value in vX |
|
||||||
// | fX1e | Add x to I |
|
// | fX1e | Add vX to I |
|
||||||
// | fX29 | Load sprite for character x into I |
|
// | fX29 | Load sprite for character x into I |
|
||||||
// | fX33 | BCD convert X into I[0..3] |
|
// | fX33 | BCD convert X into I[0..3] |
|
||||||
// | fX55 | DMA Stor from I to registers 0..X |
|
// | fX55 | DMA Stor from I to registers 0..=X |
|
||||||
// | fX65 | DMA Load from I to registers 0..X |
|
// | fX65 | DMA Load from I to registers 0..=X |
|
||||||
impl CPU {
|
impl CPU {
|
||||||
/// Fx07: Get the current DT, and put it in vX
|
/// Fx07: Get the current DT, and put it in vX
|
||||||
/// ```py
|
/// ```py
|
||||||
/// vX = DT
|
/// vX = DT
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load_delay_timer(&mut self, x: Reg) {
|
fn load_delay_timer(&mut self, x: Reg) {
|
||||||
self.v[x] = self.delay as u8;
|
self.v[x] = self.delay as u8;
|
||||||
}
|
}
|
||||||
/// Fx0A: Wait for key, then vX = K
|
/// Fx0A: Wait for key, then vX = K
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn wait_for_key(&mut self, x: Reg) {
|
fn wait_for_key(&mut self, x: Reg) {
|
||||||
if let Some(key) = self.flags.lastkey {
|
if let Some(key) = self.flags.lastkey {
|
||||||
self.v[x] = key as u8;
|
self.v[x] = key as u8;
|
||||||
@ -1131,7 +1080,7 @@ impl CPU {
|
|||||||
/// ```py
|
/// ```py
|
||||||
/// DT = vX
|
/// DT = vX
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn store_delay_timer(&mut self, x: Reg) {
|
fn store_delay_timer(&mut self, x: Reg) {
|
||||||
self.delay = self.v[x] as f64;
|
self.delay = self.v[x] as f64;
|
||||||
}
|
}
|
||||||
@ -1139,7 +1088,7 @@ impl CPU {
|
|||||||
/// ```py
|
/// ```py
|
||||||
/// ST = vX;
|
/// ST = vX;
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn store_sound_timer(&mut self, x: Reg) {
|
fn store_sound_timer(&mut self, x: Reg) {
|
||||||
self.sound = self.v[x] as f64;
|
self.sound = self.v[x] as f64;
|
||||||
}
|
}
|
||||||
@ -1147,7 +1096,7 @@ impl CPU {
|
|||||||
/// ```py
|
/// ```py
|
||||||
/// I += vX;
|
/// I += vX;
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn add_i(&mut self, x: Reg) {
|
fn add_i(&mut self, x: Reg) {
|
||||||
self.i += self.v[x] as u16;
|
self.i += self.v[x] as u16;
|
||||||
}
|
}
|
||||||
@ -1155,24 +1104,24 @@ impl CPU {
|
|||||||
/// ```py
|
/// ```py
|
||||||
/// I = sprite(X);
|
/// I = sprite(X);
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load_sprite(&mut self, x: Reg) {
|
fn load_sprite(&mut self, x: Reg) {
|
||||||
self.i = self.font + (5 * (self.v[x] as Adr % 0x10));
|
self.i = self.font + (5 * (self.v[x] as Adr % 0x10));
|
||||||
}
|
}
|
||||||
/// Fx33: BCD convert X into I`[0..3]`
|
/// Fx33: BCD convert X into I`[0..3]`
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn bcd_convert(&mut self, x: Reg, bus: &mut Bus) {
|
fn bcd_convert(&mut self, x: Reg, bus: &mut Bus) {
|
||||||
let x = self.v[x];
|
let x = self.v[x];
|
||||||
bus.write(self.i.wrapping_add(2), x % 10);
|
bus.write(self.i.wrapping_add(2), x % 10);
|
||||||
bus.write(self.i.wrapping_add(1), x / 10 % 10);
|
bus.write(self.i.wrapping_add(1), x / 10 % 10);
|
||||||
bus.write(self.i, x / 100 % 10);
|
bus.write(self.i, x / 100 % 10);
|
||||||
}
|
}
|
||||||
/// Fx55: DMA Stor from I to registers 0..X
|
/// Fx55: DMA Stor from I to registers 0..=X
|
||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// The original chip-8 interpreter uses I to directly index memory,
|
/// The original chip-8 interpreter uses I to directly index memory,
|
||||||
/// with the side effect of leaving I as I+X+1 after the transfer is done.
|
/// with the side effect of leaving I as I+X+1 after the transfer is done.
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn store_dma(&mut self, x: Reg, bus: &mut Bus) {
|
fn store_dma(&mut self, x: Reg, bus: &mut Bus) {
|
||||||
let i = self.i as usize;
|
let i = self.i as usize;
|
||||||
for (reg, value) in bus
|
for (reg, value) in bus
|
||||||
@ -1187,16 +1136,16 @@ impl CPU {
|
|||||||
self.i += x as Adr + 1;
|
self.i += x as Adr + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Fx65: DMA Load from I to registers 0..X
|
/// Fx65: DMA Load from I to registers 0..=X
|
||||||
///
|
///
|
||||||
/// # Quirk
|
/// # Quirk
|
||||||
/// The original chip-8 interpreter uses I to directly index memory,
|
/// The original chip-8 interpreter uses I to directly index memory,
|
||||||
/// with the side effect of leaving I as I+X+1 after the transfer is done.
|
/// with the side effect of leaving I as I+X+1 after the transfer is done.
|
||||||
#[inline]
|
#[inline(always)]
|
||||||
fn load_dma(&mut self, x: Reg, bus: &mut Bus) {
|
fn load_dma(&mut self, x: Reg, bus: &mut Bus) {
|
||||||
let i = self.i as usize;
|
let i = self.i as usize;
|
||||||
for (reg, value) in bus
|
for (reg, value) in bus
|
||||||
.get(i + 0..=i + x)
|
.get(i..=i + x)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
|
@ -1,417 +0,0 @@
|
|||||||
// (c) 2023 John A. Breaux
|
|
||||||
// This code is licensed under MIT license (see LICENSE.txt for details)
|
|
||||||
|
|
||||||
//! A disassembler for Chip-8 opcodes
|
|
||||||
|
|
||||||
use super::{Adr, Nib, Reg};
|
|
||||||
use owo_colors::{OwoColorize, Style};
|
|
||||||
type Ins = Nib;
|
|
||||||
|
|
||||||
/// Extracts the I nibble of an IXYN instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn i(ins: u16) -> Ins {
|
|
||||||
(ins >> 12 & 0xf) as Ins
|
|
||||||
}
|
|
||||||
/// Extracts the X nibble of an IXYN instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn x(ins: u16) -> Reg {
|
|
||||||
(ins >> 8 & 0xf) as Reg
|
|
||||||
}
|
|
||||||
/// Extracts the Y nibble of an IXYN instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn y(ins: u16) -> Reg {
|
|
||||||
(ins >> 4 & 0xf) as Reg
|
|
||||||
}
|
|
||||||
/// Extracts the N nibble of an IXYN instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn n(ins: u16) -> Nib {
|
|
||||||
(ins & 0xf) as Nib
|
|
||||||
}
|
|
||||||
/// Extracts the B byte of an IXBB instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn b(ins: u16) -> u8 {
|
|
||||||
(ins & 0xff) as u8
|
|
||||||
}
|
|
||||||
/// Extracts the ADR trinibble of an IADR instruction
|
|
||||||
#[inline]
|
|
||||||
pub fn a(ins: u16) -> Adr {
|
|
||||||
ins & 0x0fff
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Disassembles Chip-8 instructions, printing them in the provided [owo_colors::Style]s
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Disassemble {
|
|
||||||
invalid: Style,
|
|
||||||
normal: Style,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Disassemble {
|
|
||||||
fn default() -> Self {
|
|
||||||
Disassemble::builder().build()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Public API
|
|
||||||
impl Disassemble {
|
|
||||||
/// Returns a new Disassemble with the provided Styles
|
|
||||||
pub fn new(invalid: Style, normal: Style) -> Disassemble {
|
|
||||||
Disassemble { invalid, normal }
|
|
||||||
}
|
|
||||||
/// Creates a [DisassembleBuilder], for partial configuration
|
|
||||||
pub fn builder() -> DisassembleBuilder {
|
|
||||||
DisassembleBuilder::default()
|
|
||||||
}
|
|
||||||
/// Disassemble a single instruction
|
|
||||||
pub fn instruction(&self, opcode: u16) -> String {
|
|
||||||
let (i, x, y, n, b, a) = (
|
|
||||||
i(opcode),
|
|
||||||
x(opcode),
|
|
||||||
y(opcode),
|
|
||||||
n(opcode),
|
|
||||||
b(opcode),
|
|
||||||
a(opcode),
|
|
||||||
);
|
|
||||||
match i {
|
|
||||||
// # Issue a system call
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 00e0 | Clear screen memory to all 0 |
|
|
||||||
// | 00ee | Return from subroutine |
|
|
||||||
0x0 => match a {
|
|
||||||
0x0e0 => self.clear_screen(),
|
|
||||||
0x0ee => self.ret(),
|
|
||||||
_ => self.sys(a),
|
|
||||||
},
|
|
||||||
// | 1aaa | Sets pc to an absolute address
|
|
||||||
0x1 => self.jump(a),
|
|
||||||
// | 2aaa | Pushes pc onto the stack, then jumps to a
|
|
||||||
0x2 => self.call(a),
|
|
||||||
// | 3xbb | Skips next instruction if register X == b
|
|
||||||
0x3 => self.skip_equals_immediate(x, b),
|
|
||||||
// | 4xbb | Skips next instruction if register X != b
|
|
||||||
0x4 => self.skip_not_equals_immediate(x, b),
|
|
||||||
// # Performs a register-register comparison
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 9XY0 | Skip next instruction if vX == vY |
|
|
||||||
0x5 => match n {
|
|
||||||
0x0 => self.skip_equals(x, y),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// 6xbb: Loads immediate byte b into register vX
|
|
||||||
0x6 => self.load_immediate(x, b),
|
|
||||||
// 7xbb: Adds immediate byte b to register vX
|
|
||||||
0x7 => self.add_immediate(x, b),
|
|
||||||
// # Performs ALU operation
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 8xy0 | Y = X |
|
|
||||||
// | 8xy1 | X = X | Y |
|
|
||||||
// | 8xy2 | X = X & Y |
|
|
||||||
// | 8xy3 | X = X ^ Y |
|
|
||||||
// | 8xy4 | X = X + Y; Set vF=carry |
|
|
||||||
// | 8xy5 | X = X - Y; Set vF=carry |
|
|
||||||
// | 8xy6 | X = X >> 1 |
|
|
||||||
// | 8xy7 | X = Y - X; Set vF=carry |
|
|
||||||
// | 8xyE | X = X << 1 |
|
|
||||||
0x8 => match n {
|
|
||||||
0x0 => self.load(x, y),
|
|
||||||
0x1 => self.or(x, y),
|
|
||||||
0x2 => self.and(x, y),
|
|
||||||
0x3 => self.xor(x, y),
|
|
||||||
0x4 => self.add(x, y),
|
|
||||||
0x5 => self.sub(x, y),
|
|
||||||
0x6 => self.shift_right(x),
|
|
||||||
0x7 => self.backwards_sub(x, y),
|
|
||||||
0xE => self.shift_left(x),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// # Performs a register-register comparison
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | 9XY0 | Skip next instruction if vX != vY |
|
|
||||||
0x9 => match n {
|
|
||||||
0 => self.skip_not_equals(x, y),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
// Aaaa: Load address #a into register I
|
|
||||||
0xa => self.load_i_immediate(a),
|
|
||||||
// Baaa: Jump to &adr + v0
|
|
||||||
0xb => self.jump_indexed(a),
|
|
||||||
// Cxbb: Stores a random number + the provided byte into vX
|
|
||||||
0xc => self.rand(x, b),
|
|
||||||
// Dxyn: Draws n-byte sprite to the screen at coordinates (vX, vY)
|
|
||||||
0xd => self.draw(x, y, n),
|
|
||||||
|
|
||||||
// # Skips instruction on value of keypress
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | eX9e | Skip next instruction if key == #X |
|
|
||||||
// | eXa1 | Skip next instruction if key != #X |
|
|
||||||
0xe => match b {
|
|
||||||
0x9e => self.skip_key_equals(x),
|
|
||||||
0xa1 => self.skip_key_not_equals(x),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
|
|
||||||
// # Performs IO
|
|
||||||
// |opcode| effect |
|
|
||||||
// |------|------------------------------------|
|
|
||||||
// | fX07 | Set vX to value in delay timer |
|
|
||||||
// | fX0a | Wait for input, store in vX m |
|
|
||||||
// | fX15 | Set sound timer to the value in vX |
|
|
||||||
// | fX18 | set delay timer to the value in vX |
|
|
||||||
// | fX1e | Add x to I |
|
|
||||||
// | fX29 | Load sprite for character x into I |
|
|
||||||
// | fX33 | BCD convert X into I[0..3] |
|
|
||||||
// | fX55 | DMA Stor from I to registers 0..X |
|
|
||||||
// | fX65 | DMA Load from I to registers 0..X |
|
|
||||||
0xf => match b {
|
|
||||||
0x07 => self.load_delay_timer(x),
|
|
||||||
0x0A => self.wait_for_key(x),
|
|
||||||
0x15 => self.store_delay_timer(x),
|
|
||||||
0x18 => self.store_sound_timer(x),
|
|
||||||
0x1E => self.add_to_indirect(x),
|
|
||||||
0x29 => self.load_sprite(x),
|
|
||||||
0x33 => self.bcd_convert(x),
|
|
||||||
0x55 => self.store_dma(x),
|
|
||||||
0x65 => self.load_dma(x),
|
|
||||||
_ => self.unimplemented(opcode),
|
|
||||||
},
|
|
||||||
_ => unreachable!("Extracted nibble from byte, got >nibble?"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Private api
|
|
||||||
impl Disassemble {
|
|
||||||
/// Unused instructions
|
|
||||||
fn unimplemented(&self, opcode: u16) -> String {
|
|
||||||
format!("inval {opcode:04x}")
|
|
||||||
.style(self.invalid)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `0aaa`: Handles a "machine language function call" (lmao)
|
|
||||||
pub fn sys(&self, a: Adr) -> String {
|
|
||||||
format!("sysc {a:03x}").style(self.invalid).to_string()
|
|
||||||
}
|
|
||||||
/// `00e0`: Clears the screen memory to 0
|
|
||||||
pub fn clear_screen(&self) -> String {
|
|
||||||
"cls ".style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `00ee`: Returns from subroutine
|
|
||||||
pub fn ret(&self) -> String {
|
|
||||||
"ret ".style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `1aaa`: Sets the program counter to an absolute address
|
|
||||||
pub fn jump(&self, a: Adr) -> String {
|
|
||||||
format!("jmp {a:03x}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `2aaa`: Pushes pc onto the stack, then jumps to a
|
|
||||||
pub fn call(&self, a: Adr) -> String {
|
|
||||||
format!("call {a:03x}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `3xbb`: Skips the next instruction if register X == b
|
|
||||||
pub fn skip_equals_immediate(&self, x: Reg, b: u8) -> String {
|
|
||||||
format!("se #{b:02x}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `4xbb`: Skips the next instruction if register X != b
|
|
||||||
pub fn skip_not_equals_immediate(&self, x: Reg, b: u8) -> String {
|
|
||||||
format!("sne #{b:02x}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `5xy0`: Skips the next instruction if register X != register Y
|
|
||||||
pub fn skip_equals(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("se v{x:X}, v{y:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `6xbb`: Loads immediate byte b into register vX
|
|
||||||
pub fn load_immediate(&self, x: Reg, b: u8) -> String {
|
|
||||||
format!("mov #{b:02x}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `7xbb`: Adds immediate byte b to register vX
|
|
||||||
pub fn add_immediate(&self, x: Reg, b: u8) -> String {
|
|
||||||
format!("add #{b:02x}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy0`: Loads the value of y into x
|
|
||||||
pub fn load(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("mov v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy1`: Performs bitwise or of vX and vY, and stores the result in vX
|
|
||||||
pub fn or(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("or v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy2`: Performs bitwise and of vX and vY, and stores the result in vX
|
|
||||||
pub fn and(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("and v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `8xy3`: Performs bitwise xor of vX and vY, and stores the result in vX
|
|
||||||
pub fn xor(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("xor v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy4`: Performs addition of vX and vY, and stores the result in vX
|
|
||||||
pub fn add(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("add v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy5`: Performs subtraction of vX and vY, and stores the result in vX
|
|
||||||
pub fn sub(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("sub v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `8xy6`: Performs bitwise right shift of vX
|
|
||||||
pub fn shift_right(&self, x: Reg) -> String {
|
|
||||||
format!("shr v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `8xy7`: Performs subtraction of vY and vX, and stores the result in vX
|
|
||||||
pub fn backwards_sub(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("bsub v{y:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// 8X_E: Performs bitwise left shift of vX
|
|
||||||
pub fn shift_left(&self, x: Reg) -> String {
|
|
||||||
format!("shl v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `9xy0`: Skip next instruction if X != y
|
|
||||||
pub fn skip_not_equals(&self, x: Reg, y: Reg) -> String {
|
|
||||||
format!("sne v{x:X}, v{y:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// Aadr: Load address #adr into register I
|
|
||||||
pub fn load_i_immediate(&self, a: Adr) -> String {
|
|
||||||
format!("mov ${a:03x}, I").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// Badr: Jump to &adr + v0
|
|
||||||
pub fn jump_indexed(&self, a: Adr) -> String {
|
|
||||||
format!("jmp ${a:03x}+v0").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Cxbb`: Stores a random number + the provided byte into vX
|
|
||||||
/// Pretty sure the input byte is supposed to be the seed of a LFSR or something
|
|
||||||
pub fn rand(&self, x: Reg, b: u8) -> String {
|
|
||||||
format!("rand #{b:X}, v{x:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `Dxyn`: Draws n-byte sprite to the screen at coordinates (vX, vY)
|
|
||||||
pub fn draw(&self, x: Reg, y: Reg, n: Nib) -> String {
|
|
||||||
format!("draw #{n:x}, v{x:X}, v{y:X}")
|
|
||||||
.style(self.normal)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
/// `Ex9E`: Skip next instruction if key == #X
|
|
||||||
pub fn skip_key_equals(&self, x: Reg) -> String {
|
|
||||||
format!("sek v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `ExaE`: Skip next instruction if key != #X
|
|
||||||
pub fn skip_key_not_equals(&self, x: Reg) -> String {
|
|
||||||
format!("snek v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx07`: Get the current DT, and put it in vX
|
|
||||||
/// ```py
|
|
||||||
/// vX = DT
|
|
||||||
/// ```
|
|
||||||
pub fn load_delay_timer(&self, x: Reg) -> String {
|
|
||||||
format!("mov DT, v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx0A`: Wait for key, then vX = K
|
|
||||||
pub fn wait_for_key(&self, x: Reg) -> String {
|
|
||||||
format!("waitk v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx15`: Load vX into DT
|
|
||||||
/// ```py
|
|
||||||
/// DT = vX
|
|
||||||
/// ```
|
|
||||||
pub fn store_delay_timer(&self, x: Reg) -> String {
|
|
||||||
format!("mov v{x:X}, DT").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx18`: Load vX into ST
|
|
||||||
/// ```py
|
|
||||||
/// ST = vX;
|
|
||||||
/// ```
|
|
||||||
pub fn store_sound_timer(&self, x: Reg) -> String {
|
|
||||||
format!("mov v{x:X}, ST").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx1e`: Add vX to I,
|
|
||||||
/// ```py
|
|
||||||
/// I += vX;
|
|
||||||
/// ```
|
|
||||||
pub fn add_to_indirect(&self, x: Reg) -> String {
|
|
||||||
format!("add v{x:X}, I").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx29`: Load sprite for character in vX into I
|
|
||||||
/// ```py
|
|
||||||
/// I = sprite(X);
|
|
||||||
/// ```
|
|
||||||
pub fn load_sprite(&self, x: Reg) -> String {
|
|
||||||
format!("font v{x:X}, I").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx33`: BCD convert X into I`[0..3]`
|
|
||||||
pub fn bcd_convert(&self, x: Reg) -> String {
|
|
||||||
format!("bcd v{x:X}, &I").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx55`: DMA Stor from I to registers 0..X
|
|
||||||
pub fn store_dma(&self, x: Reg) -> String {
|
|
||||||
format!("dmao v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
/// `Fx65`: DMA Load from I to registers 0..X
|
|
||||||
pub fn load_dma(&self, x: Reg) -> String {
|
|
||||||
format!("dmai v{x:X}").style(self.normal).to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builder for [Disassemble]rs
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct DisassembleBuilder {
|
|
||||||
invalid: Option<Style>,
|
|
||||||
normal: Option<Style>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DisassembleBuilder {
|
|
||||||
/// Styles invalid (or unimplemented) instructions
|
|
||||||
pub fn invalid(mut self, style: Style) -> Self {
|
|
||||||
self.invalid = Some(style);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
/// Styles valid (implemented) instructions
|
|
||||||
pub fn normal(mut self, style: Style) -> Self {
|
|
||||||
self.normal = Some(style);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
/// Builds a Disassemble
|
|
||||||
pub fn build(self) -> Disassemble {
|
|
||||||
Disassemble {
|
|
||||||
invalid: if let Some(style) = self.invalid {
|
|
||||||
style
|
|
||||||
} else {
|
|
||||||
Style::new().bold().red()
|
|
||||||
},
|
|
||||||
normal: if let Some(style) = self.normal {
|
|
||||||
style
|
|
||||||
} else {
|
|
||||||
Style::new().green()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
184
src/cpu/disassembler.rs
Normal file
184
src/cpu/disassembler.rs
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
//! A disassembler for Chip-8 opcodes
|
||||||
|
#![allow(clippy::bad_bit_mask)]
|
||||||
|
use super::Disassembler;
|
||||||
|
use imperative_rs::InstructionSet;
|
||||||
|
use owo_colors::{OwoColorize, Style};
|
||||||
|
use std::fmt::Display;
|
||||||
|
|
||||||
|
#[allow(non_camel_case_types, non_snake_case, missing_docs)]
|
||||||
|
#[derive(Clone, Copy, Debug, InstructionSet, PartialEq, Eq)]
|
||||||
|
/// Implements a Disassembler using imperative_rs
|
||||||
|
pub enum Insn {
|
||||||
|
/// | 00e0 | Clear screen memory to 0s
|
||||||
|
#[opcode = "0x00e0"]
|
||||||
|
cls,
|
||||||
|
/// | 00ee | Return from subroutine
|
||||||
|
#[opcode = "0x00ee"]
|
||||||
|
ret,
|
||||||
|
/// | 1aaa | Jumps to an absolute address
|
||||||
|
#[opcode = "0x1AAA"]
|
||||||
|
jmp { A: u16 },
|
||||||
|
/// | 2aaa | Pushes pc onto the stack, then jumps to a
|
||||||
|
#[opcode = "0x2AAA"]
|
||||||
|
call { A: u16 },
|
||||||
|
/// | 3xbb | Skips next instruction if register X == b
|
||||||
|
#[opcode = "0x3xBB"]
|
||||||
|
seb { B: u8, x: usize },
|
||||||
|
/// | 4xbb | Skips next instruction if register X != b
|
||||||
|
#[opcode = "0x4xBB"]
|
||||||
|
sneb { B: u8, x: usize },
|
||||||
|
/// | 9XY0 | Skip next instruction if vX == vY |
|
||||||
|
#[opcode = "0x5xy0"]
|
||||||
|
se { y: usize, x: usize },
|
||||||
|
/// | 6xbb | Loads immediate byte b into register vX
|
||||||
|
#[opcode = "0x6xBB"]
|
||||||
|
movb { B: u8, x: usize },
|
||||||
|
/// | 7xbb | Adds immediate byte b to register vX
|
||||||
|
#[opcode = "0x7xBB"]
|
||||||
|
addb { B: u8, x: usize },
|
||||||
|
/// | 8xy0 | Loads the value of y into x
|
||||||
|
#[opcode = "0x8xy0"]
|
||||||
|
mov { x: usize, y: usize },
|
||||||
|
/// | 8xy1 | Performs bitwise or of vX and vY, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy1"]
|
||||||
|
or { y: usize, x: usize },
|
||||||
|
/// | 8xy2 | Performs bitwise and of vX and vY, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy2"]
|
||||||
|
and { y: usize, x: usize },
|
||||||
|
/// | 8xy3 | Performs bitwise xor of vX and vY, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy3"]
|
||||||
|
xor { y: usize, x: usize },
|
||||||
|
/// | 8xy4 | Performs addition of vX and vY, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy4"]
|
||||||
|
add { y: usize, x: usize },
|
||||||
|
/// | 8xy5 | Performs subtraction of vX and vY, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy5"]
|
||||||
|
sub { y: usize, x: usize },
|
||||||
|
/// | 8xy6 | Performs bitwise right shift of vX (or vY)
|
||||||
|
#[opcode = "0x8xy6"]
|
||||||
|
shr { y: usize, x: usize },
|
||||||
|
/// | 8xy7 | Performs subtraction of vY and vX, and stores the result in vX
|
||||||
|
#[opcode = "0x8xy7"]
|
||||||
|
bsub { y: usize, x: usize },
|
||||||
|
/// | 8xyE | Performs bitwise left shift of vX
|
||||||
|
#[opcode = "0x8xye"]
|
||||||
|
shl { y: usize, x: usize },
|
||||||
|
/// | 9XY0 | Skip next instruction if vX != vY
|
||||||
|
#[opcode = "0x9xy0"]
|
||||||
|
sne { y: usize, x: usize },
|
||||||
|
/// | Aaaa | Load address #a into register I
|
||||||
|
#[opcode = "0xaAAA"]
|
||||||
|
movI { A: u16 },
|
||||||
|
/// | Baaa | Jump to &adr + v0
|
||||||
|
#[opcode = "0xbAAA"]
|
||||||
|
jmpr { A: u16 },
|
||||||
|
/// | Cxbb | Stores a random number & the provided byte into vX
|
||||||
|
#[opcode = "0xcxBB"]
|
||||||
|
rand { B: u8, x: usize },
|
||||||
|
/// | Dxyn | Draws n-byte sprite to the screen at coordinates (vX, vY)
|
||||||
|
#[opcode = "0xdxyn"]
|
||||||
|
draw { x: usize, y: usize, n: u8 },
|
||||||
|
/// | eX9e | Skip next instruction if key == vX
|
||||||
|
#[opcode = "0xex9e"]
|
||||||
|
sek { x: usize },
|
||||||
|
/// | eXa1 | Skip next instruction if key != vX
|
||||||
|
#[opcode = "0xexa1"]
|
||||||
|
snek { x: usize },
|
||||||
|
// | fX07 | Set vX to value in delay timer
|
||||||
|
#[opcode = "0xfx07"]
|
||||||
|
getdt { x: usize },
|
||||||
|
// | fX0a | Wait for input, store key in vX
|
||||||
|
#[opcode = "0xfx0a"]
|
||||||
|
waitk { x: usize },
|
||||||
|
// | fX15 | Set sound timer to the value in vX
|
||||||
|
#[opcode = "0xfx15"]
|
||||||
|
setdt { x: usize },
|
||||||
|
// | fX18 | set delay timer to the value in vX
|
||||||
|
#[opcode = "0xfx18"]
|
||||||
|
movst { x: usize },
|
||||||
|
// | fX1e | Add vX to I
|
||||||
|
#[opcode = "0xfx1e"]
|
||||||
|
addI { x: usize },
|
||||||
|
// | fX29 | Load sprite for character x into I
|
||||||
|
#[opcode = "0xfx29"]
|
||||||
|
font { x: usize },
|
||||||
|
// | fX33 | BCD convert X into I[0..3]
|
||||||
|
#[opcode = "0xfx33"]
|
||||||
|
bcd { x: usize },
|
||||||
|
// | fX55 | DMA Stor from I to registers 0..X
|
||||||
|
#[opcode = "0xfx55"]
|
||||||
|
dmao { x: usize },
|
||||||
|
// | fX65 | DMA Load from I to registers 0..X
|
||||||
|
#[opcode = "0xfx65"]
|
||||||
|
dmai { x: usize },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Insn {
|
||||||
|
#[rustfmt::skip]
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Insn::cls => write!(f, "cls "),
|
||||||
|
Insn::ret => write!(f, "ret "),
|
||||||
|
Insn::jmp { A } => write!(f, "jmp {A:03x}"),
|
||||||
|
Insn::call { A } => write!(f, "call {A:03x}"),
|
||||||
|
Insn::seb { B, x } => write!(f, "se #{B:02x}, v{x:X}"),
|
||||||
|
Insn::sneb { B, x } => write!(f, "sne #{B:02x}, v{x:X}"),
|
||||||
|
Insn::se { y, x } => write!(f, "se v{x:X}, v{y:X}"),
|
||||||
|
Insn::movb { B, x } => write!(f, "mov #{B:02x}, v{x:X}"),
|
||||||
|
Insn::addb { B, x } => write!(f, "add #{B:02x}, v{x:X}"),
|
||||||
|
Insn::mov { x, y } => write!(f, "mov v{y:X}, v{x:X}"),
|
||||||
|
Insn::or { y, x } => write!(f, "or v{y:X}, v{x:X}"),
|
||||||
|
Insn::and { y, x } => write!(f, "and v{y:X}, v{x:X}"),
|
||||||
|
Insn::xor { y, x } => write!(f, "xor v{y:X}, v{x:X}"),
|
||||||
|
Insn::add { y, x } => write!(f, "add v{y:X}, v{x:X}"),
|
||||||
|
Insn::sub { y, x } => write!(f, "sub v{y:X}, v{x:X}"),
|
||||||
|
Insn::shr { y, x } => write!(f, "shr v{y:X}, v{x:X}"),
|
||||||
|
Insn::bsub { y, x } => write!(f, "bsub v{y:X}, v{x:X}"),
|
||||||
|
Insn::shl { y, x } => write!(f, "shl v{y:X}, v{x:X}"),
|
||||||
|
Insn::sne { y, x } => write!(f, "sne v{x:X}, v{y:X}"),
|
||||||
|
Insn::movI { A } => write!(f, "mov ${A:03x}, I"),
|
||||||
|
Insn::jmpr { A } => write!(f, "jmp ${A:03x}+v0"),
|
||||||
|
Insn::rand { B, x } => write!(f, "rand #{B:02x}, v{x:X}"),
|
||||||
|
Insn::draw { x, y, n } => write!(f, "draw #{n:x}, v{x:X}, v{y:X}"),
|
||||||
|
Insn::sek { x } => write!(f, "sek v{x:X}"),
|
||||||
|
Insn::snek { x } => write!(f, "snek v{x:X}"),
|
||||||
|
Insn::getdt { x } => write!(f, "mov DT, v{x:X}"),
|
||||||
|
Insn::waitk { x } => write!(f, "waitk v{x:X}"),
|
||||||
|
Insn::setdt { x } => write!(f, "mov v{x:X}, DT"),
|
||||||
|
Insn::movst { x } => write!(f, "mov v{x:X}, ST"),
|
||||||
|
Insn::addI { x } => write!(f, "add v{x:X}, I"),
|
||||||
|
Insn::font { x } => write!(f, "font v{x:X}, I"),
|
||||||
|
Insn::bcd { x } => write!(f, "bcd v{x:X}, &I"),
|
||||||
|
Insn::dmao { x } => write!(f, "dmao v{x:X}"),
|
||||||
|
Insn::dmai { x } => write!(f, "dmai v{x:X}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disassembles Chip-8 instructions, printing them in the provided [owo_colors::Style]s
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Dis {
|
||||||
|
/// Styles invalid instructions
|
||||||
|
pub invalid: Style,
|
||||||
|
/// Styles valid instruction
|
||||||
|
pub normal: Style,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Dis {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
invalid: Style::new().bold().red(),
|
||||||
|
normal: Style::new().green(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Disassembler for Dis {
|
||||||
|
fn once(&self, insn: u16) -> String {
|
||||||
|
if let Ok((_, insn)) = Insn::decode(&insn.to_be_bytes()) {
|
||||||
|
format!("{}", insn.style(self.normal))
|
||||||
|
} else {
|
||||||
|
format!("{}", format_args!("inval {insn:04x}").style(self.invalid))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -54,28 +54,28 @@ mod unimplemented {
|
|||||||
fn ins_5xyn() {
|
fn ins_5xyn() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
bus.write(0x200u16, 0x500fu16); // 0x500f is not an instruction
|
bus.write(0x200u16, 0x500fu16); // 0x500f is not an instruction
|
||||||
cpu.tick(&mut bus);
|
cpu.tick(&mut bus).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
#[should_panic]
|
||||||
fn ins_8xyn() {
|
fn ins_8xyn() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
bus.write(0x200u16, 0x800fu16); // 0x800f is not an instruction
|
bus.write(0x200u16, 0x800fu16); // 0x800f is not an instruction
|
||||||
cpu.tick(&mut bus);
|
cpu.tick(&mut bus).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
#[should_panic]
|
||||||
fn ins_9xyn() {
|
fn ins_9xyn() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
bus.write(0x200u16, 0x900fu16); // 0x800f is not an instruction
|
bus.write(0x200u16, 0x900fu16); // 0x800f is not an instruction
|
||||||
cpu.tick(&mut bus);
|
cpu.tick(&mut bus).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic]
|
#[should_panic]
|
||||||
fn ins_exbb() {
|
fn ins_exbb() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
bus.write(0x200u16, 0xe00fu16); // 0xe00f is not an instruction
|
bus.write(0x200u16, 0xe00fu16); // 0xe00f is not an instruction
|
||||||
cpu.tick(&mut bus);
|
cpu.tick(&mut bus).unwrap();
|
||||||
}
|
}
|
||||||
// Fxbb
|
// Fxbb
|
||||||
#[test]
|
#[test]
|
||||||
@ -83,22 +83,12 @@ mod unimplemented {
|
|||||||
fn ins_fxbb() {
|
fn ins_fxbb() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
bus.write(0x200u16, 0xf00fu16); // 0xf00f is not an instruction
|
bus.write(0x200u16, 0xf00fu16); // 0xf00f is not an instruction
|
||||||
cpu.tick(&mut bus);
|
cpu.tick(&mut bus).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mod sys {
|
mod sys {
|
||||||
use super::*;
|
use super::*;
|
||||||
/// 0aaa: Handles a "machine language function call" (lmao)
|
|
||||||
#[test]
|
|
||||||
#[should_panic]
|
|
||||||
fn sys() {
|
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
|
||||||
bus.write(0x200u16, 0x0200u16); // 0x0200 is not one of the allowed routines
|
|
||||||
cpu.tick(&mut bus);
|
|
||||||
cpu.sys(0x200);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 00e0: Clears the screen memory to 0
|
/// 00e0: Clears the screen memory to 0
|
||||||
#[test]
|
#[test]
|
||||||
fn clear_screen() {
|
fn clear_screen() {
|
||||||
@ -119,7 +109,7 @@ mod sys {
|
|||||||
// Place the address on the stack
|
// Place the address on the stack
|
||||||
bus.write(cpu.sp.wrapping_add(2), test_addr);
|
bus.write(cpu.sp.wrapping_add(2), test_addr);
|
||||||
|
|
||||||
cpu.ret(&mut bus);
|
cpu.ret(&bus);
|
||||||
|
|
||||||
// Verify the current address is the address from the stack
|
// Verify the current address is the address from the stack
|
||||||
assert_eq!(test_addr, cpu.pc);
|
assert_eq!(test_addr, cpu.pc);
|
||||||
@ -639,11 +629,13 @@ mod io {
|
|||||||
for test in SCREEN_TESTS {
|
for test in SCREEN_TESTS {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
cpu.flags.quirks = test.quirks;
|
cpu.flags.quirks = test.quirks;
|
||||||
|
// Debug mode is 5x slower
|
||||||
|
cpu.flags.debug = false;
|
||||||
// Load the test program
|
// Load the test program
|
||||||
bus = bus.load_region(Program, test.program);
|
bus = bus.load_region(Program, test.program);
|
||||||
// Run the test program for the specified number of steps
|
// Run the test program for the specified number of steps
|
||||||
while cpu.cycle() < test.steps {
|
while cpu.cycle() < test.steps {
|
||||||
cpu.multistep(&mut bus, test.steps - cpu.cycle());
|
cpu.multistep(&mut bus, test.steps - cpu.cycle()).unwrap();
|
||||||
}
|
}
|
||||||
// Compare the screen to the reference screen buffer
|
// Compare the screen to the reference screen buffer
|
||||||
bus.print_screen().unwrap();
|
bus.print_screen().unwrap();
|
||||||
@ -723,20 +715,20 @@ mod io {
|
|||||||
for x in 0..0xf {
|
for x in 0..0xf {
|
||||||
cpu.v[x] = 0xff;
|
cpu.v[x] = 0xff;
|
||||||
cpu.wait_for_key(x);
|
cpu.wait_for_key(x);
|
||||||
assert_eq!(true, cpu.flags.keypause);
|
assert!(cpu.flags.keypause);
|
||||||
assert_eq!(0xff, cpu.v[x]);
|
assert_eq!(0xff, cpu.v[x]);
|
||||||
// There are three parts to a button press
|
// There are three parts to a button press
|
||||||
// When the button is pressed
|
// When the button is pressed
|
||||||
cpu.press(key);
|
cpu.press(key);
|
||||||
assert_eq!(true, cpu.flags.keypause);
|
assert!(cpu.flags.keypause);
|
||||||
assert_eq!(0xff, cpu.v[x]);
|
assert_eq!(0xff, cpu.v[x]);
|
||||||
// When the button is held
|
// When the button is held
|
||||||
cpu.wait_for_key(x);
|
cpu.wait_for_key(x);
|
||||||
assert_eq!(true, cpu.flags.keypause);
|
assert!(cpu.flags.keypause);
|
||||||
assert_eq!(0xff, cpu.v[x]);
|
assert_eq!(0xff, cpu.v[x]);
|
||||||
// And when the button is released!
|
// And when the button is released!
|
||||||
cpu.release(key);
|
cpu.release(key);
|
||||||
assert_eq!(false, cpu.flags.keypause);
|
assert!(!cpu.flags.keypause);
|
||||||
assert_eq!(Some(key), cpu.flags.lastkey);
|
assert_eq!(Some(key), cpu.flags.lastkey);
|
||||||
cpu.wait_for_key(x);
|
cpu.wait_for_key(x);
|
||||||
assert_eq!(key as u8, cpu.v[x]);
|
assert_eq!(key as u8, cpu.v[x]);
|
||||||
@ -888,7 +880,7 @@ mod io {
|
|||||||
const DATA: &[u8] = b"ABCDEFGHIJKLMNOP";
|
const DATA: &[u8] = b"ABCDEFGHIJKLMNOP";
|
||||||
// Load some test data into memory
|
// Load some test data into memory
|
||||||
let addr = 0x456;
|
let addr = 0x456;
|
||||||
cpu.v.as_mut_slice().write(DATA).unwrap();
|
cpu.v.as_mut_slice().write_all(DATA).unwrap();
|
||||||
for len in 0..16 {
|
for len in 0..16 {
|
||||||
// Perform DMA store
|
// Perform DMA store
|
||||||
cpu.i = addr as u16;
|
cpu.i = addr as u16;
|
||||||
@ -898,7 +890,7 @@ mod io {
|
|||||||
assert_eq!(bus[0..=len], DATA[0..=len]);
|
assert_eq!(bus[0..=len], DATA[0..=len]);
|
||||||
assert_eq!(bus[len + 1..], [0; 16][len + 1..]);
|
assert_eq!(bus[len + 1..], [0; 16][len + 1..]);
|
||||||
// clear
|
// clear
|
||||||
bus.write(&[0; 16]).unwrap();
|
bus.write_all(&[0; 16]).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -912,7 +904,7 @@ mod io {
|
|||||||
let addr = 0x456;
|
let addr = 0x456;
|
||||||
bus.get_mut(addr..addr + DATA.len())
|
bus.get_mut(addr..addr + DATA.len())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.write(DATA)
|
.write_all(DATA)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
for len in 0..16 {
|
for len in 0..16 {
|
||||||
// Perform DMA load
|
// Perform DMA load
|
||||||
@ -938,7 +930,7 @@ mod behavior {
|
|||||||
cpu.flags.monotonic = None;
|
cpu.flags.monotonic = None;
|
||||||
cpu.delay = 10.0;
|
cpu.delay = 10.0;
|
||||||
for _ in 0..2 {
|
for _ in 0..2 {
|
||||||
cpu.multistep(&mut bus, 8);
|
cpu.multistep(&mut bus, 8).unwrap();
|
||||||
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
||||||
}
|
}
|
||||||
// time is within 1 frame deviance over a theoretical 2 frame pause
|
// time is within 1 frame deviance over a theoretical 2 frame pause
|
||||||
@ -950,7 +942,7 @@ mod behavior {
|
|||||||
cpu.flags.monotonic = None; // disable monotonic timing
|
cpu.flags.monotonic = None; // disable monotonic timing
|
||||||
cpu.sound = 10.0;
|
cpu.sound = 10.0;
|
||||||
for _ in 0..2 {
|
for _ in 0..2 {
|
||||||
cpu.multistep(&mut bus, 8);
|
cpu.multistep(&mut bus, 8).unwrap();
|
||||||
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
||||||
}
|
}
|
||||||
// time is within 1 frame deviance over a theoretical 2 frame pause
|
// time is within 1 frame deviance over a theoretical 2 frame pause
|
||||||
@ -962,11 +954,11 @@ mod behavior {
|
|||||||
cpu.flags.monotonic = None; // disable monotonic timing
|
cpu.flags.monotonic = None; // disable monotonic timing
|
||||||
cpu.flags.vbi_wait = true;
|
cpu.flags.vbi_wait = true;
|
||||||
for _ in 0..2 {
|
for _ in 0..2 {
|
||||||
cpu.multistep(&mut bus, 8);
|
cpu.multistep(&mut bus, 8).unwrap();
|
||||||
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
std::thread::sleep(Duration::from_secs_f64(1.0 / 60.0));
|
||||||
}
|
}
|
||||||
// Display wait is disabled after a 1 frame pause
|
// Display wait is disabled after a 1 frame pause
|
||||||
assert_eq!(false, cpu.flags.vbi_wait);
|
assert!(!cpu.flags.vbi_wait);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mod breakpoint {
|
mod breakpoint {
|
||||||
@ -975,8 +967,8 @@ mod behavior {
|
|||||||
fn hit_break() {
|
fn hit_break() {
|
||||||
let (mut cpu, mut bus) = setup_environment();
|
let (mut cpu, mut bus) = setup_environment();
|
||||||
cpu.set_break(0x202);
|
cpu.set_break(0x202);
|
||||||
cpu.multistep(&mut bus, 10);
|
cpu.multistep(&mut bus, 10).unwrap();
|
||||||
assert_eq!(true, cpu.flags.pause);
|
assert!(cpu.flags.pause);
|
||||||
assert_eq!(0x202, cpu.pc);
|
assert_eq!(0x202, cpu.pc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,7 +14,7 @@ fn run_single_op(op: &[u8]) -> CPU {
|
|||||||
);
|
);
|
||||||
cpu.v = *INDX;
|
cpu.v = *INDX;
|
||||||
cpu.flags.quirks = Quirks::from(true);
|
cpu.flags.quirks = Quirks::from(true);
|
||||||
cpu.tick(&mut bus); // will panic if unimplemented
|
cpu.tick(&mut bus).unwrap(); // will panic if unimplemented
|
||||||
cpu
|
cpu
|
||||||
}
|
}
|
||||||
|
|
||||||
|
13
src/error.rs
13
src/error.rs
@ -3,6 +3,8 @@
|
|||||||
|
|
||||||
//! Error type for Chirp
|
//! Error type for Chirp
|
||||||
|
|
||||||
|
use std::ops::Range;
|
||||||
|
|
||||||
use crate::bus::Region;
|
use crate::bus::Region;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
@ -13,7 +15,7 @@ pub type Result<T> = std::result::Result<T, Error>;
|
|||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Represents an unimplemented operation
|
/// Represents an unimplemented operation
|
||||||
#[error("Unrecognized opcode {word}")]
|
#[error("Unrecognized opcode: {word:04x}")]
|
||||||
UnimplementedInstruction {
|
UnimplementedInstruction {
|
||||||
/// The offending word
|
/// The offending word
|
||||||
word: u16,
|
word: u16,
|
||||||
@ -24,9 +26,18 @@ pub enum Error {
|
|||||||
/// The offending [Region]
|
/// The offending [Region]
|
||||||
region: Region,
|
region: Region,
|
||||||
},
|
},
|
||||||
|
/// Tried to fetch [Range] from bus, received nothing
|
||||||
|
#[error("Invalid range {range:04x?} for bus")]
|
||||||
|
InvalidBusRange {
|
||||||
|
/// The offending [Range]
|
||||||
|
range: Range<usize>,
|
||||||
|
},
|
||||||
/// Error originated in [std::io]
|
/// Error originated in [std::io]
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
IoError(#[from] std::io::Error),
|
IoError(#[from] std::io::Error),
|
||||||
|
/// Error originated in [std::array::TryFromSliceError]
|
||||||
|
#[error(transparent)]
|
||||||
|
TryFromSliceError(#[from] std::array::TryFromSliceError),
|
||||||
/// Error originated in [minifb]
|
/// Error originated in [minifb]
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
MinifbError(#[from] minifb::Error),
|
MinifbError(#[from] minifb::Error),
|
||||||
|
26
src/io.rs
26
src/io.rs
@ -7,6 +7,7 @@
|
|||||||
use std::{
|
use std::{
|
||||||
ffi::OsStr,
|
ffi::OsStr,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
time::Instant,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -48,6 +49,7 @@ impl UIBuilder {
|
|||||||
keyboard: Default::default(),
|
keyboard: Default::default(),
|
||||||
fb: Default::default(),
|
fb: Default::default(),
|
||||||
rom: self.rom.to_owned().unwrap_or_default(),
|
rom: self.rom.to_owned().unwrap_or_default(),
|
||||||
|
time: Instant::now(),
|
||||||
};
|
};
|
||||||
Ok(ui)
|
Ok(ui)
|
||||||
}
|
}
|
||||||
@ -108,7 +110,7 @@ impl FrameBuffer {
|
|||||||
if let Some(screen) = bus.get_region(Region::Screen) {
|
if let Some(screen) = bus.get_region(Region::Screen) {
|
||||||
for (idx, byte) in screen.iter().enumerate() {
|
for (idx, byte) in screen.iter().enumerate() {
|
||||||
for bit in 0..8 {
|
for bit in 0..8 {
|
||||||
self.buffer[8 * idx + bit] = if byte & (1 << 7 - bit) as u8 != 0 {
|
self.buffer[8 * idx + bit] = if byte & (1 << (7 - bit)) as u8 != 0 {
|
||||||
self.format.fg
|
self.format.fg
|
||||||
} else {
|
} else {
|
||||||
self.format.bg
|
self.format.bg
|
||||||
@ -135,6 +137,7 @@ pub struct UI {
|
|||||||
keyboard: Vec<Key>,
|
keyboard: Vec<Key>,
|
||||||
fb: FrameBuffer,
|
fb: FrameBuffer,
|
||||||
rom: PathBuf,
|
rom: PathBuf,
|
||||||
|
time: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UI {
|
impl UI {
|
||||||
@ -143,15 +146,22 @@ impl UI {
|
|||||||
if ch8.cpu.flags.pause {
|
if ch8.cpu.flags.pause {
|
||||||
self.window.set_title("Chirp ⏸")
|
self.window.set_title("Chirp ⏸")
|
||||||
} else {
|
} else {
|
||||||
self.window.set_title("Chirp ▶");
|
self.window.set_title(&format!(
|
||||||
|
"Chirp ▶ {:2?}",
|
||||||
|
(1.0 / self.time.elapsed().as_secs_f64()).trunc()
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
if !self.window.is_open() {
|
||||||
|
std::process::exit(0);
|
||||||
|
}
|
||||||
|
self.time = Instant::now();
|
||||||
// update framebuffer
|
// update framebuffer
|
||||||
self.fb.render(&mut self.window, &mut ch8.bus);
|
self.fb.render(&mut self.window, &ch8.bus);
|
||||||
}
|
}
|
||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn keys(&mut self, ch8: &mut Chip8) -> Option<()> {
|
pub fn keys(&mut self, ch8: &mut Chip8) -> Result<Option<()>> {
|
||||||
// TODO: Remove this hacky workaround for minifb's broken get_keys_* functions.
|
// TODO: Remove this hacky workaround for minifb's broken get_keys_* functions.
|
||||||
let get_keys_pressed = || {
|
let get_keys_pressed = || {
|
||||||
self.window
|
self.window
|
||||||
@ -179,7 +189,7 @@ impl UI {
|
|||||||
.print_screen()
|
.print_screen()
|
||||||
.expect("The 'screen' memory region should exist"),
|
.expect("The 'screen' memory region should exist"),
|
||||||
F3 => {
|
F3 => {
|
||||||
debug_dump_screen(&ch8, &self.rom).expect("Unable to write debug screen dump");
|
debug_dump_screen(ch8, &self.rom).expect("Unable to write debug screen dump");
|
||||||
}
|
}
|
||||||
F4 | Slash => {
|
F4 | Slash => {
|
||||||
eprintln!("Debug {}.", {
|
eprintln!("Debug {}.", {
|
||||||
@ -201,7 +211,7 @@ impl UI {
|
|||||||
}),
|
}),
|
||||||
F6 | Enter => {
|
F6 | Enter => {
|
||||||
eprintln!("Step");
|
eprintln!("Step");
|
||||||
ch8.cpu.singlestep(&mut ch8.bus);
|
ch8.cpu.singlestep(&mut ch8.bus)?;
|
||||||
}
|
}
|
||||||
F7 => {
|
F7 => {
|
||||||
eprintln!("Set breakpoint {:03x}.", ch8.cpu.pc());
|
eprintln!("Set breakpoint {:03x}.", ch8.cpu.pc());
|
||||||
@ -216,12 +226,12 @@ impl UI {
|
|||||||
ch8.cpu.soft_reset();
|
ch8.cpu.soft_reset();
|
||||||
ch8.bus.clear_region(Screen);
|
ch8.bus.clear_region(Screen);
|
||||||
}
|
}
|
||||||
Escape => return None,
|
Escape => return Ok(None),
|
||||||
key => ch8.cpu.press(identify_key(key)),
|
key => ch8.cpu.press(identify_key(key)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.keyboard = self.window.get_keys();
|
self.keyboard = self.window.get_keys();
|
||||||
Some(())
|
Ok(Some(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// (c) 2023 John A. Breaux
|
// (c) 2023 John A. Breaux
|
||||||
// This code is licensed under MIT license (see LICENSE.txt for details)
|
// This code is licensed under MIT license (see LICENSE.txt for details)
|
||||||
#![cfg_attr(feature = "unstable", feature(no_coverage))]
|
#![cfg_attr(feature = "unstable", feature(no_coverage))]
|
||||||
#![deny(missing_docs)]
|
#![deny(missing_docs, clippy::all)]
|
||||||
//! This crate implements a Chip-8 interpreter as if it were a real CPU architecture,
|
//! This crate implements a Chip-8 interpreter as if it were a real CPU architecture,
|
||||||
//! to the best of my current knowledge. As it's the first emulator project I've
|
//! to the best of my current knowledge. As it's the first emulator project I've
|
||||||
//! embarked on, and I'm fairly new to Rust, it's going to be rough around the edges.
|
//! embarked on, and I'm fairly new to Rust, it's going to be rough around the edges.
|
||||||
@ -19,7 +19,7 @@ pub mod prelude {
|
|||||||
use super::*;
|
use super::*;
|
||||||
pub use crate::bus;
|
pub use crate::bus;
|
||||||
pub use bus::{Bus, Read, Region::*, Write};
|
pub use bus::{Bus, Read, Region::*, Write};
|
||||||
pub use cpu::{disassemble::Disassemble, ControlFlags, CPU};
|
pub use cpu::{disassembler::Dis, ControlFlags, CPU};
|
||||||
pub use error::Result;
|
pub use error::Result;
|
||||||
pub use io::{UIBuilder, *};
|
pub use io::{UIBuilder, *};
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,7 @@ fn run_screentest(test: SuiteTest, mut cpu: CPU, mut bus: Bus) {
|
|||||||
bus = bus.load_region(Program, test.program);
|
bus = bus.load_region(Program, test.program);
|
||||||
// The test suite always initiates a keypause on test completion
|
// The test suite always initiates a keypause on test completion
|
||||||
while !cpu.flags.keypause {
|
while !cpu.flags.keypause {
|
||||||
cpu.multistep(&mut bus, 8);
|
cpu.multistep(&mut bus, 8).unwrap();
|
||||||
}
|
}
|
||||||
// Compare the screen to the reference screen buffer
|
// Compare the screen to the reference screen buffer
|
||||||
bus.print_screen().unwrap();
|
bus.print_screen().unwrap();
|
||||||
|
@ -22,6 +22,7 @@ mod bus {
|
|||||||
assert_eq!(r1, r2);
|
assert_eq!(r1, r2);
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
#[allow(clippy::clone_on_copy)]
|
||||||
fn clone() {
|
fn clone() {
|
||||||
let r1 = Screen;
|
let r1 = Screen;
|
||||||
let r2 = r1.clone();
|
let r2 = r1.clone();
|
||||||
@ -189,6 +190,23 @@ mod cpu {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mod dis {
|
||||||
|
use chirp::cpu::disassembler::Insn;
|
||||||
|
use imperative_rs::InstructionSet;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::clone_on_copy)]
|
||||||
|
fn clone() {
|
||||||
|
let opcode = Insn::decode(&[0xef, 0xa1]).unwrap().1; // random valid opcode
|
||||||
|
let clone = opcode.clone();
|
||||||
|
assert_eq!(opcode, clone);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn debug() {
|
||||||
|
println!("{:?}", Insn::decode(b"AA")) // "sne #41, v1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn error() {
|
fn error() {
|
||||||
let error = chirp::error::Error::MissingRegion { region: Screen };
|
let error = chirp::error::Error::MissingRegion { region: Screen };
|
||||||
@ -210,6 +228,7 @@ mod ui_builder {
|
|||||||
println!("{ui_builder:?}");
|
println!("{ui_builder:?}");
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
#[allow(clippy::redundant_clone)]
|
||||||
fn clone_debug() {
|
fn clone_debug() {
|
||||||
let ui_builder_clone = UIBuilder::default().clone();
|
let ui_builder_clone = UIBuilder::default().clone();
|
||||||
println!("{ui_builder_clone:?}");
|
println!("{ui_builder_clone:?}");
|
||||||
@ -236,7 +255,7 @@ mod ui {
|
|||||||
let mut ch8 = new_chip8();
|
let mut ch8 = new_chip8();
|
||||||
let ch8 = &mut ch8;
|
let ch8 = &mut ch8;
|
||||||
ui.frame(ch8).unwrap();
|
ui.frame(ch8).unwrap();
|
||||||
ui.keys(ch8);
|
ui.keys(ch8).unwrap();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
Loading…
Reference in New Issue
Block a user