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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use std::{cell::RefCell, fmt::Display, rc::Rc};
use crate::{chunk::Chunk, code::OpCode, lua::Lua, value::Value};
/////////////
///
pub struct CallFrame {
pub function: Rc<Closure>, // pointer
// ip: *const OpCode
// pub base: usize,
// pointer point sinto VM values stack
pub stack_snapshot: usize,
pub local_stack: *mut Value,
pub ip: *const OpCode,
}
impl<'frame> CallFrame {
pub fn new(function: Rc<Closure>, stack_snapshot: usize) -> Self {
let ip = function.function.chunk.code.as_ptr();
Self {
function,
ip,
local_stack: std::ptr::null_mut(),
stack_snapshot,
}
}
pub fn current_instruction(&self) -> &crate::code::OpCode {
// &self.function.chunk.code[self.ip]
unsafe { &*self.ip }
}
/** shift ip by 1 instruction */
pub fn iterate(&mut self) {
// self.ip += 1;
self.ip = unsafe { self.ip.add(1) };
}
/** DANGER: does not shift ip, only returns instruction set in range past ip */
pub fn get_next_n_codes(&self, n: usize) -> &[OpCode] {
// &self.function.chunk.code[self.ip..self.ip + n]
const SIZE: usize = std::mem::size_of::<OpCode>();
unsafe { std::slice::from_raw_parts(self.ip.add(1), n * SIZE) }
}
/** move ip N instructions over */
pub fn shift(&mut self, n: usize) {
// self.ip += n;
self.ip = unsafe { self.ip.add(n) };
}
pub fn set_val(&mut self, index: u8, value: Value) {
// self.stack[index as usize] = value;
unsafe { *self.local_stack.add(index as usize) = value };
}
pub fn get_val(&self, index: u8) -> &Value {
// &self.stack[index as usize]
// println!("get_val: {}", index);
// println!("top: {}", unsafe { &*self.local_stack });
unsafe { &*self.local_stack.add(index as usize) }
}
pub fn get_val_mut(&self, index: u8) -> &mut Value {
unsafe { &mut *self.local_stack.add(index as usize) }
}
pub fn print_local_stack(&self) {
println!("local stack: {:?}", unsafe {
std::slice::from_raw_parts(self.local_stack, 10)
});
}
// pub fn push(&mut self, value: Value) {
// // TODO can we push to the stack by pointer? Or should we just push on a Vec?
// // *self.stack_top= value;
// // unsafe { *self.stack_top = value };
// // self.stack.push(value);
// // self.stack_top = self.stack.as_ptr().add(self.stack.len());
// // unsafe { *self.stack_top = value };
// // self.stack_top = unsafe { self.stack_top.add(1) };
// self.stack.push(value);
// }
// pub fn push(&mut self, value: Value) {
// println!("pushing: {}", value);
// // self.stack.push(value);
// self.stack = unsafe { self.stack.add(1) };
// unsafe { *self.stack = value };
// }
/** pop and return top of stack */
// pub fn pop(&mut self) -> Value {
// // self.stack.pop().unwrap()
// // let d = self.stack.wrapping_add(1);
// // take value
// let v = unsafe { std::mem::replace(&mut *self.stack, Value::Nil) };
// self.stack = unsafe { self.stack.sub(1) };
// v
// // let o = unsafe { &*self.stack };
// // o
// }
/** pop N number of values from stack */
// pub fn popn(&mut self, n: u8) {
// // self.stack.truncate(self.stack.len() - n as usize);
// self.stack = unsafe { self.stack.sub(n as usize) };
// }
/** take and replace with a Nil */
pub fn take(&mut self) -> &Value {
// self.stack_top = unsafe { self.stack_top.sub(1) };
// unsafe { *self.stack_top }
let v = unsafe { &*self.local_stack };
unsafe { *self.local_stack = Value::Nil };
v
}
// TODO validate safety of this, compiler has to be solid af!
pub fn forward(&mut self, offset: u16) {
// self.ip += offset as usize;
self.ip = unsafe { self.ip.add(offset as usize) };
}
pub fn rewind(&mut self, offset: u16) {
// self.ip -= offset as usize;
self.ip = unsafe { self.ip.sub(offset as usize) };
// println!("rewind: {}", unsafe { &*self.ip });
}
}
#[derive(Default)]
pub struct FunctionObject {
pub is_script: bool,
pub name: Option<String>,
pub chunk: Chunk,
pub upvalue_count: u8,
// pub arity: usize,
}
impl FunctionObject {
pub fn new(name: Option<String>, is_script: bool) -> Self {
Self {
name,
is_script,
chunk: Chunk::new(),
upvalue_count: 0,
}
}
pub fn set_chunk(&mut self, chunk: Chunk) {
self.chunk = chunk;
}
}
impl Display for FunctionObject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_script {
write!(
f,
"module={}",
self.name.as_ref().unwrap_or(&"root".to_string())
)
} else {
write!(
f,
"fn {}()",
self.name.as_ref().unwrap_or(&"anonymous".to_string())
)
}
}
}
pub type NativeFunction = fn(&mut Lua, Vec<Value>) -> Value; // TODO should be Result<Value,SiltError> for runtime errors
pub struct NativeObject {
name: String,
pub function: fn(&mut Lua, Vec<Value>) -> Value,
}
impl NativeObject {
pub fn new(name: String, function: NativeFunction) -> Self {
Self { name, function }
}
}
pub struct Closure {
pub function: Rc<FunctionObject>,
pub upvalues: Vec<Rc<RefCell<UpValue>>>,
}
impl Closure {
pub fn new(function: Rc<FunctionObject>, upvalues: Vec<Rc<RefCell<UpValue>>>) -> Self {
Self { function, upvalues }
}
pub fn print_upvalues(&self) {
self.upvalues.iter().enumerate().for_each(|(i, f)| {
println!("fn-up {}:{}", i, f.borrow());
});
}
}
pub struct UpValue {
// is_open: bool,
// obj?
pub index: u8,
closed: Value,
pub location: *mut Value,
// pub value: *mut Value, // TODO oshould be a RC mutex of the value ideally
}
impl UpValue {
pub fn new(index: u8, location: *mut Value) -> Self {
Self {
index,
closed: Value::Nil,
location,
}
}
pub fn set_value(&mut self, value: Value) {
unsafe { *self.location = value }
}
pub fn close_around(&mut self, value: Value) {
self.closed = value;
self.location = &mut self.closed as *mut Value;
}
pub fn close(&mut self) {
#[cfg(feature = "dev-out")]
println!("closing: {}", unsafe { &*self.location });
self.closed = unsafe { self.location.replace(Value::Nil) };
#[cfg(feature = "dev-out")]
println!("closed: {}", self.closed);
self.location = &mut self.closed as *mut Value;
}
pub fn copy_value(&self) -> Value {
#[cfg(feature = "dev-out")]
println!("copying: {}", unsafe { &*self.location });
unsafe { (*self.location).clone() }
}
pub fn get_location(&self) -> *mut Value {
#[cfg(feature = "dev-out")]
println!("getting location: {}", unsafe { &*self.location });
self.location
}
// pub fn get(&self) -> &Value {
// unsafe { &*self.value }
// }
// pub fn set(&mut self, value: Value) {
// unsafe { *self.value = value };
// }
}
impl Display for UpValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"⬆️{}x{}@{}",
unsafe { &*self.location },
self.closed,
self.index
)
}
}