use super::ir::{Label, Lbl, Mnemonic, Op};
use super::lower::PatchHandle;
pub(super) enum TapeItem {
Emit { mnemonic: Mnemonic, ops: Vec<Op> },
EmitPatched { mnemonic: Mnemonic, ops: Vec<Op> },
Bind(Label),
Align(u32),
Embed { data: Box<[u8]>, label: Label },
}
pub(super) struct ReverseTape {
items: Vec<TapeItem>,
next_virtual: u32,
next_patch: u32,
}
impl ReverseTape {
pub(super) fn new() -> Self {
Self {
items: Vec::new(),
next_virtual: 0,
next_patch: 0,
}
}
pub(super) fn push_emit(&mut self, mnemonic: Mnemonic, ops: &[Op]) {
self.items.push(TapeItem::Emit {
mnemonic,
ops: ops.to_vec(),
});
}
pub(super) fn push_emit_patched(&mut self, mnemonic: Mnemonic, ops: &[Op]) -> PatchHandle {
let id = self.next_patch;
self.next_patch += 1;
self.items.push(TapeItem::EmitPatched {
mnemonic,
ops: ops.to_vec(),
});
PatchHandle::Virtual(id)
}
pub(super) fn push_bind(&mut self, label: Label) {
self.check_virtual(label);
self.items.push(TapeItem::Bind(label));
}
pub(super) fn push_align(&mut self, alignment: u32) {
self.items.push(TapeItem::Align(alignment));
}
pub(super) fn push_embed(&mut self, data: &[u8]) -> Label {
let label = self.next_virtual();
self.items.push(TapeItem::Embed {
data: data.into(),
label,
});
label
}
pub(super) fn next_virtual(&mut self) -> Label {
let id = self.next_virtual;
self.next_virtual += 1;
Label(id)
}
pub(super) fn is_virtual(&self, label: Label) -> bool {
label.0 < self.next_virtual
}
pub(super) fn virtual_count(&self) -> u32 {
self.next_virtual
}
pub(super) fn patch_count(&self) -> u32 {
self.next_patch
}
pub(super) fn take(&mut self) -> Vec<TapeItem> {
std::mem::take(&mut self.items)
}
#[allow(clippy::panic)]
fn check_virtual(&self, label: Label) {
if !self.is_virtual(label) {
panic!("onlineasm: label handle does not belong to this assembler");
}
}
}
#[allow(clippy::panic)]
pub(super) fn remap_label(v: Label, real: &[Label]) -> Label {
match real.get(v.0 as usize) {
Some(&r) => r,
None => panic!("onlineasm: label handle does not belong to this assembler"),
}
}
pub(super) fn remap_op(op: Op, real: &[Label]) -> Op {
match op {
Op::Label(Lbl::Bound(v)) => Op::Label(Lbl::Bound(remap_label(v, real))),
other => other,
}
}
pub(super) fn remap_ops(ops: &[Op], real: &[Label]) -> Vec<Op> {
ops.iter().map(|op| remap_op(*op, real)).collect()
}