-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm.h
142 lines (132 loc) · 2.51 KB
/
vm.h
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
#pragma once
#include <vector>
#include <iostream>
#include "compiler.h"
enum class svType : uint32_t
{
num,
_bool,
stackFrame,
hv
};
enum class hvType : uint32_t
{
string
};
struct hv
{
~hv()
{
switch (type)
{
case hvType::string:
delete str;
break;
}
}
int refCount;
hvType type;
union
{
std::string* str;
};
};
struct sf
{
uint32_t returnPc;
uint32_t returnSf;
uint32_t numParams;
};
struct sv
{
sv(const sv& other)
{
*this = other;
}
sv& operator=(const sv& other)
{
type = other.type;
switch (type)
{
case svType::num:
num = other.num;
break;
case svType::_bool:
b = other.b;
break;
case svType::stackFrame:
sf = other.sf;
break;
case svType::hv:
heapVal = other.heapVal;
heapVal->refCount++;
//std::cout << "inc copy" << std::endl;
break;
}
return *this;
}
~sv()
{
if (type == svType::hv)
{
//std::cout << "dec" << std::endl;
if (0 >= --(heapVal->refCount))
{
switch (heapVal->type)
{
case hvType::string:
{
delete heapVal;
heapVal = nullptr;
}
break;
}
}
}
}
sv(double num)
{
type = svType::num;
this->num = num;
}
sv(bool b)
{
type = svType::_bool;
this->b = b;
}
sv(sf sf)
{
type = svType::stackFrame;
this->sf = sf;
}
sv(hv* hv)
{
type = svType::hv;
this->heapVal = hv;
hv->refCount++;
//std::cout << "inc hv*" << std::endl;
}
svType type;
union
{
double num;
bool b;
struct sf sf;
hv* heapVal;
};
};
class vm
{
public:
vm(std::map<std::string, Function> functions, std::vector<std::string> stringTable, std::vector<uint64_t> bc);
sv Run(std::string func, const std::vector<sv>& params);
void Register(std::string name, std::function<sv(std::vector<sv>&)> func);
private:
std::string StackToString();
std::vector<uint64_t> bc;
std::map<std::string, Function> functions;
std::vector<sv> s;
std::vector<hv*> strTable;
uint32_t pc;
uint32_t sf;
};