-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.stlx
59 lines (53 loc) · 1.25 KB
/
brainfuck.stlx
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
execBF := procedure(code) {
code := cleanup(code);
braceMap := buildBraceMap(code);
//print(braceMap);
tape := [];
cellptr := 1;
codeptr := 1;
while(codeptr < #code + 1) {
//print("tape:" + tape);
if (tape[cellptr] == om) {
tape[cellptr] := 0;
}
match (code[codeptr]) {
case "+": tape[cellptr] := tape[cellptr] + 1;
case "-": tape[cellptr] := tape[cellptr] - 1;
case "<": cellptr := cellptr - 1;
case ">": cellptr := cellptr + 1;
case ".": nPrint(char(tape[cellptr]));
case ",": tape[cellptr] := char2ascii(get());
case "[":
if (tape[cellptr] == 0) {
codeptr := braceMap[codeptr];
}
case "]":
if (tape[cellptr] != 0) {
codeptr := braceMap[codeptr];
}
}
codeptr := codeptr + 1;
}
};
char2ascii := procedure(ch) {
return arb({n : n in {0..127} | char(n) == ch});
};
cleanup := procedure(code) {
return join([c : c in code | c in "+-><[],."], "");
};
buildBraceMap := procedure(code) {
tmpBraceStack := [];
braceMap := {};
code := split(code, "");
for ([char, pos] in code >< [1 .. #code]) {
if (char == "[") {
tmpBraceStack := tmpBraceStack + [pos];
}
if (char == "]") {
start := fromE(tmpBraceStack);
braceMap[start] := pos;
braceMap[pos] := start;
}
}
return braceMap;
};