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(codegen): add AsValue macro support for enums #286

Merged
merged 2 commits into from
Oct 25, 2020
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions crates/mun_codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ categories = ["Game development", "Mun"]

[dependencies]
abi = { version = "=0.2.0", path = "../mun_abi", package = "mun_abi" }
bytemuck = "1.4.1"
hir = { version = "=0.2.0", path = "../mun_hir", package = "mun_hir" }
itertools = "0.9.0"
mun_codegen_macros = { path = "../mun_codegen_macros", package = "mun_codegen_macros" }
Expand Down
20 changes: 19 additions & 1 deletion crates/mun_codegen/src/ir/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::value::{AsValue, IrValueContext, SizedValueType, TransparentValue, Value};
use crate::value::{
AsValue, BytesOrPtr, IrTypeContext, IrValueContext, SizedValueType, TransparentValue, Value,
};
use itertools::Itertools;
use mun_codegen_macros::AsValue;

Expand All @@ -8,6 +10,10 @@ impl<'ink> TransparentValue<'ink> for abi::Guid {
fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
self.0.as_value(context)
}

fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![self.0.to_vec().into()]
}
}

impl<'ink> TransparentValue<'ink> for abi::Privacy {
Expand All @@ -16,6 +22,10 @@ impl<'ink> TransparentValue<'ink> for abi::Privacy {
fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
(*self as u8).as_value(context)
}

fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![vec![*self as u8].into()]
}
}

impl<'ink> TransparentValue<'ink> for abi::TypeGroup {
Expand All @@ -24,6 +34,10 @@ impl<'ink> TransparentValue<'ink> for abi::TypeGroup {
fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
(*self as u8).as_value(context)
}

fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![vec![*self as u8].into()]
}
}

impl<'ink> TransparentValue<'ink> for abi::StructMemoryKind {
Expand All @@ -32,6 +46,10 @@ impl<'ink> TransparentValue<'ink> for abi::StructMemoryKind {
fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
(self.clone() as u8).as_value(context)
}

fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![vec![self.clone() as u8].into()]
}
}

#[derive(AsValue)]
Expand Down
16 changes: 14 additions & 2 deletions crates/mun_codegen/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use crate::{
db::{CodeGenDatabase, CodeGenDatabaseStorage},
OptimizationLevel,
};
use hir::{FileId, RelativePathBuf, SourceDatabase, SourceRoot, SourceRootId};
use hir::{FileId, HirDatabase, RelativePathBuf, SourceDatabase, SourceRoot, SourceRootId};
use mun_target::spec::Target;
use parking_lot::Mutex;
use std::sync::Arc;

Expand All @@ -15,7 +16,6 @@ use std::sync::Arc;
hir::HirDatabaseStorage,
CodeGenDatabaseStorage
)]
#[derive(Default)]
pub(crate) struct MockDatabase {
storage: salsa::Storage<Self>,
events: Mutex<Option<Vec<salsa::Event>>>,
Expand Down Expand Up @@ -60,6 +60,18 @@ impl hir::Upcast<dyn CodeGenDatabase> for MockDatabase {
}
}

impl Default for MockDatabase {
fn default() -> Self {
let mut db: MockDatabase = MockDatabase {
storage: Default::default(),
events: Default::default(),
};
db.set_optimization_level(OptimizationLevel::Default);
db.set_target(Target::host_target().unwrap());
db
}
}

impl MockDatabase {
/// Creates a database from the given text.
pub fn with_single_file(text: &str) -> (MockDatabase, FileId) {
Expand Down
20 changes: 14 additions & 6 deletions crates/mun_codegen/src/value/array_value.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::value::{
AddressableType, AsValue, ConcreteValueType, IrTypeContext, IrValueContext, PointerValueType,
SizedValueType, TypeValue, Value, ValueType,
use super::{
AddressableType, AsValue, ConcreteValueType, HasConstValue, IrTypeContext, IrValueContext,
PointerValueType, SizedValueType, TypeValue, Value, ValueType,
};
use inkwell::{
types::{BasicType, PointerType},
values::PointerValue,
AddressSpace,
};
use inkwell::types::{BasicType, PointerType};
use inkwell::values::PointerValue;
use inkwell::AddressSpace;

impl<'ink, T: ConcreteValueType<'ink>> ConcreteValueType<'ink> for [T] {
type Value = inkwell::values::ArrayValue<'ink>;
Expand Down Expand Up @@ -91,6 +93,12 @@ impl_array!(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32, 36, 0x40, 0x80, 0x100
);

impl<'ink, T: ConcreteValueType<'ink> + HasConstValue> HasConstValue for &[T] {
fn has_const_value() -> bool {
T::has_const_value()
}
}

impl<'ink, E: SizedValueType<'ink>, T: AsValue<'ink, E>> AsValue<'ink, [E]> for &[T]
where
E::Value: ConstArrayValue<'ink>,
Expand Down
30 changes: 27 additions & 3 deletions crates/mun_codegen/src/value/float_value.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use super::{
AsValue, ConcreteValueType, IrTypeContext, IrValueContext, PointerValueType, SizedValueType,
Value,
AddressableType, AsBytesAndPtrs, AsValue, BytesOrPtr, ConcreteValueType, HasConstValue,
IrTypeContext, IrValueContext, PointerValueType, SizedValueType, Value,
};
use crate::value::AddressableType;
use inkwell::{types::PointerType, AddressSpace};

impl<'ink> ConcreteValueType<'ink> for f32 {
Expand Down Expand Up @@ -44,17 +43,42 @@ impl<'ink> PointerValueType<'ink> for f64 {
impl<'ink> AddressableType<'ink, f32> for f32 {}
impl<'ink> AddressableType<'ink, f64> for f64 {}

impl HasConstValue for f32 {
fn has_const_value() -> bool {
true
}
}

impl HasConstValue for f64 {
fn has_const_value() -> bool {
true
}
}

impl<'ink> AsValue<'ink, f32> for f32 {
fn as_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, f32> {
Value::from_raw(
<Self as SizedValueType>::get_ir_type(context.type_context).const_float(*self as f64),
)
}
}

impl<'ink> AsValue<'ink, f64> for f64 {
fn as_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, f64> {
Value::from_raw(
<Self as SizedValueType>::get_ir_type(context.type_context).const_float(*self),
)
}
}

impl<'ink> AsBytesAndPtrs<'ink> for f32 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<f32, [u8; 4]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for f64 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<f64, [u8; 8]>(self).to_vec().into()]
}
}
58 changes: 56 additions & 2 deletions crates/mun_codegen/src/value/int_value.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
AddressableType, AsValue, ConcreteValueType, IrTypeContext, IrValueContext, PointerValueType,
SizedValueType, Value,
AddressableType, AsBytesAndPtrs, AsValue, BytesOrPtr, ConcreteValueType, HasConstValue,
IrTypeContext, IrValueContext, PointerValueType, SizedValueType, Value,
};
use inkwell::AddressSpace;

Expand All @@ -24,6 +24,12 @@ macro_rules! impl_as_int_ir_value {
}

impl<'ink> AddressableType<'ink, $ty> for $ty {}

impl HasConstValue for $ty {
fn has_const_value() -> bool {
true
}
}
)*
}
}
Expand Down Expand Up @@ -110,3 +116,51 @@ impl<'ink> AsValue<'ink, i64> for i64 {
)
}
}

impl<'ink> AsBytesAndPtrs<'ink> for u8 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<u8, [u8; 1]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for u16 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<u16, [u8; 2]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for u32 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<u32, [u8; 4]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for u64 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<u64, [u8; 8]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for i8 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<i8, [u8; 1]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for i16 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<i16, [u8; 2]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for i32 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<i32, [u8; 4]>(self).to_vec().into()]
}
}

impl<'ink> AsBytesAndPtrs<'ink> for i64 {
fn as_bytes_and_ptrs(&self, _: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
vec![bytemuck::cast_ref::<i64, [u8; 8]>(self).to_vec().into()]
}
}
103 changes: 102 additions & 1 deletion crates/mun_codegen/src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use std::hash::Hash;
/// is returned. This allows transparent composition. e.g.:
///
/// ```rust
/// # use mun_codegen::value::{AsValue, IrValueContext, TransparentValue, Value};
/// # use mun_codegen::value::{AsValue, BytesOrPtr, IrTypeContext, IrValueContext, TransparentValue, Value};
/// struct Foo {
/// value: u32,
/// bar: f32,
Expand All @@ -49,6 +49,13 @@ use std::hash::Hash;
/// fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
/// (self.value, self.bar).as_value(context)
/// }
///
/// fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
/// vec![
/// bytemuck::cast_ref::<u32, [u8; 4]>(&self.value).to_vec().into(),
/// bytemuck::cast_ref::<f32, [u8; 4]>(&self.bar).to_vec().into(),
/// ]
/// }
/// }
/// ```
///
Expand Down Expand Up @@ -87,6 +94,44 @@ pub trait TransparentValue<'ink> {

/// Converts the instance to the target value
fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target>;

/// Converts the instance to bytes and pointers. All pointers remain pointer values, whereas
/// all other value types are converted to bytes.
fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>>;
}

/// Contains either a value converted to bytes or a pointer to the value.
///
/// This is used for generating constant enum types.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BytesOrPtr<'ink> {
Bytes(Vec<u8>),
UntypedPtr(PointerValue<'ink>),
}

impl<'ink> From<Vec<u8>> for BytesOrPtr<'ink> {
fn from(bytes: Vec<u8>) -> Self {
BytesOrPtr::Bytes(bytes)
}
}

impl<'ink> From<PointerValue<'ink>> for BytesOrPtr<'ink> {
fn from(ptr: PointerValue<'ink>) -> Self {
BytesOrPtr::UntypedPtr(ptr)
}
}

/// Converts a value to its raw byte representation, while leaving pointers intact.
pub trait AsBytesAndPtrs<'ink> {
/// Converts the instance to bytes and pointers. All pointers remain pointer values, whereas
/// all other value types are converted to bytes.
fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>>;
}

/// Signals whether the instance can construct a matching LLVM constant IR value.
pub trait HasConstValue {
/// Returns whether the instance can be converted into an LLVM IR value.
fn has_const_value() -> bool;
}

/// The context in which an `IrType` operates.
Expand Down Expand Up @@ -389,6 +434,15 @@ impl<
}
}

impl<'ink, T> HasConstValue for T
where
T: TransparentValue<'ink>,
{
fn has_const_value() -> bool {
true
}
}

// Transparent values can also be represented as `Value<Self>`.
impl<'ink, T> AsValue<'ink, T> for T
where
Expand All @@ -398,3 +452,50 @@ where
Value::from_raw(self.as_target_value(context).value)
}
}

#[cfg(test)]
mod tests {
use super::{AsBytesAndPtrs, HasConstValue};
use crate::{code_gen::CodeGenContext, mock::MockDatabase, value::IrTypeContext};
use bytemuck::from_bytes;
use std::mem::size_of;

macro_rules! test_as_bytes_and_ptrs_primitive {
($($ty:ty),+) => {
$(
paste::item! {
#[test]
fn [<test_has_const_value_ $ty>]() {
assert_eq!($ty::has_const_value(), true);
}
}
paste::item! {
#[test]
fn [<test_as_bytes_and_ptrs_ $ty>]() {
let bytes: Vec<u8> = (0..(size_of::<$ty>() as u8)).collect();
let value = from_bytes::<$ty>(&bytes);

let inkwell_context = inkwell::context::Context::create();

let db = MockDatabase::default();
let codegen_context = CodeGenContext::new(&inkwell_context, &db);

let target_data = codegen_context.target_machine.get_target_data();
let type_context = IrTypeContext {
context: &inkwell_context,
target_data: &target_data,
struct_types: &codegen_context.rust_types,
};

assert_eq!(
value.as_bytes_and_ptrs(&type_context),
vec![bytes.into()],
);
}
}
)+
};
}

test_as_bytes_and_ptrs_primitive!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
}
Loading