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

Add support for opaque structs (allowing recursive types to be defined) #17

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
24 changes: 23 additions & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ impl StructType {
ty.into()
})
}
/// Make a new named struct without defining its fields yet.
///
/// You can use this opaque struct without defining its fields (for creating recursive types, etc.). When you want to define its fields (which may include itself), use set_elements().
pub fn new_opaque<'a>(context: &'a Context, name: &str) -> &'a StructType {
util::with_cstr(name, |name| unsafe {
core::LLVMStructCreateNamed(context.into(), name).into()
})
}
/// Set the elements that make up this struct.
///
/// Can only be called once, and only on a StructType created through the new_opaque() function.
/// Returns Err(()) if the struct is not opaque.
pub fn set_elements<'a>(&self, fields: &[&'a Type], packed: bool) -> Result<(), ()> {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about returning a Result<(), ()>, but I'm not sure what the rust convention is when an operation has no return value regardless of whether it succeeds or fails.

And returning a bool seems wrong.

unsafe {
if core::LLVMIsOpaqueStruct(self.into()) != 0 {
core::LLVMStructSetBody(self.into(), fields.as_ptr() as *mut LLVMTypeRef, fields.len() as c_uint, packed as c_int);
Ok(())
} else {
Err(())
}
}
}
/// Returns the elements that make up this struct.
pub fn get_elements(&self) -> Vec<&Type> {
unsafe {
Expand Down Expand Up @@ -229,4 +251,4 @@ impl ArrayType {
pub fn get_length(&self) -> usize {
unsafe { core::LLVMGetArrayLength(self.into()) as usize }
}
}
}