Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add to_ref and Deref functions for the context #579

Merged
merged 2 commits into from
Aug 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}