1use ahash::AHasher;
2use serde::ser::SerializeMap;
3use serde::{Serialize, Serializer};
4use std::collections::HashMap;
5use std::hash::BuildHasherDefault;
6use std::rc::Rc;
7use std::sync::Arc;
8use thiserror::Error;
9
10use crate::arena::UnsafeArena;
11use crate::compiler::{Compiler, CompilerError};
12use crate::expression::{Standard, Unary};
13use crate::lexer::{Lexer, LexerError};
14use crate::parser::{Parser, ParserError};
15use crate::variable::Variable;
16use crate::vm::{VMError, VM};
17use crate::{Expression, ExpressionKind};
18
19type ADefHasher = BuildHasherDefault<AHasher>;
20
21#[derive(Debug)]
28pub struct Isolate<'arena> {
29 lexer: Lexer<'arena>,
30 compiler: Compiler,
31 vm: VM,
32
33 bump: UnsafeArena<'arena>,
34
35 environment: Option<Variable>,
36 references: HashMap<String, Variable, ADefHasher>,
37}
38
39impl<'a> Isolate<'a> {
40 pub fn new() -> Self {
41 Self {
42 lexer: Lexer::new(),
43 compiler: Compiler::new(),
44 vm: VM::new(),
45
46 bump: UnsafeArena::new(),
47
48 environment: None,
49 references: Default::default(),
50 }
51 }
52
53 pub fn with_environment(variable: Variable) -> Self {
54 let mut isolate = Isolate::new();
55 isolate.set_environment(variable);
56
57 isolate
58 }
59
60 pub fn set_environment(
61 &mut self,
62 variable: Variable,
63 ) {
64 self.environment.replace(variable);
65 }
66
67 pub fn update_environment<F>(
68 &mut self,
69 mut updater: F,
70 ) where
71 F: FnMut(Option<&mut Variable>),
72 {
73 updater(self.environment.as_mut());
74 }
75
76 pub fn set_reference(
77 &mut self,
78 reference: &'a str,
79 ) -> Result<(), IsolateError> {
80 let reference_value = match self.references.get(reference) {
81 Some(value) => value.clone(),
82 None => {
83 let result = self.run_standard(reference)?;
84 self.references.insert(reference.to_string(), result.clone());
85 result
86 },
87 };
88
89 if !matches!(&mut self.environment, Some(Variable::Object(_))) {
90 self.environment.replace(Variable::empty_object());
91 }
92
93 let Some(Variable::Object(environment_object_ref)) = &self.environment
94 else {
95 return Err(IsolateError::ReferenceError);
96 };
97
98 let mut environment_object = environment_object_ref.borrow_mut();
99 environment_object.insert(Rc::from("$"), reference_value);
100
101 Ok(())
102 }
103
104 pub fn get_reference(
105 &self,
106 reference: &str,
107 ) -> Option<Variable> {
108 self.references.get(reference).cloned()
109 }
110
111 pub fn clear_references(&mut self) {
112 self.references.clear();
113 }
114
115 fn run_internal(
116 &mut self,
117 source: &'a str,
118 kind: ExpressionKind,
119 ) -> Result<(), IsolateError> {
120 self.bump.with_mut(|b| b.reset());
121 let bump = self.bump.get();
122
123 let tokens = self.lexer.tokenize(source)?;
124
125 let base_parser = Parser::try_new(tokens, bump)?;
126 let parser_result = match kind {
127 ExpressionKind::Unary => base_parser.unary().parse(),
128 ExpressionKind::Standard => base_parser.standard().parse(),
129 };
130
131 parser_result.error()?;
132
133 self.compiler.compile(parser_result.root)?;
134
135 Ok(())
136 }
137
138 pub fn compile_standard(
139 &mut self,
140 source: &'a str,
141 ) -> Result<Expression<Standard>, IsolateError> {
142 self.run_internal(source, ExpressionKind::Standard)?;
143 let bytecode = self.compiler.get_bytecode().to_vec();
144
145 Ok(Expression::new_standard(Arc::new(bytecode)))
146 }
147
148 pub fn run_standard(
149 &mut self,
150 source: &'a str,
151 ) -> Result<Variable, IsolateError> {
152 self.run_internal(source, ExpressionKind::Standard)?;
153
154 let bytecode = self.compiler.get_bytecode();
155 let result = self.vm.run(
156 bytecode,
157 self.environment.clone().unwrap_or(Variable::Null),
158 )?;
159
160 Ok(result)
161 }
162
163 pub fn run_standard_with_state<S: Send + Sync + 'static>(
167 &mut self,
168 source: &'a str,
169 state: Arc<S>,
170 ) -> Result<Variable, IsolateError> {
171 let _guard = crate::functions::StateGuard::new(state);
173
174 self.run_standard(source)
176 }
177
178 pub fn compile_unary(
179 &mut self,
180 source: &'a str,
181 ) -> Result<Expression<Unary>, IsolateError> {
182 self.run_internal(source, ExpressionKind::Unary)?;
183 let bytecode = self.compiler.get_bytecode().to_vec();
184
185 Ok(Expression::new_unary(Arc::new(bytecode)))
186 }
187
188 pub fn run_unary(
189 &mut self,
190 source: &'a str,
191 ) -> Result<bool, IsolateError> {
192 self.run_internal(source, ExpressionKind::Unary)?;
193
194 let bytecode = self.compiler.get_bytecode();
195 let result = self.vm.run(
196 bytecode,
197 self.environment.clone().unwrap_or(Variable::Null),
198 )?;
199
200 result.as_bool().ok_or_else(|| IsolateError::ValueCastError)
201 }
202
203 pub fn run_unary_with_state<S: Send + Sync + 'static>(
207 &mut self,
208 source: &'a str,
209 state: Arc<S>,
210 ) -> Result<bool, IsolateError> {
211 let _guard = crate::functions::StateGuard::new(state);
213
214 self.run_unary(source)
216 }
217}
218
219#[derive(Debug, Error)]
221pub enum IsolateError {
222 #[error("词法分析器错误: {source}")]
223 LexerError { source: LexerError },
224
225 #[error("解析器错误: {source}")]
226 ParserError { source: ParserError },
227
228 #[error("编译器错误: {source}")]
229 CompilerError { source: CompilerError },
230
231 #[error("虚拟机错误: {source}")]
232 VMError { source: VMError },
233
234 #[error("值转换错误")]
235 ValueCastError,
236
237 #[error("计算引用失败")]
238 ReferenceError,
239
240 #[error("缺少上下文引用")]
241 MissingContextReference,
242}
243
244impl Serialize for IsolateError {
245 fn serialize<S>(
246 &self,
247 serializer: S,
248 ) -> Result<S::Ok, S::Error>
249 where
250 S: Serializer,
251 {
252 let mut map = serializer.serialize_map(None)?;
253
254 match &self {
255 IsolateError::ReferenceError => {
256 map.serialize_entry("type", "referenceError")?;
257 },
258 IsolateError::MissingContextReference => {
259 map.serialize_entry("type", "missingContextReference")?;
260 },
261 IsolateError::ValueCastError => {
262 map.serialize_entry("type", "valueCastError")?;
263 },
264 IsolateError::LexerError { source } => {
265 map.serialize_entry("type", "lexerError")?;
266 map.serialize_entry("source", source.to_string().as_str())?;
267 },
268 IsolateError::ParserError { source } => {
269 map.serialize_entry("type", "parserError")?;
270 map.serialize_entry("source", source.to_string().as_str())?;
271 },
272 IsolateError::CompilerError { source } => {
273 map.serialize_entry("type", "compilerError")?;
274 map.serialize_entry("source", source.to_string().as_str())?;
275 },
276 IsolateError::VMError { source } => {
277 map.serialize_entry("type", "vmError")?;
278 map.serialize_entry("source", source.to_string().as_str())?;
279 },
280 }
281
282 map.end()
283 }
284}
285
286impl From<LexerError> for IsolateError {
287 fn from(source: LexerError) -> Self {
288 IsolateError::LexerError { source }
289 }
290}
291
292impl From<ParserError> for IsolateError {
293 fn from(source: ParserError) -> Self {
294 IsolateError::ParserError { source }
295 }
296}
297
298impl From<VMError> for IsolateError {
299 fn from(source: VMError) -> Self {
300 IsolateError::VMError { source }
301 }
302}
303
304impl From<CompilerError> for IsolateError {
305 fn from(source: CompilerError) -> Self {
306 IsolateError::CompilerError { source }
307 }
308}