Skip to main content

aether/
evaluator.rs

1// src/evaluator.rs
2//! Evaluator for executing Aether AST
3
4use 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/// Runtime errors
151#[derive(Debug, Clone, PartialEq)]
152pub enum RuntimeError {
153    /// Variable not found
154    UndefinedVariable(String),
155
156    /// Type mismatch - simple message
157    TypeError(String),
158
159    /// Type mismatch - detailed version
160    TypeErrorDetailed { expected: String, got: String },
161
162    /// Invalid operation
163    InvalidOperation(String),
164
165    /// Division by zero
166    DivisionByZero,
167
168    /// Function not found or not callable
169    NotCallable(String),
170
171    /// Wrong number of arguments
172    WrongArity { expected: usize, got: usize },
173
174    /// Return statement (used for control flow)
175    Return(Value),
176
177    /// Yield statement (used for generators)
178    Yield(Value),
179
180    /// Break statement (used for loop control)
181    Break,
182
183    /// Continue statement (used for loop control)
184    Continue,
185
186    /// Throw statement (user-thrown error)
187    Throw(Value),
188
189    /// Structured Import/Export module errors (with import chain)
190    ImportError(Box<ImportError>),
191
192    /// Attach a captured call stack to an error.
193    WithCallStack {
194        error: Box<RuntimeError>,
195        call_stack: Vec<CallFrame>,
196    },
197
198    /// Execution limit exceeded
199    ExecutionLimit(crate::runtime::ExecutionLimitError),
200
201    /// Custom error message (用于IO操作等)
202    CustomError(String),
203
204    /// Debugger pause (not a real error, used for control flow)
205    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/// A structured, machine-readable error report.
300///
301/// This is intended for CLI/host integrations that need stable fields
302/// (instead of parsing human-readable error strings).
303#[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
469/// Evaluator for Aether programs
470pub struct Evaluator {
471    /// Global environment
472    env: Rc<RefCell<Environment>>,
473    /// Built-in function registry
474    registry: BuiltInRegistry,
475    /// In-memory trace buffer (for DSL-safe debugging; no stdout/files/network)
476    /// Monotonic sequence for trace entries (starts at 1)
477    trace_seq: u64,
478    /// Structured trace entries (new in Stage 3.2)
479    trace_entries: VecDeque<crate::runtime::TraceEntry>,
480    /// Maximum number of trace entries to keep in buffer
481    trace_buffer_size: usize,
482    /// 整数字面量超过该位数后切换为 BigInteger(Import 路径解析用)
483    bigint_threshold: usize,
484
485    /// Module resolver (Import/Export). Defaults to disabled for DSL safety.
486    module_resolver: Box<dyn ModuleResolver>,
487    /// Module export cache: module_id -> exports
488    module_cache: HashMap<String, HashMap<String, Value>>,
489    /// Module load stack for cycle detection
490    module_stack: Vec<String>,
491    /// Current module export table stack (only when evaluating an imported module)
492    export_stack: Vec<HashMap<String, Value>>,
493    /// Optional base directory context for resolving relative imports (e.g. eval_file)
494    import_base_stack: Vec<ModuleContext>,
495
496    /// Call stack for better debugging (user functions + builtins)
497    call_stack: Vec<CallFrame>,
498
499    /// Execution limits configuration
500    limits: crate::runtime::ExecutionLimits,
501    /// Current source file being executed (for debugger)
502    current_source_file: Option<String>,
503    /// Current line number being executed (for debugger)
504    current_line: std::cell::Cell<usize>,
505    /// Step counter (for step limit enforcement)
506    step_counter: std::cell::Cell<usize>,
507    /// Call stack depth counter (for recursion depth limit enforcement)
508    call_stack_depth: std::cell::Cell<usize>,
509    /// Execution start time (for timeout enforcement)
510    start_time: std::cell::Cell<Option<std::time::Instant>>,
511
512    /// 调试器状态(与 DebuggerSession 共享同一实例;None 时暂停检查零开销)
513    debugger: Option<Rc<RefCell<crate::debugger::DebuggerState>>>,
514    /// 暂停时回调的调试钩子:在其中运行调试 REPL;返回 true 表示终止程序
515    #[allow(clippy::type_complexity)]
516    debug_hook: Option<Box<dyn FnMut(&mut Evaluator) -> bool>>,
517
518    /// Yield 收集槽:Some 时 Stmt::Yield 把值收入其中并继续执行
519    /// (生成器急切收集期间由 collect_generator 挂载),
520    /// None 时 Yield 保持 RuntimeError::Yield 传播(顶层 Yield 报错)。
521    yield_sink: Option<Rc<RefCell<Vec<Value>>>>,
522
523    /// 正在强制求值的 Lazy 变量名(循环定义检测:
524    /// `Lazy Y (Y + 1)` 在求值期间再次读取自身时直接报错)
525    forcing_lazy: Vec<String>,
526
527    /// 条件断点条件字符串 → 解析结果(None = 解析失败,永不满足)。
528    /// 懒解析首次命中时进行,避免每条语句都尝试解析
529    debug_cond_cache: HashMap<String, Option<Expr>>,
530}
531
532impl Evaluator {
533    /// Default maximum number of trace entries to keep in buffer
534    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    /// Check and increment step counter
544    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    /// Reset execution step counter (host-facing).
560    ///
561    /// This is intended to be called at the start of a *top-level* evaluation.
562    pub fn reset_step_counter(&mut self) {
563        self.step_counter.set(0);
564    }
565
566    /// Return the current execution step count.
567    ///
568    /// Note: this counts evaluated statements (one increment per statement).
569    pub fn step_count(&self) -> usize {
570        self.step_counter.get()
571    }
572
573    /// Set the current source file (for debugger)
574    pub fn set_source_file(&mut self, file: String) {
575        self.current_source_file = Some(file);
576    }
577
578    /// Get the current source file (for debugger)
579    pub fn get_source_file(&self) -> Option<&str> {
580        self.current_source_file.as_deref()
581    }
582
583    /// Set the current line number (for debugger)
584    pub fn set_current_line(&self, line: usize) {
585        self.current_line.set(line);
586    }
587
588    /// Get the current line number (for debugger)
589    pub fn get_current_line(&self) -> usize {
590        self.current_line.get()
591    }
592
593    /// Get the call stack (for debugger)
594    pub fn get_call_stack(&self) -> &[CallFrame] {
595        &self.call_stack
596    }
597
598    /// Get call stack depth (for debugger)
599    pub fn get_call_stack_depth(&self) -> usize {
600        self.call_stack_depth.get()
601    }
602
603    /// 挂载调试器:`state` 与 DebuggerSession 共享,`hook` 在命中断点/步进时回调,
604    /// 返回 true 表示终止程序(以 DebugPause 错误向上传播)
605    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    /// 卸载调试器(若尚有未处理的暂停将直接继续执行)
616    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    /// 调试器是否已挂载
624    pub fn debugger_attached(&self) -> bool {
625        self.debugger.is_some()
626    }
627
628    /// 按作用域链查找变量(供调试器暂停时 `print`,可见函数内局部变量)
629    pub fn lookup_variable(&self, name: &str) -> Option<Value> {
630        self.env.borrow().get(name)
631    }
632
633    /// 条件断点条件求值:
634    /// - 条件字符串懒解析并缓存(解析失败缓存 None → 永不满足);
635    /// - 用**当前环境**求值(可见循环变量等局部状态),只有
636    ///   `Boolean(true)` 视为满足,其余取值与求值错误一律不暂停。
637    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    /// 调试器暂停检查:每条语句执行前调用。
649    ///
650    /// 命中断点或步进条件时回调调试钩子;解释器的 Rust 调用栈保持原样,
651    /// 钩子返回后从暂停语句自然继续。钩子返回 true 时以 DebugPause 终止程序
652    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        // 条件断点在位置命中后用当前环境求值条件(为假或求值失败不暂停)
660        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            // 挂载了状态但没有钩子(如库内测试直接构造):退化为继续执行
675            false
676        };
677
678        if quit {
679            return Err(RuntimeError::DebugPause);
680        }
681        Ok(Value::Null)
682    }
683
684    /// 求值一条带行号的语句:先做调试器暂停检查,再执行语句
685    fn eval_located(&mut self, located: &Located) -> EvalResult {
686        self.check_debug_pause(located.line)?;
687        self.eval_statement(&located.stmt)
688    }
689
690    /// Check execution timeout
691    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    /// Enter function call (check recursion depth)
709    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    /// Exit function call (decrement recursion depth)
723    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    /// Set execution limits (public API)
731    pub fn set_limits(&mut self, limits: crate::runtime::ExecutionLimits) {
732        self.limits = limits;
733    }
734
735    /// Get execution limits (public API)
736    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    /// Create a new evaluator (默认禁用IO)
765    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    /// Create a new evaluator with custom IO permissions
773    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    /// Create a new evaluator with custom IO permissions and trace buffer size
778    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        // Register built-in functions with permissions
785        let registry = BuiltInRegistry::with_permissions(permissions);
786        Self::register_builtins_into_env(&registry, &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    /// Create evaluator with custom environment
820    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    /// Clear the call stack (used by top-level entry points like `Aether::eval`).
854    pub fn clear_call_stack(&mut self) {
855        self.call_stack.clear();
856    }
857
858    /// Configure the module resolver used for `Import/Export`.
859    pub fn set_module_resolver(&mut self, resolver: Box<dyn ModuleResolver>) {
860        self.module_resolver = resolver;
861    }
862
863    /// Push a base directory context for resolving relative imports.
864    ///
865    /// This is typically used by CLI `eval_file()` wrappers.
866    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    /// Pop the most recent base directory context.
874    pub fn pop_import_base(&mut self) {
875        self.import_base_stack.pop();
876    }
877
878    /// 追加一条**无级别**的 TRACE 记录(`TRACE(...)` 脚本内置函数)。
879    ///
880    /// 统一存储为结构化条目(level=Info、category=TRACE、label 为
881    /// 首个字符串参数),`trace_by_label` / `trace_by_category` 对脚本
882    /// TRACE 同样生效;字符串视图由 [`Self::take_trace`] 派生。
883    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    /// Push a structured trace entry(唯一存储路径)
896    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    /// Drain the trace buffer:结构化条目派生为字符串后清空。
907    ///
908    /// - `TRACE(...)` 条目(category=TRACE)保持历史格式
909    ///   `#N payload` / `#N [label] payload`(CLI `--trace` 输出不变);
910    /// - 级别条目(TRACE_DEBUG 等)为 `#N [LEVEL:category] payload`。
911    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    /// Get all structured trace entries
931    pub fn trace_records(&self) -> Vec<crate::runtime::TraceEntry> {
932        self.trace_entries.iter().cloned().collect()
933    }
934
935    /// Filter trace entries by level
936    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    /// Filter trace entries by category
948    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    /// Filter trace entries by label
957    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    /// Filter trace entries by time range (since)
966    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    /// Apply complex filter to trace entries
975    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    /// Get trace statistics
987    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    /// Clear the trace buffer.
1008    pub fn clear_trace(&mut self) {
1009        self.trace_entries.clear();
1010        self.trace_seq = 0;
1011    }
1012
1013    /// Set the maximum number of trace entries to keep in buffer
1014    ///
1015    /// If the new size is smaller than the current number of entries,
1016    /// excess entries will be removed from the front of the buffer.
1017    pub fn set_trace_buffer_size(&mut self, size: usize) {
1018        self.trace_buffer_size = size;
1019
1020        // Trim existing buffer if necessary
1021        while self.trace_entries.len() > size {
1022            self.trace_entries.pop_front();
1023        }
1024    }
1025
1026    /// Set the big-integer threshold used when parsing imported modules
1027    pub fn set_bigint_threshold(&mut self, threshold: usize) {
1028        self.bigint_threshold = threshold;
1029    }
1030
1031    /// Reset the environment (clear all variables and re-register built-ins)
1032    ///
1033    /// This is useful for engine pooling and global singleton patterns
1034    /// where you want to reuse an engine instance but ensure isolation.
1035    pub fn reset_env(&mut self) {
1036        // Create new environment
1037        self.env = Rc::new(RefCell::new(Environment::new()));
1038
1039        // Avoid leaking trace across pooled executions
1040        self.trace_entries.clear();
1041        self.trace_seq = 0;
1042
1043        // Reset module contexts (cache is kept; can be cleared explicitly by host if needed)
1044        self.import_base_stack.clear();
1045        self.export_stack.clear();
1046        self.module_stack.clear();
1047
1048        // Avoid leaking call stack across pooled executions
1049        self.call_stack.clear();
1050
1051        // Re-register built-in functions
1052        Self::register_builtins_into_env(&self.registry, &mut self.env.borrow_mut());
1053    }
1054
1055    /// Set a global variable from the host (without requiring `eval`).
1056    pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
1057        self.env.borrow_mut().set(name.into(), value);
1058    }
1059
1060    /// Get a global variable value from the environment
1061    pub fn get_global(&self, name: &str) -> Option<Value> {
1062        self.env.borrow().get(name)
1063    }
1064
1065    /// Enter a child scope (new environment whose parent is the current env).
1066    ///
1067    /// Returns the previous environment handle; pass it back to `restore_env()`.
1068    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    /// Restore a previously saved environment handle (typically from `enter_child_scope()`).
1076    pub fn restore_env(&mut self, prev: Rc<RefCell<Environment>>) {
1077        self.env = prev;
1078    }
1079
1080    /// Evaluate a program
1081    pub fn eval_program(&mut self, program: &Program) -> EvalResult {
1082        // Record start time for timeout checking
1083        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    /// Evaluate a statement
1097    pub fn eval_statement(&mut self, stmt: &Stmt) -> EvalResult {
1098        // Check execution limits before each statement
1099        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                // Evaluate the value to be assigned
1115                let val = self.eval_expression(value)?;
1116
1117                // For simple identifier objects, we can modify in place
1118                if let Expr::Identifier(name) = object.as_ref() {
1119                    // Get the object from environment
1120                    let obj = self
1121                        .env
1122                        .borrow()
1123                        .get(name)
1124                        .ok_or_else(|| RuntimeError::UndefinedVariable(name.clone()))?;
1125
1126                    // Evaluate the index
1127                    let idx_val = self.eval_expression(index)?;
1128
1129                    // Modify based on object type
1130                    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                    // Update the variable in environment
1157                    self.env.borrow_mut().set(name.clone(), new_obj);
1158                    Ok(val)
1159                } else {
1160                    // For complex expressions, we can't modify in place
1161                    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                // 生成器定义 = 模板内核(捕获当前环境)。
1182                // 调用 `Set G NAME(args)` 时由 call_function 的 Generator 分支
1183                // 绑定参数并派生新实例;NEXT 时急切收集。
1184                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                    // 生成器收集期间:收入缓冲并继续执行函数体
1215                    Some(sink) => {
1216                        sink.borrow_mut().push(val);
1217                        Ok(Value::Null)
1218                    }
1219                    // 顶层(或普通函数中)的 Yield 是错误
1220                    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                // 生成器先急切收集(副作用恰好一次),再按数组迭代
1267                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                // 生成器先急切收集(副作用恰好一次),再按数组迭代
1311                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    /// Evaluate an expression
1396    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                // 解析期已构造完成,直接包装为分母为 1 的分数
1402                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                // 读取即强制:Lazy 在第一次被读取时求值并记忆化
1424                match val {
1425                    Value::Lazy { .. } => self.force_lazy(name),
1426                    forced => Ok(forced),
1427                }
1428            }
1429
1430            Expr::Binary { left, op, right } => {
1431                // Short-circuit evaluation for And and Or
1432                match op {
1433                    BinOp::And => {
1434                        let left_val = self.eval_expression(left)?;
1435                        if !left_val.is_truthy() {
1436                            // Short-circuit: left is falsy, return left without evaluating right
1437                            Ok(left_val)
1438                        } else {
1439                            // left is truthy, return right value
1440                            self.eval_expression(right)
1441                        }
1442                    }
1443                    BinOp::Or => {
1444                        let left_val = self.eval_expression(left)?;
1445                        if left_val.is_truthy() {
1446                            // Short-circuit: left is truthy, return left without evaluating right
1447                            Ok(left_val)
1448                        } else {
1449                            // left is falsy, return right value
1450                            self.eval_expression(right)
1451                        }
1452                    }
1453                    // For other operators, evaluate both sides
1454                    _ => {
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                // Create a closure by capturing the current environment
1574                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    /// Evaluate binary operation
1586    /// 混合运算提升:Number → Fraction(数值核心统一规则)。
1587    ///
1588    /// 涉及 Fraction 的算术一律精确计算——整数经十进制字符串转换,
1589    /// 非整数经连分数重建(`0.5 + TO_FRACTION(1/3) == 5/6`)。
1590    /// 转换只对非有限值失败,此处给出可读错误。
1591    /// 两个分母为 1 的分数(整数)的乘法快速路径。
1592    ///
1593    /// `Ratio` 的算术运算符内置 gcd 规约,而 num-bigint 的二进制 gcd 对
1594    /// 大整数逐位移位:阶乘这类「大数 × 小整数」热循环中,大操作数低位
1595    /// 含大量零比特,规约反复对整个大数移位,总代价 O(n²)(2000 次累乘
1596    /// 需要 30 秒以上)。分母为 1 的整数乘整数恒为最简形式,直接
1597    /// `new_raw` 构造结果即可跳过规约。
1598    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    /// 位运算求值:& | ^ << >>
1613    ///
1614    /// 操作数必须是整数值(Number 需 fract()==0,Fraction 需分母为 1)。
1615    fn eval_bitwise_op(&self, left: &Value, op: &BinOp, right: &Value) -> EvalResult {
1616        use num_traits::ToPrimitive;
1617
1618        // 将操作数规整为 BigInt(整数)
1619        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                // 移位量转 usize;负数移位量不支持
1656                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        // 两侧都是小数值 Number 时返回 Number,保持小整数运算的现有行为;
1669        // 否则返回 Fraction(与 BigInt 求值约定一致)
1670        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                        // 如果两个数都是整数,且足够大,使用精确计算
1712                        if a.fract() == 0.0 && b.fract() == 0.0 {
1713                            // 检查是否超过 f64 的安全整数范围 (2^53)
1714                            let max_safe = 9007199254740992.0; // 2^53
1715                            if a.abs() > max_safe || b.abs() > max_safe {
1716                                // 使用 Fraction (BigInt) 进行精确计算
1717                                use num_bigint::BigInt;
1718                                use num_rational::Ratio;
1719
1720                                // 将 f64 转换为字符串再转为 BigInt,避免精度损失
1721                                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            // And/Or 在 eval_expression 中短路求值,正常不会到达此处
1848            // (保留穷尽臂以防未来新增调用路径时静默错误)
1849            BinOp::And | BinOp::Or => Err(RuntimeError::InvalidOperation(
1850                "逻辑运算符必须在表达式求值中短路处理".to_string(),
1851            )),
1852        }
1853    }
1854
1855    /// Evaluate unary operation
1856    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    /// Call a function with arguments
1871    fn call_function(
1872        &mut self,
1873        name_hint: Option<&str>,
1874        func: &Value,
1875        args: Vec<Value>,
1876    ) -> EvalResult {
1877        // Check recursion depth limit
1878        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                // Create new environment for function execution
1937                let func_env = Rc::new(RefCell::new(Environment::with_parent(Rc::clone(env))));
1938
1939                // Bind parameters
1940                for (param, arg) in params.iter().zip(args.iter()) {
1941                    func_env.borrow_mut().set(param.clone(), arg.clone());
1942                }
1943
1944                // Execute function body
1945                let prev_env = Rc::clone(&self.env);
1946                self.env = func_env;
1947
1948                // 函数体求值期间切换到定义文件:模块内函数体的行断点按定义文件命中
1949                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                // 具名用户函数入口的函数断点检查(lambda 无名,跳过)。
1955                // 在参数绑定与作用域切换之后进行:暂停时 `print` 可见参数,
1956                // 暂停位置同步指向函数体首条语句
1957                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                // Special handling for TRACE functions
2006                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                        // Optional label: TRACE("label", x, y)
2022                        // If only one argument is provided, treat it as the payload (backward compatible).
2023                        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                        // Structured TRACE functions (Stage 3.2)
2037                        // Usage: TRACE_DEBUG("category", value1, value2, ...)
2038                        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                        // Parse level from function name
2052                        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                        // Parse category
2061                        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                        // Collect values (args[1..])
2078                        let values = args[1..].to_vec();
2079
2080                        // Create and push structured entry
2081                        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/DONE 需要驱动求值器(收集函数体),
2090                    // 无法作为纯 builtin 实现,在此按名拦截
2091                    // (builtins 侧注册了永错存根,仅用于名字解析)
2092                    "NEXT" => self.builtin_next(&args),
2093                    "DONE" => self.builtin_done(&args),
2094                    _ => {
2095                        // Get the built-in function from the registry
2096                        if let Some((func, _arity)) = self.registry.get(name) {
2097                            // Call the built-in function
2098                            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            // 调用生成器定义 `Set G NAME(args)`:绑定参数,派生新实例
2117            // (内核不共享——每次调用产生独立的消费序列;
2118            //   直接克隆生成器值 `Set G2 G` 才共享消费状态)
2119            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    /// 急切收集生成器:首次触发时完整执行函数体**一次**。
2163    ///
2164    /// - 挂载 `yield_sink`,Stmt::Yield 将值收入缓冲并继续;
2165    /// - `Return` 提前结束收集(其后的 Yield 自然不发生);
2166    /// - 走 enter_call/步数限制:无限生成器触发 ExecutionLimits 报错
2167    ///   而非挂死;
2168    /// - 结果写入内核 `collected`,之后 NEXT 按位置弹出。
2169    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        // 先取走定义信息,避免跨求值持有 RefCell 借用
2177        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                // Return 提前结束收集(值丢弃,语义为「提前完成」)
2195                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    /// NEXT(G):弹出下一个 Yield 值;耗尽后返回 Null(不报错)。
2214    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    /// DONE(G):是否已消费完(未开始收集时为 false)。
2247    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    /// 强制求值 Lazy 变量:读取即触发,首次求值后写回记忆化。
2272    ///
2273    /// 在 Lazy 自带的环境中求值表达式;enter_call 提供递归保护
2274    /// (自引用 `Lazy Y (Y + 1)` 触发递归上限而非死循环)。
2275    /// 求值成功后以结果值**替换**两个作用域中的 Lazy 槽位
2276    /// (定义作用域 update + 当前读取作用域 set)。
2277    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        // 循环定义检测:求值期间再次读取自身(直接或间接)立即报错,
2296        // 不进入递归——树遍历解释器的深层递归会先撑爆原生栈
2297        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
2313        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    // 实现 MAP 内置函数
2319    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    // 实现 FILTER 内置函数
2349    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    // 实现 REDUCE 内置函数
2381    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        // Parse module
2540        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        // Evaluate in an isolated environment with builtins registered.
2553        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        // Push module import base (for relative imports inside the module)
2559        self.import_base_stack.push(ModuleContext {
2560            module_id: resolved.module_id.clone(),
2561            base_dir: resolved.base_dir.clone(),
2562        });
2563
2564        // Push export table
2565        self.export_stack.push(HashMap::new());
2566
2567        // 模块求值期间切换当前源文件,使调试器可按 模块:行号 设置断点
2568        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        // Pop stacks and restore env (must happen even on error)
2574        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        // Pop module stack
2580        let _ = self.module_stack.pop();
2581
2582        // Propagate module evaluation error (cleanup already done)
2583        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}