calyx_utils/
id.rs

1// use serde::{Serialize, Serializer};
2
3pub type GSym = symbol_table::GlobalSymbol;
4
5/// Represents an identifier in a Calyx program
6#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug, PartialOrd, Ord)]
7#[cfg_attr(
8    feature = "serialize",
9    derive(serde::Deserialize),
10    serde(transparent)
11)]
12pub struct Id {
13    pub id: GSym,
14}
15
16impl Id {
17    pub fn new<S: ToString>(id: S) -> Self {
18        Self {
19            id: GSym::from(id.to_string()),
20        }
21    }
22}
23
24/* =================== Impls for Id to make them easier to use ============== */
25
26impl Default for Id {
27    fn default() -> Self {
28        Id::new("")
29    }
30}
31
32impl std::fmt::Display for Id {
33    fn fmt(
34        &self,
35        f: &mut std::fmt::Formatter<'_>,
36    ) -> Result<(), std::fmt::Error> {
37        write!(f, "{}", self.id)
38    }
39}
40
41impl AsRef<str> for Id {
42    fn as_ref(&self) -> &str {
43        self.id.as_str()
44    }
45}
46
47impl From<&str> for Id {
48    fn from(s: &str) -> Self {
49        Id::new(s)
50    }
51}
52
53impl From<String> for Id {
54    fn from(s: String) -> Self {
55        Id::new(s)
56    }
57}
58
59impl PartialEq<GSym> for Id {
60    fn eq(&self, other: &GSym) -> bool {
61        self.id == *other
62    }
63}
64impl PartialEq<str> for Id {
65    fn eq(&self, other: &str) -> bool {
66        self.id == GSym::from(other)
67    }
68}
69impl PartialEq<&str> for Id {
70    fn eq(&self, other: &&str) -> bool {
71        self.id == GSym::from(*other)
72    }
73}
74impl PartialEq<&Id> for Id {
75    fn eq(&self, other: &&Id) -> bool {
76        self.id == other.id
77    }
78}
79impl PartialEq<String> for Id {
80    fn eq(&self, other: &String) -> bool {
81        self.id == GSym::from(other)
82    }
83}
84
85impl From<Id> for GSym {
86    fn from(id: Id) -> Self {
87        id.id
88    }
89}
90
91impl From<&Id> for GSym {
92    fn from(id: &Id) -> Self {
93        id.id
94    }
95}
96
97#[cfg(feature = "serialize")]
98impl serde::Serialize for Id {
99    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
100    where
101        S: serde::Serializer,
102    {
103        self.id.serialize(serializer)
104    }
105}
106
107/// A trait representing something in the IR that has a name.
108pub trait GetName {
109    /// Return a reference to the object's name
110    fn name(&self) -> Id;
111}