-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.cpp
More file actions
102 lines (99 loc) · 1.64 KB
/
token.cpp
File metadata and controls
102 lines (99 loc) · 1.64 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
#include "insn.h"
#include <vector>
#include <iostream>
#include <fstream>
int *sp, stack[100], result;
unsigned char *pc;
clock_t st, ed;
bool iserr;
std::string input_path = "bytecode/bytecode.txt";
void exec(std::vector<unsigned char> bytecode)
{
pc = &bytecode[0];
sp = &stack[0];
static void *dispatch_table[] = {
&&nop,
&&int0,
&&int1,
&&int2,
&&int3,
&&int4,
&&int5,
&&int6,
&&int7,
&&int8,
&&add,
&&sub,
&&mul,
&&div,
&&ret,
};
st = clock();
#define DISPATCH() goto *dispatch_table[*pc++]
DISPATCH();
nop:
DISPATCH();
int0:
*sp++ = 0;
DISPATCH();
int1:
*sp++ = 1;
DISPATCH();
int2:
*sp++ = 2;
DISPATCH();
int3:
*sp++ = 3;
DISPATCH();
int4:
*sp++ = 4;
DISPATCH();
int5:
*sp++ = 5;
DISPATCH();
int6:
*sp++ = 6;
DISPATCH();
int7:
*sp++ = 7;
DISPATCH();
int8:
*sp++ = 8;
DISPATCH();
add:
sp[-2] += sp[-1];
sp--;
DISPATCH();
sub:
sp[-2] -= sp[-1];
sp--;
DISPATCH();
mul:
sp[-2] *= sp[-1];
sp--;
DISPATCH();
div:
sp[-2] /= sp[-1];
sp--;
DISPATCH();
ret:
result = sp[-1];
iserr = false;
}
int main(int argc, char *argv[])
{
std::ifstream infile(input_path);
if (!infile)
{
std::cerr << "No input file.\n";
return 1;
}
std::vector<unsigned char> bytecode;
std::string line;
while (std::getline(infile, line))
bytecode.push_back(std::stoi(line));
infile.close();
exec(bytecode);
ed = clock();
std::cout << ed - st << std::endl;
}