near_vm_compiler/
sourceloc.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/2.3.0/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#[repr(transparent)]
18pub struct SourceLoc(u32);
19
20impl SourceLoc {
21    /// Create a new source location with the given bits.
22    pub fn new(bits: u32) -> Self {
23        Self(bits)
24    }
25
26    /// Is this the default source location?
27    pub fn is_default(self) -> bool {
28        self == Default::default()
29    }
30
31    /// Read the bits of this source location.
32    pub fn bits(self) -> u32 {
33        self.0
34    }
35}
36
37impl Default for SourceLoc {
38    fn default() -> Self {
39        Self(!0)
40    }
41}
42
43impl fmt::Display for SourceLoc {
44    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45        if self.is_default() {
46            write!(f, "0x-")
47        } else {
48            write!(f, "0x{:04x}", self.0)
49        }
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::SourceLoc;
56    use crate::lib::std::string::ToString;
57
58    #[test]
59    fn display() {
60        assert_eq!(SourceLoc::default().to_string(), "0x-");
61        assert_eq!(SourceLoc::new(0).to_string(), "0x0000");
62        assert_eq!(SourceLoc::new(16).to_string(), "0x0010");
63        assert_eq!(SourceLoc::new(0xabcdef).to_string(), "0xabcdef");
64    }
65}