Skip to content
desirecoPublic

About

An experimental Forth-inspired language with readable composition and a Go interpreter.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Zhex

Small words. Big ideas.

Zhex is an experimental Forth-inspired language for builders: you build the vocabulary you program with, and compose small operations into larger programs. It keeps the idea of passing values through a sequence of words, while adding named inputs, local values, familiar expressions, and clear control flow.

The first interpreter is written in Go. It runs real .zhex files with console input and output. The language is still taking shape; syntax and APIs may change. No version numbers exist yet — versioning starts with the standard library's 0.1 release (versioning policy).

Website and examples · Manifesto · Getting started · Language reference · Roadmap · Project board

What it looks like

word square(n: Int) -> Int
    let result = n * n
    result

let line = read-line("Number: ") try
let number = text.to-int(line) try

flow number
    square
    print

Enter 7 and it prints 49. A word is a function. A flow passes each result to the next word. The checker infers local types and verifies that the operations fit together before the program runs.

Try it

Install Git and Go 1.23 or newer — getting started lists the per-OS install commands — then clone the repository and build the interpreter once.

Linux and macOS:

git clone https://github.com/desireco/zhex.git
cd zhex
go build -o bin/zhex ./cmd/zhex
export PATH="$PWD/bin:$PATH"

Windows (PowerShell):

git clone https://github.com/desireco/zhex.git
cd zhex
go build -o bin\zhex.exe .\cmd\zhex
$env:Path = "$PWD\bin;$env:Path"

The PATH change applies to the current terminal only. To make the command permanent, run just install — it builds the interpreter and copies it to ~/.local/bin (created if missing; pass another folder as an argument), which must be on your PATH; getting started covers the details, including Windows and common problems.

Run the greeting program; it asks for your name and prints a greeting:

zhex run examples/hello.zhex

The first build downloads the few small Go modules the interpreter uses; later builds work offline.

For more examples:

zhex run examples/fizzbuzz.zhex
zhex run examples/fibonacci.zhex
zhex run examples/factorial.zhex
zhex run examples/palindrome.zhex
zhex run examples/gcd.zhex
zhex run examples/times-table.zhex
zhex run examples/life.zhex
zhex run examples/edit-distance.zhex
zhex run examples/text-stats.zhex examples/text-stats-sample.txt
zhex run examples/file-work.zhex .
zhex run examples/env-config.zhex .

Start with the short guide for input, output, and the main language constructs.

Editor support provides syntax highlighting for Vim/Neovim, VS Code, and Zed.

Compile to WebAssembly or native Go

zhex compile file.zhex [-o out] [--target=browser|wasi|native] turns a program into a standalone WebAssembly module or a native binary. The whole program is checked first, exactly as zhex run checks it — a program that fails the checker produces no artifact. The default --target=browser builds a module for a web page or JavaScript host; --target=wasi builds one that runs under a WebAssembly runner such as wasmtime:

zhex compile examples/collatz.zhex --target=wasi
wasmtime run --dir .::/ examples/collatz.wasm

The WebAssembly targets need the free wasm-tools assembler — cargo install wasm-tools, pacman -S wasm-tools, or brew install wasm-tools — and running the module in a browser needs nothing else. Compiled modules cost roughly 38–40 KB gzipped regardless of program size.

--target=native emits a self-contained program directory — readable main.go, go.mod, and the zhexrt runtime sources — and builds it with the Go toolchain, keeping the interpreter's full 128-bit integers:

zhex compile examples/collatz.zhex --target=native
printf '27\n' | examples/collatz/collatz

The compiling guide covers targets, diagnostics, and which constructs compile today; docs/wasm-plan.md records the WebAssembly compiler's design.

Learn through examples

The examples page groups complete, inline source programs into language basics and algorithms.

Language basics

Example What it demonstrates
Greeting Read a line, build a string, and print it.
Composition Typed words, inferred locals, and a flow that prints 32.
With blocks Fix one seed value and apply many operations to it — every step receives the seed.
Calls Define a word and call it with either parentheses or the simple comma-separated form.
Word defaults Infer a parameter type from its default, evaluate defaults lazily, and create fresh mutable defaults per call.
Partial calls Use explicit holes with words and built-ins, capture values, and handle a fallible partial when it is invoked.
Records A nominal named type, positional constructor, and immutable fields.
Choices Declare concrete and one-parameter alternatives and handle them with a match.
Lists and arrays Shared storage, checked reads, concise indexed writes, dual-binding iteration, predicate selection of elements and rows, row-major arrays, and overlap-preserving resize.
Maps Inferred key/value types, Option lookup, insertion order, updates, and map operations in flows.
Dates and time zones Compare a calendar day and 24 elapsed hours across a daylight-saving transition.
JSON configuration Decode a typed record with defaults for missing fields, then encode it as compact JSON.
JSON trees Parse a heterogeneous payload into a Json tree, walk it with a recursive word, and encode it back byte-for-byte.
XML configuration Decode an embedded XML document with attribute fields, a list of endpoint records, and an optional owner.
Text stats Program arguments, whole-file counts, and streamed uppercased lines.
Line filter Split embedded records, select by literal prefix and suffix, and join a report.
Score report Trim and score embedded records with list.map, list.filter, list.fold, list.find, list.any, and list.all.
Sorting Rank records with list.sort-by and a named key word, and sort plain text with list.sort.
File write Attempt a checked report write and handle the failed Result with catch.
Lexical paths Compose and decompose paths with file.join, base, extension, and directory-of.
File work folder Create a work folder, write reports into it, inspect them, and remove the whole tree.
Env configuration Write a .env fixture, load it with env.load, and read each setting back as an Option match.
Error recovery Catch invalid numeric text, show a short explanation, and continue with a fallback value.
Exit status Validate a requested status and end deliberately with console.exit.
Filter tool The first end-to-end application: zhex run examples/filter.zhex <pattern> <file> prints the lines containing a literal, case-sensitive pattern; wrong arguments fail with a usage line and a missing file reports its natural FileError. Not a registered website example — it needs arguments to run.
Math modules A two-file program: use math imports a sibling library and keeps one helper underscore-private.
HTML page A two-file program over the html composition module: text escapes by default, markup nests through element with one deliberate html.raw, and a javascript: link target is rejected.
Markdown report A two-file program: use md renders records and lists into a Markdown report through a pure-Zhex module.
Markdown module tests Parse Markdown into the flat block list, edit sections and blocks, and pin the round-trip and HTML export laws through md.parse, the section and block words, md.render, and md.to-html.
Module tests A three-file program: the sibling test module's check(condition, label) fails the run with its label when a condition is false — the *.test.zhex shape the zhex test runner discovers.
EPUB book A three-file program: the epub module assembles a two-chapter EPUB 3 archive — mimetype first — over the pure-Zhex zip writer, in memory for deterministic output.
EPUB module tests Pin the UTF-8 encoder vectors, the container/OPF/nav XML parts, mimetype-first ordering, and the whole-book bytes.
ZIP module tests Pin the known CRC32 vectors, a byte-pinned single-entry archive, and the empty edges of the stored-ZIP writer.
PDF document A two-file program: the pdf module hand-emits a three-chapter book with wrapped paragraphs, 24pt chapter titles, and page breaks, writes it, prints its structural facts, and removes it.
PDF module tests Pin the PDF objects, xref offsets, WinAnsi-escaped text, and whole-document bytes.
Text diff A two-file program: the diff module computes the Myers line diff between two texts, prints it review-style, and applies it back — apply(diff(a, b) try, a) == b.
Diff module tests Pin the diff and patch law over kept, deleted, and inserted lines and the CRLF normalization rule.
Writer showcase The whole text model in one program: load a draft through the md module, outline it, run sentence and word passes, edit by section and block, and publish markdown and an md.to-html fragment.
Writer module tests Pin the showcase's outline, passes, edits, and published forms.

Algorithms

Example What it demonstrates
FizzBuzz Decisions, remainders, and a bounded loop.
Fibonacci Explicitly mutable locals and iterative calculation.
Factorial Accumulation and integer boundaries.
Palindrome Text input, comparison, and Unicode code-point reversal.
GCD Euclid's algorithm by recursion, seeded into a flow.
Times table A bounded loop building strings from integers.
Game of Life Carry a finite grid through generations in a flow; out-of-board neighbors are dead.
Edit distance Use a two-dimensional dynamic-programming table to compare strings by Unicode code point.
Collatz steps Count each number's steps to reach 1 with a while loop that ends by its condition.

The example guide records expected output and edge cases. The language contract defines the current rules.

What works today

The interpreter supports typed word definitions, named parameters, inferred or explicitly annotated local types, immutable let bindings, mutable var bindings, nominal records and one-parameter choices with exhaustive matching, shared mutable lists, arrays, and maps, integers, booleans, strings, conditions, bounded loops, and checked flows. Console reads, program arguments, printing, integer formatting, 25 text words, line buffers, streamed file reads, and typed JSON decoding/encoding are built in. Programs split across files: use math imports the sibling math.zhex, its words and types are callable qualified (math.gcd, model.Customer), and a leading underscore keeps a word or type private to its file. An interactive REPL, zhex repl, checks and runs each entry as you type it, keeping words, values, types, and adopted modules across the session. A compiler, zhex compile, turns the same checked programs into standalone WebAssembly modules for browser and WASI hosts, or into native Go binaries with the interpreter's full 128-bit integers.

The whole file is checked before execution, including unused word bodies. Static errors do not prompt or consume input. Runtime errors report a source location; integer overflow, division by zero, invalid input, and end-of-input are handled explicitly.

Where we are heading

We want a readable, modular language for command-line tools, games, web applications and servers, HTML/text processing, and database software. High performance is a goal to establish through implementation and measurement.

The current interpreter defines and tests behavior; the compilers reuse those checked programs. Generic records and words, and broader resource scopes, are future work. Zhex is inspired by Forth; it does not aim for Forth compatibility. Mirth, Factor, and 8th also inform the design research. Further language presentation research explores how to explain the language through readable examples.

Tests are part of the language

Tests describe source programs, supplied input, expected output, and expected errors. They validate the examples as well as scope, evaluation order, type checking, arithmetic boundaries, Unicode, and input/output failures.

go test ./...
go test -race ./...
go vet ./...

See the test catalog to find the executable specification for each feature.

Development commands

With just installed, run just to list the project's commands:

just test
just check
just build
just install
just run fibonacci
just site

just run starts the greeting example and keeps console input available. Install site dependencies with npm ci --prefix site (Node 22.23.4 or newer (or Node 24)). just site builds the website and serves it at 127.0.0.1:8000/zhex/. Pass a different port with just site 8080, or build without serving with just build-site. just test-race runs the race checks. The underlying Go commands remain available directly.

Project documents

License

MIT — see LICENSE. Copyright © 2026 Dakic OnLine LLC (Zeljko Dakic).

About

An experimental Forth-inspired language with readable composition and a Go interpreter.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages