cranelift_codegen/ir/
sourceloc.rs1use core::fmt;
7#[cfg(feature = "enable-serde")]
8use serde_derive::{Deserialize, Serialize};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
19pub struct SourceLoc(u32);
20
21impl SourceLoc {
22 pub fn new(bits: u32) -> Self {
24 Self(bits)
25 }
26
27 pub fn is_default(self) -> bool {
29 self == Default::default()
30 }
31
32 pub fn bits(self) -> u32 {
34 self.0
35 }
36}
37
38impl Default for SourceLoc {
39 fn default() -> Self {
40 Self(!0)
41 }
42}
43
44impl fmt::Display for SourceLoc {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 if self.is_default() {
47 write!(f, "@-")
48 } else {
49 write!(f, "@{:04x}", self.0)
50 }
51 }
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
57pub struct RelSourceLoc(u32);
58
59impl RelSourceLoc {
60 pub fn new(bits: u32) -> Self {
62 Self(bits)
63 }
64
65 pub fn from_base_offset(base: SourceLoc, offset: SourceLoc) -> Self {
67 if base.is_default() || offset.is_default() {
68 Self::default()
69 } else {
70 Self(offset.bits().wrapping_sub(base.bits()))
71 }
72 }
73
74 pub fn expand(&self, base: SourceLoc) -> SourceLoc {
76 if self.is_default() || base.is_default() {
77 Default::default()
78 } else {
79 SourceLoc::new(self.0.wrapping_add(base.bits()))
80 }
81 }
82
83 pub fn is_default(self) -> bool {
85 self == Default::default()
86 }
87}
88
89impl Default for RelSourceLoc {
90 fn default() -> Self {
91 Self(!0)
92 }
93}
94
95impl fmt::Display for RelSourceLoc {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 if self.is_default() {
98 write!(f, "@-")
99 } else {
100 write!(f, "@+{:04x}", self.0)
101 }
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use crate::ir::SourceLoc;
108 use alloc::string::ToString;
109
110 #[test]
111 fn display() {
112 assert_eq!(SourceLoc::default().to_string(), "@-");
113 assert_eq!(SourceLoc::new(0).to_string(), "@0000");
114 assert_eq!(SourceLoc::new(16).to_string(), "@0010");
115 assert_eq!(SourceLoc::new(0xabcdef).to_string(), "@abcdef");
116 }
117}