-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlibbrainfunk.cpp
More file actions
451 lines (368 loc) · 13.9 KB
/
libbrainfunk.cpp
File metadata and controls
451 lines (368 loc) · 13.9 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#include "libbrainfunk.hpp"
#include "ctre.hpp"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
/* ================================================================
* Brainfunk implementation
* ================================================================ */
// ------------------------------------------------------------------
// Construction / destruction
// ------------------------------------------------------------------
Brainfunk::Brainfunk(std::size_t memsize) {
if (memsize == 0) {
throw BrainfunkException("Memory size must be greater than zero");
}
ptr_ = 0;
memory_.resize(memsize, memory_t{0});
}
Brainfunk::~Brainfunk() = default; // RAII handles everything
void Brainfunk::clear() {
reset_state();
bitcode_.clear();
}
void Brainfunk::reset_state() {
std::fill(memory_.begin(), memory_.end(), memory_t{0});
ptr_ = 0;
pc_ = 0;
}
// ------------------------------------------------------------------
// count_mul_offset – accumulates one mul/offset pair
// ------------------------------------------------------------------
namespace {
void validate_brackets(std::string_view code) {
std::vector<std::size_t> stack;
for (std::size_t i = 0; i < code.size(); ++i) {
if (code[i] == '[') {
stack.push_back(i);
} else if (code[i] == ']') {
if (stack.empty()) {
throw BrainfunkException("Unmatched closing bracket");
}
stack.pop_back();
}
}
if (!stack.empty()) {
throw BrainfunkException("Unmatched opening bracket");
}
}
void count_mul_offset(std::string_view text,
std::vector<memory_t>& mul,
std::vector<offset_t>& offset,
offset_t last_offset) {
auto add = count_net(text, "+-");
auto mov = count_net(text, "><");
mul.emplace_back(static_cast<memory_t>(add % 256));
offset.emplace_back(mov + last_offset);
}
} // anonymous namespace
// ------------------------------------------------------------------
// translate – Brainfuck source → bitcode
// ------------------------------------------------------------------
void Brainfunk::translate(std::string_view code) {
bitcode_.clear();
bitcode_.reserve(code.size() + 1);
/* Validate bracket matching */
validate_brackets(code);
std::vector<addr_t> stack; // jump-address stack
offset_t last_pc = 0;
while (!code.empty()) {
/* ---------- Optimisation patterns ---------- */
if (code.front() == '[') {
if (try_parse_mul_offset_loop_(code)) continue;
if (try_parse_scan_loop_(code)) continue;
if (try_parse_set_zero_loop_(code)) continue;
/* Fall through – ordinary loop */
bitcode_.emplace_back(Opcode::X); // placeholder
stack.push_back(bitcode_.size() - 1);
code.remove_prefix(1);
continue;
}
if (code.front() == ']') {
if (stack.empty()) {
throw BrainfunkException("Unmatched closing bracket");
}
last_pc = static_cast<offset_t>(stack.back());
stack.pop_back();
auto pc = static_cast<offset_t>(bitcode_.size());
bitcode_.emplace_back(Opcode::JN, last_pc - pc);
bitcode_[static_cast<std::size_t>(last_pc)] =
Bitcode(Opcode::JE, pc - last_pc);
code.remove_prefix(1);
continue;
}
/* ---- simple instructions ---- */
if (code.front() == '+' || code.front() == '-') {
auto [net, len] = leading_run(code, "+-");
bitcode_.emplace_back(Opcode::A,
static_cast<memory_t>(net));
code.remove_prefix(len);
continue;
}
if (code.front() == '>' || code.front() == '<') {
auto [net, len] = leading_run(code, "><");
bitcode_.emplace_back(Opcode::M,
static_cast<offset_t>(net));
code.remove_prefix(len);
continue;
}
if (code.front() == '.') {
bitcode_.emplace_back(Opcode::IO, IO_OUT);
code.remove_prefix(1);
continue;
}
if (code.front() == ',') {
bitcode_.emplace_back(Opcode::IO, IO_IN);
code.remove_prefix(1);
continue;
}
/* Skip any unrecognised character */
code.remove_prefix(1);
}
bitcode_.emplace_back(Opcode::H);
if (!stack.empty()) {
throw BrainfunkException("Unmatched opening bracket");
}
}
// ------------------------------------------------------------------
// try_parse_mul_offset_loop_
//
// Pattern: [ -? ( [><]+ [+-]+ )+ [><]+ ] (mode 1: starts with '-')
// [ ( [><]+ [+-]+ )+ [><]+ - ] (mode 2: ends with '-')
//
// When a match is found we emit one MUL instruction per
// (offset, mul) pair, followed by an S(0) to clear the cell.
// ------------------------------------------------------------------
bool Brainfunk::try_parse_mul_offset_loop_(std::string_view& code) {
// clang-format off
auto m = ctre::starts_with<
"^\\[(\\-([\\<\\>]+[\\+\\-]+)+[\\<\\>]+|([\\<\\>]+[\\+\\-]+)+[\\<\\>]+\\-)\\]"
>(code);
// clang-format on
if (!m) return false;
std::string_view body = m.to_view();
/* Must return to the original cell */
if (count_net(body, "><") != 0) return false;
/* Strip brackets */
int mode;
if (body[1] == '-') { // mode 1: [- ...]
body.remove_prefix(2);
mode = 1;
} else { // mode 2: [ ... -]
body.remove_prefix(1);
mode = 2;
}
std::vector<memory_t> mul;
std::vector<offset_t> offset;
while (auto p = ctre::starts_with<"^[\\>\\<]+[\\+\\-]+">(body)) {
count_mul_offset(p.to_view(), mul, offset,
offset.empty() ? 0 : offset.back());
body.remove_prefix(p.size());
}
/* In mode 2 the last pair is a fake – we omit it */
auto pairs = (mode == 2) ? offset.size() - 1 : offset.size();
assert(pairs > 0);
for (std::size_t i = 0; i < pairs; ++i) {
bitcode_.emplace_back(Opcode::MUL, mul[i], offset[i]);
}
/* Insert S(0) to clear the cell */
bitcode_.emplace_back(Opcode::S, memory_t{0});
code.remove_prefix(m.size());
return true;
}
// ------------------------------------------------------------------
// try_parse_scan_loop_
//
// Pattern: [ [><]+ ] → F(offset)
// ------------------------------------------------------------------
bool Brainfunk::try_parse_scan_loop_(std::string_view& code) {
auto m = ctre::starts_with<"^\\[[\\>\\<]+\\]">(code);
if (!m) return false;
auto net = count_net(m.to_view(), "><");
bitcode_.emplace_back(Opcode::F, static_cast<offset_t>(net));
code.remove_prefix(m.size());
return true;
}
// ------------------------------------------------------------------
// try_parse_set_zero_loop_
//
// Pattern: [ [+-]+ ] → S(0) (but only when the length is odd)
// ------------------------------------------------------------------
bool Brainfunk::try_parse_set_zero_loop_(std::string_view& code) {
auto m = ctre::starts_with<"^\\[[\\+\\-]+\\]">(code);
if (!m) return false;
auto net = count_net(m.to_view(), "+-");
/* The operation inside is e.g. "+-", net == 0 but length == 2.
* We need the parity of the *length* of the inner run of +- to be odd.
* The original code checked net just to be sure, but really it's
* the length parity that matters. Keep the original semantics:
* net must be odd for the net effect to be set-to-zero. */
if (net % 2 != 1 && net % 2 != -1) return false;
bitcode_.emplace_back(Opcode::S, memory_t{0});
code.remove_prefix(m.size());
return true;
}
// ------------------------------------------------------------------
// dump – prints bitcode as plain text or C source
// ------------------------------------------------------------------
void Brainfunk::dump(std::ostream& os, Format format) const {
if (format == Format::C) {
// clang-format off
os << "#include <stdio.h>\n"
"#include <stdlib.h>\n"
"#include <stdint.h>\n"
"uint8_t *base;\n"
"uint8_t *mem;\n"
"#define MEMSIZE\t\t(1<<21)\n"
"#define\tX(x)\t/* NOP */\n"
"#define\tA(x)\t*mem += x\n"
"#define\tS(x)\t*mem = x\n"
"#define\tMUL(offset, mul)\tmem[offset] += *mem * mul\n"
"#define\tF(x)\twhile(*mem != 0) mem += x\n"
"#define\tM(x)\tmem += x\n"
"#define\tJE(x)\twhile(*mem) {\n"
"#define\tJN(x)\t}\n"
"#define\tH()\texit(0);\n"
"static inline void IO(uint8_t arg)\n"
"{\n"
"\tint c = 0;\n"
"\tswitch(arg)\n"
"\t{\n"
"\t\tcase 0: /* IN */ c = getchar(); *mem = c == EOF ? 0 : c; break;\n"
"\t\tcase 1: /* OUT */ putchar(*mem); break;\n"
"\t}\n"
"}\n"
"int main(void)\n"
"{\n"
"\tsetvbuf(stdin, NULL, _IONBF, 0);\n"
"\tsetvbuf(stdout, NULL, _IONBF, 0);\n"
"\tbase = (uint8_t *)calloc(MEMSIZE, sizeof(uint8_t));\n"
"\tif(!base) { puts(\"Out of memory\"); exit(1); }\n"
"\tmem = base + MEMSIZE/2;\n\n";
// clang-format on
}
for (addr_t pc = 0; pc < bitcode_.size(); ++pc) {
if (format == Format::BIT)
os << pc << ":\t" << bitcode_[pc].to_string(BITCODE_FORMAT_PLAIN)
<< '\n';
else
os << bitcode_[pc].to_string(BITCODE_FORMAT_C) << '\n';
}
if (format == Format::C) {
os << "}" << std::endl;
}
}
// ------------------------------------------------------------------
// run – execute the bitcode
// ------------------------------------------------------------------
void Brainfunk::run(std::istream& is, std::ostream& os) {
reset_state();
while (step(is, os)) {
/* nothing — step() handles everything */
}
}
// ------------------------------------------------------------------
// step – execute exactly one bitcode instruction
// ------------------------------------------------------------------
bool Brainfunk::step(std::istream& is, std::ostream& os) {
if (bitcode_.empty() || pc_ >= bitcode_.size()) return false;
auto mem_span = std::span(memory_);
return bitcode_[pc_].execute(mem_span, pc_, ptr_, is, os);
}
/* ================================================================
* Bitcode implementation
* ================================================================ */
// ------------------------------------------------------------------
// to_string
// ------------------------------------------------------------------
std::string Bitcode::to_string(int format) const {
auto idx = static_cast<std::size_t>(opcode_);
std::ostringstream operand;
/* Build the operand string */
std::visit([&](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, memory_t>) {
operand << static_cast<unsigned>(arg);
} else if constexpr (std::is_same_v<T, offset_t>) {
operand << arg;
} else if constexpr (std::is_same_v<T, DualOperand>) {
operand << arg.offset << ", " << static_cast<unsigned>(arg.mul);
} else {
operand << ""; // std::monostate – no operand
}
}, operand_);
/* Format output */
if (format == BITCODE_FORMAT_C) {
return opcode_name(idx) + std::string("(") + operand.str() + std::string(");");
}
return opcode_name(idx) + std::string("\t") + operand.str();
}
// ------------------------------------------------------------------
// execute – runs one instruction, returns false on halt
// ------------------------------------------------------------------
bool Bitcode::execute(std::span<memory_t> memory,
addr_t& pc,
addr_t& ptr,
std::istream& is,
std::ostream& os) const {
auto size = memory.size();
switch (opcode_) {
case Opcode::X:
throw BrainfunkException("Empty instruction");
case Opcode::A:
memory[ptr] += std::get<memory_t>(operand_);
break;
case Opcode::S:
memory[ptr] = std::get<memory_t>(operand_);
break;
case Opcode::MUL: {
auto d = std::get<DualOperand>(operand_);
memory[wrap_offset(ptr, d.offset, size)] +=
static_cast<memory_t>(memory[ptr] * d.mul);
break;
}
case Opcode::F: {
auto off = std::get<offset_t>(operand_);
while (memory[ptr] != 0) {
ptr = wrap_offset(ptr, off, size);
}
break;
}
case Opcode::M:
ptr = wrap_offset(ptr, std::get<offset_t>(operand_), size);
break;
case Opcode::JE:
if (memory[ptr] == 0) {
pc += static_cast<addr_t>(std::get<offset_t>(operand_));
}
break;
case Opcode::JN:
if (memory[ptr] != 0) {
pc += static_cast<addr_t>(std::get<offset_t>(operand_));
}
break;
case Opcode::IO: {
auto which = std::get<memory_t>(operand_);
if (which == IO_IN) {
memory_t io_input = 0;
is >> std::noskipws >> io_input;
if (is.eof()) io_input = 0;
memory[ptr] = io_input;
} else {
os << static_cast<char>(memory[ptr]) << std::flush;
}
break;
}
case Opcode::H:
return false; // halt
default:
throw BrainfunkException("Invalid opcode");
}
++pc;
return true;
}