onion-vm 0.3.4

Virtual machine runtime for the Onion programming language with async execution and garbage collection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Onion 虚拟机执行上下文与帧管理。
//!
//! - `Frame`:单个执行帧,包含变量表和操作数栈。
//! - `Context`:多帧调用栈,支持变量作用域、栈操作、帧切换等。
//! - 提供丰富的栈操作、变量管理与调试辅助方法。

use rustc_hash::FxHashMap as HashMap;

use crate::{
    lambda::runnable::RuntimeError,
    types::{
        lambda::vm_instructions::instruction_set::VMInstructionPackage, object::OnionStaticObject,
    },
    utils::format_object_summary,
};

/// 虚拟机执行帧。
///
/// 包含变量表和操作数栈,代表一次函数调用或执行环境。
#[derive(Clone, Debug)]
pub struct Frame {
    /// 变量表,key 为常量池索引
    variables: HashMap<usize, OnionStaticObject>,
    /// 操作数栈
    stack: Vec<OnionStaticObject>,
}

impl Frame {
    pub fn new() -> Self {
        Frame {
            variables: HashMap::default(),
            stack: Vec::new(),
        }
    }
    #[inline(always)]
    pub fn get_stack(&self) -> &Vec<OnionStaticObject> {
        &self.stack
    }
    #[inline(always)]
    pub fn get_stack_mut(&mut self) -> &mut Vec<OnionStaticObject> {
        &mut self.stack
    }

    pub fn format_context(&self, package: &VMInstructionPackage) -> String {
        let mut parts = Vec::new();
        let string_pool = package.get_string_pool();

        // --- Part 1: Format Variables ---
        if self.variables.is_empty() {
            parts.push("  - Variables: (none)".to_string());
        } else {
            parts.push("  - Variables:".to_string());
            for (id, value) in &self.variables {
                // [关键修改] 使用 id 从 string_pool 中查找变量名
                let var_name = string_pool
                    .get(*id)
                    .map(|s| s.as_ref())
                    .unwrap_or("<Unknown Var>");

                let value_summary = format_object_summary(value.weak());
                parts.push(format!("    - {}: {}", var_name, value_summary));
            }
        }

        // --- Part 2: Format Operand Stack ---
        if self.stack.is_empty() {
            parts.push("  - Operand Stack: (empty)".to_string());
        } else {
            parts.push(format!("  - Operand Stack ({} items):", self.stack.len()));
            for (i, value) in self.stack.iter().rev().enumerate() {
                // [修改点] 在这里也使用辅助函数
                let value_summary = format_object_summary(value.weak());
                parts.push(format!("    - [Top - {}]: {}", i, value_summary));
            }
        }

        parts.join("\n")
    }
}

/// Onion 虚拟机执行上下文。
///
/// 管理多帧调用栈,支持作用域、变量、栈和帧的各种操作。
#[derive(Clone)]
pub struct Context {
    /// 调用帧栈,栈顶为当前活跃帧
    frames: Vec<Frame>,
}

impl Context {
    pub fn new() -> Self {
        Context { frames: Vec::new() }
    }

    pub fn push_frame(&mut self, frame: Frame) {
        self.frames.push(frame);
    }

    pub fn pop_frame(&mut self) -> Result<Frame, RuntimeError> {
        match self.frames.pop() {
            Some(frame) => Ok(frame),
            None => Err(RuntimeError::DetailedError(
                "Cannot pop frame from empty context".into(),
            )),
        }
    }
    pub fn concat_last_frame(&mut self) -> Result<(), RuntimeError> {
        if self.frames.len() < 2 {
            return Ok(());
        }

        let last_frame = self.frames.pop().unwrap();
        let second_last_frame = self.frames.last_mut().unwrap();
        second_last_frame.stack.extend(last_frame.stack);
        Ok(())
    }
    pub fn clear_stack(&mut self) {
        if self.frames.len() > 0 {
            self.frames.last_mut().unwrap().stack.clear();
        }
    }

    pub fn push_object(&mut self, object: OnionStaticObject) -> Result<(), RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot push object to empty context".into(),
            ));
        }
        self.frames.last_mut().unwrap().stack.push(object);
        Ok(())
    }

    pub fn pop(&mut self) -> Result<OnionStaticObject, RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot pop object from empty context".into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        if last_frame.get_stack().len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot pop object from empty stack".into(),
            ));
        }
        let stack = last_frame.get_stack_mut();
        Ok(stack.pop().unwrap())
    }

    pub fn discard_objects(&mut self, count: usize) -> Result<(), RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot discard objects from empty context"
                    .to_string()
                    .into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        let stack = last_frame.get_stack_mut();
        if stack.len() < count {
            return Err(RuntimeError::DetailedError(
                "Cannot discard more objects than available in stack"
                    .to_string()
                    .into(),
            ));
        }
        stack.truncate(stack.len() - count);
        Ok(())
    }

    pub fn discard_objects_offset(
        &mut self,
        offset: usize,
        count: usize,
    ) -> Result<(), RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot discard objects from empty context"
                    .to_string()
                    .into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        let stack = last_frame.get_stack_mut();
        if stack.len() < offset + count {
            return Err(RuntimeError::DetailedError(
                "Cannot discard more objects than available in stack"
                    .to_string()
                    .into(),
            ));
        }

        // 使用 drain 一次性删除范围内的元素
        let remove_start = stack.len() - offset - count;
        let remove_end = stack.len() - offset;
        stack.drain(remove_start..remove_end);
        Ok(())
    }

    pub fn get_object_rev(&self, idx: usize) -> Result<&OnionStaticObject, RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot get object from empty context".into(),
            ));
        }
        let last_frame = self.frames.last().unwrap();
        if last_frame.get_stack().len() <= idx {
            return Err(RuntimeError::DetailedError(
                "Cannot get object from empty stack".into(),
            ));
        }
        let stack = last_frame.get_stack();
        match stack.get(stack.len() - 1 - idx) {
            None => Err(RuntimeError::DetailedError("Index out of bounds".into())),
            Some(o) => Ok(o),
        }
    }

    pub fn get_object_rev_mut(
        &mut self,
        idx: usize,
    ) -> Result<&mut OnionStaticObject, RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot get object from empty context".into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        if last_frame.get_stack().len() <= idx {
            return Err(RuntimeError::DetailedError(
                "Cannot get object from empty stack".into(),
            ));
        }
        let stack = last_frame.get_stack_mut();
        let idx = stack.len() - 1 - idx;
        match stack.get_mut(idx) {
            None => Err(RuntimeError::DetailedError("Index out of bounds".into())),
            Some(o) => Ok(o),
        }
    }

    #[inline(always)]
    pub fn let_variable(
        &mut self,
        name: usize,
        value: OnionStaticObject,
    ) -> Result<(), RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::InvalidOperation(
                "Cannot let variable in empty context".into(),
            ));
        }

        let last_frame = self.frames.last_mut().unwrap();
        last_frame.variables.insert(name, value);
        Ok(())
    }

    #[inline(always)]
    pub fn get_variable(&self, name: usize) -> Option<&OnionStaticObject> {
        if self.frames.len() == 0 {
            return None;
        } // 反向遍历所有帧,从最新的帧开始查找
        for frame in self.frames.iter().rev() {
            if let Some(value) = frame.variables.get(&name) {
                return Some(value);
            }
        }
        None
    }

    fn _debug_print(&self) {
        println!("Context Debug Print:");
        for (i, frame) in self.frames.iter().enumerate() {
            println!("Frame {}: {:?}", i, frame);
        }
    }

    pub fn get_variable_mut(&mut self, name: usize) -> Option<&mut OnionStaticObject> {
        if self.frames.len() == 0 {
            return None;
        } // 反向遍历所有帧,从最新的帧开始查找
        for frame in self.frames.iter_mut().rev() {
            if let Some(value) = frame.variables.get_mut(&name) {
                return Some(value);
            }
        }
        None
    }

    pub fn swap(&mut self, idx1: usize, idx2: usize) -> Result<(), RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot swap objects in empty context".into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        let stack = last_frame.get_stack_mut();
        if stack.len() <= idx1 || stack.len() <= idx2 {
            return Err(RuntimeError::DetailedError(
                "Cannot swap objects in empty stack".into(),
            ));
        }
        let len = stack.len();
        stack.swap(len - 1 - idx1, len - 1 - idx2);
        Ok(())
    }

    pub fn get_current_stack_mut(&mut self) -> Result<&mut Vec<OnionStaticObject>, RuntimeError> {
        if self.frames.len() == 0 {
            return Err(RuntimeError::DetailedError(
                "Cannot get stack from empty context".into(),
            ));
        }
        let last_frame = self.frames.last_mut().unwrap();
        Ok(last_frame.get_stack_mut())
    }

    #[inline(always)]
    pub fn push_to_stack(stack: &mut Vec<OnionStaticObject>, object: OnionStaticObject) {
        stack.push(object);
    }

    pub fn pop_from_stack(
        stack: &mut Vec<OnionStaticObject>,
    ) -> Result<OnionStaticObject, RuntimeError> {
        if stack.is_empty() {
            return Err(RuntimeError::DetailedError(
                "Cannot pop from empty stack".into(),
            ));
        }
        Ok(stack.pop().unwrap())
    }

    #[inline(always)]
    pub fn discard_from_stack(
        stack: &mut Vec<OnionStaticObject>,
        count: usize,
    ) -> Result<(), RuntimeError> {
        if stack.len() < count {
            return Err(RuntimeError::DetailedError(
                "Cannot discard more objects than available in stack"
                    .to_string()
                    .into(),
            ));
        }
        stack.truncate(stack.len() - count);
        Ok(())
    }

    #[inline(always)]
    pub fn get_object_from_stack(
        stack: &Vec<OnionStaticObject>,
        idx: usize,
    ) -> Result<&OnionStaticObject, RuntimeError> {
        if stack.len() <= idx {
            return Err(RuntimeError::DetailedError("Index out of bounds".into()));
        }
        Ok(&stack[stack.len() - 1 - idx])
    }

    #[inline(always)]
    pub fn get_objects_slice(
        stack: &Vec<OnionStaticObject>,
        idx: usize,
        len: usize,
    ) -> Result<&[OnionStaticObject], RuntimeError> {
        // 如果长度为0,直接返回空切片
        if len == 0 {
            return Ok(&[]);
        }

        if stack.len() <= idx {
            return Err(RuntimeError::DetailedError("Index out of bounds".into()));
        }

        if idx + len > stack.len() {
            return Err(RuntimeError::DetailedError(
                "Slice length exceeds available elements".into(),
            ));
        }

        let start = stack.len() - idx - len;
        let end = stack.len() - idx;
        Ok(&stack[start..end])
    }
    pub fn replace_last_object(stack: &mut Vec<OnionStaticObject>, object: OnionStaticObject) {
        let last_index = stack.len() - 1;
        stack[last_index] = object;
    }

    pub fn format_context(&self, package: &VMInstructionPackage) -> String {
        if self.frames.is_empty() {
            return "Context: (No active frames)".to_string();
        }

        let mut parts = Vec::new();
        parts.push(format!("Call Stack ({} frames):", self.frames.len()));

        // 从栈顶(最近的调用帧)开始打印
        for (i, frame) in self.frames.iter().rev().enumerate() {
            // 你需要一种方法来命名你的帧。这通常与函数名相关联。
            // 暂时我们用索引代替。
            parts.push(format!("--- Frame #{} (most recent) ---", i));

            // 调用我们刚刚为 Frame 实现的 format_context
            let frame_context = frame.format_context(package);
            parts.push(frame_context);
        }

        parts.join("\n")
    }
}