feel free to email me at
Forth to C.

Forth to C.

I am writing sort of Forth to C translator in Python (github) and trying to write software in that language along the way.

So here is what i learnt from this process in no particular order:

1. I don't need (or want) most of Forth. Like flat memory or colon.

Having no interactive enviroment produces quite different Forth from standard. Actually the only reason i choosed Forth is that i can make my own language without hassles of parsing. And i like density of Forth code.

2. Tail calls are hard.

It's easy to make self-recursion, but optimizing tail call to a different function (in Forth it's every function in front of semicolon) is hard.

3. Return stack juggling is impossible.

C compiler will inline short forth functions very often, this breaks even possibility of doing meaningful return stack juggling.

4. Macros are fun.

I write them in python, and this dual-language barrier between code and compiler makes use of macros explicit and obvious. I really feel when i need to write a macro (mostly because there is no way to solve it with my Forth).

5. Interfacing is fun.

One of the greatest pains of Forth is working with outside world. Having FFI helps but only that much. Now i simply have words "c" and "cdef" so i can write things like this:

c #include <stdio.h>
cdef uprint printf("%u",lang_internal_pop());

6. No stack

I am not there yet, but seems like with putting some constraints on my Forth i can produce C code without explicit data stack, by passing things in function arguments and C variables. Not sure i want it, it will add quite a lot of complexity to translator.

7. Data

Instead of flat memory of traditional Forths i use arrays of records.

data point 400 x y
data square 100 a b c d

This creates 400 points and 100 squares. Things reference each other by index. Syntax to access them is not very helpful yet.

I use index register and words 'point!x' 'point@x' to access fields. Do not work very well.

Perhaps i can leverage #6 here and add type system but really unsure i want it.

8. Debugging

Debugging is hard. GDB helps, but many errors are actually due to language being too alien to what i am used to. And no help from compiler in catching errors. Looks like, #6 and #7 may help with that not sure to what extent.

8. Literate programming

Not related, but literate programming helps a lot when you have no clue what you are doing.

Code: (github)