-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfsk.mank
120 lines (110 loc) · 2.59 KB
/
brainfsk.mank
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
pod ProgramState {
cells: char[],
current_cell: i32,
char_ouput: \char -> (),
char_input: \ -> char
}
proc bf_interpret(program: str, state: ref ProgramState) {
bind { .cells: ref, .current_cell: ref } = state;
bracket_map := make_bracket_map(program);
pc := 0;
loop {
if pc >= program.length {
break;
}
instr := program[pc];
switch instr {
'+' => {
cells[current_cell] += 1 as char;
},
'-' => {
cells[current_cell] -= 1 as char;
},
'>' => {
current_cell += 1;
if current_cell >= cells.length {
current_cell = 0;
}
},
'<' => {
current_cell -= 1;
if current_cell < 0 {
current_cell = cells.length - 1;
}
},
'.' => {
state.char_ouput(cells[current_cell]);
},
',' => {
cells[current_cell] = state.char_input();
},
'[' => {
if cells[current_cell] == 0 as char {
pc = bracket_map[pc];
}
},
']' => {
if cells[current_cell] != 0 as char {
pc = bracket_map[pc] - 1;
}
}
}
pc += 1;
}
}
fun make_bracket_map: i32[] (program: str) {
# Kinda a waste of space (but we don't have maps yet)
bracket_map := vec!([=0; program.length]);
open_brackets := new_vec@(i32)();
for i in 0 .. program.length {
instr := program[i];
if instr == '[' {
push_back(open_brackets, i);
} else if instr == ']' {
start := open_brackets[open_brackets.length - 1];
pop_back(open_brackets);
bracket_map[start] = i;
bracket_map[i] = start;
}
}
assert!(open_brackets.length == 0, "program should not contain unmatched brackets");
bracket_map
}
fun new_program_state: ProgramState (
cell_count: i32,
char_ouput: \char -> (),
char_input: \ -> char
) {
ProgramState {
.cells = vec!([=0 as char; cell_count]),
.current_cell = 0,
.char_ouput = char_ouput,
.char_input = char_input
}
}
proc reset_program_state (state: ref ProgramState) {
state.current_cell = 0;
fill_vec(state.cells, 0 as char, state.cells.length);
}
proc bf_repl(cell_count: i32) {
state := new_program_state(cell_count,
\c -> { _ := putchar(c); },
\ -> { getchar() as char });
loop {
bf := prompt(">");
bf_interpret(bf, state);
reset_program_state(state);
}
}
proc main (args: str[]) {
cell_count := if args.length > 1 {
bind (cell_count, success) = parse_int(args[1]);
if (!success) {
fail("expected integer cell count");
}
cell_count
} else {
30000
}
bf_repl(cell_count);
}