Skip to content

Commit

Permalink
Refactor execute()
Browse files Browse the repository at this point in the history
  • Loading branch information
lyrakisk committed Jul 22, 2024
1 parent 966b137 commit 7ab5710
Showing 1 changed file with 40 additions and 23 deletions.
63 changes: 40 additions & 23 deletions src/cpu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ enum FlagStates {
SET = 1,
}

enum InstructionExecutionError {
INTERRUPT_HANDLING_NOT_IMPLEMENTED,
}

#[derive(Debug)]
pub struct CPU {
struct CPU {
pub register_a: u8,
pub register_x: u8,
pub register_y: u8,
Expand Down Expand Up @@ -57,87 +61,91 @@ impl CPU {

let instruction = &INSTRUCTIONS[&opcode];

if let Some(_) = self.execute(&instruction) {
return;
match self.execute(&instruction) {
Ok(()) => (),
Err(InstructionExecutionError::INTERRUPT_HANDLING_NOT_IMPLEMENTED) => {
return;
}
}

self.program_counter += (instruction.bytes as u16) - 1;
}
}

fn execute(&mut self, instruction: &Instruction) -> Option<ExitCode> {
fn execute(&mut self, instruction: &Instruction) -> Result<(), InstructionExecutionError> {
match instruction.name {
"ADC" => {
self.adc(&instruction.addressing_mode);
None
Ok(())
}
"AND" => {
self.and(&instruction.addressing_mode);
None
Ok(())
}
"ASL" => {
self.asl(&instruction.addressing_mode);
None
Ok(())
}
"BCC" => {
self.bcc();
None
Ok(())
}
"BCS" => {
self.bcs();
None
Ok(())
}
"BEQ" => {
self.beq();
None
Ok(())
}
"BMI" => {
self.bmi();
None
Ok(())
}
"BNE" => {
self.bne();
None
Ok(())
}
"BPL" => {
self.bpl();
None
Ok(())
}
"BVC" => {
self.bvc();
None
Ok(())
}
"BVS" => {
self.bvs();
None
Ok(())
}
"CLC" => {
self.clc();
None
Ok(())
}
"CLV" => {
self.clv();
None
Ok(())
}
"CMP" => {
self.cmp(&instruction.addressing_mode);
None
Ok(())
}
"BRK" => Some(0),
"BRK" => Err(InstructionExecutionError::INTERRUPT_HANDLING_NOT_IMPLEMENTED),
"LDA" => {
self.lda(&instruction.addressing_mode);
None
Ok(())
}
"TAX" => {
self.tax();
None
Ok(())
}
"INX" => {
self.inx();
None
Ok(())
}
"SBC" => {
self.sbc(&instruction.addressing_mode);
None
Ok(())
}
_ => {
todo!();
Expand Down Expand Up @@ -514,6 +522,8 @@ mod test_cpu {
assert_eq!(cpu.status, expected);
}

// TODO: test that illegal opcodes are ignored

#[test]
fn lda_correctly_sets_negative_flag() {
let program = vec![0xa9, 0x05, 0x00];
Expand Down Expand Up @@ -948,4 +958,11 @@ mod test_cpu {
let result = cpu.get_operand(&AddressingMode::Accumulator);
assert_eq!(result, 0x80);
}

#[test]
fn run_test_from_json() {
// init cpu
// update state
// while next instruction, execute()
}
}

0 comments on commit 7ab5710

Please sign in to comment.