Canablize a runtime: embedding a language in Forth
After implementing Forth, I realized that transparent access to the runtime allows embeddeing another programming language.
Brainfuck is hardly a language.
Consisting only of single-character tokens, each can be translated directly: Brainfuck's [
, <
, or +
are, in Forth vocabulary, "words" that can be defined like any other.
Brainfuck loops can re-write into Forth's native WHILE
–REPEAT
loops with meta-programming (POSTPONE
and IMMEDIATE
).
The last component is Brainfuck's memory, modeled with an array TAPE
and pointer HEAD
.
It's surprising, to me, to see one programming language shaped out of another so directly:
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 , > , [ < + > - ]