use super::Lbl;
use crate::ir::Label;
use smallvec::SmallVec;
pub use offlineasm_ir::ExpandError as LowerError;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PatchHandle {
Jump(asmkit::PatchableJump),
Data(asmkit::DataLabel),
Virtual(u32),
}
impl PatchHandle {
pub fn jump(self) -> Option<asmkit::PatchableJump> {
match self {
PatchHandle::Jump(j) => Some(j),
_ => None,
}
}
pub fn data(self) -> Option<asmkit::DataLabel> {
match self {
PatchHandle::Data(d) => Some(d),
_ => None,
}
}
#[allow(clippy::panic)]
pub fn expect_jump(self) -> asmkit::PatchableJump {
match self {
PatchHandle::Jump(j) => j,
PatchHandle::Virtual(_) => panic!(
"onlineasm: backward patch handle is unresolved; use `Finished::location` after `finish`"
),
PatchHandle::Data(_) => panic!("onlineasm: patch handle is an immediate, not a jump"),
}
}
#[allow(clippy::panic)]
pub fn expect_data(self) -> asmkit::DataLabel {
match self {
PatchHandle::Data(d) => d,
PatchHandle::Virtual(_) => panic!(
"onlineasm: backward patch handle is unresolved; use `Finished::location` after `finish`"
),
PatchHandle::Jump(_) => panic!("onlineasm: patch handle is a jump, not an immediate"),
}
}
}
pub struct LabelResolver<'a> {
labels: &'a [asmkit::Label],
base: u32,
fresh: SmallVec<[(u32, asmkit::Label); 2]>,
}
impl<'a> LabelResolver<'a> {
pub fn new(labels: &'a [asmkit::Label], base: u32) -> Self {
Self {
labels,
base,
fresh: SmallVec::new(),
}
}
pub fn resolve(&mut self, l: Lbl, new_label: impl FnOnce() -> asmkit::Label) -> asmkit::Label {
match l {
Lbl::Bound(h) => {
h.0.checked_sub(self.base)
.and_then(|i| self.labels.get(i as usize))
.copied()
.unwrap_or_else(new_label)
}
Lbl::Fresh(i) => {
if let Some(pos) = self.fresh.iter().position(|&(id, _)| id == i) {
return self.fresh[pos].1;
}
let label = new_label();
self.fresh.push((i, label));
label
}
}
}
pub fn get(&self, l: Label) -> Option<asmkit::Label> {
l.0.checked_sub(self.base)
.and_then(|i| self.labels.get(i as usize))
.copied()
}
}