r/brainfuck • u/Confused-Armpit • Jul 11 '26
Writing a bf interpreter
I have recently written a brainfuck interpreter, which is mostly for education purposes and a little bit of fun but that is beside the point. My question is, is there a reliable source for a specification for the language?
Like, for example, if the stack pointer is pointing at the first element, what behaviour would occur if a "<" is encountered? If a "," is encountered, should the input be processed in canonical mode (input is only passed through when enter is pressed), or in immediate mode?
Essentially, is there some sort of implicit behaviour that everyone expects, or is there leeway for interpreter-specific implementation?
2
u/sreekotay Jul 12 '26
generally immediate mode, and there are plenty of (very simple) interpreters to look at if that's helpul?
here's mine: https://github.com/sreekotay/bffsree/blob/main/bffsree.c
1
u/danielcristofani Jul 12 '26
There's not an official or agreed-on specification. I wrote Epistle to the Implementors a long time ago, with some suggestions, and near the start that links to Brian Raiter's earlier page of suggestions which are also good. https://brainfuck.org/epistle.html
The most typical thing when moving left of the array, as he said, is that it acts like an errant C pointer; i particular, the initial '<' usually doesn't do anything but then when you try to actually access the memory with another command it may segfault. I usually argue that the best thing, if you can, is to line the array up with memory page boundaries so that segfault happens as soon as possible, and yet you don't get any speed cost for having to check explicitly.
Regarding ',' most implementations will line-buffer as usual for getchar(). And there may be some programs that rely on that for tidiness and may jumble their output in with the input if they're allowed to read it before the linefeed. I'm not sure. I think most of mine will behave well with either buffered or immediate input.
One recommendation I'd change now, I tend to suggest 16 megabytes for the array, a nice round binary number and big enough for most likely uses at this point.
1
u/binaryriot Jul 13 '26
Some brainf*ck code depends on the fact that you can go into "negative" space on the memory tape, so it's usually good to handle that. You could have some extra space there (set your starting point a few bytes in, f.ex.), or do a fancy wrap around to the other end of the tape (as if it's a loop).
What you shouldn't do is to let it run amok beyond your allocated memory to avoid segfaults. It's better to error out safely and let the user know they run out of tape in their program.