use crate::{
isa::insn_len,
relocate::{self, Branch, Destination, Node, RelocateError},
Mode, Target,
};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AsmError {
DuplicateLabel(String),
UndefinedLabel(String),
InvalidCondition,
InvalidInstruction,
Layout(RelocateError),
}
pub struct Asm {
target: Target,
mode: Mode,
nodes: Vec<Node>,
labels: BTreeMap<String, usize>,
references: Vec<(usize, String)>,
}
impl Asm {
pub fn new(target: Target, mode: Mode) -> Result<Self, AsmError> {
if !target.supports(mode) {
return Err(AsmError::Layout(RelocateError::UnsupportedMode));
}
Ok(Self {
target,
mode,
nodes: Vec::new(),
labels: BTreeMap::new(),
references: Vec::new(),
})
}
pub fn label(&mut self, name: &str) -> Result<(), AsmError> {
if self.labels.contains_key(name) {
return Err(AsmError::DuplicateLabel(name.into()));
}
self.labels.insert(name.into(), self.nodes.len());
Ok(())
}
pub fn instruction(&mut self, bytes: &[u8]) -> Result<(), AsmError> {
if insn_len(bytes, self.target, self.mode) != Some(bytes.len()) {
return Err(AsmError::InvalidInstruction);
}
if !matches!(relocate::classify(bytes, self.target, 0), Ok(None)) {
return Err(AsmError::InvalidInstruction);
}
self.nodes.push(Node {
bytes: bytes.to_vec(),
branch: None,
});
Ok(())
}
pub fn branch(&mut self, condition: u8, label: &str) -> Result<(), AsmError> {
if condition > 15 {
return Err(AsmError::InvalidCondition);
}
self.reference(Branch::Conditional(condition), label);
Ok(())
}
pub fn call(&mut self, label: &str) {
self.reference(Branch::Subroutine, label);
}
fn reference(&mut self, branch: Branch, label: &str) {
self.references.push((self.nodes.len(), label.into()));
self.nodes.push(Node {
bytes: vec![0, 0],
branch: Some((branch, Destination::Node(0))),
});
}
pub fn finish(mut self, origin: u32) -> Result<Vec<u8>, AsmError> {
for (index, label) in self.references {
let destination = *self
.labels
.get(&label)
.ok_or(AsmError::UndefinedLabel(label))?;
self.nodes[index].branch.as_mut().unwrap().1 = Destination::Node(destination);
}
relocate::layout(self.nodes, origin, self.target, self.mode)
.map(|(bytes, _)| bytes)
.map_err(AsmError::Layout)
}
}