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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use crate::instructions::{Binary, Unary};
use crate::{
    generate_bin_op_methods, generate_builder, generate_unary_op_methods, BinaryOperation,
    CallFrame, Instruction, Lifecycle, Module, Number, Register, RigzType, Scope, UnaryOperation,
    VMError, Value, Variable,
};
use indexmap::map::Entry;
use indexmap::IndexMap;
use log::{trace, Level};

pub enum VMState<'vm> {
    Running,
    Done(Value<'vm>),
    Ran(Value<'vm>),
}

#[derive(Clone, Debug, Default)]
pub struct VMOptions {
    pub enable_logging: bool,
    pub disable_modules: bool,
    pub disable_lifecyles: bool,
    pub disable_variable_cleanup: bool,
}

#[derive(Clone, Debug)]
pub struct VM<'vm> {
    pub scopes: Vec<Scope<'vm>>,
    pub current: CallFrame<'vm>,
    pub frames: Vec<CallFrame<'vm>>,
    pub registers: IndexMap<usize, Value<'vm>>,
    pub lifecycles: IndexMap<&'vm str, Lifecycle<'vm>>,
    pub modules: IndexMap<&'vm str, Module<'vm>>,
    pub sp: usize,
    pub options: VMOptions,
}

impl<'vm> Default for VM<'vm> {
    #[inline]
    fn default() -> Self {
        Self {
            scopes: vec![Scope::new()],
            current: Default::default(),
            frames: vec![],
            registers: Default::default(),
            lifecycles: Default::default(),
            modules: Default::default(),
            sp: 0,
            options: Default::default(),
        }
    }
}

impl<'vm> VM<'vm> {
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    generate_builder!();

    pub fn insert_register(&mut self, register: Register, value: Value<'vm>) {
        if register <= 1 {
            return;
        }

        self.registers.insert(register, value);
    }

    pub fn get_registers(&mut self, registers: Vec<Register>) -> Result<Vec<Value<'vm>>, VMError> {
        let len = registers.len();
        let mut result = Vec::with_capacity(len);
        for register in registers {
            result.push(self.get_register(register)?);
        }
        Ok(result)
    }

    #[inline]
    pub fn get_register(&mut self, register: Register) -> Result<Value<'vm>, VMError> {
        if register == 0 {
            return Ok(Value::None);
        }

        if register == 1 {
            return Ok(Value::Number(Number::Int(1)));
        }

        let v = match self.registers.get(&register) {
            None => return Err(VMError::EmptyRegister(format!("R{} is empty", register))),
            Some(v) => v.clone(),
        };

        if let Value::ScopeId(scope, output) = v {
            self.handle_scope(scope, register, output)
        } else {
            Ok(v)
        }
    }

    #[inline]
    pub fn get_register_mut(
        &'vm mut self,
        register: Register,
    ) -> Result<&'vm mut Value<'vm>, VMError> {
        match self.registers.get_mut(&register) {
            None => Err(VMError::EmptyRegister(format!("R{} is empty", register))),
            Some(v) => Ok(v),
        }
    }

    #[inline]
    pub fn handle_scope(
        &mut self,
        scope: usize,
        original: Register,
        output: Register,
    ) -> Result<Value<'vm>, VMError> {
        self.call_frame(scope, output)?;
        match self.run_scope()? {
            VMState::Running => unreachable!(),
            VMState::Done(v) | VMState::Ran(v) => {
                self.insert_register(original, v.clone());
                Ok(v)
            }
        }
    }

    /// Value is replaced with None, shifting the registers breaks the program. Scopes are not evaluated, use `remove_register_eval_scope` instead.
    pub fn remove_register(&mut self, register: Register) -> Result<Value<'vm>, VMError> {
        self.remove_register_value(register)
    }

    #[inline]
    fn remove_register_value(&mut self, register: Register) -> Result<Value<'vm>, VMError> {
        match self.registers.get_mut(&register) {
            None => Err(VMError::EmptyRegister(format!("R{} is empty", register))),
            Some(v) => {
                let value = std::mem::take(v);
                *v = Value::None;
                Ok(value)
            }
        }
    }

    /// Value is replaced with None, shifting the registers breaks the program.

    pub fn remove_register_eval_scope(
        &mut self,
        register: Register,
    ) -> Result<Value<'vm>, VMError> {
        let value = self.remove_register_value(register)?;

        if let Value::ScopeId(scope, output) = value {
            self.handle_scope(scope, register, output)
        } else {
            Ok(value)
        }
    }

    pub fn process_ret(
        &mut self,
        output: Register,
        process: Option<fn(value: Value<'vm>) -> VMState<'vm>>,
    ) -> Result<VMState<'vm>, VMError> {
        let current = self.current.output;
        let source = self.get_register(current)?;
        self.insert_register(output, source.clone());
        match self.frames.pop() {
            None => return Ok(VMState::Done(source)),
            Some(c) => {
                self.clear_frame()?;
                self.sp = c.scope_id;
                self.current = c;
                match process {
                    None => {}
                    Some(process) => return Ok(process(source)),
                }
            }
        }
        Ok(VMState::Running)
    }

    pub fn clear_frame(&mut self) -> Result<(), VMError> {
        if self.options.disable_variable_cleanup {
            return Ok(());
        }

        let variables = std::mem::take(&mut self.current.variables);
        for reg in variables.values() {
            let _ = match reg {
                Variable::Let(r) | Variable::Mut(r) => self.remove_register(*r)?,
            };
        }
        Ok(())
    }

    pub fn process_instruction(
        &mut self,
        instruction: Instruction<'vm>,
    ) -> Result<VMState<'vm>, VMError> {
        trace!("Running {:?}", instruction);
        self.current.pc += 1;
        match instruction {
            Instruction::Ret(output) => self.process_ret(output, None),
            instruction => self.process_core_instruction(instruction),
        }
    }

    pub fn process_instruction_scope(
        &mut self,
        instruction: Instruction<'vm>,
    ) -> Result<VMState<'vm>, VMError> {
        trace!("Running {:?} (scope)", instruction);
        self.current.pc += 1;
        match instruction {
            Instruction::Ret(output) => self.process_ret(output, Some(|s| VMState::Ran(s))),
            ins => self.process_core_instruction(ins),
        }
    }

    fn next_instruction(&self) -> Result<Option<Instruction<'vm>>, VMError> {
        let scope_id = self.sp;
        match self.scopes.get(scope_id) {
            None => Err(VMError::ScopeError(format!(
                "Scope {} does not exist",
                scope_id
            ))),
            Some(s) => match s.instructions.get(self.current.pc) {
                None => Ok(None),
                // TODO delay cloning until instruction is being used (some instructions can be copied with &)
                Some(s) => Ok(Some(s.clone())),
            },
        }
    }

    pub fn run(&mut self) -> Result<Value, VMError> {
        loop {
            let instruction = match self.next_instruction()? {
                // TODO this should probably be an error requiring explicit halt, result would be none
                None => return Ok(Value::None),
                Some(s) => s,
            };

            match self.process_instruction(instruction)? {
                VMState::Ran(v) => {
                    return Err(VMError::RuntimeError(format!(
                        "Unexpected ran state: {}",
                        v
                    )))
                }
                VMState::Running => {}
                VMState::Done(v) => return Ok(v),
            };
        }
    }

    pub fn run_scope(&mut self) -> Result<VMState<'vm>, VMError> {
        loop {
            let instruction = match self.next_instruction()? {
                // TODO this should probably be an error requiring explicit halt, result would be none
                None => return Ok(VMState::Done(Value::None)),
                Some(s) => s,
            };

            match self.process_instruction_scope(instruction)? {
                VMState::Running => {}
                s => return Ok(s),
            };
        }
    }

    pub fn load_mut(&mut self, name: &'vm str, reg: Register) -> Result<(), VMError> {
        match self.current.variables.entry(name) {
            Entry::Occupied(mut var) => match var.get() {
                Variable::Let(_) => {
                    return Err(VMError::UnsupportedOperation(format!(
                        "Cannot overwrite let variable: {}",
                        *var.key()
                    )))
                }
                Variable::Mut(_) => {
                    var.insert(Variable::Mut(reg));
                }
            },
            Entry::Vacant(e) => {
                e.insert(Variable::Mut(reg));
            }
        }
        Ok(())
    }

    pub fn load_let(&mut self, name: &'vm str, reg: Register) -> Result<(), VMError> {
        match self.current.variables.entry(name) {
            Entry::Occupied(v) => {
                return Err(VMError::UnsupportedOperation(format!(
                    "Cannot overwrite let variable: {}",
                    *v.key()
                )))
            }
            Entry::Vacant(e) => {
                e.insert(Variable::Let(reg));
            }
        }
        Ok(())
    }

    pub fn call_frame(&mut self, scope_index: usize, output: Register) -> Result<(), VMError> {
        if self.scopes.len() <= scope_index {
            return Err(VMError::ScopeDoesNotExist(format!(
                "{} does not exist",
                scope_index
            )));
        }
        let current = std::mem::take(&mut self.current);
        self.frames.push(current);
        self.sp = scope_index;
        self.current = CallFrame::child(scope_index, self.frames.len() - 1, output);
        Ok(())
    }

    pub fn run_lifecycles(&mut self) -> IndexMap<String, ()> {
        let mut futures = IndexMap::with_capacity(self.lifecycles.len());
        for (name, l) in &mut self.lifecycles {
            trace!("Starting Lifecycle: {}", name);
            futures.insert(name.to_string(), l.run());
        }
        futures
    }

    /// Snapshots can't include modules or messages from in progress lifecycles
    pub fn snapshot(&self) -> Vec<u8> {
        todo!()
    }

    pub fn load_snapshot(&mut self) {
        todo!()
    }
}