use super::decode::{ByteRegister, Instruction};
const CONDITIONS: [&str; 16] = [
"BRA", "BRN", "BHI", "BLS", "BCC", "BCS", "BNE", "BEQ", "BVC", "BVS", "BPL", "BMI", "BGE",
"BLT", "BGT", "BLE",
];
fn byte_register(register: ByteRegister) -> String {
let code = register.code();
if code < 8 {
format!("R{code}H")
} else {
format!("R{}L", code - 8)
}
}
fn branch_operand(displacement: i8) -> String {
let offset = i16::from(displacement) + 2;
if offset >= 0 {
format!("$+{offset}:8")
} else {
format!("${offset}:8")
}
}
pub fn disassemble(instruction: Instruction) -> String {
match instruction {
Instruction::Nop => "NOP".into(),
Instruction::Sleep => "SLEEP".into(),
Instruction::Rts => "RTS".into(),
Instruction::Rte => "RTE".into(),
Instruction::AddByte {
source,
destination,
} => {
format!(
"ADD.B {},{}",
byte_register(source),
byte_register(destination)
)
}
Instruction::MovByte {
source,
destination,
} => {
format!(
"MOV.B {},{}",
byte_register(source),
byte_register(destination)
)
}
Instruction::Branch {
condition,
displacement,
} => {
let mnemonic = CONDITIONS
.get(usize::from(condition))
.copied()
.unwrap_or("B??");
format!("{mnemonic} {}", branch_operand(displacement))
}
Instruction::BranchSubroutine { displacement } => {
format!("BSR {}", branch_operand(displacement))
}
}
}