refactor 2 electric boogaloo

This commit is contained in:
2025-06-15 21:40:43 +01:00
parent 277f210b3e
commit 2b8281157e
30 changed files with 125 additions and 71 deletions
+156
View File
@@ -0,0 +1,156 @@
//! Various types of arguments that instructions can take, alongside encoding and decoding logic.
use crate::{
instructions::{RegisterParseError, encode::Encode},
prelude::Register,
};
/// A list of errors that can be returned when decoding instruction arguments.
#[derive(Debug)]
pub enum ArgsDecodeError {
/// The register was not valid.
InvalidRegister(u8),
}
impl From<RegisterParseError> for ArgsDecodeError {
fn from(value: RegisterParseError) -> Self {
match value {
RegisterParseError::InvalidIndex(idx) => Self::InvalidRegister(idx),
}
}
}
impl std::fmt::Display for ArgsDecodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidRegister(idx) => {
write!(f, "invalid register index, got {idx:x}")?;
}
}
Ok(())
}
}
impl std::error::Error for ArgsDecodeError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Used by instructions with 2 registers and an immediate argument.
pub struct ITypeArgs {
pub immediate: u16,
pub r1: Register,
/// May not actually be used by some instructions taking an immediate e.g. LUI. This is solved by making the constructor take Options.
pub r2: Register,
}
impl ITypeArgs {
#[must_use]
/// Creates a new [`ITypeArgs`]. If r1 or r2 is unset, they will be replaced with [`Register::NoReg`].
pub fn new(immediate: u16, r1: Option<Register>, r2: Option<Register>) -> Self {
let r1 = r1.unwrap_or_default();
let r2 = r2.unwrap_or_default();
Self { immediate, r1, r2 }
}
}
impl Encode for ITypeArgs {
/// Encodes an I-type instruction from its fields. These must have some unused high-order
/// bits set to 0 else the bit shifting logic gets fucked.
fn encode(self, opcode: u8) -> u32 {
let opcode = u32::from(opcode);
let r1 = self.r1 as u32;
let dr = self.r2 as u32;
let immediate = u32::from(self.immediate);
(opcode << 26) | (r1 << 21) | (dr << 16) | immediate
}
}
impl TryFrom<u32> for ITypeArgs {
type Error = ArgsDecodeError;
fn try_from(data: u32) -> Result<Self, Self::Error> {
let r1 = ((data >> 21) & 0x1F) as u8;
let r2 = ((data >> 16) & 0x1F) as u8;
let immediate = data as u16;
let r1 = r1.try_into()?;
let r2 = r2.try_into()?;
Ok(Self { immediate, r1, r2 })
}
}
/// Used by instructions not using immediates (besides 5 bit shift values).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RTypeArgs {
pub sr1: Register,
pub sr2: Register,
pub dr: Register,
/// 5 bit shift amount.
pub shamt: u8,
}
impl RTypeArgs {
#[must_use]
/// Creates a new [`RTypeArgs`]. If any registers are unset, they will be replaced with [`Register::NoReg`]. If `shamt` is unset, it will be set to 0.
pub fn new(
sr1: Option<Register>,
sr2: Option<Register>,
dr: Option<Register>,
shamt: Option<u8>,
) -> Self {
let sr1 = sr1.unwrap_or_default();
let shamt = shamt.unwrap_or_default();
let sr2 = sr2.unwrap_or_default();
let dr = dr.unwrap_or_default();
Self {
sr1,
sr2,
dr,
shamt,
}
}
}
impl Encode for RTypeArgs {
/// Encodes an R-type instruction from its fields. These must have unused high-order
/// bits set to 0 else the bit shifting logic is fucked.
///
/// # Arguments
///
/// - `shamt`: The amount to shift value (used only in shift instructions, otherwise 0).
fn encode(self, opcode: u8) -> u32 {
let opcode = u32::from(opcode);
let sr1 = self.sr1 as u32;
let sr2 = self.sr2 as u32;
let dr = self.dr as u32;
let shamt = u32::from(self.shamt);
(opcode << 26) | (sr1 << 21) | (sr2 << 16) | (dr << 11) | (shamt << 6)
}
}
impl TryFrom<u32> for RTypeArgs {
type Error = ArgsDecodeError;
fn try_from(data: u32) -> Result<Self, Self::Error> {
let sr1 = ((data >> 21) & 0x1F) as u8;
let sr2 = ((data >> 16) & 0x1F) as u8;
let dr = ((data >> 11) & 0x1F) as u8;
let shamt = ((data >> 6) & 0x1F) as u8;
let sr1_reg = sr1.try_into()?;
let sr2_reg = sr2.try_into()?;
let dr_reg = dr.try_into()?;
Ok(Self {
sr1: sr1_reg,
sr2: sr2_reg,
dr: dr_reg,
shamt,
})
}
}
+63
View File
@@ -0,0 +1,63 @@
use crate::prelude::*;
/// Not to be used directly, just call [`Instruction::encode`].
pub trait Encode {
fn encode(self, opcode: u8) -> u32;
}
/// Encodes a zero argument instruction.
fn encode_no_args(opcode: u8) -> u32 {
let opcode = u32::from(opcode);
let sr1 = Register::NoReg as u32;
let sr2 = Register::NoReg as u32;
let dr = Register::NoReg as u32;
let shamt = 0;
(opcode << 26) | (sr1 << 21) | (sr2 << 16) | (dr << 11) | (shamt << 6)
}
/// Expands to a match statement that calls encode on instructions that implement [`Encode`]:
///
/// # Usage
///
/// ```rs
/// encode_instruction!(self, with_args: [...], no_args: [...], special: [...] )
/// ```
macro_rules! encode_instruction {
($self:expr, with_args: [$($variant:ident),+ $(,)?], no_args: [$($no_arg_variant:ident),* $(,)?] $(, special: [$($special:pat => $body:expr),* $(,)?])?) => {
match $self {
$(
Instruction::$variant(args) => args.encode($self.opcode()),
)+
$(
Instruction::$no_arg_variant => encode_no_args($self.opcode()),
)*
$($(
$special => $body,
)*)?
}
};
}
impl Encode for Instruction {
fn encode(self, _: u8) -> u32 {
encode_instruction!(
self,
with_args: [
Mov, MovSigned, LoadByte, LoadByteSigned, LoadHalfword,
LoadHalfwordSigned, LoadWord, StoreByte, StoreHalfword,
StoreWord, LoadLowerImmediate, LoadUpperImmediate, Jump,
JumpEq, JumpNeq, JumpGt, JumpGe, JumpLt, JumpLe, Compare,
Add, Sub, Increment, Decrement, ShiftLeft, ShiftRight,
And, Or, Not, Xor, Nand, Nor, Xnor
],
no_args: [Nop, IntReturn, Halt],
special: [
Self::Interrupt(_) => todo!()
]
)
}
}
#[cfg(test)]
mod tests;
+95
View File
@@ -0,0 +1,95 @@
use crate::prelude::*;
#[test]
fn test_encode_nop() {
let no_reg = Register::NoReg as u32;
let no_op = u32::from(Instruction::Nop.opcode());
let expected = no_op << 26 | no_reg << 21 | no_reg << 16 | no_reg << 11;
let got = Instruction::Nop.encode();
assert_eq!(expected, got);
}
#[test]
fn test_encode_mov() {
let rg0 = Register::Rg0 as u32;
let rg1 = Register::Rg1 as u32;
let no_reg = Register::NoReg as u32;
let instruction = Instruction::Mov(RTypeArgs::new(
Some(Register::Rg0),
None,
Some(Register::Rg1),
None,
));
let mov = u32::from(instruction.opcode());
let expected = mov << 26 | rg0 << 21 | no_reg << 16 | rg1 << 11;
let got = instruction.encode();
assert_eq!(expected, got);
}
#[test]
fn test_encode_load_byte() {
let rg0 = Register::Rg0 as u32;
let rg1 = Register::Rg1 as u32;
let immediate = 100;
let instruction = Instruction::LoadByte(ITypeArgs::new(
immediate,
Some(Register::Rg0),
Some(Register::Rg1),
));
let load_byte = u32::from(instruction.opcode());
let expected = load_byte << 26 | rg0 << 21 | rg1 << 16 | u32::from(immediate);
let got = instruction.encode();
assert_eq!(expected, got);
}
#[test]
fn test_encode_shift_left_shamt() {
let rg0 = Register::Rg0 as u32;
let no_reg = Register::NoReg as u32;
let shift_amount = 5;
let instruction = Instruction::ShiftLeft(RTypeArgs::new(
Some(Register::Rg0),
None,
None,
Some(shift_amount),
));
let shift_left = u32::from(instruction.opcode());
let expected =
shift_left << 26 | rg0 << 21 | no_reg << 16 | no_reg << 11 | u32::from(shift_amount) << 6;
let got = instruction.encode();
assert_eq!(expected, got);
}
#[test]
fn test_encode_shift_left_reg() {
let rg0 = Register::Rg0 as u32;
let rg1 = Register::Rg1 as u32;
let no_reg = Register::NoReg as u32;
let instruction = Instruction::ShiftLeft(RTypeArgs::new(
Some(Register::Rg0),
Some(Register::Rg1),
None,
None,
));
let shift_left = u32::from(instruction.opcode());
let expected = shift_left << 26 | rg0 << 21 | rg1 << 16 | no_reg << 11;
let got = instruction.encode();
assert_eq!(expected, got);
}
+54
View File
@@ -0,0 +1,54 @@
//! All the errors that may be returned from [`instructions`].
use crate::prelude::*;
#[derive(Debug)]
/// Error type for parsing register numbers.
pub enum RegisterParseError {
InvalidIndex(u8),
}
impl std::fmt::Display for RegisterParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidIndex(idx) => write!(f, "invalid index given ({idx})"),
}
}
}
impl std::error::Error for RegisterParseError {}
/// A list of errors that can be returned when decoding instructions.
#[derive(Debug)]
pub enum InstructionDecodeError {
/// Some field was incorrect. Returns an error for debugging purposes.
InvalidArgument(ArgsDecodeError),
/// Some opcode was invalid. Returns the offending opcode for debugging purposes etc.
InvalidOpcode(u8),
}
impl From<ArgsDecodeError> for InstructionDecodeError {
fn from(err: ArgsDecodeError) -> Self {
Self::InvalidArgument(err)
}
}
impl std::fmt::Display for InstructionDecodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidOpcode(code) => write!(f, "invalid opcode, got {code:x}")?,
Self::InvalidArgument(err) => write!(f, "invalid arguments, got an error {err}")?,
}
Ok(())
}
}
impl std::error::Error for InstructionDecodeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidArgument(err) => Some(err),
_ => None,
}
}
}
+211
View File
@@ -0,0 +1,211 @@
#![allow(clippy::unwrap_used)]
use crate::prelude::*;
#[test]
fn test_opcode_nop() {
let instr = Instruction::Nop;
assert_eq!(instr.opcode(), 0x0);
}
#[test]
fn test_opcode_data_transfer() {
let args = RTypeArgs::new(None, None, None, None);
assert_eq!(Instruction::Mov(args).opcode(), 0x1);
assert_eq!(Instruction::MovSigned(args).opcode(), 0x2);
let iargs = ITypeArgs::new(0, None, None);
assert_eq!(Instruction::LoadByte(iargs).opcode(), 0x3);
assert_eq!(Instruction::LoadByteSigned(iargs).opcode(), 0x4);
assert_eq!(Instruction::LoadHalfword(iargs).opcode(), 0x5);
assert_eq!(Instruction::LoadHalfwordSigned(iargs).opcode(), 0x6);
assert_eq!(Instruction::LoadWord(iargs).opcode(), 0x7);
assert_eq!(Instruction::StoreByte(iargs).opcode(), 0x8);
assert_eq!(Instruction::StoreHalfword(iargs).opcode(), 0x9);
assert_eq!(Instruction::StoreWord(iargs).opcode(), 0xA);
assert_eq!(Instruction::LoadLowerImmediate(iargs).opcode(), 0xB);
assert_eq!(Instruction::LoadUpperImmediate(iargs).opcode(), 0xC);
}
#[test]
fn test_opcode_jump_instructions() {
let args = ITypeArgs::new(0, None, None);
assert_eq!(Instruction::Jump(args).opcode(), 0xD);
assert_eq!(Instruction::JumpEq(args).opcode(), 0xE);
assert_eq!(Instruction::JumpNeq(args).opcode(), 0xF);
assert_eq!(Instruction::JumpGt(args).opcode(), 0x10);
assert_eq!(Instruction::JumpGe(args).opcode(), 0x11);
assert_eq!(Instruction::JumpLt(args).opcode(), 0x12);
assert_eq!(Instruction::JumpLe(args).opcode(), 0x13);
}
#[test]
fn test_opcode_arithmetic() {
let args = RTypeArgs::new(None, None, None, None);
assert_eq!(Instruction::Compare(args).opcode(), 0x14);
assert_eq!(Instruction::Increment(args).opcode(), 0x15);
assert_eq!(Instruction::Decrement(args).opcode(), 0x16);
assert_eq!(Instruction::ShiftLeft(args).opcode(), 0x17);
assert_eq!(Instruction::ShiftRight(args).opcode(), 0x18);
assert_eq!(Instruction::Add(args).opcode(), 0x19);
assert_eq!(Instruction::Sub(args).opcode(), 0x1A);
}
#[test]
fn test_opcode_logical() {
let args = RTypeArgs::new(None, None, None, None);
assert_eq!(Instruction::And(args).opcode(), 0x1B);
assert_eq!(Instruction::Or(args).opcode(), 0x1C);
assert_eq!(Instruction::Not(args).opcode(), 0x1D);
assert_eq!(Instruction::Xor(args).opcode(), 0x1E);
assert_eq!(Instruction::Nand(args).opcode(), 0x1F);
assert_eq!(Instruction::Nor(args).opcode(), 0x20);
assert_eq!(Instruction::Xnor(args).opcode(), 0x21);
}
#[test]
fn test_opcode_misc() {
let interrupt = Interrupt::Software(5);
assert_eq!(Instruction::Interrupt(interrupt).opcode(), 0x22);
assert_eq!(Instruction::IntReturn.opcode(), 0x23);
assert_eq!(Instruction::Halt.opcode(), 0x24);
}
#[test]
fn test_opcode_with_different_args() {
let args1 = RTypeArgs::new(
Some(Register::Rg0),
Some(Register::Rg1),
Some(Register::Rg2),
Some(5),
);
let args2 = RTypeArgs::new(
Some(Register::Acc),
Some(Register::Spr),
Some(Register::Bpr),
Some(31),
);
// Opcode should be the same regardless of arguments
assert_eq!(
Instruction::Add(args1).opcode(),
Instruction::Add(args2).opcode()
);
assert_eq!(
Instruction::Sub(args1).opcode(),
Instruction::Sub(args2).opcode()
);
}
#[test]
fn test_opcode_boundary_values() {
// Test highest opcode value
assert_eq!(Instruction::Halt.opcode(), 0x24);
// Test lowest opcode value
assert_eq!(Instruction::Nop.opcode(), 0x0);
}
#[test]
fn test_instruction_decode_nop() {
let instr = Instruction::Nop;
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_data_transfer() {
let args = RTypeArgs::new(
Some(Register::Rg0),
Some(Register::Rg1),
Some(Register::Rg2),
Some(5),
);
let instr = Instruction::Mov(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
let iargs = ITypeArgs::new(100, Some(Register::Rg3), Some(Register::Rg4));
let instr = Instruction::LoadWord(iargs);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_jump() {
let args = ITypeArgs::new(200, Some(Register::Acc), Some(Register::Spr));
let instr = Instruction::Jump(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
let instr = Instruction::JumpEq(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_arithmetic() {
let args = RTypeArgs::new(
Some(Register::Bpr),
Some(Register::Rg7),
Some(Register::Rgf),
Some(31),
);
let instr = Instruction::Add(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
let instr = Instruction::Compare(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_logical() {
let args = RTypeArgs::new(
Some(Register::Rg8),
Some(Register::Rg9),
Some(Register::Rga),
Some(15),
);
let instr = Instruction::And(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
let instr = Instruction::Xor(args);
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_misc() {
let instr = Instruction::Halt;
let encoded = instr.encode();
let decoded = Instruction::decode(encoded).unwrap();
assert_eq!(instr, decoded);
}
#[test]
fn test_instruction_decode_invalid() {
// Test with invalid opcode.
let invalid_encoded = 0xFF00_0000;
assert!(Instruction::decode(invalid_encoded).is_err());
}
// TODO: Get interrupts working.
// #[test]
// fn test_instruction_decode_interrupt() {
// let interrupt = Interrupt::Software(10);
// let instr = Instruction::Interrupt(interrupt);
// let encoded = instr.encode();
// let decoded = Instruction::decode(encoded).unwrap();
// assert_eq!(instr, decoded);
// }