use core::fmt;
use crate::branch::Branch;
use crate::flags::FlagEffect;
use crate::tokens::TokenSink;
pub trait Decoded: fmt::Debug {
fn write_tokens_at(&self, address: u64, sink: &mut dyn TokenSink) -> fmt::Result;
fn length(&self) -> u8;
fn flags(&self) -> FlagEffect;
fn branch_at(&self, address: u64) -> Branch;
fn encoding_name(&self) -> &'static str;
fn unpredictable(&self) -> bool;
fn marked_text_at(&self, address: u64) -> Result<String, fmt::Error> {
let mut text = String::new();
self.write_tokens_at(address, &mut text)?;
if self.unpredictable() {
text.push_str(UNPREDICTABLE_MARK);
}
Ok(text)
}
}
pub const UNPREDICTABLE_MARK: &str = " (unpredictable)";
#[macro_export]
macro_rules! decoded {
($instruction:ty) => {
impl $crate::decode::Decoded for $instruction {
fn write_tokens_at(
&self,
address: u64,
sink: &mut dyn $crate::tokens::TokenSink,
) -> ::core::fmt::Result {
self.at(address).write_tokens(sink)
}
fn length(&self) -> u8 {
self.encoding().length()
}
fn flags(&self) -> $crate::flags::FlagEffect {
<$instruction>::flags(self)
}
fn branch_at(&self, address: u64) -> $crate::branch::Branch {
self.at(address).branch()
}
fn encoding_name(&self) -> &'static str {
self.encoding().name()
}
fn unpredictable(&self) -> bool {
<$instruction>::unpredictable(self)
}
}
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DecodeError {
UNDEF,
NOP,
Unallocated,
Unpredictable,
ReservedHint,
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UNDEF => f.write_str("UNDEFINED"),
Self::NOP => f.write_str("NOP"),
Self::Unallocated => f.write_str("UNALLOCATED"),
Self::Unpredictable => f.write_str("UNPREDICTABLE"),
Self::ReservedHint => f.write_str("reserved hint"),
}
}
}