use core::fmt;
#[cfg(feature = "enable-serde")]
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct SourceLoc(u32);
impl SourceLoc {
pub fn new(bits: u32) -> Self {
Self(bits)
}
pub fn is_default(self) -> bool {
self == Default::default()
}
pub fn bits(self) -> u32 {
self.0
}
}
impl Default for SourceLoc {
fn default() -> Self {
Self(0x7fff_ffff)
}
}
impl fmt::Display for SourceLoc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_default() {
write!(f, "@-")
} else {
write!(f, "@{:04x}", self.0)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct RelSourceLoc(u32);
impl RelSourceLoc {
pub fn new(bits: u32) -> Self {
Self(bits)
}
pub fn from_base_offset(base: SourceLoc, offset: SourceLoc) -> Self {
if base.is_default() || offset.is_default() {
Self::default()
} else {
Self(offset.bits().wrapping_sub(base.bits()) & MaybeRelSourceLoc::MASK)
}
}
pub fn expand(&self, base: SourceLoc) -> SourceLoc {
if self.is_default() || base.is_default() {
Default::default()
} else {
SourceLoc::new(self.0.wrapping_add(base.bits()) & MaybeRelSourceLoc::MASK)
}
}
pub fn is_default(self) -> bool {
self == Default::default()
}
}
impl Default for RelSourceLoc {
fn default() -> Self {
Self(0x7fff_ffff)
}
}
impl fmt::Display for RelSourceLoc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_default() {
write!(f, "@-")
} else {
write!(f, "@+{:04x}", self.0)
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "enable-serde",
derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
pub struct MaybeRelSourceLoc(u32);
impl MaybeRelSourceLoc {
const REL_BIT: u32 = 0x8000_0000;
const MASK: u32 = !Self::REL_BIT;
pub fn rel(loc: RelSourceLoc) -> Self {
debug_assert!(loc.0 & Self::MASK == loc.0);
MaybeRelSourceLoc(loc.0 | Self::REL_BIT)
}
pub fn abs(loc: SourceLoc) -> Self {
debug_assert!(loc.0 & Self::MASK == loc.0);
MaybeRelSourceLoc(loc.0)
}
pub fn is_rel(&self) -> bool {
self.0 & Self::REL_BIT != 0
}
pub fn is_abs(&self) -> bool {
self.0 & Self::REL_BIT == 0
}
pub fn as_rel(&self) -> RelSourceLoc {
assert!(self.is_rel());
RelSourceLoc(self.0 & Self::MASK)
}
pub fn as_abs(&self) -> SourceLoc {
assert!(self.is_abs());
SourceLoc(self.0)
}
pub fn relocate(&self, base: SourceLoc) -> SourceLoc {
self.as_rel().expand(base)
}
}
#[cfg(test)]
mod tests {
use crate::ir::SourceLoc;
use alloc::string::ToString;
#[test]
fn display() {
assert_eq!(SourceLoc::default().to_string(), "@-");
assert_eq!(SourceLoc::new(0).to_string(), "@0000");
assert_eq!(SourceLoc::new(16).to_string(), "@0010");
assert_eq!(SourceLoc::new(0xabcdef).to_string(), "@abcdef");
}
}