-
Notifications
You must be signed in to change notification settings - Fork 1
/
Brainfuck.CPP
executable file
·157 lines (144 loc) · 2.85 KB
/
Brainfuck.CPP
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
Brainfuck interpreter for TempleOS.
*/
U8 Input() {
return GetI64( "Brainfuck: enter cell value (000 to 255): ", 0, 0,
255 ) ( U8 );
}
U0 Err( U8* message, U8* code, I64 ip ) {
I64 i = 0;
I64 line = 1;
I64 column = 0;
while ( i < ip ) {
if ( code[ i ] == '\n' ) {
++line;
column = 0;
}
else {
++column;
}
++i;
}
Print( "Brainfuck:%d:%d: error: %s\n", line, column, message );
}
U0 BrainfuckExecute( U8* code ) {
U8 data[ 30000 ];
MemSet( data, 0, sizeof( data ) );
I64 ip = 0;
I64 old_ip = 0;
I64 dp = 0;
I64 depth = 0;
select:
switch ( code[ ip ] ) {
case '>': goto gt;
case '<': goto lt;
case '+': goto plus;
case '-': goto minus;
case '.': goto dot;
case ',': goto comma;
case '[': goto lbrac;
case ']': goto rbrac;
case '\0':
finish:
return;
// Any other character is ignored.
default:
++ip;
goto select;
}
// Move data pointer to next element.
gt:
if ( dp >= sizeof( data ) ) {
Err( "attempting to set data pointer beyond upper limit", code, ip );
goto finish;
}
++dp;
++ip;
goto select;
// Move data pointer to previous element.
lt:
if ( ! dp ) {
Err( "attempting to set data pointer below 0", code, ip );
goto finish;
}
--dp;
++ip;
goto select;
// Increment element at data pointer.
plus:
++data[ dp ];
++ip;
goto select;
// Decrement element at data pointer.
minus:
--data[ dp ];
++ip;
goto select;
// Print element at data pointer.
dot:
Print( "%c", data[ dp ] );
++ip;
goto select;
// Read value from user and place it at data pointer.
comma:
data[ dp ] = Input();
++ip;
goto select;
// Go to matching right bracket when element at data pointer is zero.
lbrac:
if ( data[ dp ] ) {
++ip;
goto select;
}
depth = 0;
old_ip = ip;
while ( TRUE ) {
++ip;
switch ( code[ ip ] ) {
case '[':
++depth;
break;
case ']':
if ( depth ) {
--depth;
}
else {
++ip;
goto select;
}
break;
case '\0':
Err( "missing matching ']'", code, old_ip );
goto finish;
}
}
// Go back to matching left bracket when element at data pointer is
// nonzero.
rbrac:
if ( ! data[ dp ] ) {
++ip;
goto select;
}
depth = 0;
old_ip = ip;
while ( TRUE ) {
if ( ! ip ) {
Err( "missing matching '['", code, old_ip );
goto finish;
}
--ip;
switch ( code[ ip ] ) {
case ']':
++depth;
break;
case '[':
if ( depth ) {
--depth;
}
else {
++ip;
goto select;
}
}
}
}