crafting-interpreters/lox/bf.lox

101 lines
2.2 KiB
Text
Raw Permalink Normal View History

2025-05-27 09:22:29 +02:00
class Cell {
init(previous, next, data) {
this.previous = previous;
this.next = next;
this.data = data;
}
}
class Tape {
init() {
this.current = Cell(nil, nil, 0);
}
backward() {
if (this.current.previous == nil) {
this.current.previous = Cell(nil, this.current, 0);
}
this.current = this.current.previous;
}
forward() {
if (this.current.next == nil) {
this.current.next = Cell(this.current, nil, 0);
}
this.current = this.current.next;
}
increment() {
this.current.data = this.current.data + 1;
}
decrement() {
this.current.data = this.current.data - 1;
}
}
class Interpreter {
init(bfpath) {
this.bfpath = bfpath;
}
run() {
var tape = Tape();
var instruction = read(this.bfpath);
while (instruction != nil) {
if (instruction == ">") {
tape.forward();
}
if (instruction == "<") {
tape.backward();
}
if (instruction == "+") {
tape.increment();
}
if (instruction == "-") {
tape.decrement();
}
if (instruction == ".") {
asciiOut(tape.current.data);
}
if (instruction == ",") {
tape.current.data = promptAscii("");
2025-05-27 09:22:29 +02:00
}
2025-05-28 12:02:49 +02:00
if (instruction == "[" and tape.current.data == 0) {
2025-05-27 09:22:29 +02:00
instruction = read(this.bfpath);
var bracketCount = 1;
while (bracketCount > 0 and instruction != nil) {
if (instruction == "[") { bracketCount = bracketCount + 1; }
if (instruction == "]") { bracketCount = bracketCount - 1; }
if (bracketCount > 0) { instruction = read(this.bfpath); }
}
}
2025-05-28 12:02:49 +02:00
if (instruction == "]" and tape.current.data != 0) {
2025-05-27 09:22:29 +02:00
instruction = read(this.bfpath, true);
var bracketCount = 1;
while (bracketCount > 0 and instruction != nil) {
if (instruction == "]") { bracketCount = bracketCount + 1; }
if (instruction == "[") { bracketCount = bracketCount - 1; }
if (bracketCount > 0) { instruction = read(this.bfpath, true); }
}
}
instruction = read(this.bfpath);
}
}
}
2025-05-28 21:58:35 +02:00
var bfScript = args(0);
var interpreter = Interpreter(bfScript);
2025-05-27 09:22:29 +02:00
interpreter.run();