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    pub fn run_standard_with_state(
168        &mut self,
169        source: &'a str,
170        state: Arc<State>,
171    ) -> Result<Variable, IsolateError> {
172        // 设置State上下文给自定义函数使用
173        crate::functions::custom::CustomFunctionRegistry::set_current_state(
174            Some(state),
175        );
176
177        // 运行表达式
178        let result = self.run_standard(source);
179
180        // 清理State上下文
181        crate::functions::custom::CustomFunctionRegistry::set_current_state(
182            None,
183        );
184
185        result
186    }
187
188    pub fn compile_unary(
189        &mut self,
190        source: &'a str,
191    ) -> Result<Expression<Unary>, IsolateError> {
192        self.run_internal(source, ExpressionKind::Unary)?;
193        let bytecode = self.compiler.get_bytecode().to_vec();
194
195        Ok(Expression::new_unary(Arc::new(bytecode)))
196    }
197
198    pub fn run_unary(
199        &mut self,
200        source: &'a str,
201    ) -> Result<bool, IsolateError> {
202        self.run_internal(source, ExpressionKind::Unary)?;
203
204        let bytecode = self.compiler.get_bytecode();
205        let result = self.vm.run(
206            bytecode,
207            self.environment.clone().unwrap_or(Variable::Null),
208        )?;
209
210        result.as_bool().ok_or_else(|| IsolateError::ValueCastError)
211    }
212
213    /// 运行一元表达式,并传入State供自定义函数使用
214    pub fn run_unary_with_state(
215        &mut self,
216        source: &'a str,
217        state: Arc<State>,
218    ) -> Result<bool, IsolateError> {
219        // 设置State上下文给自定义函数使用
220        crate::functions::custom::CustomFunctionRegistry::set_current_state(
221            Some(state),
222        );
223
224        // 运行表达式
225        let result = self.run_unary(source);
226
227        // 清理State上下文
228        crate::functions::custom::CustomFunctionRegistry::set_current_state(
229            None,
230        );
231
232        result
233    }
234
235    /// 注册自定义函数(可在表达式中直接调用)
236    pub fn register_custom_function<F>(
237        name: String,
238        params: Vec<crate::variable::VariableType>,
239        return_type: crate::variable::VariableType,
240        executor: F,
241    ) -> Result<(), String>
242    where
243        F: Fn(
244                &crate::functions::arguments::Arguments,
245                Option<&Arc<moduforge_state::State>>,
246            ) -> Result<Variable, anyhow::Error>
247            + 'static,
248    {
249        let signature = crate::functions::defs::FunctionSignature {
250            parameters: params,
251            return_type,
252        };
253
254        crate::functions::custom::CustomFunctionRegistry::register_function(
255            name,
256            signature,
257            Box::new(executor),
258        )
259    }
260
261    /// 列出所有已注册的自定义函数
262    pub fn list_custom_functions() -> Vec<String> {
263        crate::functions::custom::CustomFunctionRegistry::list_functions()
264    }
265
266    /// 清空所有自定义函数
267    pub fn clear_custom_functions() {
268        crate::functions::custom::CustomFunctionRegistry::clear()
269    }
270}
271
272/// Errors which happen within isolate or during evaluation
273#[derive(Debug, Error)]
274pub enum IsolateError {
275    #[error("词法分析器错误: {source}")]
276    LexerError { source: LexerError },
277
278    #[error("解析器错误: {source}")]
279    ParserError { source: ParserError },
280
281    #[error("编译器错误: {source}")]
282    CompilerError { source: CompilerError },
283
284    #[error("虚拟机错误: {source}")]
285    VMError { source: VMError },
286
287    #[error("值转换错误")]
288    ValueCastError,
289
290    #[error("计算引用失败")]
291    ReferenceError,
292
293    #[error("缺少上下文引用")]
294    MissingContextReference,
295}
296
297impl Serialize for IsolateError {
298    fn serialize<S>(
299        &self,
300        serializer: S,
301    ) -> Result<S::Ok, S::Error>
302    where
303        S: Serializer,
304    {
305        let mut map = serializer.serialize_map(None)?;
306
307        match &self {
308            IsolateError::ReferenceError => {
309                map.serialize_entry("type", "referenceError")?;
310            },
311            IsolateError::MissingContextReference => {
312                map.serialize_entry("type", "missingContextReference")?;
313            },
314            IsolateError::ValueCastError => {
315                map.serialize_entry("type", "valueCastError")?;
316            },
317            IsolateError::LexerError { source } => {
318                map.serialize_entry("type", "lexerError")?;
319                map.serialize_entry("source", source.to_string().as_str())?;
320            },
321            IsolateError::ParserError { source } => {
322                map.serialize_entry("type", "parserError")?;
323                map.serialize_entry("source", source.to_string().as_str())?;
324            },
325            IsolateError::CompilerError { source } => {
326                map.serialize_entry("type", "compilerError")?;
327                map.serialize_entry("source", source.to_string().as_str())?;
328            },
329            IsolateError::VMError { source } => {
330                map.serialize_entry("type", "vmError")?;
331                map.serialize_entry("source", source.to_string().as_str())?;
332            },
333        }
334
335        map.end()
336    }
337}
338
339impl From<LexerError> for IsolateError {
340    fn from(source: LexerError) -> Self {
341        IsolateError::LexerError { source }
342    }
343}
344
345impl From<ParserError> for IsolateError {
346    fn from(source: ParserError) -> Self {
347        IsolateError::ParserError { source }
348    }
349}
350
351impl From<VMError> for IsolateError {
352    fn from(source: VMError) -> Self {
353        IsolateError::VMError { source }
354    }
355}
356
357impl From<CompilerError> for IsolateError {
358    fn from(source: CompilerError) -> Self {
359        IsolateError::CompilerError { source }
360    }
361}