-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-vm.h
More file actions
124 lines (106 loc) · 2.25 KB
/
stack-vm.h
File metadata and controls
124 lines (106 loc) · 2.25 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
#ifndef STACK_VM_H
#define STACK_VM_H
#include <stdint.h>
#include <stdbool.h>
// --------------- 类型系统 ---------------
// 常量定义
#define MAX_PROPS 64
// 值类型枚举
typedef enum {
VAL_NUMBER,
VAL_STRING,
VAL_BOOLEAN,
VAL_UNDEFINED,
VAL_NULL,
VAL_OBJECT
} ValueType;
// 前向声明
typedef struct Value Value;
typedef struct Env Env;
// 对象头
typedef struct ObjectHeader {
int ref_count;
ValueType type;
} ObjectHeader;
// 字符串对象
typedef struct {
ObjectHeader header;
size_t length;
char* chars;
} StringObject;
// 基础对象
typedef struct {
ObjectHeader header;
int property_count;
char** prop_names;
Value* prop_values;
} Object;
// 值类型
struct Value {
ValueType type;
union {
double number;
bool boolean;
ObjectHeader* obj;
} data;
};
// --------------- 变量环境 ---------------
#define MAX_VARS 32
// 环境结构体
struct Env {
char* names[MAX_VARS];
Value values[MAX_VARS];
int var_count;
Env* parent;
};
// --------------- 栈式虚拟机 ---------------
typedef struct {
Value stack[64];
int sp;
Env* current_env;
int call_stack[16];
int call_sp;
} StackVM;
// --------------- 字节码指令 ---------------
typedef enum {
OP_PUSH_NUM,
OP_PUSH_STR,
OP_PUSH_BOOL,
OP_PUSH_UNDEFINED,
OP_PUSH_NULL,
OP_PUSH_VAR,
OP_STORE_VAR,
OP_ADD,
OP_CALL,
OP_RET,
OP_PRINT,
OP_EXIT,
OP_NEW_OBJECT,
OP_SET_PROP,
OP_GET_PROP,
OP_PUSH_ENV,
OP_POP_ENV
} OpCode;
// --------------- 函数声明 ---------------
// 值操作
Value val_number(double num);
Value val_boolean(bool b);
Value val_undefined();
Value val_null();
Value val_string(const char* str);
Value val_object();
void val_free(Value v);
// 环境操作
Value env_get(Env* env, const char* name);
void env_set(Env* env, const char* name, Value val);
Env* create_env(Env* parent);
void free_env(Env* env);
// 虚拟机操作
void vm_init(StackVM* vm);
void vm_push(StackVM* vm, Value val);
Value vm_pop(StackVM* vm);
void vm_pop_free(StackVM* vm);
void vm_call(StackVM* vm, int func_ip);
int vm_ret(StackVM* vm);
void vm_execute(StackVM* vm, const uint8_t* bytecode, int len);
#endif // STACK_VM_H