Skip to main content

asmkit/core/
builder.rs

1//! Deferred instruction builder.
2//!
3//! A [`Builder`] records a sequence of nodes (instructions and label-bind points) so passes
4//! can inspect and mutate them: most importantly a future register-allocation pass: before
5//! machine code is produced. Replaying a builder into an [`InstSink`] (implemented by each
6//! architecture's `Assembler`) emits the exact same bytes as direct assembly: labels and
7//! relocations are recorded at emit time and resolved by `CodeBuffer::finish()` as usual.
8
9use smallvec::SmallVec;
10
11use crate::AsmError;
12
13use super::arch_traits::Arch;
14use super::inst::Inst;
15use super::operand::Label;
16
17/// A node recorded by a [`Builder`].
18#[derive(Clone, Copy, Debug)]
19pub enum Node {
20    /// An instruction with its operands.
21    Inst(Inst),
22    /// Binds a label at this position when replayed.
23    Label(Label),
24}
25
26/// Sink that consumes replayed nodes: implemented by each architecture's `Assembler`.
27pub trait InstSink {
28    /// Target architecture accepted by this sink.
29    fn arch(&self) -> Arch;
30
31    /// Emits one recorded instruction.
32    fn emit_inst(&mut self, inst: &Inst) -> Result<(), AsmError>;
33
34    /// Binds a label at the current position.
35    fn bind_label(&mut self, label: Label) -> Result<(), AsmError>;
36}
37
38/// Records instructions and label-bind points for deferred emission.
39#[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    /// Creates an empty builder.
53    pub fn new() -> Self {
54        Self::for_arch(Arch::HOST)
55    }
56
57    /// Creates a builder that accepts instructions for `arch` only.
58    pub fn for_arch(arch: Arch) -> Self {
59        Self {
60            arch,
61            nodes: SmallVec::new(),
62        }
63    }
64
65    /// Architecture accepted by this builder.
66    pub const fn arch(&self) -> Arch {
67        self.arch
68    }
69
70    /// Returns the number of recorded nodes.
71    pub fn len(&self) -> usize {
72        self.nodes.len()
73    }
74
75    /// Tests whether the builder is empty.
76    pub fn is_empty(&self) -> bool {
77        self.nodes.is_empty()
78    }
79
80    /// Removes all recorded nodes.
81    pub fn clear(&mut self) {
82        self.nodes.clear();
83    }
84
85    /// Records an instruction.
86    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    /// Records a label-bind point.
95    pub fn push_label(&mut self, label: Label) {
96        self.nodes.push(Node::Label(label));
97    }
98
99    /// Returns the recorded nodes.
100    pub fn nodes(&self) -> &[Node] {
101        &self.nodes
102    }
103
104    /// Replaces an instruction node after checking that it belongs to this builder.
105    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    /// Replays all recorded nodes into `sink`, in order.
120    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}