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