use super::Lbl;
use std::collections::HashMap;
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],
fresh: HashMap<u32, asmkit::Label>,
}
impl<'a> LabelResolver<'a> {
pub fn new(labels: &'a [asmkit::Label]) -> Self {
Self {
labels,
fresh: HashMap::new(),
}
}
pub fn resolve(&mut self, l: Lbl, new_label: impl FnOnce() -> asmkit::Label) -> asmkit::Label {
match l {
Lbl::Bound(h) => self
.labels
.get(h.0 as usize)
.copied()
.unwrap_or_else(new_label),
Lbl::Fresh(i) => *self.fresh.entry(i).or_insert_with(new_label),
}
}
}