A self hosting forth compiler

This repository is for a post on Qiita. This post is a tutorial to make a self hosting forth compiler for x64 Windows.

How to build

Just type make on a POSIX-like system such as msys.

$ make

You will get 4 files. forth0.exe, forth1.exe, forth2.exe, and forth3.exe.

  • forth0.exe is a forth compiler written in C.
  • forth1.exe is a forth compiler written in forth, but generated by a compiler written in C.
  • forth2.exe is a forth compiler written in forth, and generated by a compiler written in forth.
  • forth3.exe is a forth compiler written in forth, and generated by a compiler written in forth.
  • The contents of forth2.exe and forth3.exe are the same.

How to run forth0.exe

forth0.exe reads a program from the standard input and compile it. The entry point is main.

If you have test.ft like this:

: main
  msvcrt.init ( load msvcrt.dll and define '.' )
  1 2 + .
  bye
;

You can compile and run test.ft like this:

$ cat core.ft msvcrt.ft test.ft | ./forth0.exe test.exe
$ ./test
3

How to run forthN.exe where N >= 1

forthN.exe reads a list of files from the standard input and run them. If forthN.exe reads -- the following input are treated as a forth program.

For example:

$ echo test.ft -- main | ./forth1.exe
3
$ echo '-- 1 2 + . ' | ./forth1.exe
3
$ echo '-- : w 1 2 + . ; w' | ./forth1.exe
3

If forthN.exe reads --save, the next input is a filename for a .exe file.

$ echo 'core.ft msvcrt.ft test.ft --save test.exe' | ./forth1.exe
$ ./test
3