parser/instructions/
mod.rs

1pub mod operand;
2pub mod nop;
3pub mod ld;
4pub mod xor;
5
6use super::error;
7use super::InstructionTrait;
8use operand::{Reg8, Reg16, Operand};
9use nop::Nop;
10use ld::Ld;
11use xor::Xor;
12
13use std::fmt;
14
15#[derive(Debug, PartialEq)]
16pub enum Instruction {
17    Nop(Nop),
18    Ld(Ld),
19    Xor(Xor),
20}
21
22impl Instruction {
23    pub fn get_instruction(&self) -> &dyn InstructionTrait {
24        match self {
25            Self::Nop(inst) => inst,
26            Self::Ld(inst) => inst,
27            Self::Xor(inst) => inst,
28        }
29    }
30}
31
32impl fmt::Display for Instruction {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        match self {
35            Self::Nop(nop) => write!(f, "{}", nop),
36            Self::Ld(ld) => write!(f, "{}", ld),
37            Self::Xor(xor) => write!(f, "{}", xor),
38        }
39    }
40}
41
42pub fn decode(opcode: u8, bytes: &[u8]) -> Result<Instruction, error::ParserError> {
43    let inst: Instruction = match opcode {
44        0x00 => Nop::new().into(),
45        0x01 => Ld::new(Operand::Reg16(Reg16::BC), Operand::imm16_from_bytes(bytes)?, 3).into(),
46        0x11 => Ld::new(Operand::Reg16(Reg16::DE), Operand::imm16_from_bytes(bytes)?, 3).into(),
47        0x21 => Ld::new(Operand::Reg16(Reg16::HL), Operand::imm16_from_bytes(bytes)?, 3).into(),
48        0x31 => Ld::new(Operand::Reg16(Reg16::SP), Operand::imm16_from_bytes(bytes)?, 3).into(),
49        0xA8 => Xor::new(Operand::Reg8(Reg8::B)).into(),
50        0xA9 => Xor::new(Operand::Reg8(Reg8::C)).into(),
51        0xAA => Xor::new(Operand::Reg8(Reg8::D)).into(),
52        0xAB => Xor::new(Operand::Reg8(Reg8::E)).into(),
53        0xAC => Xor::new(Operand::Reg8(Reg8::H)).into(),
54        0xAD => Xor::new(Operand::Reg8(Reg8::L)).into(),
55        0xAE => Xor::new(Operand::DerefReg(Reg16::HL)).into(),
56        0xAF => Xor::new(Operand::Reg8(Reg8::A)).into(),
57        0xEE => Xor::new(Operand::imm8_from_bytes(bytes)?).into(),
58        _ => return Err(error::ParserError::InvalidOpcode(opcode)),
59    };
60
61    Ok(inst)
62}