1use crate::ast::{BinOp, Expr, Located, Program, Stmt, UnaryOp};
5use crate::builtins::BuiltInRegistry;
6use crate::environment::Environment;
7use crate::module_system::{
8 DisabledModuleResolver, ModuleContext, ModuleResolveError, ModuleResolver, ResolvedModule,
9};
10use crate::value::{GeneratorInner, Value};
11use num_bigint::BigInt;
12use num_rational::Ratio;
13use serde_json::{Value as JsonValue, json};
14use std::cell::RefCell;
15use std::collections::HashMap;
16use std::collections::VecDeque;
17use std::rc::Rc;
18
19#[derive(Debug, Clone, PartialEq)]
20pub struct CallFrame {
21 pub name: String,
22 pub signature: String,
23}
24
25#[derive(Debug, Clone, PartialEq)]
26pub enum ImportErrorKind {
27 ImportDisabled,
28 InvalidSpecifier,
29 NoBaseDir,
30 NotFound,
31 AccessDenied,
32 IoError,
33 NotExported,
34 CircularImport,
35 ParseFailed,
36}
37
38#[derive(Debug, Clone, PartialEq)]
39pub struct ImportError {
40 pub kind: ImportErrorKind,
41 pub specifier: String,
42 pub detail: Option<String>,
43 pub symbol: Option<String>,
44 pub module_id: Option<String>,
45 pub import_chain: Vec<String>,
46 pub cycle: Option<Vec<String>>,
47}
48
49impl ImportError {
50 fn from_resolve_error(
51 specifier: &str,
52 err: ModuleResolveError,
53 import_chain: Vec<String>,
54 ) -> Self {
55 match err {
56 ModuleResolveError::ImportDisabled => ImportError {
57 kind: ImportErrorKind::ImportDisabled,
58 specifier: specifier.to_string(),
59 detail: None,
60 symbol: None,
61 module_id: None,
62 import_chain,
63 cycle: None,
64 },
65 ModuleResolveError::InvalidSpecifier(s) => ImportError {
66 kind: ImportErrorKind::InvalidSpecifier,
67 specifier: specifier.to_string(),
68 detail: Some(s),
69 symbol: None,
70 module_id: None,
71 import_chain,
72 cycle: None,
73 },
74 ModuleResolveError::NoBaseDir(s) => ImportError {
75 kind: ImportErrorKind::NoBaseDir,
76 specifier: specifier.to_string(),
77 detail: Some(s),
78 symbol: None,
79 module_id: None,
80 import_chain,
81 cycle: None,
82 },
83 ModuleResolveError::NotFound(s) => ImportError {
84 kind: ImportErrorKind::NotFound,
85 specifier: specifier.to_string(),
86 detail: Some(s),
87 symbol: None,
88 module_id: None,
89 import_chain,
90 cycle: None,
91 },
92 ModuleResolveError::AccessDenied(s) => ImportError {
93 kind: ImportErrorKind::AccessDenied,
94 specifier: specifier.to_string(),
95 detail: Some(s),
96 symbol: None,
97 module_id: None,
98 import_chain,
99 cycle: None,
100 },
101 ModuleResolveError::IoError(s) => ImportError {
102 kind: ImportErrorKind::IoError,
103 specifier: specifier.to_string(),
104 detail: Some(s),
105 symbol: None,
106 module_id: None,
107 import_chain,
108 cycle: None,
109 },
110 }
111 }
112
113 fn not_exported(specifier: &str, symbol: &str, import_chain: Vec<String>) -> Self {
114 ImportError {
115 kind: ImportErrorKind::NotExported,
116 specifier: specifier.to_string(),
117 detail: None,
118 symbol: Some(symbol.to_string()),
119 module_id: None,
120 import_chain,
121 cycle: None,
122 }
123 }
124
125 fn circular(module_id: &str, cycle: Vec<String>, import_chain: Vec<String>) -> Self {
126 ImportError {
127 kind: ImportErrorKind::CircularImport,
128 specifier: module_id.to_string(),
129 detail: None,
130 symbol: None,
131 module_id: Some(module_id.to_string()),
132 import_chain,
133 cycle: Some(cycle),
134 }
135 }
136
137 fn parse_failed(module_id: &str, detail: String, import_chain: Vec<String>) -> Self {
138 ImportError {
139 kind: ImportErrorKind::ParseFailed,
140 specifier: module_id.to_string(),
141 detail: Some(detail),
142 symbol: None,
143 module_id: Some(module_id.to_string()),
144 import_chain,
145 cycle: None,
146 }
147 }
148}
149
150#[derive(Debug, Clone, PartialEq)]
152pub enum RuntimeError {
153 UndefinedVariable(String),
155
156 TypeError(String),
158
159 TypeErrorDetailed { expected: String, got: String },
161
162 InvalidOperation(String),
164
165 DivisionByZero,
167
168 NotCallable(String),
170
171 WrongArity { expected: usize, got: usize },
173
174 Return(Value),
176
177 Yield(Value),
179
180 Break,
182
183 Continue,
185
186 Throw(Value),
188
189 ImportError(Box<ImportError>),
191
192 WithCallStack {
194 error: Box<RuntimeError>,
195 call_stack: Vec<CallFrame>,
196 },
197
198 ExecutionLimit(crate::runtime::ExecutionLimitError),
200
201 CustomError(String),
203
204 DebugPause,
206}
207
208impl std::fmt::Display for RuntimeError {
209 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
210 match self {
211 RuntimeError::UndefinedVariable(name) => write!(f, "Undefined variable: {}", name),
212 RuntimeError::TypeError(msg) => write!(f, "Type error: {}", msg),
213 RuntimeError::TypeErrorDetailed { expected, got } => {
214 write!(f, "Type error: expected {}, got {}", expected, got)
215 }
216 RuntimeError::InvalidOperation(msg) => write!(f, "Invalid operation: {}", msg),
217 RuntimeError::DivisionByZero => write!(f, "Division by zero"),
218 RuntimeError::NotCallable(name) => write!(f, "Not callable: {}", name),
219 RuntimeError::WrongArity { expected, got } => {
220 write!(
221 f,
222 "Wrong number of arguments: expected {}, got {}",
223 expected, got
224 )
225 }
226 RuntimeError::Return(val) => write!(f, "Return: {}", val),
227 RuntimeError::Yield(val) => write!(f, "Yield: {}", val),
228 RuntimeError::Break => write!(f, "Break outside of loop"),
229 RuntimeError::Continue => write!(f, "Continue outside of loop"),
230 RuntimeError::Throw(val) => write!(f, "Throw: {}", val),
231 RuntimeError::ImportError(e) => {
232 let msg = match e.kind {
233 ImportErrorKind::ImportDisabled => "Import is disabled".to_string(),
234 ImportErrorKind::InvalidSpecifier => format!(
235 "Invalid module specifier: {}",
236 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
237 ),
238 ImportErrorKind::NoBaseDir => format!(
239 "No base directory to resolve specifier: {}",
240 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
241 ),
242 ImportErrorKind::NotFound => format!(
243 "Module not found: {}",
244 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
245 ),
246 ImportErrorKind::AccessDenied => format!(
247 "Module access denied: {}",
248 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
249 ),
250 ImportErrorKind::IoError => format!(
251 "Module IO error: {}",
252 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
253 ),
254 ImportErrorKind::NotExported => format!(
255 "'{}' is not exported by module {}",
256 e.symbol.clone().unwrap_or_else(|| "<unknown>".to_string()),
257 e.specifier
258 ),
259 ImportErrorKind::CircularImport => {
260 let cycle = e.cycle.clone().unwrap_or_else(|| vec![e.specifier.clone()]);
261 format!("circular import detected: {}", cycle.join(" -> "))
262 }
263 ImportErrorKind::ParseFailed => format!(
264 "parse failed for module {}: {}",
265 e.module_id.clone().unwrap_or_else(|| e.specifier.clone()),
266 e.detail.clone().unwrap_or_else(|| "<unknown>".to_string())
267 ),
268 };
269
270 write!(f, "Import error: {}", msg)?;
271 if !e.import_chain.is_empty() {
272 write!(f, "\nImport chain: {}", e.import_chain.join(" -> "))?;
273 }
274 Ok(())
275 }
276 RuntimeError::WithCallStack { error, call_stack } => {
277 write!(f, "{}", error)?;
278 if !call_stack.is_empty() {
279 let frames = call_stack
280 .iter()
281 .map(|fr| fr.signature.as_str())
282 .collect::<Vec<_>>()
283 .join(" -> ");
284 write!(f, "\nCall stack: {}", frames)?;
285 }
286 Ok(())
287 }
288 RuntimeError::CustomError(msg) => write!(f, "{}", msg),
289 RuntimeError::ExecutionLimit(e) => write!(f, "{}", e),
290 RuntimeError::DebugPause => write!(f, "Debugger pause"),
291 }
292 }
293}
294
295impl std::error::Error for RuntimeError {}
296
297pub type EvalResult = Result<Value, RuntimeError>;
298
299#[derive(Debug, Clone, PartialEq)]
304pub struct ErrorReport {
305 pub phase: String,
306 pub kind: String,
307 pub message: String,
308 pub import_chain: Vec<String>,
309 pub call_stack: Vec<CallFrame>,
310}
311
312impl ErrorReport {
313 pub fn io_error(message: impl Into<String>) -> Self {
314 ErrorReport {
315 phase: "io".to_string(),
316 kind: "IoError".to_string(),
317 message: message.into(),
318 import_chain: Vec::new(),
319 call_stack: Vec::new(),
320 }
321 }
322
323 pub fn parse_error(message: impl Into<String>) -> Self {
324 ErrorReport {
325 phase: "parse".to_string(),
326 kind: "ParseError".to_string(),
327 message: message.into(),
328 import_chain: Vec::new(),
329 call_stack: Vec::new(),
330 }
331 }
332
333 pub fn to_json_value(&self) -> JsonValue {
334 let call_stack = self
335 .call_stack
336 .iter()
337 .map(|fr| json!({"name": fr.name, "signature": fr.signature}))
338 .collect::<Vec<_>>();
339
340 json!({
341 "phase": self.phase,
342 "kind": self.kind,
343 "message": self.message,
344 "import_chain": self.import_chain,
345 "call_stack": call_stack,
346 })
347 }
348
349 pub fn to_json_pretty(&self) -> String {
350 serde_json::to_string_pretty(&self.to_json_value()).unwrap_or_else(|_| {
351 "{\n \"error\": \"failed to serialize ErrorReport\"\n}".to_string()
352 })
353 }
354}
355
356impl RuntimeError {
357 fn peel_call_stack(&self) -> (&RuntimeError, Vec<CallFrame>) {
358 let mut current = self;
359 let mut frames: Vec<CallFrame> = Vec::new();
360
361 while let RuntimeError::WithCallStack { error, call_stack } = current {
362 if frames.is_empty() {
363 frames = call_stack.clone();
364 }
365 current = error.as_ref();
366 }
367
368 (current, frames)
369 }
370
371 fn kind_name(&self) -> String {
372 match self {
373 RuntimeError::UndefinedVariable(_) => "UndefinedVariable",
374 RuntimeError::TypeError(_) | RuntimeError::TypeErrorDetailed { .. } => "TypeError",
375 RuntimeError::InvalidOperation(_) => "InvalidOperation",
376 RuntimeError::DivisionByZero => "DivisionByZero",
377 RuntimeError::NotCallable(_) => "NotCallable",
378 RuntimeError::WrongArity { .. } => "WrongArity",
379 RuntimeError::Return(_) => "Return",
380 RuntimeError::Yield(_) => "Yield",
381 RuntimeError::Break => "Break",
382 RuntimeError::Continue => "Continue",
383 RuntimeError::Throw(_) => "Throw",
384 RuntimeError::ImportError(e) => match e.kind {
385 ImportErrorKind::ImportDisabled => "ImportDisabled",
386 ImportErrorKind::InvalidSpecifier => "InvalidSpecifier",
387 ImportErrorKind::NoBaseDir => "NoBaseDir",
388 ImportErrorKind::NotFound => "NotFound",
389 ImportErrorKind::AccessDenied => "AccessDenied",
390 ImportErrorKind::IoError => "IoError",
391 ImportErrorKind::NotExported => "NotExported",
392 ImportErrorKind::CircularImport => "CircularImport",
393 ImportErrorKind::ParseFailed => "ParseFailed",
394 },
395 RuntimeError::WithCallStack { .. } => "WithCallStack",
396 RuntimeError::ExecutionLimit(_) => "ExecutionLimit",
397 RuntimeError::CustomError(_) => "CustomError",
398 RuntimeError::DebugPause => "DebugPause",
399 }
400 .to_string()
401 }
402
403 fn base_message(&self) -> String {
404 match self {
405 RuntimeError::WithCallStack { error, .. } => error.base_message(),
406 RuntimeError::ImportError(e) => {
407 let msg = match e.kind {
408 ImportErrorKind::ImportDisabled => "Import is disabled".to_string(),
409 ImportErrorKind::InvalidSpecifier => format!(
410 "Invalid module specifier: {}",
411 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
412 ),
413 ImportErrorKind::NoBaseDir => format!(
414 "No base directory to resolve specifier: {}",
415 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
416 ),
417 ImportErrorKind::NotFound => format!(
418 "Module not found: {}",
419 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
420 ),
421 ImportErrorKind::AccessDenied => format!(
422 "Module access denied: {}",
423 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
424 ),
425 ImportErrorKind::IoError => format!(
426 "Module IO error: {}",
427 e.detail.clone().unwrap_or_else(|| e.specifier.clone())
428 ),
429 ImportErrorKind::NotExported => format!(
430 "'{}' is not exported by module {}",
431 e.symbol.clone().unwrap_or_else(|| "<unknown>".to_string()),
432 e.specifier
433 ),
434 ImportErrorKind::CircularImport => {
435 let cycle = e.cycle.clone().unwrap_or_else(|| vec![e.specifier.clone()]);
436 format!("circular import detected: {}", cycle.join(" -> "))
437 }
438 ImportErrorKind::ParseFailed => format!(
439 "parse failed for module {}: {}",
440 e.module_id.clone().unwrap_or_else(|| e.specifier.clone()),
441 e.detail.clone().unwrap_or_else(|| "<unknown>".to_string())
442 ),
443 };
444
445 format!("Import error: {msg}")
446 }
447 other => other.to_string(),
448 }
449 }
450
451 pub fn to_error_report(&self) -> ErrorReport {
452 let (base, call_stack) = self.peel_call_stack();
453
454 let import_chain = match base {
455 RuntimeError::ImportError(e) => e.import_chain.clone(),
456 _ => Vec::new(),
457 };
458
459 ErrorReport {
460 phase: "runtime".to_string(),
461 kind: base.kind_name(),
462 message: base.base_message(),
463 import_chain,
464 call_stack,
465 }
466 }
467}
468
469pub struct Evaluator {
471 env: Rc<RefCell<Environment>>,
473 registry: BuiltInRegistry,
475 trace_seq: u64,
478 trace_entries: VecDeque<crate::runtime::TraceEntry>,
480 trace_buffer_size: usize,
482 bigint_threshold: usize,
484
485 module_resolver: Box<dyn ModuleResolver>,
487 module_cache: HashMap<String, HashMap<String, Value>>,
489 module_stack: Vec<String>,
491 export_stack: Vec<HashMap<String, Value>>,
493 import_base_stack: Vec<ModuleContext>,
495
496 call_stack: Vec<CallFrame>,
498
499 limits: crate::runtime::ExecutionLimits,
501 current_source_file: Option<String>,
503 current_line: std::cell::Cell<usize>,
505 step_counter: std::cell::Cell<usize>,
507 call_stack_depth: std::cell::Cell<usize>,
509 start_time: std::cell::Cell<Option<std::time::Instant>>,
511
512 debugger: Option<Rc<RefCell<crate::debugger::DebuggerState>>>,
514 #[allow(clippy::type_complexity)]
516 debug_hook: Option<Box<dyn FnMut(&mut Evaluator) -> bool>>,
517
518 yield_sink: Option<Rc<RefCell<Vec<Value>>>>,
522
523 forcing_lazy: Vec<String>,
526
527 debug_cond_cache: HashMap<String, Option<Expr>>,
530}
531
532impl Evaluator {
533 const DEFAULT_TRACE_BUFFER_SIZE: usize = 1024;
535
536 fn register_builtins_into_env(registry: &BuiltInRegistry, env: &mut Environment) {
537 for name in registry.names() {
538 let arity = registry.get(&name).map(|(_, a)| a).unwrap_or(0);
539 env.set(name.clone(), Value::BuiltIn { name, arity });
540 }
541 }
542
543 fn eval_step(&self) -> Result<(), RuntimeError> {
545 let steps = self.step_counter.get();
546
547 if let Some(limit) = self.limits.max_steps
548 && steps >= limit
549 {
550 return Err(RuntimeError::ExecutionLimit(
551 crate::runtime::ExecutionLimitError::StepLimitExceeded { steps, limit },
552 ));
553 }
554
555 self.step_counter.set(steps + 1);
556 Ok(())
557 }
558
559 pub fn reset_step_counter(&mut self) {
563 self.step_counter.set(0);
564 }
565
566 pub fn step_count(&self) -> usize {
570 self.step_counter.get()
571 }
572
573 pub fn set_source_file(&mut self, file: String) {
575 self.current_source_file = Some(file);
576 }
577
578 pub fn get_source_file(&self) -> Option<&str> {
580 self.current_source_file.as_deref()
581 }
582
583 pub fn set_current_line(&self, line: usize) {
585 self.current_line.set(line);
586 }
587
588 pub fn get_current_line(&self) -> usize {
590 self.current_line.get()
591 }
592
593 pub fn get_call_stack(&self) -> &[CallFrame] {
595 &self.call_stack
596 }
597
598 pub fn get_call_stack_depth(&self) -> usize {
600 self.call_stack_depth.get()
601 }
602
603 pub fn attach_debugger(
606 &mut self,
607 state: Rc<RefCell<crate::debugger::DebuggerState>>,
608 hook: Box<dyn FnMut(&mut Evaluator) -> bool>,
609 ) {
610 state.borrow_mut().activate();
611 self.debugger = Some(state);
612 self.debug_hook = Some(hook);
613 }
614
615 pub fn detach_debugger(&mut self) {
617 if let Some(state) = self.debugger.take() {
618 state.borrow_mut().deactivate();
619 }
620 self.debug_hook = None;
621 }
622
623 pub fn debugger_attached(&self) -> bool {
625 self.debugger.is_some()
626 }
627
628 pub fn lookup_variable(&self, name: &str) -> Option<Value> {
630 self.env.borrow().get(name)
631 }
632
633 fn eval_debug_condition(&mut self, cond: &str) -> bool {
638 if !self.debug_cond_cache.contains_key(cond) {
639 let parsed = crate::parser::Parser::parse_expression_source(cond).ok();
640 self.debug_cond_cache.insert(cond.to_string(), parsed);
641 }
642 let Some(Some(expr)) = self.debug_cond_cache.get(cond).cloned() else {
643 return false;
644 };
645 matches!(self.eval_expression(&expr), Ok(Value::Boolean(true)))
646 }
647
648 fn check_debug_pause(&mut self, line: usize) -> EvalResult {
653 let Some(state) = self.debugger.clone() else {
654 return Ok(Value::Null);
655 };
656
657 let file = self.current_source_file.clone().unwrap_or_default();
658 let depth = self.call_stack_depth.get();
659 let mut eval_cond = |cond: &str| self.eval_debug_condition(cond);
661 if !state
662 .borrow_mut()
663 .should_pause(&file, line, depth, &mut eval_cond)
664 {
665 return Ok(Value::Null);
666 }
667
668 self.current_line.set(line);
669 let quit = if let Some(mut hook) = self.debug_hook.take() {
670 let quit = hook(self);
671 self.debug_hook = Some(hook);
672 quit
673 } else {
674 false
676 };
677
678 if quit {
679 return Err(RuntimeError::DebugPause);
680 }
681 Ok(Value::Null)
682 }
683
684 fn eval_located(&mut self, located: &Located) -> EvalResult {
686 self.check_debug_pause(located.line)?;
687 self.eval_statement(&located.stmt)
688 }
689
690 fn check_timeout(&self) -> Result<(), RuntimeError> {
692 if let Some(limit_ms) = self.limits.max_duration_ms
693 && let Some(start) = self.start_time.get()
694 {
695 let elapsed = start.elapsed().as_millis() as u64;
696 if elapsed >= limit_ms {
697 return Err(RuntimeError::ExecutionLimit(
698 crate::runtime::ExecutionLimitError::DurationExceeded {
699 duration_ms: elapsed,
700 limit: limit_ms,
701 },
702 ));
703 }
704 }
705 Ok(())
706 }
707
708 fn enter_call(&self) -> Result<(), RuntimeError> {
710 if let Some(limit) = self.limits.max_recursion_depth {
711 let depth = self.call_stack_depth.get();
712 if depth >= limit {
713 return Err(RuntimeError::ExecutionLimit(
714 crate::runtime::ExecutionLimitError::RecursionDepthExceeded { depth, limit },
715 ));
716 }
717 self.call_stack_depth.set(depth + 1);
718 }
719 Ok(())
720 }
721
722 fn exit_call(&self) {
724 if self.limits.max_recursion_depth.is_some() {
725 let depth = self.call_stack_depth.get();
726 self.call_stack_depth.set(depth.saturating_sub(1));
727 }
728 }
729
730 pub fn set_limits(&mut self, limits: crate::runtime::ExecutionLimits) {
732 self.limits = limits;
733 }
734
735 pub fn limits(&self) -> &crate::runtime::ExecutionLimits {
737 &self.limits
738 }
739
740 fn is_control_flow_error(err: &RuntimeError) -> bool {
741 matches!(
742 err,
743 RuntimeError::Return(_)
744 | RuntimeError::Yield(_)
745 | RuntimeError::Break
746 | RuntimeError::Continue
747 | RuntimeError::DebugPause
748 )
749 }
750
751 fn attach_call_stack_if_absent(&self, err: RuntimeError) -> RuntimeError {
752 if Self::is_control_flow_error(&err) {
753 return err;
754 }
755 match err {
756 RuntimeError::WithCallStack { .. } => err,
757 other => RuntimeError::WithCallStack {
758 error: Box::new(other),
759 call_stack: self.call_stack.clone(),
760 },
761 }
762 }
763
764 pub fn new() -> Self {
766 Self::with_permissions_and_trace_buffer(
767 crate::builtins::IOPermissions::default(),
768 Self::DEFAULT_TRACE_BUFFER_SIZE,
769 )
770 }
771
772 pub fn with_permissions(permissions: crate::builtins::IOPermissions) -> Self {
774 Self::with_permissions_and_trace_buffer(permissions, Self::DEFAULT_TRACE_BUFFER_SIZE)
775 }
776
777 pub fn with_permissions_and_trace_buffer(
779 permissions: crate::builtins::IOPermissions,
780 trace_buffer_size: usize,
781 ) -> Self {
782 let env = Rc::new(RefCell::new(Environment::new()));
783
784 let registry = BuiltInRegistry::with_permissions(permissions);
786 Self::register_builtins_into_env(®istry, &mut env.borrow_mut());
787
788 Evaluator {
789 env,
790 registry,
791 trace_seq: 0,
792 trace_entries: VecDeque::new(),
793 trace_buffer_size,
794 bigint_threshold: crate::lexer::DEFAULT_BIGINT_THRESHOLD,
795
796 module_resolver: Box::new(DisabledModuleResolver),
797 module_cache: HashMap::new(),
798 module_stack: Vec::new(),
799 export_stack: Vec::new(),
800 import_base_stack: Vec::new(),
801
802 call_stack: Vec::new(),
803
804 limits: crate::runtime::ExecutionLimits::default(),
805 current_source_file: None,
806 current_line: std::cell::Cell::new(0),
807 step_counter: std::cell::Cell::new(0),
808 call_stack_depth: std::cell::Cell::new(0),
809 start_time: std::cell::Cell::new(None),
810
811 debugger: None,
812 debug_hook: None,
813 yield_sink: None,
814 debug_cond_cache: HashMap::new(),
815 forcing_lazy: Vec::new(),
816 }
817 }
818
819 pub fn with_env(env: Rc<RefCell<Environment>>) -> Self {
821 let registry = BuiltInRegistry::new();
822 Evaluator {
823 env,
824 registry,
825 trace_seq: 0,
826 trace_entries: VecDeque::new(),
827 trace_buffer_size: Self::DEFAULT_TRACE_BUFFER_SIZE,
828 bigint_threshold: crate::lexer::DEFAULT_BIGINT_THRESHOLD,
829
830 module_resolver: Box::new(DisabledModuleResolver),
831 module_cache: HashMap::new(),
832 module_stack: Vec::new(),
833 export_stack: Vec::new(),
834 import_base_stack: Vec::new(),
835
836 call_stack: Vec::new(),
837
838 limits: crate::runtime::ExecutionLimits::default(),
839 current_source_file: None,
840 current_line: std::cell::Cell::new(0),
841 step_counter: std::cell::Cell::new(0),
842 call_stack_depth: std::cell::Cell::new(0),
843 start_time: std::cell::Cell::new(None),
844
845 debugger: None,
846 debug_hook: None,
847 yield_sink: None,
848 debug_cond_cache: HashMap::new(),
849 forcing_lazy: Vec::new(),
850 }
851 }
852
853 pub fn clear_call_stack(&mut self) {
855 self.call_stack.clear();
856 }
857
858 pub fn set_module_resolver(&mut self, resolver: Box<dyn ModuleResolver>) {
860 self.module_resolver = resolver;
861 }
862
863 pub fn push_import_base(&mut self, module_id: String, base_dir: Option<std::path::PathBuf>) {
867 self.import_base_stack.push(ModuleContext {
868 module_id,
869 base_dir,
870 });
871 }
872
873 pub fn pop_import_base(&mut self) {
875 self.import_base_stack.pop();
876 }
877
878 pub fn trace_push(&mut self, label: Option<&str>, values: &[Value]) {
884 let mut entry = crate::runtime::TraceEntry::new(
885 crate::runtime::TraceLevel::Info,
886 "TRACE".to_string(),
887 values.to_vec(),
888 );
889 if let Some(l) = label {
890 entry = entry.with_label(l.to_string());
891 }
892 self.trace_push_entry(entry);
893 }
894
895 fn trace_push_entry(&mut self, mut entry: crate::runtime::TraceEntry) {
897 self.trace_seq = self.trace_seq.saturating_add(1);
898 entry.seq = self.trace_seq;
899
900 if self.trace_entries.len() >= self.trace_buffer_size {
901 self.trace_entries.pop_front();
902 }
903 self.trace_entries.push_back(entry);
904 }
905
906 pub fn take_trace(&mut self) -> Vec<String> {
912 self.trace_entries
913 .drain(..)
914 .map(|e| {
915 let payload = e
916 .values
917 .iter()
918 .map(|v| v.to_string())
919 .collect::<Vec<_>>()
920 .join(" ");
921 match (&e.category[..], &e.label) {
922 ("TRACE", Some(l)) => format!("#{} [{}] {}", e.seq, l, payload),
923 ("TRACE", None) => format!("#{} {}", e.seq, payload),
924 _ => format!("#{} {}", e.seq, e.format()),
925 }
926 })
927 .collect()
928 }
929
930 pub fn trace_records(&self) -> Vec<crate::runtime::TraceEntry> {
932 self.trace_entries.iter().cloned().collect()
933 }
934
935 pub fn trace_by_level(
937 &self,
938 level: crate::runtime::TraceLevel,
939 ) -> Vec<crate::runtime::TraceEntry> {
940 self.trace_entries
941 .iter()
942 .filter(|e| e.level == level)
943 .cloned()
944 .collect()
945 }
946
947 pub fn trace_by_category(&self, category: &str) -> Vec<crate::runtime::TraceEntry> {
949 self.trace_entries
950 .iter()
951 .filter(|e| e.category == category)
952 .cloned()
953 .collect()
954 }
955
956 pub fn trace_by_label(&self, label: &str) -> Vec<crate::runtime::TraceEntry> {
958 self.trace_entries
959 .iter()
960 .filter(|e| e.label.as_deref() == Some(label))
961 .cloned()
962 .collect()
963 }
964
965 pub fn trace_since(&self, since: std::time::Instant) -> Vec<crate::runtime::TraceEntry> {
967 self.trace_entries
968 .iter()
969 .filter(|e| e.timestamp >= since)
970 .cloned()
971 .collect()
972 }
973
974 pub fn trace_filter(
976 &self,
977 filter: &crate::runtime::TraceFilter,
978 ) -> Vec<crate::runtime::TraceEntry> {
979 self.trace_entries
980 .iter()
981 .filter(|e| filter.matches(e))
982 .cloned()
983 .collect()
984 }
985
986 pub fn trace_stats(&self) -> crate::runtime::TraceStats {
988 use std::collections::HashMap;
989
990 let mut by_level = HashMap::new();
991 let mut by_category = HashMap::new();
992
993 for entry in &self.trace_entries {
994 *by_level.entry(entry.level).or_insert(0) += 1;
995 *by_category.entry(entry.category.clone()).or_insert(0) += 1;
996 }
997
998 crate::runtime::TraceStats {
999 total_entries: self.trace_entries.len(),
1000 by_level,
1001 by_category,
1002 buffer_size: self.trace_buffer_size,
1003 buffer_full: self.trace_entries.len() >= self.trace_buffer_size,
1004 }
1005 }
1006
1007 pub fn clear_trace(&mut self) {
1009 self.trace_entries.clear();
1010 self.trace_seq = 0;
1011 }
1012
1013 pub fn set_trace_buffer_size(&mut self, size: usize) {
1018 self.trace_buffer_size = size;
1019
1020 while self.trace_entries.len() > size {
1022 self.trace_entries.pop_front();
1023 }
1024 }
1025
1026 pub fn set_bigint_threshold(&mut self, threshold: usize) {
1028 self.bigint_threshold = threshold;
1029 }
1030
1031 pub fn reset_env(&mut self) {
1036 self.env = Rc::new(RefCell::new(Environment::new()));
1038
1039 self.trace_entries.clear();
1041 self.trace_seq = 0;
1042
1043 self.import_base_stack.clear();
1045 self.export_stack.clear();
1046 self.module_stack.clear();
1047
1048 self.call_stack.clear();
1050
1051 Self::register_builtins_into_env(&self.registry, &mut self.env.borrow_mut());
1053 }
1054
1055 pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
1057 self.env.borrow_mut().set(name.into(), value);
1058 }
1059
1060 pub fn get_global(&self, name: &str) -> Option<Value> {
1062 self.env.borrow().get(name)
1063 }
1064
1065 pub fn enter_child_scope(&mut self) -> Rc<RefCell<Environment>> {
1069 let prev = Rc::clone(&self.env);
1070 let child = Rc::new(RefCell::new(Environment::with_parent(Rc::clone(&prev))));
1071 self.env = child;
1072 prev
1073 }
1074
1075 pub fn restore_env(&mut self, prev: Rc<RefCell<Environment>>) {
1077 self.env = prev;
1078 }
1079
1080 pub fn eval_program(&mut self, program: &Program) -> EvalResult {
1082 if self.limits.max_duration_ms.is_some() {
1084 self.start_time.set(Some(std::time::Instant::now()));
1085 }
1086
1087 let mut result = Value::Null;
1088
1089 for located in program {
1090 result = self.eval_located(located)?;
1091 }
1092
1093 Ok(result)
1094 }
1095
1096 pub fn eval_statement(&mut self, stmt: &Stmt) -> EvalResult {
1098 self.eval_step()?;
1100 self.check_timeout()?;
1101
1102 match stmt {
1103 Stmt::Set { name, value } => {
1104 let val = self.eval_expression(value)?;
1105 self.env.borrow_mut().set(name.clone(), val.clone());
1106 Ok(val)
1107 }
1108
1109 Stmt::SetIndex {
1110 object,
1111 index,
1112 value,
1113 } => {
1114 let val = self.eval_expression(value)?;
1116
1117 if let Expr::Identifier(name) = object.as_ref() {
1119 let obj = self
1121 .env
1122 .borrow()
1123 .get(name)
1124 .ok_or_else(|| RuntimeError::UndefinedVariable(name.clone()))?;
1125
1126 let idx_val = self.eval_expression(index)?;
1128
1129 let new_obj = match (obj, idx_val) {
1131 (Value::Array(mut arr), Value::Number(n)) => {
1132 let idx = n as usize;
1133 if idx >= arr.len() {
1134 return Err(RuntimeError::InvalidOperation(format!(
1135 "Index {} out of bounds (array length: {})",
1136 idx,
1137 arr.len()
1138 )));
1139 }
1140 arr[idx] = val.clone();
1141 Value::Array(arr)
1142 }
1143 (Value::Dict(mut dict), Value::String(key)) => {
1144 dict.insert(key, val.clone());
1145 Value::Dict(dict)
1146 }
1147 (obj, idx) => {
1148 return Err(RuntimeError::TypeError(format!(
1149 "Cannot index {} with {}",
1150 obj.type_name(),
1151 idx.type_name()
1152 )));
1153 }
1154 };
1155
1156 self.env.borrow_mut().set(name.clone(), new_obj);
1158 Ok(val)
1159 } else {
1160 Err(RuntimeError::InvalidOperation(
1162 "Can only assign to simple variable indices (e.g., dict[key], not expr[key])"
1163 .to_string(),
1164 ))
1165 }
1166 }
1167
1168 Stmt::FuncDef { name, params, body } => {
1169 let func = Value::Function {
1170 name: Some(name.clone()),
1171 params: params.clone(),
1172 body: body.clone(),
1173 env: Rc::clone(&self.env),
1174 file: self.current_source_file.clone(),
1175 };
1176 self.env.borrow_mut().set(name.clone(), func.clone());
1177 Ok(func)
1178 }
1179
1180 Stmt::GeneratorDef { name, params, body } => {
1181 let inner = Rc::new(RefCell::new(GeneratorInner {
1185 params: params.clone(),
1186 body: body.clone(),
1187 env: Rc::clone(&self.env),
1188 collected: None,
1189 position: 0,
1190 }));
1191 let r#gen = Value::Generator { inner };
1192 self.env.borrow_mut().set(name.clone(), r#gen.clone());
1193 Ok(r#gen)
1194 }
1195
1196 Stmt::LazyDef { name, expr } => {
1197 let lazy = Value::Lazy {
1198 expr: expr.clone(),
1199 env: Rc::clone(&self.env),
1200 cached: None,
1201 };
1202 self.env.borrow_mut().set(name.clone(), lazy.clone());
1203 Ok(lazy)
1204 }
1205
1206 Stmt::Return(expr) => {
1207 let val = self.eval_expression(expr)?;
1208 Err(RuntimeError::Return(val))
1209 }
1210
1211 Stmt::Yield(expr) => {
1212 let val = self.eval_expression(expr)?;
1213 match &self.yield_sink {
1214 Some(sink) => {
1216 sink.borrow_mut().push(val);
1217 Ok(Value::Null)
1218 }
1219 None => Err(RuntimeError::Yield(val)),
1221 }
1222 }
1223
1224 Stmt::Break => Err(RuntimeError::Break),
1225
1226 Stmt::Continue => Err(RuntimeError::Continue),
1227
1228 Stmt::While { condition, body } => {
1229 let mut result = Value::Null;
1230
1231 loop {
1232 let cond = self.eval_expression(condition)?;
1233 if !cond.is_truthy() {
1234 break;
1235 }
1236
1237 let mut should_break = false;
1238 for located in body {
1239 match self.eval_located(located) {
1240 Ok(val) => result = val,
1241 Err(RuntimeError::Break) => {
1242 should_break = true;
1243 break;
1244 }
1245 Err(RuntimeError::Continue) => break,
1246 Err(e) => return Err(e),
1247 }
1248 }
1249
1250 if should_break {
1251 break;
1252 }
1253 }
1254
1255 Ok(result)
1256 }
1257
1258 Stmt::For {
1259 var,
1260 iterable,
1261 body,
1262 } => {
1263 let iter_val = self.eval_expression(iterable)?;
1264 let mut result = Value::Null;
1265
1266 let items: Vec<Value> = match iter_val {
1268 Value::Array(arr) => arr,
1269 Value::Generator { inner } => self.collect_generator(&inner)?,
1270 other => {
1271 return Err(RuntimeError::TypeError(format!(
1272 "Cannot iterate over {}",
1273 other.type_name()
1274 )));
1275 }
1276 };
1277 {
1278 let mut should_break = false;
1279 for item in items {
1280 self.env.borrow_mut().set(var.clone(), item);
1281 for located in body {
1282 match self.eval_located(located) {
1283 Ok(val) => result = val,
1284 Err(RuntimeError::Break) => {
1285 should_break = true;
1286 break;
1287 }
1288 Err(RuntimeError::Continue) => break,
1289 Err(e) => return Err(e),
1290 }
1291 }
1292 if should_break {
1293 break;
1294 }
1295 }
1296 }
1297
1298 Ok(result)
1299 }
1300
1301 Stmt::ForIndexed {
1302 index_var,
1303 value_var,
1304 iterable,
1305 body,
1306 } => {
1307 let iter_val = self.eval_expression(iterable)?;
1308 let mut result = Value::Null;
1309
1310 let items: Vec<Value> = match iter_val {
1312 Value::Array(arr) => arr,
1313 Value::Generator { inner } => self.collect_generator(&inner)?,
1314 other => {
1315 return Err(RuntimeError::TypeError(format!(
1316 "Cannot iterate over {}",
1317 other.type_name()
1318 )));
1319 }
1320 };
1321 {
1322 let mut should_break = false;
1323 for (idx, item) in items.iter().enumerate() {
1324 self.env
1325 .borrow_mut()
1326 .set(index_var.clone(), Value::Number(idx as f64));
1327 self.env.borrow_mut().set(value_var.clone(), item.clone());
1328 for located in body {
1329 match self.eval_located(located) {
1330 Ok(val) => result = val,
1331 Err(RuntimeError::Break) => {
1332 should_break = true;
1333 break;
1334 }
1335 Err(RuntimeError::Continue) => break,
1336 Err(e) => return Err(e),
1337 }
1338 }
1339 if should_break {
1340 break;
1341 }
1342 }
1343 }
1344
1345 Ok(result)
1346 }
1347
1348 Stmt::Switch {
1349 expr,
1350 cases,
1351 default,
1352 } => {
1353 let val = self.eval_expression(expr)?;
1354
1355 for (case_expr, case_body) in cases {
1356 let case_val = self.eval_expression(case_expr)?;
1357 if val.equals(&case_val) {
1358 let mut result = Value::Null;
1359 for located in case_body {
1360 result = self.eval_located(located)?;
1361 }
1362 return Ok(result);
1363 }
1364 }
1365
1366 if let Some(default_body) = default {
1367 let mut result = Value::Null;
1368 for located in default_body {
1369 result = self.eval_located(located)?;
1370 }
1371 return Ok(result);
1372 }
1373
1374 Ok(Value::Null)
1375 }
1376
1377 Stmt::Import {
1378 names,
1379 path,
1380 aliases,
1381 namespace,
1382 } => self.eval_import(names, path, aliases, namespace.as_ref()),
1383
1384 Stmt::Export(name) => self.eval_export(name),
1385
1386 Stmt::Throw(expr) => {
1387 let val = self.eval_expression(expr)?;
1388 Err(RuntimeError::Throw(val))
1389 }
1390
1391 Stmt::Expression(expr) => self.eval_expression(expr),
1392 }
1393 }
1394
1395 pub fn eval_expression(&mut self, expr: &Expr) -> EvalResult {
1397 match expr {
1398 Expr::Number(n) => Ok(Value::Number(*n)),
1399
1400 Expr::BigInteger(big_int) => {
1401 use num_bigint::BigInt;
1403 use num_rational::Ratio;
1404
1405 Ok(Value::Fraction(Ratio::new(
1406 big_int.clone(),
1407 BigInt::from(1),
1408 )))
1409 }
1410
1411 Expr::String(s) => Ok(Value::String(s.clone())),
1412
1413 Expr::Boolean(b) => Ok(Value::Boolean(*b)),
1414
1415 Expr::Null => Ok(Value::Null),
1416
1417 Expr::Identifier(name) => {
1418 let val = self
1419 .env
1420 .borrow()
1421 .get(name)
1422 .ok_or_else(|| RuntimeError::UndefinedVariable(name.clone()))?;
1423 match val {
1425 Value::Lazy { .. } => self.force_lazy(name),
1426 forced => Ok(forced),
1427 }
1428 }
1429
1430 Expr::Binary { left, op, right } => {
1431 match op {
1433 BinOp::And => {
1434 let left_val = self.eval_expression(left)?;
1435 if !left_val.is_truthy() {
1436 Ok(left_val)
1438 } else {
1439 self.eval_expression(right)
1441 }
1442 }
1443 BinOp::Or => {
1444 let left_val = self.eval_expression(left)?;
1445 if left_val.is_truthy() {
1446 Ok(left_val)
1448 } else {
1449 self.eval_expression(right)
1451 }
1452 }
1453 _ => {
1455 let left_val = self.eval_expression(left)?;
1456 let right_val = self.eval_expression(right)?;
1457 self.eval_binary_op(&left_val, op, &right_val)
1458 }
1459 }
1460 }
1461
1462 Expr::Unary { op, expr } => {
1463 let val = self.eval_expression(expr)?;
1464 self.eval_unary_op(op, &val)
1465 }
1466
1467 Expr::Call { func, args } => {
1468 let name_hint = match func.as_ref() {
1469 Expr::Identifier(name) => Some(name.clone()),
1470 _ => None,
1471 };
1472 let func_val = self.eval_expression(func)?;
1473 let arg_vals: Result<Vec<_>, _> =
1474 args.iter().map(|arg| self.eval_expression(arg)).collect();
1475 let arg_vals = arg_vals?;
1476
1477 self.call_function(name_hint.as_deref(), &func_val, arg_vals)
1478 }
1479
1480 Expr::Array(elements) => {
1481 let vals: Result<Vec<_>, _> =
1482 elements.iter().map(|e| self.eval_expression(e)).collect();
1483 Ok(Value::Array(vals?))
1484 }
1485
1486 Expr::Dict(pairs) => {
1487 let mut map = std::collections::HashMap::new();
1488 for (key, value_expr) in pairs {
1489 let value = self.eval_expression(value_expr)?;
1490 map.insert(key.clone(), value);
1491 }
1492 Ok(Value::Dict(map))
1493 }
1494
1495 Expr::Index { object, index } => {
1496 let obj_val = self.eval_expression(object)?;
1497 let idx_val = self.eval_expression(index)?;
1498
1499 match (obj_val, idx_val) {
1500 (Value::Array(arr), Value::Number(n)) => {
1501 let idx = n as usize;
1502 arr.get(idx).cloned().ok_or_else(|| {
1503 RuntimeError::InvalidOperation(format!("Index {} out of bounds", idx))
1504 })
1505 }
1506 (Value::String(s), Value::Number(n)) => {
1507 let idx = n as usize;
1508 let chars: Vec<char> = s.chars().collect();
1509 chars
1510 .get(idx)
1511 .cloned()
1512 .map(|ch| Value::String(ch.to_string()))
1513 .ok_or_else(|| {
1514 RuntimeError::InvalidOperation(format!(
1515 "Index {} out of bounds (string length: {})",
1516 idx,
1517 chars.len()
1518 ))
1519 })
1520 }
1521 (Value::Dict(dict), Value::String(key)) => {
1522 dict.get(&key).cloned().ok_or_else(|| {
1523 RuntimeError::InvalidOperation(format!("Key '{}' not found", key))
1524 })
1525 }
1526 (obj, idx) => Err(RuntimeError::TypeError(format!(
1527 "Cannot index {} with {}",
1528 obj.type_name(),
1529 idx.type_name()
1530 ))),
1531 }
1532 }
1533
1534 Expr::If {
1535 condition,
1536 then_branch,
1537 elif_branches,
1538 else_branch,
1539 } => {
1540 let cond = self.eval_expression(condition)?;
1541
1542 if cond.is_truthy() {
1543 let mut result = Value::Null;
1544 for located in then_branch {
1545 result = self.eval_located(located)?;
1546 }
1547 return Ok(result);
1548 }
1549
1550 for (elif_cond, elif_body) in elif_branches {
1551 let cond = self.eval_expression(elif_cond)?;
1552 if cond.is_truthy() {
1553 let mut result = Value::Null;
1554 for located in elif_body {
1555 result = self.eval_located(located)?;
1556 }
1557 return Ok(result);
1558 }
1559 }
1560
1561 if let Some(else_body) = else_branch {
1562 let mut result = Value::Null;
1563 for located in else_body {
1564 result = self.eval_located(located)?;
1565 }
1566 return Ok(result);
1567 }
1568
1569 Ok(Value::Null)
1570 }
1571
1572 Expr::Lambda { params, body } => {
1573 Ok(Value::Function {
1575 name: None,
1576 params: params.clone(),
1577 body: body.clone(),
1578 env: Rc::clone(&self.env),
1579 file: self.current_source_file.clone(),
1580 })
1581 }
1582 }
1583 }
1584
1585 fn mul_integer_fraction(a: &Ratio<BigInt>, b: &Ratio<BigInt>) -> Ratio<BigInt> {
1599 if a.denom() == &BigInt::from(1) && b.denom() == &BigInt::from(1) {
1600 Ratio::new_raw(a.numer() * b.numer(), BigInt::from(1))
1601 } else {
1602 a * b
1603 }
1604 }
1605
1606 fn lift_number(a: &f64) -> Result<Ratio<BigInt>, RuntimeError> {
1607 crate::numeric::f64_to_fraction(*a).ok_or_else(|| {
1608 RuntimeError::TypeError("无法将非有限 Number 提升为 Fraction".to_string())
1609 })
1610 }
1611
1612 fn eval_bitwise_op(&self, left: &Value, op: &BinOp, right: &Value) -> EvalResult {
1616 use num_traits::ToPrimitive;
1617
1618 let to_bigint = |v: &Value| -> Result<BigInt, RuntimeError> {
1620 match v {
1621 Value::Number(n) => {
1622 if n.fract() != 0.0 {
1623 Err(RuntimeError::TypeError("位运算要求整数操作数".to_string()))
1624 } else {
1625 let s = format!("{:.0}", n);
1626 BigInt::parse_bytes(s.as_bytes(), 10)
1627 .ok_or_else(|| RuntimeError::TypeError("无法转换的整数值".to_string()))
1628 }
1629 }
1630 Value::Fraction(f) => {
1631 if f.denom() != &BigInt::from(1) {
1632 Err(RuntimeError::TypeError(
1633 "位运算要求整数操作数(分数分母必须为 1)".to_string(),
1634 ))
1635 } else {
1636 Ok(f.numer().clone())
1637 }
1638 }
1639 _ => Err(RuntimeError::TypeError(format!(
1640 "位运算不支持 {} 类型",
1641 v.type_name()
1642 ))),
1643 }
1644 };
1645
1646 let l = to_bigint(left)?;
1647 let r = to_bigint(right)?;
1648 let both_number = matches!((left, right), (Value::Number(_), Value::Number(_)));
1649
1650 let result: BigInt = match op {
1651 BinOp::BitAnd => l & r,
1652 BinOp::BitOr => l | r,
1653 BinOp::BitXor => l ^ r,
1654 BinOp::Shl | BinOp::Shr => {
1655 let shift = r
1657 .to_usize()
1658 .ok_or_else(|| RuntimeError::TypeError("移位量必须是非负整数".to_string()))?;
1659 if op == &BinOp::Shl {
1660 l << shift
1661 } else {
1662 l >> shift
1663 }
1664 }
1665 _ => unreachable!("eval_bitwise_op 仅处理位运算符"),
1666 };
1667
1668 if both_number && let Some(f) = result.to_f64() {
1671 return Ok(Value::Number(f));
1672 }
1673 Ok(Value::Fraction(Ratio::new(result, BigInt::from(1))))
1674 }
1675
1676 fn eval_binary_op(&self, left: &Value, op: &BinOp, right: &Value) -> EvalResult {
1677 match op {
1678 BinOp::Add => match (left, right) {
1679 (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
1680 (Value::String(a), Value::String(b)) => Ok(Value::String(format!("{}{}", a, b))),
1681 (Value::Fraction(a), Value::Fraction(b)) => Ok(Value::Fraction(a + b)),
1682 (Value::Number(a), Value::Fraction(b)) | (Value::Fraction(b), Value::Number(a)) => {
1683 Ok(Value::Fraction(Self::lift_number(a)? + b))
1684 }
1685 _ => Err(RuntimeError::TypeError(format!(
1686 "Cannot add {} and {}",
1687 left.type_name(),
1688 right.type_name()
1689 ))),
1690 },
1691
1692 BinOp::Subtract => match (left, right) {
1693 (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a - b)),
1694 (Value::Fraction(a), Value::Fraction(b)) => Ok(Value::Fraction(a - b)),
1695 (Value::Number(a), Value::Fraction(b)) => {
1696 Ok(Value::Fraction(Self::lift_number(a)? - b))
1697 }
1698 (Value::Fraction(a), Value::Number(b)) => {
1699 Ok(Value::Fraction(a - Self::lift_number(b)?))
1700 }
1701 _ => Err(RuntimeError::TypeError(format!(
1702 "Cannot subtract {} from {}",
1703 right.type_name(),
1704 left.type_name()
1705 ))),
1706 },
1707
1708 BinOp::Multiply => {
1709 match (left, right) {
1710 (Value::Number(a), Value::Number(b)) => {
1711 if a.fract() == 0.0 && b.fract() == 0.0 {
1713 let max_safe = 9007199254740992.0; if a.abs() > max_safe || b.abs() > max_safe {
1716 use num_bigint::BigInt;
1718 use num_rational::Ratio;
1719
1720 let a_str = format!("{:.0}", a);
1722 let b_str = format!("{:.0}", b);
1723
1724 if let (Ok(a_big), Ok(b_big)) =
1725 (a_str.parse::<BigInt>(), b_str.parse::<BigInt>())
1726 {
1727 let result_big = a_big * b_big;
1728 let frac = Ratio::new(result_big, BigInt::from(1));
1729 return Ok(Value::Fraction(frac));
1730 }
1731 }
1732 }
1733 Ok(Value::Number(a * b))
1734 }
1735 (Value::Fraction(a), Value::Fraction(b)) => {
1736 Ok(Value::Fraction(Self::mul_integer_fraction(a, b)))
1737 }
1738 (Value::Number(a), Value::Fraction(b))
1739 | (Value::Fraction(b), Value::Number(a)) => Ok(Value::Fraction(
1740 Self::mul_integer_fraction(&Self::lift_number(a)?, b),
1741 )),
1742 _ => Err(RuntimeError::TypeError(format!(
1743 "Cannot multiply {} and {}",
1744 left.type_name(),
1745 right.type_name()
1746 ))),
1747 }
1748 }
1749
1750 BinOp::Divide => match (left, right) {
1751 (Value::Number(a), Value::Number(b)) => {
1752 if *b == 0.0 {
1753 Err(RuntimeError::DivisionByZero)
1754 } else {
1755 Ok(Value::Number(a / b))
1756 }
1757 }
1758 (Value::Fraction(a), Value::Fraction(b)) => {
1759 use num_traits::Zero;
1760 if b.is_zero() {
1761 Err(RuntimeError::DivisionByZero)
1762 } else {
1763 Ok(Value::Fraction(a / b))
1764 }
1765 }
1766 (Value::Number(a), Value::Fraction(b)) => {
1767 use num_traits::Zero;
1768 if b.is_zero() {
1769 Err(RuntimeError::DivisionByZero)
1770 } else {
1771 Ok(Value::Fraction(Self::lift_number(a)? / b))
1772 }
1773 }
1774 (Value::Fraction(a), Value::Number(b)) => {
1775 if *b == 0.0 {
1776 Err(RuntimeError::DivisionByZero)
1777 } else {
1778 Ok(Value::Fraction(a / Self::lift_number(b)?))
1779 }
1780 }
1781 _ => Err(RuntimeError::TypeError(format!(
1782 "Cannot divide {} by {}",
1783 left.type_name(),
1784 right.type_name()
1785 ))),
1786 },
1787
1788 BinOp::Modulo => match (left, right) {
1789 (Value::Number(a), Value::Number(b)) => {
1790 if *b == 0.0 {
1791 Err(RuntimeError::DivisionByZero)
1792 } else {
1793 Ok(Value::Number(a % b))
1794 }
1795 }
1796 _ => Err(RuntimeError::TypeError(format!(
1797 "Cannot modulo {} by {}",
1798 left.type_name(),
1799 right.type_name()
1800 ))),
1801 },
1802
1803 BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor | BinOp::Shl | BinOp::Shr => {
1804 self.eval_bitwise_op(left, op, right)
1805 }
1806
1807 BinOp::Equal => Ok(Value::Boolean(left.equals(right))),
1808
1809 BinOp::NotEqual => Ok(Value::Boolean(!left.equals(right))),
1810
1811 BinOp::Less => match left.compare(right) {
1812 Some(ord) => Ok(Value::Boolean(ord == std::cmp::Ordering::Less)),
1813 None => Err(RuntimeError::TypeError(format!(
1814 "Cannot compare {} and {}",
1815 left.type_name(),
1816 right.type_name()
1817 ))),
1818 },
1819
1820 BinOp::LessEqual => match left.compare(right) {
1821 Some(ord) => Ok(Value::Boolean(ord != std::cmp::Ordering::Greater)),
1822 None => Err(RuntimeError::TypeError(format!(
1823 "Cannot compare {} and {}",
1824 left.type_name(),
1825 right.type_name()
1826 ))),
1827 },
1828
1829 BinOp::Greater => match left.compare(right) {
1830 Some(ord) => Ok(Value::Boolean(ord == std::cmp::Ordering::Greater)),
1831 None => Err(RuntimeError::TypeError(format!(
1832 "Cannot compare {} and {}",
1833 left.type_name(),
1834 right.type_name()
1835 ))),
1836 },
1837
1838 BinOp::GreaterEqual => match left.compare(right) {
1839 Some(ord) => Ok(Value::Boolean(ord != std::cmp::Ordering::Less)),
1840 None => Err(RuntimeError::TypeError(format!(
1841 "Cannot compare {} and {}",
1842 left.type_name(),
1843 right.type_name()
1844 ))),
1845 },
1846
1847 BinOp::And | BinOp::Or => Err(RuntimeError::InvalidOperation(
1850 "逻辑运算符必须在表达式求值中短路处理".to_string(),
1851 )),
1852 }
1853 }
1854
1855 fn eval_unary_op(&self, op: &UnaryOp, val: &Value) -> EvalResult {
1857 match op {
1858 UnaryOp::Minus => match val {
1859 Value::Number(n) => Ok(Value::Number(-n)),
1860 _ => Err(RuntimeError::TypeError(format!(
1861 "Cannot negate {}",
1862 val.type_name()
1863 ))),
1864 },
1865
1866 UnaryOp::Not => Ok(Value::Boolean(!val.is_truthy())),
1867 }
1868 }
1869
1870 fn call_function(
1872 &mut self,
1873 name_hint: Option<&str>,
1874 func: &Value,
1875 args: Vec<Value>,
1876 ) -> EvalResult {
1877 self.enter_call()?;
1879
1880 let frame = match func {
1881 Value::Function { name, params, .. } => {
1882 let display_name = name_hint
1883 .map(|s| s.to_string())
1884 .or_else(|| name.clone())
1885 .unwrap_or_else(|| "<lambda>".to_string());
1886 let signature = format!("{}({})", display_name, params.join(", "));
1887 CallFrame {
1888 name: display_name.clone(),
1889 signature,
1890 }
1891 }
1892 Value::BuiltIn { name, .. } => {
1893 let arity = self.registry.get(name).map(|(_, a)| a).unwrap_or(0);
1894 let params = if arity == 0 {
1895 String::new()
1896 } else {
1897 (1..=arity)
1898 .map(|i| format!("arg{}", i))
1899 .collect::<Vec<_>>()
1900 .join(", ")
1901 };
1902 let signature = format!("{}({})", name, params);
1903 CallFrame {
1904 name: name.clone(),
1905 signature,
1906 }
1907 }
1908 other => {
1909 let name = name_hint.unwrap_or("<call>").to_string();
1910 let signature = format!("{}(<{}>)", name, other.type_name());
1911 CallFrame { name, signature }
1912 }
1913 };
1914
1915 self.call_stack.push(frame);
1916
1917 match func {
1918 Value::Function {
1919 name,
1920 params,
1921 body,
1922 env,
1923 file,
1924 } => {
1925 if params.len() != args.len() {
1926 let err = RuntimeError::WrongArity {
1927 expected: params.len(),
1928 got: args.len(),
1929 };
1930 let err = self.attach_call_stack_if_absent(err);
1931 let _ = self.call_stack.pop();
1932 self.exit_call();
1933 return Err(err);
1934 }
1935
1936 let func_env = Rc::new(RefCell::new(Environment::with_parent(Rc::clone(env))));
1938
1939 for (param, arg) in params.iter().zip(args.iter()) {
1941 func_env.borrow_mut().set(param.clone(), arg.clone());
1942 }
1943
1944 let prev_env = Rc::clone(&self.env);
1946 self.env = func_env;
1947
1948 let prev_file = self.current_source_file.clone();
1950 if let Some(f) = file {
1951 self.current_source_file = Some(f.clone());
1952 }
1953
1954 if let Some(fname) = name
1958 && let Some(state) = self.debugger.clone()
1959 && state.borrow_mut().should_pause_at_function(fname)
1960 {
1961 if let Some(first) = body.first() {
1962 let f = self.current_source_file.clone().unwrap_or_default();
1963 state.borrow_mut().update_location(f, first.line);
1964 }
1965 if let Some(mut hook) = self.debug_hook.take() {
1966 let quit = hook(self);
1967 self.debug_hook = Some(hook);
1968 if quit {
1969 self.env = prev_env;
1970 self.current_source_file = prev_file;
1971 let _ = self.call_stack.pop();
1972 self.exit_call();
1973 return Err(RuntimeError::DebugPause);
1974 }
1975 }
1976 }
1977
1978 let mut result = Value::Null;
1979 for located in body {
1980 match self.eval_located(located) {
1981 Ok(val) => result = val,
1982 Err(RuntimeError::Return(val)) => {
1983 result = val;
1984 break;
1985 }
1986 Err(e) => {
1987 self.env = prev_env;
1988 self.current_source_file = prev_file;
1989 let e = self.attach_call_stack_if_absent(e);
1990 let _ = self.call_stack.pop();
1991 self.exit_call();
1992 return Err(e);
1993 }
1994 }
1995 }
1996
1997 self.env = prev_env;
1998 self.current_source_file = prev_file;
1999 let _ = self.call_stack.pop();
2000 self.exit_call();
2001 Ok(result)
2002 }
2003
2004 Value::BuiltIn { name, .. } => {
2005 let res = match name.as_str() {
2007 "TRACE" => {
2008 if args.is_empty() {
2009 return {
2010 let err = RuntimeError::WrongArity {
2011 expected: 1,
2012 got: 0,
2013 };
2014 let err = self.attach_call_stack_if_absent(err);
2015 let _ = self.call_stack.pop();
2016 self.exit_call();
2017 Err(err)
2018 };
2019 }
2020
2021 let (label, payload_args) = if args.len() >= 2 {
2024 match &args[0] {
2025 Value::String(s) => (Some(s.as_str()), &args[1..]),
2026 _ => (None, args.as_slice()),
2027 }
2028 } else {
2029 (None, args.as_slice())
2030 };
2031
2032 self.trace_push(label, payload_args);
2033 Ok(Value::Null)
2034 }
2035 "TRACE_DEBUG" | "TRACE_INFO" | "TRACE_WARN" | "TRACE_ERROR" => {
2036 if args.len() < 2 {
2039 return {
2040 let err = RuntimeError::WrongArity {
2041 expected: 2,
2042 got: args.len(),
2043 };
2044 let err = self.attach_call_stack_if_absent(err);
2045 let _ = self.call_stack.pop();
2046 self.exit_call();
2047 Err(err)
2048 };
2049 }
2050
2051 let level = match name.as_str() {
2053 "TRACE_DEBUG" => crate::runtime::TraceLevel::Debug,
2054 "TRACE_INFO" => crate::runtime::TraceLevel::Info,
2055 "TRACE_WARN" => crate::runtime::TraceLevel::Warn,
2056 "TRACE_ERROR" => crate::runtime::TraceLevel::Error,
2057 _ => unreachable!(),
2058 };
2059
2060 let category = match &args[0] {
2062 Value::String(s) => s.clone(),
2063 _ => {
2064 return {
2065 let err = RuntimeError::CustomError(format!(
2066 "TRACE category must be a string, got {}",
2067 args[0].type_name()
2068 ));
2069 let err = self.attach_call_stack_if_absent(err);
2070 let _ = self.call_stack.pop();
2071 self.exit_call();
2072 Err(err)
2073 };
2074 }
2075 };
2076
2077 let values = args[1..].to_vec();
2079
2080 let entry = crate::runtime::TraceEntry::new(level, category, values);
2082 self.trace_push_entry(entry);
2083
2084 Ok(Value::Null)
2085 }
2086 "MAP" => self.builtin_map(&args),
2087 "FILTER" => self.builtin_filter(&args),
2088 "REDUCE" => self.builtin_reduce(&args),
2089 "NEXT" => self.builtin_next(&args),
2093 "DONE" => self.builtin_done(&args),
2094 _ => {
2095 if let Some((func, _arity)) = self.registry.get(name) {
2097 func(&args)
2099 } else {
2100 Err(RuntimeError::NotCallable(format!(
2101 "Built-in function '{}' not found",
2102 name
2103 )))
2104 }
2105 }
2106 };
2107
2108 let _ = self.call_stack.pop();
2109 self.exit_call();
2110 match res {
2111 Ok(v) => Ok(v),
2112 Err(e) => Err(self.attach_call_stack_if_absent(e)),
2113 }
2114 }
2115
2116 Value::Generator { inner } => {
2120 let (params, body, def_env) = {
2121 let g = inner.borrow();
2122 (g.params.clone(), g.body.clone(), Rc::clone(&g.env))
2123 };
2124 if params.len() != args.len() {
2125 let err = RuntimeError::WrongArity {
2126 expected: params.len(),
2127 got: args.len(),
2128 };
2129 let err = self.attach_call_stack_if_absent(err);
2130 let _ = self.call_stack.pop();
2131 self.exit_call();
2132 return Err(err);
2133 }
2134 let instance_env = Rc::new(RefCell::new(Environment::with_parent(def_env)));
2135 for (param, arg) in params.iter().zip(args.iter()) {
2136 instance_env.borrow_mut().set(param.clone(), arg.clone());
2137 }
2138 let instance = Value::Generator {
2139 inner: Rc::new(RefCell::new(GeneratorInner {
2140 params,
2141 body,
2142 env: instance_env,
2143 collected: None,
2144 position: 0,
2145 })),
2146 };
2147 let _ = self.call_stack.pop();
2148 self.exit_call();
2149 Ok(instance)
2150 }
2151
2152 _ => {
2153 let err = RuntimeError::NotCallable(func.type_name().to_string());
2154 let err = self.attach_call_stack_if_absent(err);
2155 let _ = self.call_stack.pop();
2156 self.exit_call();
2157 Err(err)
2158 }
2159 }
2160 }
2161
2162 fn collect_generator(
2170 &mut self,
2171 inner: &Rc<RefCell<GeneratorInner>>,
2172 ) -> Result<Vec<Value>, RuntimeError> {
2173 if let Some(values) = &inner.borrow().collected {
2174 return Ok(values.clone());
2175 }
2176 let (body, gen_env) = {
2178 let g = inner.borrow();
2179 (g.body.clone(), Rc::clone(&g.env))
2180 };
2181
2182 self.enter_call()?;
2183 let prev_env = Rc::clone(&self.env);
2184 self.env = gen_env;
2185
2186 let sink = Rc::new(RefCell::new(Vec::new()));
2187 let prev_sink = self.yield_sink.take();
2188 self.yield_sink = Some(Rc::clone(&sink));
2189
2190 let mut exec: Result<(), RuntimeError> = Ok(());
2191 for located in &body {
2192 match self.eval_located(located) {
2193 Ok(_) => {}
2194 Err(RuntimeError::Return(_)) => break,
2196 Err(e) => {
2197 exec = Err(e);
2198 break;
2199 }
2200 }
2201 }
2202
2203 self.yield_sink = prev_sink;
2204 self.env = prev_env;
2205 self.exit_call();
2206 exec?;
2207
2208 let values: Vec<Value> = sink.borrow().clone();
2209 inner.borrow_mut().collected = Some(values.clone());
2210 Ok(values)
2211 }
2212
2213 fn builtin_next(&mut self, args: &[Value]) -> EvalResult {
2215 if args.len() != 1 {
2216 return Err(RuntimeError::WrongArity {
2217 expected: 1,
2218 got: args.len(),
2219 });
2220 }
2221 let inner = match &args[0] {
2222 Value::Generator { inner } => Rc::clone(inner),
2223 other => {
2224 return Err(RuntimeError::TypeError(format!(
2225 "NEXT expects a Generator, got {}",
2226 other.type_name()
2227 )));
2228 }
2229 };
2230 self.collect_generator(&inner)?;
2231 let mut g = inner.borrow_mut();
2232 match g
2233 .collected
2234 .as_ref()
2235 .and_then(|v| v.get(g.position))
2236 .cloned()
2237 {
2238 Some(v) => {
2239 g.position += 1;
2240 Ok(v)
2241 }
2242 None => Ok(Value::Null),
2243 }
2244 }
2245
2246 fn builtin_done(&mut self, args: &[Value]) -> EvalResult {
2248 if args.len() != 1 {
2249 return Err(RuntimeError::WrongArity {
2250 expected: 1,
2251 got: args.len(),
2252 });
2253 }
2254 let inner = match &args[0] {
2255 Value::Generator { inner } => inner,
2256 other => {
2257 return Err(RuntimeError::TypeError(format!(
2258 "DONE expects a Generator, got {}",
2259 other.type_name()
2260 )));
2261 }
2262 };
2263 let g = inner.borrow();
2264 let done = match &g.collected {
2265 Some(values) => g.position >= values.len(),
2266 None => false,
2267 };
2268 Ok(Value::Boolean(done))
2269 }
2270
2271 fn force_lazy(&mut self, name: &str) -> EvalResult {
2278 let lazy_val = self
2279 .env
2280 .borrow()
2281 .get(name)
2282 .ok_or_else(|| RuntimeError::UndefinedVariable(name.to_string()))?;
2283 let Value::Lazy {
2284 expr,
2285 env: lazy_env,
2286 cached,
2287 } = lazy_val
2288 else {
2289 return Ok(lazy_val);
2290 };
2291 if let Some(v) = cached {
2292 return Ok(*v);
2293 }
2294
2295 if self.forcing_lazy.iter().any(|n| n == name) {
2298 return Err(RuntimeError::InvalidOperation(format!(
2299 "Lazy 变量 {name} 在自身求值期间被读取(循环定义)"
2300 )));
2301 }
2302 self.forcing_lazy.push(name.to_string());
2303
2304 let prev_env = Rc::clone(&self.env);
2305 self.env = Rc::clone(&lazy_env);
2306 let result = self.eval_expression(&expr);
2307 self.env = prev_env;
2308 self.forcing_lazy.pop();
2309
2310 let val = result?;
2311
2312 lazy_env.borrow_mut().update(name, val.clone());
2314 self.env.borrow_mut().set(name.to_string(), val.clone());
2315 Ok(val)
2316 }
2317
2318 fn builtin_map(&mut self, args: &[Value]) -> EvalResult {
2320 if args.len() != 2 {
2321 return Err(RuntimeError::WrongArity {
2322 expected: 2,
2323 got: args.len(),
2324 });
2325 }
2326
2327 let arr = match &args[0] {
2328 Value::Array(a) => a,
2329 other => {
2330 return Err(RuntimeError::TypeErrorDetailed {
2331 expected: "Array".to_string(),
2332 got: format!("{:?}", other),
2333 });
2334 }
2335 };
2336
2337 let func = &args[1];
2338
2339 let mut result = Vec::new();
2340 for item in arr {
2341 let mapped = self.call_function(None, func, vec![item.clone()])?;
2342 result.push(mapped);
2343 }
2344
2345 Ok(Value::Array(result))
2346 }
2347
2348 fn builtin_filter(&mut self, args: &[Value]) -> EvalResult {
2350 if args.len() != 2 {
2351 return Err(RuntimeError::WrongArity {
2352 expected: 2,
2353 got: args.len(),
2354 });
2355 }
2356
2357 let arr = match &args[0] {
2358 Value::Array(a) => a,
2359 other => {
2360 return Err(RuntimeError::TypeErrorDetailed {
2361 expected: "Array".to_string(),
2362 got: format!("{:?}", other),
2363 });
2364 }
2365 };
2366
2367 let predicate = &args[1];
2368
2369 let mut result = Vec::new();
2370 for item in arr {
2371 let test_result = self.call_function(None, predicate, vec![item.clone()])?;
2372 if test_result.is_truthy() {
2373 result.push(item.clone());
2374 }
2375 }
2376
2377 Ok(Value::Array(result))
2378 }
2379
2380 fn builtin_reduce(&mut self, args: &[Value]) -> EvalResult {
2382 if args.len() != 3 {
2383 return Err(RuntimeError::WrongArity {
2384 expected: 3,
2385 got: args.len(),
2386 });
2387 }
2388
2389 let arr = match &args[0] {
2390 Value::Array(a) => a,
2391 other => {
2392 return Err(RuntimeError::TypeErrorDetailed {
2393 expected: "Array".to_string(),
2394 got: format!("{:?}", other),
2395 });
2396 }
2397 };
2398
2399 let func = match &args[1] {
2400 Value::Function { .. } | Value::BuiltIn { .. } => &args[1],
2401 other => {
2402 return Err(RuntimeError::TypeErrorDetailed {
2403 expected: "Function".to_string(),
2404 got: format!("{:?}", other),
2405 });
2406 }
2407 };
2408
2409 let mut accumulator = args[2].clone();
2410
2411 for (idx, item) in arr.iter().enumerate() {
2412 let arg_count = match func {
2413 Value::Function { params, .. } => params.len(),
2414 Value::BuiltIn { arity, .. } => *arity,
2415 _ => 0,
2416 };
2417
2418 let mut call_args = Vec::new();
2419 call_args.push(accumulator);
2420 call_args.push(item.clone());
2421 if arg_count >= 3 {
2422 call_args.push(Value::Number(idx as f64));
2423 }
2424
2425 if arg_count < 2 {
2426 return Err(RuntimeError::WrongArity {
2427 expected: 2,
2428 got: arg_count,
2429 });
2430 }
2431
2432 accumulator = self.call_function(None, func, call_args)?;
2433 }
2434
2435 Ok(accumulator)
2436 }
2437}
2438
2439impl Evaluator {
2440 fn import_chain(&self) -> Vec<String> {
2441 self.import_base_stack
2442 .iter()
2443 .map(|c| c.module_id.clone())
2444 .collect()
2445 }
2446
2447 fn import_chain_with(&self, leaf: impl Into<String>) -> Vec<String> {
2448 let mut chain = self.import_chain();
2449 chain.push(leaf.into());
2450 chain
2451 }
2452
2453 fn current_import_context(&self) -> Option<&ModuleContext> {
2454 self.import_base_stack.last()
2455 }
2456
2457 fn eval_import(
2458 &mut self,
2459 names: &[String],
2460 specifier: &str,
2461 aliases: &[Option<String>],
2462 namespace: Option<&String>,
2463 ) -> EvalResult {
2464 let from_ctx = self.current_import_context();
2465
2466 let chain_for_resolve = self.import_chain_with(specifier.to_string());
2467
2468 let resolved = self
2469 .module_resolver
2470 .resolve(specifier, from_ctx)
2471 .map_err(|e| {
2472 RuntimeError::ImportError(Box::new(ImportError::from_resolve_error(
2473 specifier,
2474 e,
2475 chain_for_resolve,
2476 )))
2477 })?;
2478
2479 let exports = self.load_module(resolved)?;
2480
2481 if let Some(ns) = namespace {
2482 self.env.borrow_mut().set(ns.clone(), Value::Dict(exports));
2483 return Ok(Value::Null);
2484 }
2485
2486 for (i, name) in names.iter().enumerate() {
2487 let alias = aliases
2488 .get(i)
2489 .and_then(|a| a.clone())
2490 .unwrap_or_else(|| name.clone());
2491 let v = exports.get(name).cloned().ok_or_else(|| {
2492 RuntimeError::ImportError(Box::new(ImportError::not_exported(
2493 specifier,
2494 name,
2495 self.import_chain_with(specifier.to_string()),
2496 )))
2497 })?;
2498 self.env.borrow_mut().set(alias, v);
2499 }
2500
2501 Ok(Value::Null)
2502 }
2503
2504 fn eval_export(&mut self, name: &str) -> EvalResult {
2505 let exports = self.export_stack.last_mut().ok_or_else(|| {
2506 RuntimeError::CustomError("Export error: Export used outside of a module".to_string())
2507 })?;
2508
2509 let val = self.env.borrow().get(name).ok_or_else(|| {
2510 RuntimeError::CustomError(format!("Export error: '{}' is not defined", name))
2511 })?;
2512
2513 exports.insert(name.to_string(), val);
2514 Ok(Value::Null)
2515 }
2516
2517 fn load_module(
2518 &mut self,
2519 resolved: ResolvedModule,
2520 ) -> Result<HashMap<String, Value>, RuntimeError> {
2521 let import_chain = self.import_chain_with(resolved.module_id.clone());
2522
2523 if let Some(cached) = self.module_cache.get(&resolved.module_id) {
2524 return Ok(cached.clone());
2525 }
2526
2527 if self.module_stack.contains(&resolved.module_id) {
2528 let mut chain = self.module_stack.clone();
2529 chain.push(resolved.module_id.clone());
2530 return Err(RuntimeError::ImportError(Box::new(ImportError::circular(
2531 &resolved.module_id,
2532 chain,
2533 import_chain,
2534 ))));
2535 }
2536
2537 self.module_stack.push(resolved.module_id.clone());
2538
2539 let mut parser =
2541 crate::parser::Parser::with_bigint_threshold(&resolved.source, self.bigint_threshold);
2542 let program = match parser.parse_program() {
2543 Ok(p) => p,
2544 Err(e) => {
2545 let _ = self.module_stack.pop();
2546 return Err(RuntimeError::ImportError(Box::new(
2547 ImportError::parse_failed(&resolved.module_id, e.to_string(), import_chain),
2548 )));
2549 }
2550 };
2551
2552 let prev_env = Rc::clone(&self.env);
2554 let module_env = Rc::new(RefCell::new(Environment::new()));
2555 Self::register_builtins_into_env(&self.registry, &mut module_env.borrow_mut());
2556 self.env = module_env;
2557
2558 self.import_base_stack.push(ModuleContext {
2560 module_id: resolved.module_id.clone(),
2561 base_dir: resolved.base_dir.clone(),
2562 });
2563
2564 self.export_stack.push(HashMap::new());
2566
2567 let prev_source_file = self.current_source_file.clone();
2569 self.current_source_file = Some(resolved.module_id.clone());
2570
2571 let eval_res = self.eval_program(&program);
2572
2573 let exports = self.export_stack.pop().unwrap_or_default();
2575 self.import_base_stack.pop();
2576 self.current_source_file = prev_source_file;
2577 self.env = prev_env;
2578
2579 let _ = self.module_stack.pop();
2581
2582 let _ = eval_res.map_err(|e| self.attach_call_stack_if_absent(e))?;
2584
2585 self.module_cache
2586 .insert(resolved.module_id.clone(), exports.clone());
2587 Ok(exports)
2588 }
2589}
2590
2591impl Default for Evaluator {
2592 fn default() -> Self {
2593 Self::new()
2594 }
2595}