unc_vm_compiler/
sourceloc.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/master/ATTRIBUTIONS.md
3
4//! Source locations.
5//!
6//! A [`SourceLoc`] determines the position of a certain instruction
7//! relative to the WebAssembly module. This is used mainly for debugging
8//! and tracing errors.
9
10use crate::lib::std::fmt;
11
12/// A source location.
13///
14/// The default source location uses the all-ones bit pattern `!0`. It is used for instructions
15/// that can't be given a real source location.
16#[derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive, Debug, Clone, Copy, PartialEq, Eq)]
17#[archive(as = "Self")]
18#[repr(transparent)]
19pub struct SourceLoc(u32);
20
21impl SourceLoc {
22    /// Create a new source location with the given bits.
23    pub fn new(bits: u32) -> Self {
24        Self(bits)
25    }
26
27    /// Is this the default source location?
28    pub fn is_default(self) -> bool {
29        self == Default::default()
30    }
31
32    /// Read the bits of this source location.
33    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, "0x-")
48        } else {
49            write!(f, "0x{:04x}", self.0)
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::SourceLoc;
57    use crate::lib::std::string::ToString;
58
59    #[test]
60    fn display() {
61        assert_eq!(SourceLoc::default().to_string(), "0x-");
62        assert_eq!(SourceLoc::new(0).to_string(), "0x0000");
63        assert_eq!(SourceLoc::new(16).to_string(), "0x0010");
64        assert_eq!(SourceLoc::new(0xabcdef).to_string(), "0xabcdef");
65    }
66}