feat: add loop commands
This commit is contained in:
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@@ -9,7 +9,7 @@
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"program": "dopey.py",
|
||||
"args": ["./test.bf"],
|
||||
"args": ["./helloworld.bf"],
|
||||
"console": "integratedTerminal"
|
||||
}
|
||||
]
|
||||
|
||||
25
dopey.py
25
dopey.py
@@ -1,4 +1,5 @@
|
||||
import sys
|
||||
from io import TextIOWrapper
|
||||
from blessed import Terminal
|
||||
|
||||
# create memory buffer and pointer
|
||||
@@ -6,6 +7,7 @@ class Memory:
|
||||
BUFFER_SIZE = 30_000
|
||||
buffer = [0 for _ in range(BUFFER_SIZE)]
|
||||
pointer = 0
|
||||
loop_stack = []
|
||||
|
||||
@classmethod
|
||||
def get_pointer(cls) -> int:
|
||||
@@ -40,11 +42,11 @@ def main() -> None:
|
||||
break
|
||||
|
||||
# perform operation
|
||||
perform_operation(operation)
|
||||
perform_operation(operation, file)
|
||||
|
||||
file.close()
|
||||
|
||||
def perform_operation(operation: str) -> None:
|
||||
def perform_operation(operation: str, file: TextIOWrapper) -> None:
|
||||
if operation == Operation.SHIFT_LEFT:
|
||||
Memory.pointer -= 1
|
||||
elif operation == Operation.SHIFT_RIGHT:
|
||||
@@ -59,6 +61,25 @@ def perform_operation(operation: str) -> None:
|
||||
term = Terminal()
|
||||
with term.cbreak():
|
||||
Memory.buffer[Memory.get_pointer()] = ord(term.inkey())
|
||||
elif operation == Operation.OPEN_LOOP:
|
||||
if Memory.buffer[Memory.get_pointer()] == 0:
|
||||
while True:
|
||||
operation = file.read(1)
|
||||
if operation == Operation.CLOSE_LOOP:
|
||||
break
|
||||
elif not operation:
|
||||
print("Mismatched bracket...") # TODO add line number and column on line
|
||||
sys.exit()
|
||||
else:
|
||||
Memory.loop_stack.append(file.tell()-1)
|
||||
elif operation == Operation.CLOSE_LOOP:
|
||||
if len(Memory.loop_stack) == 0:
|
||||
print("Mismatched bracket...") # TODO add line number and column on line
|
||||
sys.exit()
|
||||
|
||||
open_loop_position = Memory.loop_stack.pop()
|
||||
if Memory.buffer[Memory.get_pointer()] != 0:
|
||||
file.seek(open_loop_position, 0)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user