|
1 | 1 | # ccforth |
2 | 2 |
|
3 | 3 | ccforth is a Forth to C compiler written in Go. It interprets |
4 | | -compile-time Forth (immediate words, metaprogramming) and emits |
| 4 | +compile-time Forth (immediate words, meta-programming) and emits |
5 | 5 | flattened C11 code that is compiled with gcc or clang to produce |
6 | 6 | standalone executables. |
7 | 7 |
|
8 | 8 | - GitHub: https://github.com/ncw/ccforth |
9 | 9 |
|
| 10 | +ccforth was written to explore the idea of having an interpreter and a |
| 11 | +compiler running simultaneously to enable meta-programming heavy Forth |
| 12 | +programs to be compiled into C. This is harder than it sounds because |
| 13 | +Forth cannot be ahead-of-time compiled by parsing alone; programs |
| 14 | +routinely execute code at compile time. The project was also an |
| 15 | +experiment in how far an AI agent could progress a compiler project - |
| 16 | +most of the initial implementation was done by Claude Opus 4.6. Go was |
| 17 | +used as the implementation language as it is low enough level to |
| 18 | +express Forth properly but easier to write than C. C was used as a |
| 19 | +compiler backend as C compilers optimize well and are available |
| 20 | +everywhere. |
| 21 | + |
10 | 22 | ## Features |
11 | 23 |
|
12 | 24 | - **Fast compiled output** — generates optimised C11, compiled with |
@@ -44,28 +56,16 @@ standalone executables. |
44 | 56 |
|
45 | 57 | ## How it works |
46 | 58 |
|
47 | | -``` |
48 | | - .fth source |
49 | | - | |
50 | | - v |
51 | | -+-----------+ +-------------+ +--------------+ |
52 | | -| Scanner |-->| Interpreter |-->| C Emitter | |
53 | | -| (lexer) | | (executes | | (generates | |
54 | | -| | | immediate | | flattened C | |
55 | | -| | | words, | | from word | |
56 | | -| | | builds | | bodies) | |
57 | | -| | | dictionary)| | | |
58 | | -+-----------+ +-------------+ +------+-------+ |
59 | | - | |
60 | | - self-contained output.c <------+ |
61 | | - (runtime inlined) |
62 | | - | |
63 | | - v |
64 | | - gcc / clang (C11) |
65 | | - | |
66 | | - v |
67 | | - standalone executable |
68 | | -``` |
| 59 | +1. **`.fth` source** is read by the **Scanner** (lexer), which |
| 60 | + tokenises it. |
| 61 | +2. The **Interpreter** executes immediate words and metaprogramming, |
| 62 | + building a dictionary of word bodies. |
| 63 | +3. The **C emitter** walks the finished dictionary and generates |
| 64 | + flattened C from the word bodies. |
| 65 | +4. The result is a self-contained **`output.c`** with the runtime |
| 66 | + inlined. |
| 67 | +5. **gcc / clang** compiles that C11 source into a **standalone |
| 68 | + executable**. |
69 | 69 |
|
70 | 70 | Forth source is processed by the **interpreter**, which executes |
71 | 71 | immediate words (like `IF`, `DO`, `:`, `;`) and allows the normal |
|
0 commit comments