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
/// Bytecode instructions for the VM
#[derive(Debug, Clone, PartialEq)]
pub enum Instruction {
// 栈操作
PushInt(i32),
PushFloat(f64),
PushBool(bool),
PushNone,
PushString(String),
PushType(crate::value::TypeObject), // Push a type object
Pop,
// 算术运算
Add,
Sub,
Mul,
Div,
Mod, // 模运算
Negate, // 一元负号
// 比较运算
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
Contains, // Check if item in container (for 'in' operator)
NotContains, // Check if item not in container (for 'not in' operator)
Is, // Identity check (pointer equality)
IsNot, // Negated identity check
// 变量
GetGlobal(String),
SetGlobal(String),
GetLocal(usize),
SetLocal(usize),
// 控制流
Jump(usize),
JumpIfFalse(usize),
JumpIfFalseOrPop(usize), // If TOS is false, jump; else pop and continue (for 'and')
JumpIfTrueOrPop(usize), // If TOS is true, jump; else pop and continue (for 'or')
// 逻辑运算
Not, // Logical not: !TOS
// 函数
MakeFunction {
name: String,
params: Vec<String>,
code_len: usize,
is_async: bool,
is_generator: bool,
},
Call(usize), // 参数数量
Return,
// 内置函数
Print(usize), // print() 函数,参数是要打印的值的数量
Int, // int() 类型转换
Float, // float() 类型转换
Str, // str() 类型转换
Len, // len() 函数
Range, // range() 函数,参数数量在栈上
IsInstance, // isinstance() 函数,检查对象类型
// 列表和字典
BuildList(usize), // 从栈顶取 n 个元素构建列表
BuildDict(usize), // 从栈顶取 n*2 个元素构建字典(键值对)
BuildTuple(usize), // 从栈顶取 n 个元素构建元组
GetItem, // 索引访问 list[i] 或 dict[key]
SetItem, // 索引赋值 list[i] = x 或 dict[key] = x
BuildSlice, // 创建切片对象 (start, stop, step)
GetItemSlice, // 使用切片获取元素
CallMethod(String, usize), // 方法调用 obj.method(args)
UnpackSequence(usize), // 解包序列到 n 个值
// 迭代器和 for 循环
GetIter, // 获取对象的迭代器
ForIter(usize), // 迭代下一个元素,如果结束则跳转到指定位置
Break, // 跳出循环
Continue, // 继续下一次循环迭代
// 异常处理
Raise, // 抛出异常,栈顶是异常对象
MakeException(crate::value::ExceptionType), // 创建异常,栈顶是消息字符串
SetupTry(usize), // 设置 try 块,参数是 except 块的位置
PopTry, // 移除 try 块(正常结束时)
GetExceptionType, // 获取异常类型(用于类型检查)
MatchException, // 检查异常类型是否匹配(支持继承)
Dup, // 复制栈顶元素
SetupFinally(usize), // 设置 finally 块,参数是 finally 块的位置
PopFinally, // 移除 finally 块
EndFinally, // 结束 finally 块,检查是否需要重新抛出异常
// 模块导入
Import(String), // 导入模块,参数是模块名
GetAttr(String), // 获取对象属性,参数是属性名
// 异步支持
Await, // 等待协程完成
// 生成器支持
Yield, // 暂停生成器并返回值
}
pub type ByteCode = Vec<Instruction>;