hugr_llvm/
types.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use std::rc::Rc;

use anyhow::Result;
use delegate::delegate;
use hugr::extension::ExtensionId;
use hugr::types::{SumType, Type, TypeName};
use inkwell::types::FunctionType;
use inkwell::{context::Context, types::BasicTypeEnum};

use crate::custom::types::{LLVMCustomTypeFn, LLVMTypeMapping};
pub use crate::sum::LLVMSumType;
use crate::utils::type_map::TypeMap;

/// A type alias for a hugr function type. We use this to disambiguate from
/// the LLVM [FunctionType].
pub type HugrFuncType = hugr::types::Signature;

/// A type alias for a hugr type. We use this to disambiguate from LLVM types.
pub type HugrType = Type;

/// A type alias for a hugr sum type.
pub type HugrSumType = SumType;

/// A type that holds [Rc] shared pointers to everything needed to convert from
/// a hugr [HugrType] to an LLVM [Type](inkwell::types).
#[derive(Clone)]
pub struct TypingSession<'c, 'a> {
    iw_context: &'c Context,
    type_converter: Rc<TypeConverter<'a>>,
}

impl<'c, 'a> TypingSession<'c, 'a> {
    delegate! {
        to self.type_converter.clone() {
            /// Convert a [HugrType] into an LLVM [Type](BasicTypeEnum).
            pub fn llvm_type(&self, [self.clone()], hugr_type: &HugrType) -> Result<BasicTypeEnum<'c>>;
            /// Convert a [HugrFuncType] into an LLVM [FunctionType].
            pub fn llvm_func_type(&self, [self.clone()], hugr_type: &HugrFuncType) -> Result<FunctionType<'c>>;
            /// Convert a hugr [HugrSumType] into an LLVM [LLVMSumType].
            pub fn llvm_sum_type(&self, [self.clone()], hugr_type: HugrSumType) -> Result<LLVMSumType<'c>>;
        }
    }

    /// Creates a new `TypingSession`.
    pub fn new(iw_context: &'c Context, type_converter: Rc<TypeConverter<'a>>) -> Self {
        Self {
            iw_context,
            type_converter,
        }
    }

    /// Returns a reference to the inner [Context].
    pub fn iw_context(&self) -> &'c Context {
        self.iw_context
    }
}

#[derive(Default)]
pub struct TypeConverter<'a>(TypeMap<'a, LLVMTypeMapping<'a>>);

impl<'a> TypeConverter<'a> {
    pub(super) fn custom_type(
        &mut self,
        custom_type: (ExtensionId, TypeName),
        handler: impl LLVMCustomTypeFn<'a>,
    ) {
        self.0.set_callback(custom_type, handler);
    }

    pub fn llvm_type<'c>(
        self: Rc<Self>,
        context: TypingSession<'c, 'a>,
        hugr_type: &HugrType,
    ) -> Result<BasicTypeEnum<'c>> {
        self.0.map_type(hugr_type, context)
    }

    pub fn llvm_func_type<'c>(
        self: Rc<Self>,
        context: TypingSession<'c, 'a>,
        hugr_type: &HugrFuncType,
    ) -> Result<FunctionType<'c>> {
        self.0.map_function_type(hugr_type, context)
    }

    pub fn llvm_sum_type<'c>(
        self: Rc<Self>,
        context: TypingSession<'c, 'a>,
        hugr_type: HugrSumType,
    ) -> Result<LLVMSumType<'c>> {
        self.0.map_sum_type(&hugr_type, context)
    }

    pub fn session<'c>(self: Rc<Self>, iw_context: &'c Context) -> TypingSession<'c, 'a> {
        TypingSession::new(iw_context, self)
    }
}

#[cfg(test)]
#[allow(drop_bounds)]
pub mod test {

    use hugr::{
        std_extensions::arithmetic::int_types::INT_TYPES,
        type_row,
        types::{SumType, Type},
    };

    use insta::assert_snapshot;
    use rstest::rstest;

    use crate::{extension::int::add_int_extensions, test::*, types::HugrFuncType};

    #[rstest]
    #[case(0,HugrFuncType::new(type_row!(Type::new_unit_sum(2)), type_row!()))]
    #[case(1, HugrFuncType::new(Type::new_unit_sum(1), Type::new_unit_sum(3)))]
    #[case(2,HugrFuncType::new(vec![], vec![Type::new_unit_sum(1), Type::new_unit_sum(1)]))]
    fn func_types(#[case] _id: i32, #[with(_id)] llvm_ctx: TestContext, #[case] ft: HugrFuncType) {
        assert_snapshot!(
            "func_type_to_llvm",
            llvm_ctx.get_typing_session().llvm_func_type(&ft).unwrap(),
            &ft.to_string()
        )
    }

    #[rstest]
    #[case(0, SumType::new_unary(0))]
    #[case(1, SumType::new_unary(1))]
    #[case(2,SumType::new([vec![Type::new_unit_sum(0), Type::new_unit_sum(1)], vec![Type::new_unit_sum(2), Type::new_unit_sum(3)]]))]
    #[case(3, SumType::new_unary(2))]
    fn sum_types(#[case] _id: i32, #[with(_id)] llvm_ctx: TestContext, #[case] st: SumType) {
        assert_snapshot!(
            "sum_type_to_llvm",
            llvm_ctx
                .get_typing_session()
                .llvm_sum_type(st.clone())
                .unwrap(),
            &st.to_string()
        )
    }

    #[rstest]
    #[case(0, INT_TYPES[0].clone())]
    #[case(1, INT_TYPES[3].clone())]
    #[case(2, INT_TYPES[4].clone())]
    #[case(3, INT_TYPES[5].clone())]
    #[case(4, INT_TYPES[6].clone())]
    #[case(5, Type::new_sum([vec![INT_TYPES[2].clone()]]))]
    #[case(6, Type::new_sum([vec![INT_TYPES[6].clone(),Type::new_unit_sum(1)], vec![Type::new_unit_sum(2), INT_TYPES[2].clone()]]))]
    #[case(7, Type::new_function(HugrFuncType::new(type_row!(Type::new_unit_sum(2)), Type::new_unit_sum(3))))]
    fn ext_types(#[case] _id: i32, #[with(_id)] mut llvm_ctx: TestContext, #[case] t: Type) {
        llvm_ctx.add_extensions(add_int_extensions);
        assert_snapshot!(
            "type_to_llvm",
            llvm_ctx.get_typing_session().llvm_type(&t).unwrap(),
            &t.to_string()
        );
    }
}