This repository was archived by the owner on Nov 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
250 lines (218 loc) · 7.48 KB
/
mod.rs
File metadata and controls
250 lines (218 loc) · 7.48 KB
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
pub mod serializer;
/// Zero语言的字节码指令集
#[derive(Debug, Clone, PartialEq)]
pub enum OpCode {
// 常量加载
LoadConst(usize), // 加载常量池中的值
LoadNull, // 加载null值
// 变量操作
LoadLocal(usize), // 加载局部变量
StoreLocal(usize), // 存储局部变量
LoadGlobal(usize), // 加载全局变量
StoreGlobal(usize), // 存储全局变量
// 算术运算
Add, // 加法
Subtract, // 减法
Multiply, // 乘法
Divide, // 除法
Modulo, // 取模
Negate, // 取负
// 比较运算
Equal, // 相等
NotEqual, // 不相等
Greater, // 大于
GreaterEqual, // 大于等于
Less, // 小于
LessEqual, // 小于等于
// 逻辑运算
Not, // 逻辑非
And, // 逻辑与
Or, // 逻辑或
// 控制流
Jump(usize), // 无条件跳转
JumpIfFalse(usize), // 条件跳转(假)
JumpIfTrue(usize), // 条件跳转(真)
Loop(usize), // 循环跳转
// 函数相关
Call(usize), // 函数调用(参数数量)
Return, // 返回
// 数组操作
NewArray(usize), // 创建新数组(参数:元素数量)
ArrayGet, // 获取数组元素 (array, index -> value)
ArraySet, // 设置数组元素 (array, index, value -> value)
ArrayLen, // 获取数组长度 (array -> length)
// 结构体操作
NewStruct(usize), // 创建新结构体(参数:字段数量)
FieldGet(usize), // 获取结构体字段 (struct, field_index -> value)
FieldSet(usize), // 设置结构体字段 (struct, field_index, value -> value)
// 栈操作
Pop, // 弹出栈顶
Dup, // 复制栈顶
// 其他
Print, // 打印
Halt, // 停止执行
}
/// 常量值类型
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Integer(i64),
Float(f64),
String(String),
Boolean(bool),
Char(char), // 字符值
Array(Vec<Value>), // 数组值
Struct(StructValue), // 结构体值
Function(Function),
Null,
}
/// 结构体值
#[derive(Debug, Clone, PartialEq)]
pub struct StructValue {
pub struct_name: String,
pub fields: Vec<Value>, // 按字段定义顺序存储
}
impl Value {
pub fn to_string(&self) -> String {
match self {
Value::Integer(i) => i.to_string(),
Value::Float(f) => f.to_string(),
Value::String(s) => s.clone(),
Value::Boolean(b) => b.to_string(),
Value::Char(c) => c.to_string(),
Value::Array(arr) => {
let elements: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
format!("[{}]", elements.join(", "))
}
Value::Struct(s) => {
format!("{} {{ {} fields }}", s.struct_name, s.fields.len())
}
Value::Function(_) => "<function>".to_string(),
Value::Null => "null".to_string(),
}
}
pub fn is_truthy(&self) -> bool {
match self {
Value::Boolean(b) => *b,
Value::Null => false,
Value::Integer(0) => false,
Value::Float(f) if *f == 0.0 => false,
Value::Array(arr) => !arr.is_empty(),
Value::Struct(_) => true,
_ => true,
}
}
pub fn as_integer(&self) -> Option<i64> {
match self {
Value::Integer(i) => Some(*i),
_ => None,
}
}
pub fn as_float(&self) -> Option<f64> {
match self {
Value::Float(f) => Some(*f),
Value::Integer(i) => Some(*i as f64),
_ => None,
}
}
pub fn as_array(&self) -> Option<&Vec<Value>> {
match self {
Value::Array(arr) => Some(arr),
_ => None,
}
}
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
match self {
Value::Array(arr) => Some(arr),
_ => None,
}
}
pub fn as_struct(&self) -> Option<&StructValue> {
match self {
Value::Struct(s) => Some(s),
_ => None,
}
}
pub fn as_struct_mut(&mut self) -> Option<&mut StructValue> {
match self {
Value::Struct(s) => Some(s),
_ => None,
}
}
}
/// 函数对象
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: String,
pub arity: usize, // 参数数量
pub chunk: Chunk, // 函数字节码
pub locals_count: usize, // 局部变量数量
}
/// 字节码块
#[derive(Debug, Clone, PartialEq)]
pub struct Chunk {
pub code: Vec<OpCode>, // 指令序列
pub constants: Vec<Value>, // 常量池
pub lines: Vec<usize>, // 行号信息(用于错误报告)
}
impl Chunk {
pub fn new() -> Self {
Chunk {
code: Vec::new(),
constants: Vec::new(),
lines: Vec::new(),
}
}
/// 添加指令
pub fn write(&mut self, op: OpCode, line: usize) {
self.code.push(op);
self.lines.push(line);
}
/// 添加常量到常量池
pub fn add_constant(&mut self, value: Value) -> usize {
self.constants.push(value);
self.constants.len() - 1
}
/// 获取指令数量
pub fn len(&self) -> usize {
self.code.len()
}
/// 反汇编(用于调试)
pub fn disassemble(&self, name: &str) {
println!("== {} ==", name);
for (offset, op) in self.code.iter().enumerate() {
self.disassemble_instruction(offset, op);
}
}
pub fn disassemble_instruction(&self, offset: usize, op: &OpCode) {
print!("{:04} ", offset);
if offset > 0 && self.lines[offset] == self.lines[offset - 1] {
print!(" | ");
} else {
print!("{:4} ", self.lines[offset]);
}
match op {
OpCode::LoadConst(idx) => {
println!("LoadConst {} '{:?}'", idx, self.constants.get(*idx));
}
OpCode::LoadLocal(idx) => println!("LoadLocal {}", idx),
OpCode::StoreLocal(idx) => println!("StoreLocal {}", idx),
OpCode::LoadGlobal(idx) => println!("LoadGlobal {}", idx),
OpCode::StoreGlobal(idx) => println!("StoreGlobal {}", idx),
OpCode::Jump(offset) => println!("Jump -> {}", offset),
OpCode::JumpIfFalse(offset) => println!("JumpIfFalse -> {}", offset),
OpCode::JumpIfTrue(offset) => println!("JumpIfTrue -> {}", offset),
OpCode::Loop(offset) => println!("Loop -> {}", offset),
OpCode::Call(arity) => println!("Call({})", arity),
OpCode::NewArray(size) => println!("NewArray({})", size),
OpCode::NewStruct(field_count) => println!("NewStruct({})", field_count),
OpCode::FieldGet(idx) => println!("FieldGet({})", idx),
OpCode::FieldSet(idx) => println!("FieldSet({})", idx),
_ => println!("{:?}", op),
}
}
}
impl Default for Chunk {
fn default() -> Self {
Self::new()
}
}