holey-bytes/hbasm/src/macros/text.rs

269 lines
10 KiB
Rust
Raw Normal View History

2023-07-21 19:26:03 -05:00
//! Macros to generate text-code assembler at [`crate::text`]
// Refering in module which generates a module to that module — is that even legal? :D
/// Generate text code based assembler
2023-07-11 19:16:23 -05:00
macro_rules! gen_text {
(
$(
$ityn:ident
($($param_i:ident: $param_ty:ident),* $(,)?)
=> [$($opcode:ident),* $(,)?],
)*
) => {
2023-07-21 19:26:03 -05:00
/// Text code based assembler
2023-07-11 19:16:23 -05:00
pub mod text {
use {
crate::{
Assembler,
macros::text::*,
},
hashbrown::HashMap,
lasso::{Key, Rodeo, Spur},
logos::{Lexer, Logos, Span},
};
paste::paste!(literify::literify! {
2023-07-21 19:26:03 -05:00
/// Assembly token
2023-07-11 19:16:23 -05:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, Logos)]
#[logos(extras = Rodeo)]
#[logos(skip r"[ \t\t]+")]
#[logos(skip r"-- .*")]
pub enum Token {
$($(#[token(~([<$opcode:lower>]), |_| hbbytecode::opcode::[<$opcode:upper>])])*)*
2023-07-11 19:23:47 -05:00
#[token("brc", |_| hbbytecode::opcode::BRC)] // Special-cased
2023-07-11 19:16:23 -05:00
Opcode(u8),
#[regex("[0-9]+", |l| l.slice().parse().ok())]
#[regex(
"-[0-9]+",
|lexer| {
Some(u64::from_ne_bytes(lexer.slice().parse::<i64>().ok()?.to_ne_bytes()))
},
)] Integer(u64),
#[regex(
"r[0-9]+",
|lexer| match lexer.slice()[1..].parse() {
Ok(n) => Some(n),
_ => None
},
)] Register(u8),
#[regex(
r"\p{XID_Start}\p{XID_Continue}*:",
|lexer| lexer.extras.get_or_intern(&lexer.slice()[..lexer.slice().len() - 1]),
)] Label(Spur),
#[regex(
r"\p{XID_Start}\p{XID_Continue}*",
|lexer| lexer.extras.get_or_intern(lexer.slice()),
)] Symbol(Spur),
#[token("\n")]
#[token(";")] ISep,
#[token(",")] PSep,
}
});
2023-07-21 19:26:03 -05:00
/// Type of error
2023-07-11 19:16:23 -05:00
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
UnexpectedToken,
InvalidToken,
UnexpectedEnd,
InvalidSymbol,
}
2023-07-21 19:26:03 -05:00
/// Text assembly error
2023-07-11 19:16:23 -05:00
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
pub kind: ErrorKind,
pub span: Span,
}
2023-07-21 19:26:03 -05:00
/// Parse code and insert instructions
2023-07-11 19:16:23 -05:00
pub fn assemble(asm: &mut Assembler, code: &str) -> Result<(), Error> {
pub struct TextAsm<'a> {
asm: &'a mut Assembler,
lexer: Lexer<'a, Token>,
symloc: HashMap<Spur, usize>,
}
impl<'a> TextAsm<'a> {
fn next(&mut self) -> Result<Token, ErrorKind> {
match self.lexer.next() {
Some(Ok(t)) => Ok(t),
Some(Err(())) => Err(ErrorKind::InvalidToken),
None => Err(ErrorKind::UnexpectedEnd),
}
}
#[inline(always)]
fn run(&mut self) -> Result<(), ErrorKind> {
loop {
match self.lexer.next() {
2023-07-21 19:26:03 -05:00
// Got an opcode
2023-07-11 19:16:23 -05:00
Some(Ok(Token::Opcode(op))) => {
match op {
2023-07-21 19:26:03 -05:00
// Take all the opcodes and match them to their corresponding functions
2023-07-11 19:16:23 -05:00
$(
$(hbbytecode::opcode::$opcode)|* => paste::paste!({
param_extract_itm!(self, $($param_i: $param_ty),*);
self.asm.[<i_param_ $ityn>](op, $($param_i),*);
}),
)*
2023-07-11 19:23:47 -05:00
// Special-cased
hbbytecode::opcode::BRC => {
param_extract_itm!(
self,
p0: R,
p1: R,
p2: u8
);
self.asm.i_param_bbb(op, p0, p1, p2);
}
2023-07-21 19:26:03 -05:00
// Already matched in Logos, should not be able to obtain
// invalid opcode.
2023-07-11 19:16:23 -05:00
_ => unreachable!(),
}
}
2023-07-21 19:26:03 -05:00
// Insert label to table
2023-07-11 19:16:23 -05:00
Some(Ok(Token::Label(lbl))) => {
self.symloc.insert(lbl, self.asm.buf.len());
}
2023-07-21 19:26:03 -05:00
// Instruction separator (LF, ;)
2023-07-11 19:16:23 -05:00
Some(Ok(Token::ISep)) => (),
Some(Ok(_)) => return Err(ErrorKind::UnexpectedToken),
Some(Err(())) => return Err(ErrorKind::InvalidToken),
None => return Ok(()),
}
}
}
}
let mut asm = TextAsm {
asm,
lexer: Token::lexer(code),
symloc: HashMap::default(),
};
asm.run()
.map_err(|kind| Error { kind, span: asm.lexer.span() })?;
2023-07-11 19:23:47 -05:00
2023-07-21 19:26:03 -05:00
// Walk table and substitute labels
// for their addresses
2023-07-11 19:16:23 -05:00
for &loc in &asm.asm.sub {
2023-07-21 19:26:03 -05:00
// Extract indices from the code and get addresses from table
2023-07-11 19:16:23 -05:00
let val = asm.symloc
.get(
2023-07-21 19:26:03 -05:00
&Spur::try_from_usize(bytemuck::pod_read_unaligned::<u64>(
&asm.asm.buf[loc..loc + core::mem::size_of::<u64>()]) as _
).unwrap()
2023-07-11 19:16:23 -05:00
)
.ok_or(Error { kind: ErrorKind::InvalidSymbol, span: 0..0 })?
.to_le_bytes();
2023-07-21 19:26:03 -05:00
// New address
2023-07-11 19:16:23 -05:00
asm.asm.buf[loc..]
.iter_mut()
.zip(val)
.for_each(|(dst, src)| *dst = src);
}
Ok(())
}
2023-07-21 19:26:03 -05:00
// Fun fact: this is a little hack
// It may slow the things a little bit down, but
// it made the macro to be made pretty nice.
//
// If you have any idea how to get rid of this,
// contributions are welcome :)
// I *likely* won't try anymore.
2023-07-11 19:16:23 -05:00
enum InternalImm {
Const(u64),
Named(Spur),
}
impl $crate::Imm for InternalImm {
#[inline]
fn insert(&self, asm: &mut Assembler) {
match self {
2023-07-21 19:26:03 -05:00
// Constant immediate, just put it in
2023-07-11 19:16:23 -05:00
Self::Const(a) => a.insert(asm),
2023-07-21 19:26:03 -05:00
// Label
2023-07-11 19:16:23 -05:00
Self::Named(a) => {
2023-07-21 19:26:03 -05:00
// Insert to the sub table that substitution will be
// requested
2023-07-11 19:16:23 -05:00
asm.sub.insert(asm.buf.len());
2023-07-21 19:26:03 -05:00
// Insert value from interner in place
2023-07-11 19:16:23 -05:00
asm.buf.extend((a.into_usize() as u64).to_le_bytes());
},
}
}
}
}
};
}
2023-07-21 19:26:03 -05:00
/// Extract item by pattern, otherwise return [`ErrorKind::UnexpectedToken`]
2023-07-11 19:16:23 -05:00
macro_rules! extract_pat {
($self:expr, $pat:pat) => {
let $pat = $self.next()?
2023-07-21 19:26:03 -05:00
else { return Err(ErrorKind::UnexpectedToken) };
2023-07-11 19:16:23 -05:00
};
}
2023-07-24 11:48:42 -05:00
/// Generate extract macro
macro_rules! gen_extract {
// Integer types have same body
($($int:ident),* $(,)?) => {
/// Extract operand from code
macro_rules! extract {
// Register (require prefixing with r)
($self:expr, R, $id:ident) => {
extract_pat!($self, Token::Register($id));
};
2023-07-11 19:16:23 -05:00
2023-07-24 11:48:42 -05:00
// Immediate
($self:expr, I, $id:ident) => {
let $id = match $self.next()? {
// Either straight up integer
Token::Integer(a) => InternalImm::Const(a),
// …or a label
Token::Symbol(a) => InternalImm::Named(a),
_ => return Err(ErrorKind::UnexpectedToken),
};
};
2023-07-11 19:23:47 -05:00
2023-07-24 11:48:42 -05:00
// Get $int, if not fitting, the token is claimed invalid
$(($self:expr, $int, $id:ident) => {
extract_pat!($self, Token::Integer($id));
let $id = $int::try_from($id).map_err(|_| ErrorKind::InvalidToken)?;
});*;
}
2023-07-11 19:16:23 -05:00
};
}
2023-07-24 11:48:42 -05:00
gen_extract!(u8, u16, u32);
2023-07-21 19:26:03 -05:00
/// Parameter extract incremental token-tree muncher
///
/// What else would it mean?
2023-07-11 19:16:23 -05:00
macro_rules! param_extract_itm {
($self:expr, $($id:ident: $ty:ident)? $(, $($tt:tt)*)?) => {
2023-07-21 19:26:03 -05:00
// Extract pattern
2023-07-11 19:16:23 -05:00
$(extract!($self, $ty, $id);)?
$(
2023-07-21 19:26:03 -05:00
// Require operand separator
2023-07-11 19:16:23 -05:00
extract_pat!($self, Token::PSep);
2023-07-21 19:26:03 -05:00
// And go to the next (recursive)
// …munch munch… yummy token trees.
2023-07-11 19:16:23 -05:00
param_extract_itm!($self, $($tt)*);
)?
};
}
pub(crate) use {extract, extract_pat, gen_text, param_extract_itm};