Skip to main content

quickpython/
bytecode.rs

1/// Bytecode instructions for the VM
2#[derive(Debug, Clone, PartialEq)]
3pub enum Instruction {
4    // 栈操作
5    PushInt(i32),
6    PushFloat(f64),
7    PushBool(bool),
8    PushNone,
9    PushString(String),
10    Pop,
11
12    // 算术运算
13    Add,
14    Sub,
15    Mul,
16    Div,
17    Mod,    // 模运算
18    Negate, // 一元负号
19
20    // 比较运算
21    Eq,
22    Ne,
23    Lt,
24    Le,
25    Gt,
26    Ge,
27
28    // 变量
29    GetGlobal(String),
30    SetGlobal(String),
31    GetLocal(usize),
32    SetLocal(usize),
33
34    // 控制流
35    Jump(usize),
36    JumpIfFalse(usize),
37
38    // 函数
39    MakeFunction {
40        name: String,
41        params: Vec<String>,
42        code_len: usize,
43    },
44    Call(usize), // 参数数量
45    Return,
46
47    // 内置函数
48    Print(usize), // print() 函数,参数是要打印的值的数量
49    Int,          // int() 类型转换
50    Float,        // float() 类型转换
51    Len,          // len() 函数
52    Range,        // range() 函数,参数数量在栈上
53
54    // 列表和字典
55    BuildList(usize),          // 从栈顶取 n 个元素构建列表
56    BuildDict(usize),          // 从栈顶取 n*2 个元素构建字典(键值对)
57    GetItem,                   // 索引访问 list[i] 或 dict[key]
58    SetItem,                   // 索引赋值 list[i] = x 或 dict[key] = x
59    CallMethod(String, usize), // 方法调用 obj.method(args)
60
61    // 迭代器和 for 循环
62    GetIter,        // 获取对象的迭代器
63    ForIter(usize), // 迭代下一个元素,如果结束则跳转到指定位置
64    Break,          // 跳出循环
65    Continue,       // 继续下一次循环迭代
66
67    // 异常处理
68    Raise,                                      // 抛出异常,栈顶是异常对象
69    MakeException(crate::value::ExceptionType), // 创建异常,栈顶是消息字符串
70    SetupTry(usize),                            // 设置 try 块,参数是 except 块的位置
71    PopTry,                                     // 移除 try 块(正常结束时)
72    GetExceptionType,                           // 获取异常类型(用于类型检查)
73    MatchException,                             // 检查异常类型是否匹配(支持继承)
74    Dup,                                        // 复制栈顶元素
75    SetupFinally(usize),                        // 设置 finally 块,参数是 finally 块的位置
76    PopFinally,                                 // 移除 finally 块
77    EndFinally,                                 // 结束 finally 块,检查是否需要重新抛出异常
78
79    // 模块导入
80    Import(String),  // 导入模块,参数是模块名
81    GetAttr(String), // 获取对象属性,参数是属性名
82}
83
84pub type ByteCode = Vec<Instruction>;