Skip to main content

melior/ir/
identifier.rs

1use crate::{
2    context::{Context, ContextRef},
3    string_ref::StringRef,
4};
5use mlir_sys::{
6    mlirIdentifierEqual, mlirIdentifierGet, mlirIdentifierGetContext, mlirIdentifierStr,
7    MlirIdentifier,
8};
9use std::marker::PhantomData;
10
11/// An identifier.
12#[derive(Clone, Copy, Debug)]
13pub struct Identifier<'c> {
14    raw: MlirIdentifier,
15    _context: PhantomData<&'c Context>,
16}
17
18impl<'c> Identifier<'c> {
19    /// Creates an identifier.
20    pub fn new(context: &'c Context, name: &str) -> Self {
21        unsafe {
22            Self::from_raw(mlirIdentifierGet(
23                context.to_raw(),
24                StringRef::new(name).to_raw(),
25            ))
26        }
27    }
28
29    /// Returns a context.
30    pub fn context(&self) -> ContextRef<'c> {
31        unsafe { ContextRef::from_raw(mlirIdentifierGetContext(self.raw)) }
32    }
33
34    /// Converts an identifier into a string reference.
35    pub fn as_string_ref(&self) -> StringRef {
36        unsafe { StringRef::from_raw(mlirIdentifierStr(self.raw)) }
37    }
38
39    /// Creates a location from a raw object.
40    ///
41    /// # Safety
42    ///
43    /// A raw object must be valid.
44    pub unsafe fn from_raw(raw: MlirIdentifier) -> Self {
45        Self {
46            raw,
47            _context: Default::default(),
48        }
49    }
50
51    /// Converts a location into a raw object.
52    pub const fn to_raw(self) -> MlirIdentifier {
53        self.raw
54    }
55}
56
57impl PartialEq for Identifier<'_> {
58    fn eq(&self, other: &Self) -> bool {
59        unsafe { mlirIdentifierEqual(self.raw, other.raw) }
60    }
61}
62
63impl Eq for Identifier<'_> {}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn new() {
71        Identifier::new(&Context::new(), "foo");
72    }
73
74    #[test]
75    fn context() {
76        Identifier::new(&Context::new(), "foo").context();
77    }
78
79    #[test]
80    fn equal() {
81        let context = Context::new();
82
83        assert_eq!(
84            Identifier::new(&context, "foo"),
85            Identifier::new(&context, "foo")
86        );
87    }
88
89    #[test]
90    fn not_equal() {
91        let context = Context::new();
92
93        assert_ne!(
94            Identifier::new(&context, "foo"),
95            Identifier::new(&context, "bar")
96        );
97    }
98}