1use smallvec::SmallVec;
10
11use crate::AsmError;
12
13use super::arch_traits::Arch;
14use super::inst::Inst;
15use super::operand::Label;
16
17#[derive(Clone, Copy, Debug)]
19pub enum Node {
20 Inst(Inst),
22 Label(Label),
24}
25
26pub trait InstSink {
28 fn arch(&self) -> Arch;
30
31 fn emit_inst(&mut self, inst: &Inst) -> Result<(), AsmError>;
33
34 fn bind_label(&mut self, label: Label) -> Result<(), AsmError>;
36}
37
38#[derive(Clone, Debug)]
40pub struct Builder {
41 arch: Arch,
42 nodes: SmallVec<[Node; 32]>,
43}
44
45impl Default for Builder {
46 fn default() -> Self {
47 Self::new()
48 }
49}
50
51impl Builder {
52 pub fn new() -> Self {
54 Self::for_arch(Arch::HOST)
55 }
56
57 pub fn for_arch(arch: Arch) -> Self {
59 Self {
60 arch,
61 nodes: SmallVec::new(),
62 }
63 }
64
65 pub const fn arch(&self) -> Arch {
67 self.arch
68 }
69
70 pub fn len(&self) -> usize {
72 self.nodes.len()
73 }
74
75 pub fn is_empty(&self) -> bool {
77 self.nodes.is_empty()
78 }
79
80 pub fn clear(&mut self) {
82 self.nodes.clear();
83 }
84
85 pub fn push_inst(&mut self, inst: Inst) -> Result<(), AsmError> {
87 if inst.arch() != self.arch {
88 return Err(AsmError::InvalidArch);
89 }
90 self.nodes.push(Node::Inst(inst));
91 Ok(())
92 }
93
94 pub fn push_label(&mut self, label: Label) {
96 self.nodes.push(Node::Label(label));
97 }
98
99 pub fn nodes(&self) -> &[Node] {
101 &self.nodes
102 }
103
104 pub fn replace_inst(&mut self, index: usize, inst: Inst) -> Result<(), AsmError> {
106 if inst.arch() != self.arch {
107 return Err(AsmError::InvalidArch);
108 }
109 let Some(node) = self.nodes.get_mut(index) else {
110 return Err(AsmError::InvalidArgument);
111 };
112 if !matches!(node, Node::Inst(_)) {
113 return Err(AsmError::InvalidState);
114 }
115 *node = Node::Inst(inst);
116 Ok(())
117 }
118
119 pub fn emit_into<S: InstSink + ?Sized>(&self, sink: &mut S) -> Result<(), AsmError> {
121 if sink.arch() != self.arch {
122 return Err(AsmError::InvalidArch);
123 }
124 for node in self.nodes.iter() {
125 match node {
126 Node::Inst(inst) => sink.emit_inst(inst)?,
127 Node::Label(label) => sink.bind_label(*label)?,
128 }
129 }
130 Ok(())
131 }
132}