Skip to content

Commit

Permalink
feat: add to_ref and Deref functions for the context (#579)
Browse files Browse the repository at this point in the history
I am one of the users of Melbourne and have found that ContextRef does
not have a publicly available method to convert to `&'c Context`, so
I've opened this PR to add the `to_ref` function for the context like
the `OperationRef` does at
https://github.com/raviqqe/melior/blob/main/melior/src/ir/operation.rs

Signed-off-by: peefy <[email protected]>
  • Loading branch information
Peefy authored Aug 25, 2024
1 parent 91a2270 commit 3214475
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 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};

/// A context of IR, dialects, and passes.
///
Expand Down Expand Up @@ -166,6 +166,22 @@ 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> PartialEq for ContextRef<'c> {
Expand Down Expand Up @@ -299,4 +315,13 @@ 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_to_ref: &Context = unsafe { &ctx_ref.to_ref() };

assert_eq!(&ctx_ref, ctx_ref_to_ref);
}
}

0 comments on commit 3214475

Please sign in to comment.