A stack-based virtual machine and compiler written in Go. This is a port of a Stack Machine written in C++ by Christian Stigen Larsen.
Stack Machine Go is a lightweight, stack-based virtual machine that executes simple programs in a Forth/PostScript-like language. It consists of:
- A virtual machine (VM) that executes bytecode
- A compiler that translates assembly-like source code to bytecode
- An interpreter that compiles and runs code on-the-fly
- A disassembler that converts bytecode back to human-readable form
- Simple but powerful instruction set
- Stack-based execution model
- Memory manipulation
- Branching and function calls
- Input/output operations
- Label-based addressing
- Go 1.18 or higher
git clone https://github.com/matt-dunleavy/stackmachine-go.git
cd smg
go build -o smg
Alternatively, use the provided Makefile:
make build
Stack Machine Go has several commands:
smg compile hello.src
# Outputs hello.bin
smg run hello.bin
smg interpret hello.src
smg disassemble hello.bin
All commands accept input from stdin if no file is specified:
cat hello.src | smg interpret
; Hello World program
'H OUT
'e OUT
'l OUT
'l OUT
'o OUT
', OUT
' OUT
'W OUT
'o OUT
'r OUT
'l OUT
'd OUT
'! OUT
'\n OUT
HALT
; Main program
'H OUT
'i OUT
'! OUT
' OUT
PUSHIP 24 ; Push return address
32 ; Call function at address 32
JMP ; Jump to function
'\n OUT ; Print newline after return
HALT ; End program
; Function that prints "there"
't OUT ; Print "there"
'h OUT
'e OUT
'r OUT
'e OUT
POPIP ; Return to caller
The Stack Machine is based on a simple stack-based architecture:
- Operations operate on a data stack
- A separate instruction pointer (IP) stack enables function calls
- Memory is organized as a flat array of 32-bit words
- Instructions are encoded as 32-bit words
See the docs directory for more detailed documentation on the architecture, instruction set, and compiler.
This project is released to the Public Domain. In jurisdictions where such terms are not recognized, the source code to this software is distributed under the terms of the ISC License. See the LICENSE file for details. The original Stack Machine was also placed in the public domain by its author, Christian Stigen Larsen.
- Original Stack Machine (C++) by Christian Stigen Larsen