use smallvec::SmallVec;
use crate::AsmError;
use super::arch_traits::Arch;
use super::inst::Inst;
use super::operand::Label;
#[derive(Clone, Copy, Debug)]
pub enum Node {
Inst(Inst),
Label(Label),
}
pub trait InstSink {
fn arch(&self) -> Arch;
fn emit_inst(&mut self, inst: &Inst) -> Result<(), AsmError>;
fn bind_label(&mut self, label: Label) -> Result<(), AsmError>;
}
#[derive(Clone, Debug)]
pub struct Builder {
arch: Arch,
nodes: SmallVec<[Node; 32]>,
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}
impl Builder {
pub fn new() -> Self {
Self::for_arch(Arch::HOST)
}
pub fn for_arch(arch: Arch) -> Self {
Self {
arch,
nodes: SmallVec::new(),
}
}
pub const fn arch(&self) -> Arch {
self.arch
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn clear(&mut self) {
self.nodes.clear();
}
pub fn push_inst(&mut self, inst: Inst) -> Result<(), AsmError> {
if inst.arch() != self.arch {
return Err(AsmError::InvalidArch);
}
self.nodes.push(Node::Inst(inst));
Ok(())
}
pub fn push_label(&mut self, label: Label) {
self.nodes.push(Node::Label(label));
}
pub fn nodes(&self) -> &[Node] {
&self.nodes
}
pub fn replace_inst(&mut self, index: usize, inst: Inst) -> Result<(), AsmError> {
if inst.arch() != self.arch {
return Err(AsmError::InvalidArch);
}
let Some(node) = self.nodes.get_mut(index) else {
return Err(AsmError::InvalidArgument);
};
if !matches!(node, Node::Inst(_)) {
return Err(AsmError::InvalidState);
}
*node = Node::Inst(inst);
Ok(())
}
pub fn emit_into<S: InstSink + ?Sized>(&self, sink: &mut S) -> Result<(), AsmError> {
if sink.arch() != self.arch {
return Err(AsmError::InvalidArch);
}
for node in self.nodes.iter() {
match node {
Node::Inst(inst) => sink.emit_inst(inst)?,
Node::Label(label) => sink.bind_label(*label)?,
}
}
Ok(())
}
}