-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.js
executable file
·74 lines (70 loc) · 1.84 KB
/
interpreter.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
const fs = require("fs");
const path = require("path");
const SPACE_BUFFER = 30000;
const space = new Uint8Array(SPACE_BUFFER);
var brainfuck = /[<>\[\].,+-]/g;
function main(program) {
// console.log("========== Starting BrainFuck ========== ");
let pA = program.match(brainfuck);
interpret(pA);
process.stdout.write("\n");
// console.log("\n ========== Program FInished ==========");
}
function interpret(symbols) {
let loop_start_point = 0;
let loopStacks = [];
let current_position = 0;
while (loop_start_point != symbols.length) {
let symbol = symbols[loop_start_point];
switch (symbol) {
case "+":
space[current_position]++;
break;
case "-":
space[current_position]--;
break;
case ".":
process.stdout.write(String.fromCharCode(space[current_position]));
break;
case ",":
// TODO - Implement
break;
case ">":
current_position++;
break;
case "<":
current_position--;
break;
case "[":
if (space[current_position]) {
loopStacks.push(loop_start_point);
} else {
// If value is 0 at the starting point of the block then skip till we find a closing bracket.
while (symbols[loop_start_point] != "]") {
loop_start_point++;
}
}
break;
case "]":
if (space[current_position]) {
let pos = loopStacks.pop();
loop_start_point = pos;
continue;
}
break;
default:
break;
}
loop_start_point++;
}
}
if (process.argv.length > 2) {
const file = process.argv[2];
fs.readFile(path.join(__dirname, file), (err, content) => {
if (err) {
console.error("Error in reading the file specified");
throw err;
}
main(content.toString());
});
}