moduforge_rules_expression/
isolate.rs

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
19
20type ADefHasher = BuildHasherDefault<AHasher>;
21
22/// Isolate 是一个组件,用于封装一个隔离的环境,用于执行表达式。
23///
24/// 重新运行 Isolate 允许通过 arena 分配器进行高效的内存重用。
25/// arena 分配器通过重用内存块来优化内存管理,从而在 Isolate 被多次重用时提高性能和资源利用率。
26///
27/// 🆕 现在支持扩展机制和State集成
28#[derive(Debug)]
29pub struct Isolate<'arena> {
30    lexer: Lexer<'arena>,
31    compiler: Compiler,
32    vm: VM,
33
34    bump: UnsafeArena<'arena>,
35
36    environment: Option<Variable>,
37    references: HashMap<String, Variable, ADefHasher>,
38}
39
40impl<'a> Isolate<'a> {
41    pub fn new() -> Self {
42        Self {
43            lexer: Lexer::new(),
44            compiler: Compiler::new(),
45            vm: VM::new(),
46
47            bump: UnsafeArena::new(),
48
49            environment: None,
50            references: Default::default(),
51        }
52    }
53
54    pub fn with_environment(variable: Variable) -> Self {
55        let mut isolate = Isolate::new();
56        isolate.set_environment(variable);
57
58        isolate
59    }
60
61    pub fn set_environment(
62        &mut self,
63        variable: Variable,
64    ) {
65        self.environment.replace(variable);
66    }
67
68    pub fn update_environment<F>(
69        &mut self,
70        mut updater: F,
71    ) where
72        F: FnMut(Option<&mut Variable>),
73    {
74        updater(self.environment.as_mut());
75    }
76
77    pub fn set_reference(
78        &mut self,
79        reference: &'a str,
80    ) -> Result<(), IsolateError> {
81        let reference_value = match self.references.get(reference) {
82            Some(value) => value.clone(),
83            None => {
84                let result = self.run_standard(reference)?;
85                self.references.insert(reference.to_string(), result.clone());
86                result
87            },
88        };
89
90        if !matches!(&mut self.environment, Some(Variable::Object(_))) {
91            self.environment.replace(Variable::empty_object());
92        }
93
94        let Some(Variable::Object(environment_object_ref)) = &self.environment
95        else {
96            return Err(IsolateError::ReferenceError);
97        };
98
99        let mut environment_object = environment_object_ref.borrow_mut();
100        environment_object.insert(Rc::from("$"), reference_value);
101
102        Ok(())
103    }
104
105    pub fn get_reference(
106        &self,
107        reference: &str,
108    ) -> Option<Variable> {
109        self.references.get(reference).cloned()
110    }
111
112    pub fn clear_references(&mut self) {
113        self.references.clear();
114    }
115
116    fn run_internal(
117        &mut self,
118        source: &'a str,
119        kind: ExpressionKind,
120    ) -> Result<(), IsolateError> {
121        self.bump.with_mut(|b| b.reset());
122        let bump = self.bump.get();
123
124        let tokens = self.lexer.tokenize(source)?;
125
126        let base_parser = Parser::try_new(tokens, bump)?;
127        let parser_result = match kind {
128            ExpressionKind::Unary => base_parser.unary().parse(),
129            ExpressionKind::Standard => base_parser.standard().parse(),
130        };
131
132        parser_result.error()?;
133
134        self.compiler.compile(parser_result.root)?;
135
136        Ok(())
137    }
138
139    pub fn compile_standard(
140        &mut self,
141        source: &'a str,
142    ) -> Result<Expression<Standard>, IsolateError> {
143        self.run_internal(source, ExpressionKind::Standard)?;
144        let bytecode = self.compiler.get_bytecode().to_vec();
145
146        Ok(Expression::new_standard(Arc::new(bytecode)))
147    }
148
149    pub fn run_standard(
150        &mut self,
151        source: &'a str,
152    ) -> Result<Variable, IsolateError> {
153        self.run_internal(source, ExpressionKind::Standard)?;
154
155        let bytecode = self.compiler.get_bytecode();
156        let result = self.vm.run(
157            bytecode,
158            self.environment.clone().unwrap_or(Variable::Null),
159        )?;
160
161        Ok(result)
162    }
163
164    /// 运行标准表达式,并传入State供自定义函数使用
165    ///
166    /// 使用 RAII 模式确保 State 的异常安全管理
167    pub fn run_standard_with_state<S: Send + Sync + 'static>(
168        &mut self,
169        source: &'a str,
170        state: Arc<S>,
171    ) -> Result<Variable, IsolateError> {
172        // 使用 StateGuard 自动管理 State 生命周期
173        let _guard = crate::functions::StateGuard::new(state);
174        
175        // 运行表达式,即使发生异常,State 也会被正确清理
176        self.run_standard(source)
177    }
178
179    pub fn compile_unary(
180        &mut self,
181        source: &'a str,
182    ) -> Result<Expression<Unary>, IsolateError> {
183        self.run_internal(source, ExpressionKind::Unary)?;
184        let bytecode = self.compiler.get_bytecode().to_vec();
185
186        Ok(Expression::new_unary(Arc::new(bytecode)))
187    }
188
189    pub fn run_unary(
190        &mut self,
191        source: &'a str,
192    ) -> Result<bool, IsolateError> {
193        self.run_internal(source, ExpressionKind::Unary)?;
194
195        let bytecode = self.compiler.get_bytecode();
196        let result = self.vm.run(
197            bytecode,
198            self.environment.clone().unwrap_or(Variable::Null),
199        )?;
200
201        result.as_bool().ok_or_else(|| IsolateError::ValueCastError)
202    }
203
204    /// 运行一元表达式,并传入State供自定义函数使用
205    ///
206    /// 使用 RAII 模式确保 State 的异常安全管理
207    pub fn run_unary_with_state<S: Send + Sync + 'static>(
208        &mut self,
209        source: &'a str,
210        state: Arc<S>,
211    ) -> Result<bool, IsolateError> {
212        // 使用 StateGuard 自动管理 State 生命周期
213        let _guard = crate::functions::StateGuard::new(state);
214        
215        // 运行表达式,即使发生异常,State 也会被正确清理
216        self.run_unary(source)
217    }
218}
219
220/// Errors which happen within isolate or during evaluation
221#[derive(Debug, Error)]
222pub enum IsolateError {
223    #[error("词法分析器错误: {source}")]
224    LexerError { source: LexerError },
225
226    #[error("解析器错误: {source}")]
227    ParserError { source: ParserError },
228
229    #[error("编译器错误: {source}")]
230    CompilerError { source: CompilerError },
231
232    #[error("虚拟机错误: {source}")]
233    VMError { source: VMError },
234
235    #[error("值转换错误")]
236    ValueCastError,
237
238    #[error("计算引用失败")]
239    ReferenceError,
240
241    #[error("缺少上下文引用")]
242    MissingContextReference,
243}
244
245impl Serialize for IsolateError {
246    fn serialize<S>(
247        &self,
248        serializer: S,
249    ) -> Result<S::Ok, S::Error>
250    where
251        S: Serializer,
252    {
253        let mut map = serializer.serialize_map(None)?;
254
255        match &self {
256            IsolateError::ReferenceError => {
257                map.serialize_entry("type", "referenceError")?;
258            },
259            IsolateError::MissingContextReference => {
260                map.serialize_entry("type", "missingContextReference")?;
261            },
262            IsolateError::ValueCastError => {
263                map.serialize_entry("type", "valueCastError")?;
264            },
265            IsolateError::LexerError { source } => {
266                map.serialize_entry("type", "lexerError")?;
267                map.serialize_entry("source", source.to_string().as_str())?;
268            },
269            IsolateError::ParserError { source } => {
270                map.serialize_entry("type", "parserError")?;
271                map.serialize_entry("source", source.to_string().as_str())?;
272            },
273            IsolateError::CompilerError { source } => {
274                map.serialize_entry("type", "compilerError")?;
275                map.serialize_entry("source", source.to_string().as_str())?;
276            },
277            IsolateError::VMError { source } => {
278                map.serialize_entry("type", "vmError")?;
279                map.serialize_entry("source", source.to_string().as_str())?;
280            },
281        }
282
283        map.end()
284    }
285}
286
287impl From<LexerError> for IsolateError {
288    fn from(source: LexerError) -> Self {
289        IsolateError::LexerError { source }
290    }
291}
292
293impl From<ParserError> for IsolateError {
294    fn from(source: ParserError) -> Self {
295        IsolateError::ParserError { source }
296    }
297}
298
299impl From<VMError> for IsolateError {
300    fn from(source: VMError) -> Self {
301        IsolateError::VMError { source }
302    }
303}
304
305impl From<CompilerError> for IsolateError {
306    fn from(source: CompilerError) -> Self {
307        IsolateError::CompilerError { source }
308    }
309}