1use std::num::TryFromIntError;
2use std::os::raw::c_uint;
3use gnu_libjit_sys::{jit_context_build_end, jit_context_build_start, jit_type_ulong, jit_context_create, jit_context_t, jit_type_long, jit_function_create, jit_type_create_signature, jit_type_float32, jit_type_float64, jit_type_int, jit_type_t, jit_abi_t, jit_type_sbyte, jit_type_ubyte, jit_type_void_ptr};
4use crate::{Abi, Function, JitType};
5
6pub struct Context {
7 context: jit_context_t,
8}
9
10#[derive(Clone, Debug)]
11pub enum Exception {
12 TooManyParams(TryFromIntError),
13 ParamIndexToLarge(TryFromIntError),
14 ArgIndexTooLarge(String),
15}
16
17impl Context {
18 pub fn new() -> Context {
19 unsafe {
20 Context { context: jit_context_create() }
21 }
22 }
23
24 pub fn build_start(&self) {
25 unsafe {
26 jit_context_build_start(self.context);
27 }
28 }
29 pub fn build_end(&self) {
30 unsafe {
31 jit_context_build_end(self.context);
32 }
33 }
34
35 pub fn function(&mut self, abi: Abi, return_type: JitType, params: Vec<JitType>) -> Result<Function, Exception> {
41 let mut params_libjit: Vec<jit_type_t> = params.iter().map(|p| p.inner).collect();
42
43 unsafe {
44 let signature = jit_type_create_signature(
45 abi as jit_abi_t,
46 return_type.inner,
47 params_libjit.as_mut_ptr(),
48 params.len() as c_uint,
49 1,
50 );
51 let function = Function::new(jit_function_create(self.context, signature), signature, params);
52 Ok(function)
53 }
54 }
55
56 pub fn int_type() -> JitType {
57 unsafe { JitType::new(jit_type_int) }
58 }
59 pub fn long_type() -> JitType {
60 unsafe { JitType::new(jit_type_long) }
61 }
62 pub fn ulong_type() -> JitType {
63 unsafe { JitType::new(jit_type_ulong) }
64 }
65 pub fn float32_type() -> JitType {
66 unsafe { JitType::new(jit_type_float32) }
67 }
68 pub fn float64_type() -> JitType { unsafe { JitType::new(jit_type_float64) } }
69 pub fn sbyte_type() -> JitType { unsafe { JitType::new(jit_type_sbyte) } }
70 pub fn ubyte_type() -> JitType { unsafe { JitType::new(jit_type_ubyte) } }
71 pub fn void_ptr_type() -> JitType { unsafe { JitType::new(jit_type_void_ptr) } }
72}