1#![no_std]
2extern crate alloc;
3use alloc::string::String;
4use alloc::vec::Vec;
5
6extern "C" {
7 fn compiler_error(err: usize) -> !;
8 fn compiler_log(err: usize);
9}
10
11pub fn throw_error(err: &str) -> ! {
12 unsafe {
13 compiler_error(cstring::from_str(err));
14 };
15}
16
17pub fn log(msg: &str) {
18 unsafe {
19 compiler_log(cstring::from_str(msg));
20 }
21}
22
23#[no_mangle]
24pub extern "C" fn malloc(size: i32) -> *mut u8 {
25 let mut buf = Vec::with_capacity(size as usize);
26 let ptr = buf.as_mut_ptr();
27 core::mem::forget(buf);
28 ptr
29}
30
31fn create_compiler_response(wasm_bytes: Vec<u8>) -> Vec<u8> {
32 let l = wasm_bytes.len() as u32;
33 let len_bytes: [u8; 4] = unsafe { core::mem::transmute(l) };
34 let mut v = Vec::<u8>::new();
35 v.extend(len_bytes.iter());
36 v.extend(wasm_bytes.iter());
37 v
38}
39
40pub fn process<T>(code_ptr: usize, processor: T) -> usize
41where
42 T: Fn(&str) -> Result<Vec<u8>, String>,
43{
44 match cstring::try_into_string(code_ptr) {
45 Ok(code) => {
46 let wasm_bytes = match processor(&code) {
47 Ok(b) => b,
48 Err(e) => throw_error(&e),
49 };
50 &create_compiler_response(wasm_bytes) as *const _ as usize
51 }
52 Err(e) => throw_error(&e),
53 }
54}