-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathprocessor.js
More file actions
47 lines (38 loc) · 1.35 KB
/
processor.js
File metadata and controls
47 lines (38 loc) · 1.35 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
import { Opcodes } from "../utils/defaults.js";
// The processor executes the exported function
export default class Processor {
constructor(func, params) {
this.func = func;
this.params = params;
this.stack = [];
}
executeFunc() {
for (const instruction of this.func.instructions) {
if (instruction == Opcodes.get_local) this.stack.push(this.params[this.func.locals.shift()]);
if (instruction == Opcodes.i32_const) this.stack.push(this.func.internals.shift());
this.#parseInstruction(instruction)
}
}
#parseInstruction(instruction) {
let result;
// We Array.prototype.reduce because we do not know in advance
// how many parameters are there
switch(instruction) {
case Opcodes.i32_add:
result = this.stack.reduce((prev, current) => prev + current, 0);
return this.stack.push(result);
case Opcodes.i32_sub:
result = this.stack.reduce((prev, current) => prev - current);
return this.stack.push(result);
case Opcodes.i32_mul:
result = this.stack.reduce((prev, current) => prev * current, 1);
return this.stack.push(result);
case Opcodes.i32_div:
result = this.stack.reduce((prev, current) => prev / current);
return this.stack.push(result);
}
}
getResult() {
return this.stack.pop()
}
}