chore: dedup u8/u16 byte/word immediate type

This commit is contained in:
2025-05-13 12:44:00 +09:00
parent 27b39ee94a
commit 4443f84297
3 changed files with 97 additions and 124 deletions

View File

@@ -1,10 +1,24 @@
use core::fmt;
// b: 8, w: 16, v: 16 -> i just treat v and w the same, if nothing blows up
#[allow(non_camel_case_types)]
pub type b = u8;
#[allow(non_camel_case_types)]
pub type w = u16;
pub type ImmediateByte = u8;
pub type ImmediateWord = u16;
#[derive(Debug, Clone)]
#[allow(dead_code)]
/// Can be used to encode either byte or word operands
pub enum ImmediateOperand {
Byte(ImmediateByte),
Word(ImmediateWord),
}
impl fmt::Display for ImmediateOperand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Byte(byte) => write!(f, "{}", byte),
Self::Word(word) => write!(f, "{}", word),
}
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
@@ -204,9 +218,9 @@ pub type RegisterId = u8;
#[allow(dead_code)]
impl Register {
/// Find the register corresponding to the 8086 bytecode ID
pub fn by_id(id: OperandWidth) -> Self {
pub fn by_id(id: ImmediateOperand) -> Self {
match id {
OperandWidth::Byte(b) => match b {
ImmediateOperand::Byte(b) => match b {
0b000 => Self::AL,
0b001 => Self::CL,
0b010 => Self::DL,
@@ -217,7 +231,7 @@ impl Register {
0b111 => Self::BH,
_ => panic!("Invalid 8bit register ID encountered"),
},
OperandWidth::Word(w) => match w {
ImmediateOperand::Word(w) => match w {
0b000 => Self::AX,
0b001 => Self::CX,
0b010 => Self::DX,
@@ -290,33 +304,6 @@ impl fmt::Display for SegmentRegister {
}
}
/// An immediate byte value for an instruction.
#[derive(Debug, Clone)]
pub struct ImmediateByte(pub b);
/// An immediate word value for an instruction
#[derive(Debug, Clone)]
pub struct ImmediateWord(pub w);
macro_rules! impl_display_and_lowerhex {
($name:ident) => {
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::fmt::LowerHex for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::LowerHex::fmt(&self.0, f)
}
}
};
}
impl_display_and_lowerhex!(ImmediateByte);
impl_display_and_lowerhex!(ImmediateWord);
#[derive(Debug, Clone)]
/// ModRM byte can either target a memory location or some register
pub enum ModRmTarget {
@@ -339,7 +326,7 @@ impl std::fmt::Display for ModRmTarget {
pub struct MemoryIndex {
pub base: Option<Register>,
pub index: Option<Register>,
pub displacement: Option<OperandWidth>,
pub displacement: Option<ImmediateOperand>,
}
impl fmt::Display for MemoryIndex {
@@ -365,20 +352,3 @@ impl fmt::Display for MemoryIndex {
}
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
/// Can be used to encode either byte or word operands
pub enum OperandWidth {
Byte(u8),
Word(u16),
}
impl fmt::Display for OperandWidth {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Byte(byte) => write!(f, "{}", byte),
Self::Word(word) => write!(f, "{}", word),
}
}
}