jetcrab\api/
interpreter.rs

1use crate::vm::instructions::Instruction;
2use crate::vm::{Bytecode, Value};
3use crate::vm::executor::Executor;
4
5pub struct Interpreter {
6    instructions: Vec<Instruction>,
7    constants: Vec<String>,
8}
9
10impl Interpreter {
11    pub fn new(instructions: Vec<Instruction>, constants: Vec<String>) -> Self {
12        Self {
13            instructions,
14            constants,
15        }
16    }
17
18    pub fn execute(&self) -> Result<Value, String> {
19        let mut executor = Executor::new();
20
21        let values: Vec<Value> = self
22            .constants
23            .iter()
24            .map(|s| {
25                if let Ok(num) = s.parse::<f64>() {
26                    Value::Number(num)
27                } else if s == "true" {
28                    Value::Boolean(true)
29                } else if s == "false" {
30                    Value::Boolean(false)
31                } else if s == "null" {
32                    Value::Null
33                } else if s == "undefined" {
34                    Value::Undefined
35                } else {
36                    Value::String(s.clone())
37                }
38            })
39            .collect();
40
41        let bytecode = Bytecode::new(self.instructions.clone());
42        executor
43            .execute(&bytecode, &values)
44            .map_err(|e| format!("Execution error: {}", e))?;
45
46        Ok(executor.stack_mut().pop().unwrap_or(Value::Undefined))
47    }
48
49    pub fn execute_with_context(
50        &self,
51        _context: &mut crate::runtime::Context,
52    ) -> Result<Value, String> {
53        let mut executor = Executor::new();
54
55        let values: Vec<Value> = self
56            .constants
57            .iter()
58            .map(|s| {
59                if let Ok(num) = s.parse::<f64>() {
60                    Value::Number(num)
61                } else if s == "true" {
62                    Value::Boolean(true)
63                } else if s == "false" {
64                    Value::Boolean(false)
65                } else if s == "null" {
66                    Value::Null
67                } else if s == "undefined" {
68                    Value::Undefined
69                } else {
70                    Value::String(s.clone())
71                }
72            })
73            .collect();
74
75        let bytecode = Bytecode::new(self.instructions.clone());
76        executor
77            .execute(&bytecode, &values)
78            .map_err(|e| format!("Execution error: {}", e))?;
79
80        Ok(executor.stack_mut().pop().unwrap_or(Value::Undefined))
81    }
82
83    pub fn get_instructions(&self) -> &[Instruction] {
84        &self.instructions
85    }
86
87    pub fn get_constants(&self) -> &[String] {
88        &self.constants
89    }
90}