Back Original

Forth Embedding Brainfuck

It is surprising to see one programming language shaped out of another. Languages with very direct access to syntax, like Forth, allow definition of the constructs of another embedded language within themselves. Brainfuck, consisting only of single-character tokens, can be baked into Forth directly: [, <, or + are Forth words defined like all others. With POSTPONE and IMMEDIATE meta-programming, Brainfuck loops become Forth-native WHILE...REPEAT loops. Model Brainfuck memory with a TAPE and HEAD, then writing an emulator is effectively writing one Forth word per Brainfuck token.

The following is a complete Brainfuck emulator:

VARIABLE TAPE 1000 CELLS ALLOT
TAPE 1000 0 FILL

VARIABLE HEAD
TAPE HEAD !

: PEEK HEAD @ @ ;
: POKE HEAD @ ! ;

: < HEAD @ 1 CELLS - HEAD ! ;
: > HEAD @ 1 CELLS + HEAD ! ;
: + PEEK 1+ POKE ;
: - PEEK 1- POKE ;
: . PEEK . ;
: , KEY POKE ;
: [ POSTPONE BEGIN POSTPONE PEEK POSTPONE WHILE ; IMMEDIATE
: ] POSTPONE REPEAT ; IMMEDIATE

\ example programs:
: echo , [ . , ] ;
: add , > , [ < + > - ]
#