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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

//! Itsy, a tiny language for embedded use.

pub mod frontend;
#[macro_use]
pub mod bytecode;
pub(crate)mod util;

use std::fmt::Debug;
use std::collections::HashMap;

/// Generates a type implementing [`VMFunc`](trait.VMFunc.html) and [`VMData`](trait.VMData.html).
///
/// ### Example:
///
/// The following code makes the two Rust functions `print(i32)` and `hello_world()` available to Itsy code compiled with `vm::<MyFns>(...)`.
///
/// ```
/// # #[macro_use] extern crate itsy; fn main() {
/// extern_rust!(MyFns, (), {
///     /// prints given i32 value
///     fn print(vm: &mut VM, value: i32) {
///         println!("print:{}", value);
///     }
///     /// prints hello world!
///     fn hello_world(vm: &mut VM) {
///         println!("hello world!");
///     }
/// });
/// # }
/// ```
#[macro_export]
macro_rules! extern_rust {
    (@enum $enum_name:ident $(, $name:tt [ $( $attr:meta ),* ] )* ) => {
        #[allow(non_camel_case_types)]
        #[repr(u16)]
        #[derive(Copy, Clone, Debug)]
        pub enum $enum_name {
            $(
                $( #[ $attr ] )*
                $name,
            )*
            #[doc(hidden)]
            _dummy
        }
    };
    // handle return values
    (@handle-ret $vm:ident, u8, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, u16, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, u32, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, u64, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, i8, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, i16, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, i32, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, i64, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, f32, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, f64, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, bool, $value:ident) => { $vm.stack.push($value); };
    (@handle-ret $vm:ident, $_:tt, $value:ident) => { // object by value
        let heap_index: u32 = $vm.heap.store($value);
        $vm.stack.push(heap_index);
    };
    // handle parameters
    (@handle-param $vm:ident, u8) => { $vm.stack.pop() };
    (@handle-param $vm:ident, u16) => { $vm.stack.pop() };
    (@handle-param $vm:ident, u32) => { $vm.stack.pop() };
    (@handle-param $vm:ident, u64) => { $vm.stack.pop() };
    (@handle-param $vm:ident, i8) => { $vm.stack.pop() };
    (@handle-param $vm:ident, i16) => { $vm.stack.pop() };
    (@handle-param $vm:ident, i32) => { $vm.stack.pop() };
    (@handle-param $vm:ident, i64) => { $vm.stack.pop() };
    (@handle-param $vm:ident, f32) => { $vm.stack.pop() };
    (@handle-param $vm:ident, f64) => { $vm.stack.pop() };
    (@handle-param $vm:ident, bool) => { $vm.stack.pop() };
    (@handle-param $vm:ident, & str) => { { // rust &str specialcase
        let heap_index: u32 = $vm.stack.pop();
        let string_ref: &String = $vm.heap.load(heap_index);
        &string_ref[..]
    } };
    (@handle-param $vm:ident, & $_:tt) => { { // object by reference
        let heap_index: u32 = $vm.stack.pop();
        $vm.heap.load(heap_index)
    } };
    (@handle-param $vm:ident, $_:tt) => { { // object by value
        let heap_index: u32 = $vm.stack.pop();
        $vm.heap.clone(heap_index)
    } };
    (@trait $enum_name:ident, $custom_type:ty $(, $name:tt, $vm:ident [ $( $arg_name:ident : $($arg_type:tt)+ ),* ] [ $($ret_type:ident)? ] $code:block )* ) => {
        impl $crate::VMFunc<$enum_name> for $enum_name {
            fn to_u16(self: Self) -> u16 {
                unsafe { ::std::mem::transmute(self) }
            }
            fn from_u16(index: u16) -> Self {
                unsafe { ::std::mem::transmute(index) }
            }
            #[allow(unused_mut)]
            fn call_info() -> ::std::collections::HashMap<&'static str, (u16, &'static str, Vec<&'static str>)> {
                let mut map = ::std::collections::HashMap::new();
                $(
                    map.insert(stringify!($name), ($enum_name::$name.to_u16(), stringify!($($ret_type)?), vec![ $(stringify!( $($arg_type)+ )),* ]));
                )*
                map
            }
        }
        impl $crate::VMData<$enum_name, $custom_type> for $enum_name {
            #[inline(always)]
            #[allow(unused_variables, unused_assignments, unused_imports)]
            fn exec(self: Self, vm: &mut $crate::bytecode::VM<$enum_name, $custom_type>) {
                use $crate::bytecode::{StackOp, HeapOp};
                match self {
                    $(
                        $enum_name::$name => {
                            let $vm = vm;
                            // set rust function arguments, insert function body
                            let ret = {
                                $(
                                    let $arg_name: $($arg_type)+ = extern_rust!(@handle-param $vm, $($arg_type)*);
                                )*
                                $code
                            };
                            // set return value, if any
                            $(
                                let ret_typed: $ret_type = ret;
                                extern_rust!(@handle-ret $vm, $ret_type, ret_typed);
                            )?
                        },
                    )*
                    $enum_name::_dummy => panic!("Attempted to execute dummy function")
                }
            }
        }
    };
    (
        $enum_name:ident, $custom_type:ty, { $(
            $( #[ $attr:meta ] )*
            fn $name:tt ( $vm:ident : & mut VM $(, $arg_name:ident : $($arg_type:tt)+ )* ) $( -> $ret_type:ident )? $code:block // ret_type cannot be ty as that can't be matched by handle-ret-val (macro shortcoming), or tt as that is ambiguous with $code. We'll just accept simple return types for now.
        )* }
    ) => {
        /// Rust function mapping. Generated from function signatures defined via the `extern_rust!` macro.
        extern_rust!(@enum $enum_name $(, $name [ $( $attr ),* ] )* );
        extern_rust!(@trait $enum_name, $custom_type $(, $name, $vm [ $( $arg_name : $($arg_type)+ ),* ] [ $( $ret_type )? ] $code )* );
    };
}

/// A default implementation of VMFunc that maps no functions.
#[allow(non_camel_case_types)]
#[repr(u16)]
#[derive(Copy, Clone, Debug)]
pub enum Standalone {
    #[doc(hidden)]
    _dummy
}
extern_rust!(@trait Standalone, ());

/// An internal trait used to make resolver, compiler and VM generic over a set of Rust functions.
/// Use the `extern_rust!` macro to generate a type implementing `VMData` and `VMFunc`.
pub trait VMFunc<T>: Clone + Debug + 'static where T: VMFunc<T> {
    #[doc(hidden)]
    fn from_u16(index: u16) -> Self;
    #[doc(hidden)]
    fn to_u16(self: Self) -> u16;
    #[doc(hidden)]
    fn call_info() -> HashMap<&'static str, (u16, &'static str, Vec<&'static str>)>;
}

/// An internal trait used to make VM generic over a set of Rust functions.
/// Use the `extern_rust!` macro to generate a type implementing `VMData` and `VMFunc`.
pub trait VMData<T, U> where T: VMFunc<T>, U: Default {
    #[doc(hidden)]
    fn exec(self: Self, vm: &mut bytecode::VM<T, U>);
}

/// One stop shop to `parse`, `resolve` and `compile` given Itsy source code and create a VM for it.
/// Program execution starts from the "main" function.
///
/// Call `run` on the returned `VM` struct to execute the program.
///
/// The following example defines a VM with an `i32` context (for custom data) and makes the
/// rust functions `print` and `send` available to it.
///
/// ```
/// use itsy::*;
///
/// extern_rust!(MyFns, i32, {
///     /// Prints given i32 value.
///     fn print(vm: &mut VM, value: i32) {
///         println!("print: {}", value);
///     }
///     /// Sets VM context to given value.
///     fn send(vm: &mut VM, value: i32) {
///         *vm.context() = value;
///     }
/// });
///
/// fn main() {
///     let mut vm = vm::<MyFns, i32>("
///         fn main() {
///             let x = 1;
///             let y = 2;
///             print(x+y);
///             send(x+y);
///         }
///     ");
///
///     vm.run();
///     println!("vm sent: {}", vm.into_context());
/// }
/// ```
///
/// Output:
/// ```text
/// print: 3
/// vm sent: 3
/// ```
pub fn vm<T, U>(program: &str) -> bytecode::VM<T, U> where T: VMFunc<T>+VMData<T, U>, U: Default {
    use crate::{frontend::{parse, resolve}, bytecode::{compile, VM}};
    let parsed = parse(program).unwrap();
    let resolved = resolve::<T>(parsed, "main");
    let program = compile(resolved);
    VM::new(program)
}