-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.js
138 lines (125 loc) · 2.73 KB
/
engine.js
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
function lex(string) {
return string
.match(/a|b|c|d/g)
.map(token => token.toUpperCase());
}
// This language has no structure, so we are jumping straight to bytecode rather than first building
// an AST
function parse(tokens) {
const bytecode = [];
for (let token of tokens) {
switch (token) {
case "A": {
bytecode.push("xA");
break;
}
case "B": {
bytecode.push("xB");
break;
}
case "C": {
bytecode.push("xC");
break;
}
case "D": {
bytecode.push("xD");
break;
}
default: {
throw new Error("invalid stuff");
}
}
}
return bytecode;
}
function interpret(bytecode) {
if (compiler.enabled) {
const count = compiler.incrementScriptCounter(bytecode);
if (count > compiler.threshold) {
if (compiler.hasCompiledScript(bytecode)) {
return compiler.runCompiledCode(bytecode);
} else {
console.log("warm up: 💡");
compiler.compileCode(bytecode);
}
}
}
for (let code of bytecode) {
switch (code) {
case "xA": {
console.log(instruction.a);
break;
}
case "xB": {
console.log(instruction.b);
break;
}
case "xC": {
console.log(instruction.c);
break;
}
case "xD": {
console.log(instruction.d);
break;
}
}
}
}
function createScript(bytecode) {
return {
counter: 0,
compiledScript: null,
bytecode
}
}
function name(bytecode) {
return bytecode.join("");
}
const compiler = {
enabled: true,
scripts: {},
threshold: 10,
incrementScriptCounter(bytecode) {
if (!this.scripts[name(bytecode)]) {
this.scripts[name(bytecode)] = createScript(bytecode);
}
return this.scripts[name(bytecode)].counter++;
},
hasCompiledScript(bytecode) {
return !!this.scripts[name(bytecode)].compiledScript;
},
runCompiledCode(bytecode) {
console.log("JIT Script ⚡");
return this.scripts[name(bytecode)].compiledScript();
},
compileCode(bytecode) {
let output = "";
for (const code of bytecode) {
switch (code) {
case "xA": {
output += `console.log("${instruction.a}");`;
break;
}
case "xB": {
output += `console.log("${instruction.b}");`;
break;
}
case "xC": {
output += `console.log("${instruction.c}");`;
break;
}
case "xD": {
output += `console.log("${instruction.d}");`;
break;
}
}
}
this.scripts[name(bytecode)].compiledScript = new Function("", output);
}
}
const instruction = {
a: "duck",
b: "goose",
c: "swan",
d: "finch"
}