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
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "common"
version.workspace = true
edition.workspace = true
authors.workspace = true
[dependencies]
+414
View File
@@ -0,0 +1,414 @@
use crate::{instructions::encode::Encode, prelude::*};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Interrupt {
Software(u8),
}
pub type Address = u32;
impl Interrupt {
const fn as_u8(self) -> u8 {
match self {
Self::Software(code) => code,
}
}
}
// TODO: This should be TryFrom.
impl From<u8> for Interrupt {
#[allow(unreachable_code)]
fn from(_code: u8) -> Self {
todo!("Implement this once a hardware interrupt convention is established.");
// Self::Software(_code)
}
}
/// Whether an [`Instruction`] is an I-type or R-type instruction.
#[non_exhaustive]
pub enum InstructionType {
Register,
Immediate,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Register {
// general purpose registers
Rg0,
Rg1,
Rg2,
Rg3,
Rg4,
Rg5,
Rg6,
Rg7,
Rg8,
Rg9,
Rga,
Rgb,
Rgc,
Rgd,
Rge,
Rgf,
// special purpose registers
Acc,
Spr,
Bpr,
Ret,
Idr,
Mmr,
Zero,
NoReg,
// system registers - can't be written to by instructions.
Mar,
Mdr,
Sts,
Cir,
Pcx,
}
impl Default for Register {
fn default() -> Self {
Self::NoReg
}
}
impl TryFrom<u8> for Register {
type Error = RegisterParseError;
fn try_from(idx: u8) -> Result<Self, Self::Error> {
if idx > 0x18 {
return Err(RegisterParseError::InvalidIndex(idx));
}
Ok(match idx {
// System registers are not indexable in the reg file so they cannot be modified by instructions.
0x0 => Self::Rg0,
0x1 => Self::Rg1,
0x2 => Self::Rg2,
0x3 => Self::Rg3,
0x4 => Self::Rg4,
0x5 => Self::Rg5,
0x6 => Self::Rg6,
0x7 => Self::Rg7,
0x8 => Self::Rg8,
0x9 => Self::Rg9,
0xA => Self::Rga,
0xB => Self::Rgb,
0xC => Self::Rgc,
0xD => Self::Rgd,
0xE => Self::Rge,
0xF => Self::Rgf,
0x10 => Self::Acc,
0x11 => Self::Spr,
0x12 => Self::Bpr,
0x13 => Self::Ret,
0x14 => Self::Idr,
0x15 => Self::Mmr,
0x16 => Self::Zero,
0x17 => Self::NoReg,
_ => unreachable!("This is already checked for in top `if` branch."),
})
}
}
impl std::fmt::Display for Register {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Rg0 => write!(f, "rg0"),
Self::Rg1 => write!(f, "rg1"),
Self::Rg2 => write!(f, "rg2"),
Self::Rg3 => write!(f, "rg3"),
Self::Rg4 => write!(f, "rg4"),
Self::Rg5 => write!(f, "rg5"),
Self::Rg6 => write!(f, "rg6"),
Self::Rg7 => write!(f, "rg7"),
Self::Rg8 => write!(f, "rg8"),
Self::Rg9 => write!(f, "rg9"),
Self::Rga => write!(f, "rga"),
Self::Rgb => write!(f, "rgb"),
Self::Rgc => write!(f, "rgc"),
Self::Rgd => write!(f, "rgd"),
Self::Rge => write!(f, "rge"),
Self::Rgf => write!(f, "rgf"),
Self::Acc => write!(f, "acc"),
Self::Spr => write!(f, "spr"),
Self::Bpr => write!(f, "bpr"),
Self::Ret => write!(f, "ret"),
Self::Idr => write!(f, "idr"),
Self::Mmr => write!(f, "mmr"),
Self::Zero => write!(f, "zero"),
Self::NoReg => write!(f, "noreg"),
Self::Mar => write!(f, "mar"),
Self::Mdr => write!(f, "mdr"),
Self::Sts => write!(f, "sts"),
Self::Cir => write!(f, "cir"),
Self::Pcx => write!(f, "pcx"),
}
}
}
#[derive(Debug, Clone, Copy, Eq)]
#[repr(u8)]
#[non_exhaustive]
/// A list of all current instructions in the DSA.
///
/// # Note
///
/// This is subject to change and is therefore marked non exhaustive.
pub enum Instruction {
// No-op
Nop = 0x0,
// Data transfer instructions
Mov(args::RTypeArgs) = 0x1,
MovSigned(args::RTypeArgs) = 0x2,
LoadByte(args::ITypeArgs) = 0x3,
LoadByteSigned(args::ITypeArgs) = 0x4,
LoadHalfword(args::ITypeArgs) = 0x5,
LoadHalfwordSigned(args::ITypeArgs) = 0x6,
LoadWord(args::ITypeArgs) = 0x7,
StoreByte(args::ITypeArgs) = 0x8,
StoreHalfword(args::ITypeArgs) = 0x9,
StoreWord(args::ITypeArgs) = 0xA,
LoadLowerImmediate(args::ITypeArgs) = 0xB,
LoadUpperImmediate(args::ITypeArgs) = 0xC,
// Jump Instructions
Jump(args::ITypeArgs) = 0xD,
JumpEq(args::ITypeArgs) = 0xE,
JumpNeq(args::ITypeArgs) = 0xF,
JumpGt(args::ITypeArgs) = 0x10,
JumpGe(args::ITypeArgs) = 0x11,
JumpLt(args::ITypeArgs) = 0x12,
JumpLe(args::ITypeArgs) = 0x13,
// Comparison
Compare(args::RTypeArgs) = 0x14,
// Arithmetic
Add(args::RTypeArgs) = 0x19,
Sub(args::RTypeArgs) = 0x1A,
Increment(args::RTypeArgs) = 0x15,
Decrement(args::RTypeArgs) = 0x16,
ShiftLeft(args::RTypeArgs) = 0x17,
ShiftRight(args::RTypeArgs) = 0x18,
// Logical
And(args::RTypeArgs) = 0x1B,
Or(args::RTypeArgs) = 0x1C,
Not(args::RTypeArgs) = 0x1D,
Xor(args::RTypeArgs) = 0x1E,
Nand(args::RTypeArgs) = 0x1F,
Nor(args::RTypeArgs) = 0x20,
Xnor(args::RTypeArgs) = 0x21,
// Misc
Interrupt(Interrupt) = 0x22,
IntReturn = 0x23,
Halt = 0x24,
}
impl PartialEq for Instruction {
fn eq(&self, other: &Self) -> bool {
self.encode() == other.encode()
}
}
impl Instruction {
/// Returns the opcode of an instruction.
///
/// # Notes
///
/// The top two bits shall be 0, opcodes are 6-bits long.
#[must_use]
pub const fn opcode(&self) -> u8 {
unsafe { *std::ptr::from_ref::<Self>(self).cast::<u8>() }
}
/// Encodes an [`Instruction`] into a word.
#[must_use]
pub fn encode(&self) -> u32 {
Encode::encode(*self, self.opcode())
}
/// Decodes an [`Instruction`] from a word `data`.
pub fn decode(data: u32) -> Result<Self, InstructionDecodeError> {
data.try_into()
}
/// Returns the mnemonic for a given [`Instruction`].
#[must_use]
pub const fn mnemonic(self) -> &'static str {
match self {
Self::Add(_) => "add",
Self::Sub(_) => "sub",
Self::Increment(_) => "inc",
Self::Decrement(_) => "dec",
Self::Compare(_) => "cmp",
Self::Halt => "hlt",
Self::And(_) => "and",
Self::IntReturn => "intr",
Self::Interrupt(_) => "int",
Self::Jump(_) => "jmp",
Self::JumpEq(_) => "jeq",
Self::JumpNeq(_) => "jneq",
Self::JumpGt(_) => "jgt",
Self::JumpGe(_) => "jge",
Self::JumpLt(_) => "jlt",
Self::JumpLe(_) => "jle",
Self::Mov(_) => "mov",
Self::MovSigned(_) => "movs",
Self::LoadByte(_) => "ldb",
Self::LoadByteSigned(_) => "ldbs",
Self::LoadHalfword(_) => "ldh",
Self::LoadHalfwordSigned(_) => "ldhs",
Self::LoadWord(_) => "ldw",
Self::StoreByte(_) => "stb",
Self::StoreHalfword(_) => "sth",
Self::StoreWord(_) => "stw",
Self::LoadLowerImmediate(_) => "lli",
Self::LoadUpperImmediate(_) => "lui",
Self::ShiftLeft(_) => "shl",
Self::ShiftRight(_) => "shr",
Self::Or(_) => "or",
Self::Not(_) => "not",
Self::Nop => "nop",
Self::Xor(_) => "xor",
Self::Nand(_) => "nand",
Self::Nor(_) => "nor",
Self::Xnor(_) => "xnor",
}
}
/// Returns the [`InstructionType`] for the given [`Instruction`].
#[must_use]
pub const fn instruction_type(self) -> InstructionType {
Self::instruction_type_from_opcode(self.opcode())
}
/// Returns the [`InstructionType`] for the given `opcode`.
#[must_use]
pub const fn instruction_type_from_opcode(opcode: u8) -> InstructionType {
match opcode {
0x3..=0x13 => InstructionType::Immediate,
_ => InstructionType::Register,
}
}
}
// Instruction decoding logic goes here.
impl std::fmt::Display for Instruction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.mnemonic())?;
match self {
Self::Mov(args) | Self::MovSigned(args) => write!(f, " {}, {}", args.sr1, args.dr),
Self::LoadByte(args)
| Self::LoadByteSigned(args)
| Self::LoadHalfword(args)
| Self::LoadHalfwordSigned(args)
| Self::LoadWord(args)
| Self::StoreByte(args)
| Self::StoreHalfword(args)
| Self::StoreWord(args) => {
write!(f, " {:x}({}), {}", args.immediate, args.r1, args.r2)
}
Self::Jump(args)
| Self::JumpEq(args)
| Self::JumpNeq(args)
| Self::JumpGt(args)
| Self::JumpGe(args)
| Self::JumpLt(args)
| Self::JumpLe(args) => {
write!(f, " ({:x}){}", args.immediate, args.r1)
}
Self::LoadLowerImmediate(args) | Self::LoadUpperImmediate(args) => {
write!(f, " {}, {}", args.r1, args.r2)
}
Self::Compare(args) | Self::Not(args) => write!(f, " {}, {}", args.sr1, args.sr2),
Self::Add(args)
| Self::Sub(args)
| Self::Xor(args)
| Self::Nand(args)
| Self::Nor(args)
| Self::Xnor(args)
| Self::ShiftLeft(args)
| Self::ShiftRight(args)
| Self::And(args)
| Self::Or(args) => {
write!(f, " {}, {}, {}", args.sr1, args.sr2, args.dr)
}
Self::Increment(a) | Self::Decrement(a) => write!(f, " {}", a.dr),
Self::Interrupt(a) => write!(f, " {}", a.as_u8()),
_ => Ok(()),
}
}
}
impl TryFrom<u32> for Instruction {
type Error = InstructionDecodeError;
/// Instruction decoding can be using using [`Instruction::try_from`]
fn try_from(data: u32) -> Result<Self, Self::Error> {
// Pull the opcode out so we can parse it correctly.
let opcode = ((data >> 26) & 0x3F) as u8;
match opcode {
0x0 => Ok(Self::Nop),
0x1 => Ok(Self::Mov(RTypeArgs::try_from(data)?)),
0x2 => Ok(Self::MovSigned(RTypeArgs::try_from(data)?)),
0x3 => Ok(Self::LoadByte(ITypeArgs::try_from(data)?)),
0x4 => Ok(Self::LoadByteSigned(ITypeArgs::try_from(data)?)),
0x5 => Ok(Self::LoadHalfword(ITypeArgs::try_from(data)?)),
0x6 => Ok(Self::LoadHalfwordSigned(ITypeArgs::try_from(data)?)),
0x7 => Ok(Self::LoadWord(ITypeArgs::try_from(data)?)),
0x8 => Ok(Self::StoreByte(ITypeArgs::try_from(data)?)),
0x9 => Ok(Self::StoreHalfword(ITypeArgs::try_from(data)?)),
0xA => Ok(Self::StoreWord(ITypeArgs::try_from(data)?)),
0xB => Ok(Self::LoadLowerImmediate(ITypeArgs::try_from(data)?)),
0xC => Ok(Self::LoadUpperImmediate(ITypeArgs::try_from(data)?)),
0xD => Ok(Self::Jump(ITypeArgs::try_from(data)?)),
0xE => Ok(Self::JumpEq(ITypeArgs::try_from(data)?)),
0xF => Ok(Self::JumpNeq(ITypeArgs::try_from(data)?)),
0x10 => Ok(Self::JumpGt(ITypeArgs::try_from(data)?)),
0x11 => Ok(Self::JumpGe(ITypeArgs::try_from(data)?)),
0x12 => Ok(Self::JumpLt(ITypeArgs::try_from(data)?)),
0x13 => Ok(Self::JumpLe(ITypeArgs::try_from(data)?)),
0x14 => Ok(Self::Compare(RTypeArgs::try_from(data)?)),
0x15 => Ok(Self::Increment(RTypeArgs::try_from(data)?)),
0x16 => Ok(Self::Decrement(RTypeArgs::try_from(data)?)),
0x17 => Ok(Self::ShiftLeft(RTypeArgs::try_from(data)?)),
0x18 => Ok(Self::ShiftRight(RTypeArgs::try_from(data)?)),
0x19 => Ok(Self::Add(RTypeArgs::try_from(data)?)),
0x1A => Ok(Self::Sub(RTypeArgs::try_from(data)?)),
0x1B => Ok(Self::And(RTypeArgs::try_from(data)?)),
0x1C => Ok(Self::Or(RTypeArgs::try_from(data)?)),
0x1D => Ok(Self::Not(RTypeArgs::try_from(data)?)),
0x1E => Ok(Self::Xor(RTypeArgs::try_from(data)?)),
0x1F => Ok(Self::Nand(RTypeArgs::try_from(data)?)),
0x20 => Ok(Self::Nor(RTypeArgs::try_from(data)?)),
0x21 => Ok(Self::Xnor(RTypeArgs::try_from(data)?)),
0x22 => Ok(Self::Interrupt(Interrupt::from((data & 0xFF) as u8))),
0x23 => Ok(Self::IntReturn),
0x24 => Ok(Self::Halt),
_ => Err(InstructionDecodeError::InvalidOpcode(opcode)),
}
}
}
pub mod args;
mod encode;
pub mod errors;
#[cfg(test)]
mod tests;
+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);
// }
+22
View File
@@ -0,0 +1,22 @@
#![deny(
clippy::unwrap_used,
clippy::nursery,
clippy::perf,
clippy::pedantic,
clippy::complexity
)]
#![allow(
clippy::cast_possible_truncation,
clippy::missing_panics_doc,
clippy::missing_errors_doc,
clippy::match_wildcard_for_single_variants
)]
pub mod instructions;
pub mod prelude {
//! A collection of types you should definitely import when working with this crate.
pub use super::instructions::{
Address, Instruction, InstructionType, Interrupt, Register, args::*, errors::*,
};
}