-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.nim
45 lines (36 loc) · 1.09 KB
/
interpreter.nim
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
include templates
var
data = newSeq[byte](30000)
dataPtr = 0
codePtr = 0
proc matchBrackets(input: string, index: int, shape: char): int =
var sequence: seq[char]
template findIndex(open, close, iter): untyped =
for j in iter:
if input[j] == open:
sequence.delete(0)
elif input[j] == close:
sequence.add(input[index])
if sequence == @[]:
return j
if shape == '[':
findIndex('[', ']', index..<input.len)
elif shape == ']':
findIndex(']', '[', index..\0)
proc interpret(code: string) =
while dataPtr >= 0 and codePtr < code.len():
case code[codePtr]:
of '>': dataPtr.inc()
of '<': dataPtr.dec()
of '+': data[dataPtr].inc()
of '-': data[dataPtr].dec()
of '.': data[dataPtr].char.write()
of ',': data[dataPtr] = readChar().byte
of '[':
if data[dataPtr] == 0: codePtr = code.matchBrackets(codePtr, '[')
of ']':
if data[dataPtr] != 0: codePtr = code.matchBrackets(codePtr, ']')
else: discard
codePtr.inc()
let input = readFile("helloworld.bf")
interpret(input)