use core::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TokenKind {
Mnemonic,
Text,
Separator,
Bracket,
Register,
Symbol,
Immediate(i64),
Integer(u64),
Float,
Address(u64),
}
pub type OperandIndex = Option<u8>;
pub trait TokenSink {
fn text(&mut self, kind: TokenKind, operand: OperandIndex, text: &str) -> fmt::Result;
fn value(
&mut self,
kind: TokenKind,
operand: OperandIndex,
value: &dyn fmt::Display,
) -> fmt::Result;
}
impl TokenSink for fmt::Formatter<'_> {
#[inline]
fn text(&mut self, _kind: TokenKind, _operand: OperandIndex, text: &str) -> fmt::Result {
self.write_str(text)
}
#[inline]
fn value(
&mut self,
_kind: TokenKind,
_operand: OperandIndex,
value: &dyn fmt::Display,
) -> fmt::Result {
value.fmt(self)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Token {
pub kind: TokenKind,
pub operand: OperandIndex,
pub text: String,
}
impl TokenSink for Vec<Token> {
fn text(&mut self, kind: TokenKind, operand: OperandIndex, text: &str) -> fmt::Result {
self.push(Token {
kind,
operand,
text: text.to_string(),
});
Ok(())
}
fn value(
&mut self,
kind: TokenKind,
operand: OperandIndex,
value: &dyn fmt::Display,
) -> fmt::Result {
self.push(Token {
kind,
operand,
text: value.to_string(),
});
Ok(())
}
}
impl TokenSink for String {
fn text(&mut self, _kind: TokenKind, _operand: OperandIndex, text: &str) -> fmt::Result {
self.push_str(text);
Ok(())
}
fn value(
&mut self,
_kind: TokenKind,
_operand: OperandIndex,
value: &dyn fmt::Display,
) -> fmt::Result {
use fmt::Write;
write!(self, "{value}")
}
}
pub struct Hex<T>(pub T);
impl<T: fmt::LowerHex> fmt::Display for Hex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0x{:x}", self.0)
}
}