goforth
This is a compiler and byte‑code interpreter for a Forth‑like language.




What is goforth?
GoForth is a tiny, fast and embeddable implementation of the Forth programming model written in Go.
It compiles GoForth source into a human‑readable byte‑code format and then executes that byte‑code on a lightweight stack‑machine (ForthVM).
The compiler can also translate GoForth into byte-code and then directly into C.
Key design goals
- Simplicity – the language surface is intentionally small.
- Speed – compilation and execution is amazingly fast.
- Extensibility – you can add new syscalls (either in C or in Go), embed GoForth in Go programs, or generate C code from GoForth sources.
Quick overview
| Component |
Responsibility |
goforth (cmd) |
REPL / script runner – reads Forth source, invokes the compiler, executes the generated byte‑code or C binary. |
compiler.go |
Parses Forth source, builds a dictionary (defs, inlines, funcs, …) and emits byte‑code. |
vm.go |
Stack‑machine that interprets the byte‑code (RDI, PRI, ADI, …). |
stack.go |
Simple generic stack implementation used by the compiler and by the VM. |
label.go |
Generates unique numeric labels for jumps. |
show.go |
REPL UI, pretty‑printing of the dictionary and debugging output. |
config.go |
Runtime configuration (debug flag, configuration, etc.). |
The compiler produces human‑readable byte‑code – e.g.
SUB min;TDP;LSI;JIN #0;DRP;JMP #1;#0 NOP;SWP;DRP;#1 NOP;END;
MAIN;L 5;L 3;CALL min;PRI;STP;
which can be inspected, benchmarked or fed into the VM directly.
Project structure
| File |
Purpose |
cmd/goforth/main.go |
Entry point (REPL, CLI handling). |
compiler.go |
Source parser, dictionary builder, byte‑code emitter. |
vm.go |
Stack‑machine implementation. |
stack.go |
Generic stack (used by both compiler and VM). |
label.go |
Numeric label generator for jumps. |
show.go |
REPL UI, pretty‑printing of dictionary and debugging output. |
config.go |
Runtime configuration (debug flag, benchmark toggles, …). |
core.fs |
Built‑in standard library (automatically embedded). |
examples/ |
Ready‑to‑run sample programs (mandelbrot, html, …). |
License
goforth is released under the MIT License – see LICENSE for details.
Why choose goforth?
| Feature |
Description |
| Embeddable |
Use GoForth as a scripting engine inside any Go program. See the Embedding section. |
| C‑code generation |
Compile selected Forth words to C, build a native binary and run it. See the Generate C‑code section. |
| Template engine |
Embed Forth code inside arbitrary text files (<?fs … ?>). See the Templates section. |
| Portable |
Runs on OpenBSD, FreeBSD, Linux, macOS and (future) Windows. |
| No external runtime |
Only the Go standard library is required. |
Note – Parallel execution on multiple goroutines is not (yet) supported.
Installation
From source (recommended)
# Install the binary to $GOBIN (default $HOME/go/bin)
go install github.com/loscoala/goforth/cmd/goforth@latest
The binary is now available as goforth.
As a library dependency
Add goforth to your module:
go get github.com/loscoala/goforth@latest
Then import it in Go code:
import "github.com/loscoala/goforth"
Build & dependencies
- Go compiler 1.26 or newer.
- For C‑code generation you also need a working C compiler (
gcc/clang).
git clone https://github.com/loscoala/goforth.git
cd goforth
./build.sh # builds the binary and runs the test‑suite
Or simply:
go build -C cmd/goforth
Usage
Run the REPL
goforth
Run a script file
goforth --file=myscript.fs
You can also pipe code:
echo ": main 5 5 + . ;" | goforth
Shebang support
Place the following on the first line of a file and make it executable:
#!goforth --file
\ your Forth code follows …
One‑liner on the command line
goforth -script '
: greet ." Hello, World!" ;
: main greet ;
'
The core library (core.fs) is automatically compiled into the goforth binary, so all built‑in words are always available.
REPL commands
| Command |
Description |
% |
Show the whole dictionary. |
% name |
Show the definition of name. |
find name |
List all definitions that contain the substring name. |
use filename |
Load and parse another file or URL (http or https). |
$ |
Dump the current data stack. |
true debug |
Toggle benchmark mode – prints byte‑code and execution time. |
quit |
Exit the REPL. |
Language basics
Global variables
forth> variable counter
forth> 15 to counter \ store 15
forth> counter . \ prints 15
Local variables
Locals are introduced with curly braces { … } and behave like ordinary stack variables but are scoped to the block.
: factorial
1 { acc } \ acc = 1 (local)
1+ 1 ?do
acc i * to acc
loop
acc ; \ result on the stack
Control structures
| Forth word |
Compiled byte‑code pattern |
Meaning |
if … else … then |
JIN #label … JMP #label … NOP #label |
Conditional execution. |
begin … while … repeat |
NOP #label … JIN #label |
Loop with post‑condition. |
do … loop / ?do … loop |
Uses the return‑stack (TTR, TR, RF, …) |
Counted loops. |
case … of … endcase |
Series of JIN / JMP / NOP |
Multi‑way branch. |
OOP – Classes
Define a class with the class keyword. The compiler automatically creates getters, setters, allocation helpers, an index operator and a size constant.
: class Point
x \ default cell size = 1
y
;
Generated words (excerpt):
Point:x \ address of field x
Point:getX \ getter
Point:setX \ setter
Point:sizeof \ total size in cells
Point:new \ allocate one zero-initialized instance on the heap
Classes can inherit:
: class ColoredPoint extends Point
color
;
All methods of Point become available as ColoredPoint:getX, ColoredPoint:setY, … .
Macros / Inlines
Inline definitions (macros) are declared with the inline keyword and are expanded at compile time.
: inline if!
@numArgs 1 @push @> @if
@f@ @t@ if #t# else #f# then
@else
{ b a } if a exec else b exec then
@then
;
Words prefixed with @ are macro‑only words; they are not emitted to the final byte‑code.
Generating C code
forth> use examples/html.fs
forth> compile test
compile writes a C source file (/tmp/...), invokes the system C compiler, and runs the resulting binary. The generated output is redirected into the REPL.
External commands
The shell word runs a shell command.
: ls [ a" ls -l" shell ] alloc ;
\ same as
: ls | ls -l $$ ;
You can also compile the word to a native binary with compile ls.
Debugging
Enable debug mode:
forth> true debug
The REPL will then print the generated byte‑code, execution time and a step‑by‑step trace (program counter, stack, return‑stack).
You can also request a manual trace:
forth> 5 3 min .
SUB min;TDP;LSI;JIN #0;DRP;JMP #1;#0 NOP;SWP;DRP;#1 NOP;END;
MAIN;L 5;L 3;CALL min;PRI;STP;
3
execution time: 15.947µs
Number of Cmds: 13
Speed: 0.000815 cmd/ns
The actual debugger can be run like this:
forth> debug 34 21 min .
Which gives the following result:
SUB min;TDP;LSI;JIN #0;DRP;JMP #1;#0 NOP;SWP;DRP;#1 NOP;END;
MAIN;L 34;L 21;CALL min;PRI;STP;
11 MAIN | | |
12 L 34 | 34 | |
13 L 21 | 34 21 | |
14 CALL min | 34 21 | 14 |
1 TDP | 34 21 34 21 | 14 |
2 LSI | 34 21 0 | 14 |
3 JIN #0 | 34 21 | 14 |
6 NOP #0 | 34 21 | 14 |
7 SWP | 21 34 | 14 |
8 DRP | 21 | 14 |
9 NOP #1 | 21 | 14 |
10 END | 21 | |
15 PRI | | | 21
16 STP
As you can see on the top there is the ByteCode and below you see the program pointer, the command, the stack, the return stack and the output.
Embedding goforth in Go
Now all you need is a ForthCompiler:
fc := goforth.NewForthCompiler()
fc.Fvm.Sysfunc = func(fvm *goforth.ForthVM, syscall int64) {
switch syscall {
case 999:
value := fvm.Pop()
fvm.Push(value + value)
fmt.Println("This is a custom sys call in Forth")
default:
fmt.Println("Not implemented")
}
}
// Parse the Core lib:
if err := fc.Parse(goforth.Core); err != nil {
goforth.PrintError(err)
}
// Run some code:
if err := fc.Run(": main .\" Hello World!\" ;"); err != nil {
goforth.PrintError(err)
}
// Call custom syscall (calculated 10+10 and prints it):
if err := fc.Run(": customcall 999 sys ; : main 10 customcall . ;"); err != nil {
goforth.PrintError(err)
}
fc.Parse – parses source (adds words to the dictionary).
fc.Run – compiles the word main and executes it immediately.
fc.Fvm.Sysfunc – hook for user‑defined system calls (e.g. syscall 100 above).
Templates
The meta‑command template <name> <filename> converts an arbitrary text file into a Forth word. Everything outside of <?fs … ?> blocks is ignored; the code inside the tags is parsed as normal GoForth.
Example html.tfs
<html>
<head>
<title><?fs title .s ?></title>
</head>
<body>
<?fs 10 0 do ?>
<p><?fs i . ?></p>
<?fs loop ?>
</body>
</html>
forth> template page html.tfs
forth> variable title
forth> a" My page" to title
forth> page \ renders the final HTML
The generated word (page) can be called like any other word; the output is written to the current output stream.
VM commands
The stack machine consists of a single LIFO stack and memory. Memory is adressed by an unsigned number. The stack and memory consists only of numbers.
| command |
description |
| RDI |
Reads a value from the input. The input is implementation dependant. |
| PRI |
Prints a value from the stack as a number. |
| PRA |
Prints a value from the stack as an character. |
| DUP |
Duplicates the top stack value. |
| OVR |
Copies the second value from the top on the top. |
| TVR |
Copies the second pair onto the top pair. |
| TWP |
Swaps the top pair with the pair under it. |
| QDP |
?dup implemented as: if the top value is zero - duplicate it - otherwise do nothing. |
| ROT |
Rotates the top three elements by pushing to stack one element “down” an taking the last element on the top. |
| TDP |
Duplicates the top pair on the stack. |
| DRP |
Drops the top element on the stack. |
| SWP |
Swaps the top pair on the stack. |
| #id NOP |
Does nothing. Used for labeling. |
| JMP #id |
Unconditional jump to label with id |
| JIN #id |
Conditional jump to label with id if the top value on the stack is zero. |
| ADI |
Simple addition of the top pair. |
| SBI |
Simple subtraction of the top pair. |
| DVI |
Simple division of the top pair. |
| LSI |
1 on the stack if the top element is less than the second element. 0 otherwise. |
| GRI |
1 on the stack if the top element id greater than the second element. 0 otherwise. |
| MLI |
Multiplies the first two elements on the stack. |
| ADF |
Simple float addition of the top pair. |
| SBF |
Simple float subtraction of the top pair. |
| MLF |
Multiplies the first two float elements on the stack. |
| DVF |
Simple float division of the top pair. |
| PRF |
Prints a float value from the stack as a number. |
| LSF |
1 on the stack if the top float element is less than the second element. 0 otherwise. |
| GRF |
1 on the stack if the top float element is greater than the second element. 0 otherwise. |
| OR |
1 if one of the first two elements on the stack unequal to 0 else 0. |
| AND |
1 if the first two elements on the stack unequal to 0 else 0. |
| NOT |
1 if the first element on the stack is 0 else 0. |
| EQI |
1 if the first two element on the stack are equal else 0. |
| LV |
Loads a value from the given address. |
| L number |
Loads a value on the stack. |
| LF float |
Loads a float on the stack. |
| STR |
Stores the second element from the stack into the memory address which is the first element from the stack. |
| SYS |
Make a syscall. The top element from the stack is used to make different syscalls. |
| STP |
Quits the execution. |
| SUB name |
Declares a subroutine. Used only for code generation. Not used by the vm |
| END |
Ends the subroutine. Used only for code generation. Not used by the vm |
| MAIN |
Declares the beginning of the main. Used only for code generation. Not used by the vm |
| GDEF |
Creates a new global variable initialized with zero |
| GSET |
Assigns the top value of the stack to a global variable |
| GBL |
Pushes the global value on top of the stack |
| LCTX |
Creates a new context of local variables |
| LDEF |
Pops the top value of the stack and copies it to the local definitions |
| LSET |
Assigns the top value of the stack to a local variable |
| LCL |
Pushes the local value on top of the stack |
| LCLR |
Clears the local definitions |
| CALL name |
Call a SUB routine. |
| REF name |
Pushes the address of a SUB on top of the stack |
| EXC |
Pops the top value from the stack and calls a SUB routine. |
| PCK |
dup = 0 pick |
| NRT |
-rot = rot rot |
| TR |
to r |
| FR |
from r |
| RF |
r fetch |
| TTR |
2 to r |
| TFR |
2 from r |
| TRF |
2 r fetch |
| INC |
Increments the top value of the stack by 1 |
| DEC |
Decrements the top value of the stack by 1 |
Happy forth‑coding!
评论