Skip to main content

onion_vm/lambda/
runnable.rs

1
2//! Onion 虚拟机运行时调度核心 trait 和类型定义。
3//! 
4//! 包含任务调度的错误类型、步骤结果类型、调度 trait 及辅助宏。
5use std::fmt::Display;
6
7use arc_gc::gc::GC;
8
9use crate::{
10    lambda::scheduler::async_scheduler::Task,
11    types::object::{OnionObjectCell, OnionStaticObject},
12};
13
14
15/// 虚拟机运行时错误类型。
16/// 
17/// 用于描述调度和执行过程中可能出现的各种错误。
18#[derive(Clone, Debug)]
19pub enum RuntimeError {
20    /// 当前指令需要重复检查直到条件满足(如异步等待)
21    Pending,
22    /// 引用失效或悬空
23    BrokenReference,
24    /// 步骤执行错误,带详细信息
25    StepError(Box<str>),
26    /// 详细错误信息
27    DetailedError(Box<str>),
28    /// 类型错误
29    InvalidType(Box<str>),
30    /// 非法操作
31    InvalidOperation(Box<str>),
32    /// 自定义错误值(可携带任意对象)
33    CustomValue(Box<OnionStaticObject>),
34    /// 借用相关错误
35    BorrowError(Box<str>),
36}
37
38impl Display for RuntimeError {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            RuntimeError::Pending => write!(f, "Pending: The operation is not yet complete"),
42            RuntimeError::StepError(msg) => write!(f, "Step Error: {}", msg),
43            RuntimeError::DetailedError(msg) => write!(f, "{}", msg),
44            RuntimeError::InvalidType(msg) => write!(f, "Invalid type: {}", msg),
45            RuntimeError::InvalidOperation(msg) => write!(f, "Invalid operation: {}", msg),
46            RuntimeError::BrokenReference => write!(f, "Broken reference encountered"),
47            RuntimeError::BorrowError(msg) => write!(f, "Borrow error: {}", msg),
48            RuntimeError::CustomValue(value) => write!(f, "Custom value error: {}", value),
49        }
50    }
51}
52
53
54/// 步骤执行结果类型。
55/// 
56/// 用于描述一次 step 调用后的调度决策。
57pub enum StepResult {
58    /// 继续当前任务
59    Continue,
60    /// 生成一个新的 Runnable 并压栈
61    NewRunnable(Box<dyn Runnable>),
62    /// 替换当前 Runnable
63    ReplaceRunnable(Box<dyn Runnable>),
64    /// 生成一个新的异步任务(如协程)
65    SpawnRunnable(Box<Task>),
66    /// 返回结果并结束当前任务
67    Return(Box<OnionStaticObject>),
68    /// 发生错误
69    Error(RuntimeError),
70}
71
72/// 辅助宏:用于简化 Result 到 StepResult 的转换。
73/// 
74/// 若 Result 为 Ok,返回值;若为 Err,直接返回 StepResult::Error。
75#[macro_export]
76macro_rules! unwrap_step_result {
77    ($result:expr) => {
78        match $result {
79            Ok(value) => value,
80            Err(error) => return StepResult::Error(error),
81        }
82    };
83}
84
85
86/// Onion 虚拟机调度核心 trait。
87/// 
88/// 所有可调度对象需实现 Runnable trait,支持 step、receive、format_context 三大接口。
89pub trait Runnable: Send + Sync + 'static {
90    /// 推进任务执行一步。
91    /// 
92    /// # 参数
93    /// * `gc` - 垃圾收集器引用
94    /// 
95    /// # 返回值
96    /// 返回 StepResult,指示调度器下一步动作
97    fn step(&mut self, gc: &mut GC<OnionObjectCell>) -> StepResult;
98
99    /// 接收子任务的结果。
100    /// 
101    /// # 参数
102    /// * `step_result` - 子任务的执行结果
103    /// * `gc` - 垃圾收集器引用
104    /// 
105    /// # 返回值
106    /// * Ok(()) - 成功处理
107    /// * Err(RuntimeError) - 默认未实现
108    #[allow(unused_variables)]
109    fn receive(
110        &mut self,
111        step_result: &StepResult,
112        gc: &mut GC<OnionObjectCell>,
113    ) -> Result<(), RuntimeError> {
114        Err(RuntimeError::DetailedError(
115            "receive not implemented".into(),
116        ))
117    }
118
119    /// 格式化当前任务的上下文信息,便于调试。
120    fn format_context(&self) -> String;
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn check_step_result_size() {
129        println!("Size of StepResult: {}", std::mem::size_of::<StepResult>());
130    }
131}