Skip to content

Commit

Permalink
feat: add to_ref and Deref functions for the context
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy committed Aug 24, 2024
1 parent d534c52 commit d1da321
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion melior/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use mlir_sys::{
mlirContextIsRegisteredOperation, mlirContextLoadAllAvailableDialects,
mlirContextSetAllowUnregisteredDialects, MlirContext, MlirDiagnostic, MlirLogicalResult,
};
use std::{ffi::c_void, marker::PhantomData};
use std::{ffi::c_void, marker::PhantomData, mem::transmute, ops::Deref};

/// A context of IR, dialects, and passes.
///
Expand Down Expand Up @@ -166,6 +166,30 @@ impl<'c> ContextRef<'c> {
_reference: Default::default(),
}
}

/// Returns a context.
///
/// This function is different from `deref` because the correct lifetime is
/// kept for the return type.
///
/// # Safety
///
/// The returned reference is safe to use only in the lifetime scope of the
/// context reference.
pub unsafe fn to_ref(&self) -> &'c Context {
// As we can't deref ContextRef<'a> into `&'a Context`, we forcibly cast its
// lifetime here to extend it from the lifetime of `ObjectRef<'a>` itself into
// `'a`.
transmute(self)
}
}

impl<'c> Deref for ContextRef<'c> {
type Target = Context;

fn deref(&self) -> &Self::Target {
unsafe { transmute(self) }
}
}

impl<'c> PartialEq for ContextRef<'c> {
Expand Down Expand Up @@ -299,4 +323,16 @@ mod tests {
assert_ne!(&other, &one_ref);
assert_ne!(&one_ref, &other);
}

#[test]
fn context_to_ref() {
let ctx = Context::new();
let ctx_ref = ctx.to_ref();
let ctx_ref_deref: &Context = &ctx_ref;
let ctx_ref_to_ref: &Context = unsafe { &ctx_ref.to_ref() };

assert_eq!(ctx_ref_deref, ctx_ref_to_ref);
assert_eq!(&ctx_ref, ctx_ref_deref);
assert_eq!(&ctx_ref, ctx_ref_to_ref);
}
}

0 comments on commit d1da321

Please sign in to comment.