add ast printer
This commit is contained in:
parent
8c500ab6a9
commit
6e02a1a644
6 changed files with 314 additions and 1 deletions
100
lox/bf.lox
Normal file
100
lox/bf.lox
Normal file
|
@ -0,0 +1,100 @@
|
|||
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 == ",") {
|
||||
|
||||
}
|
||||
|
||||
if (instruction == "[" and tape.current.data < 0.0001) {
|
||||
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); }
|
||||
}
|
||||
}
|
||||
|
||||
if (instruction == "]" and tape.current.data >= 0.0001) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var interpreter = Interpreter("bf/helloworld.bf");
|
||||
interpreter.run();
|
Loading…
Add table
Add a link
Reference in a new issue