A small procedural language with an ML-style type system.
Turkey brings type inference, algebraic data types, and first-class functions to code with familiar loops, early returns, and mutable state. The aim is to make straightforward programs easy to write, while keeping the type system strong enough to support reusable abstractions.
- Write the algorithm directly. Evaluation is strict, functions take ordinary argument lists, and loops and mutation are part of everyday code.
- Let the compiler connect the types. Types are checked statically and inferred across functions. Add annotations where they help explain an interface.
- Make alternatives explicit. Model choices with algebraic data types,
handle them with pattern matching, and compose
OptionandEitherwith?. - Build power in the library. Operators, iteration, indexing, and generic functions are defined through type classes. User-defined types can participate in the same syntax as the standard library.
Parse a few rectangles and add up their areas:
type Rectangle = Rectangle { width : Int, height : Int }
fun parseRectangle(text) {
let (width, height) = String.splitOnce(text, "x")?
Some(Rectangle {
width = Int.parse(width)?,
height = Int.parse(height)?
})
}
fun area(rect) = rect.width * rect.height
fun main() {
var total = 0
for text in ["3x4", "5x2", "oops"] {
match parseRectangle(text) {
Some(rect) -> {
total = total + area(rect)
}
None -> print("Skipping: " + text)
}
}
print(total)
}Skipping: oops
22
The compiler infers parseRectangle : fun(String) -> Option Rectangle.
Each ? unwraps a successful result; a missing separator or invalid integer
makes the parser produce None. The caller handles both cases explicitly.
Tuple destructuring, named record fields, and an ordinary mutable accumulator
work together without type annotations on the functions.
The compiler is written in Turkey. On an arm64 Mac running macOS 14.4 or
later (the runtime sleeps on os_sync_wait_on_address), it builds from the
compiler committed in bootstrap/, with no C compiler, assembler or linker
(for Linux, see below):
sh scripts/build.shThat leaves a compiler in build/stages/turkey. Save the example as
rectangles.gob, then compile and run it:
build/stages/turkey build rectangles.gob
./rectanglesTo run it from anywhere as turkey, link it onto your PATH:
sh scripts/install.sh # ~/.local/bin/turkey -> build/stages/turkey
sh scripts/install.sh ~/bin # or a directory of your choosingThe checkout is the installation: the compiler finds its library by resolving
its own path, symbolic links included, and taking the nearest lib/ holding
Prelude.gob in that directory or one above it. $TURKEY_LIB, if it is set,
names the library instead. The working directory is never searched, so a
lib/ in your own project cannot stand in for it. Rebuilding updates what
turkey runs; after moving the checkout, run install.sh again.
Besides doc ("Library documentation" below), the compiler has two commands.
build writes the program as an executable that runs as it is, with no
assembler and no linker. Without -o, it goes to the working directory, named
after the entry file without its extension; -o PATH names it, and -o -
writes it to standard output. build -S writes the program's assembly
instead, as cc -S does: to the entry file's name with .s in place of its
extension, or wherever -o names. Only -S chooses assembly. -o prog.s
without it writes an executable named prog.s. The system assembler accepts
-S's output, and the tests assemble it to check the compiler's own
encoder, but it is for reading and checking, not for building programs.
The executable is a signed Mach-O on a Mac, and on arm64 Linux an ELF that
loads glibc 2.34 or later. It is written for either target from any host, with
--target. It loads the C library -- libSystem on a Mac, glibc's libc.so.6
and libm.so.6 on Linux -- and the libraries the program calls into: a program
that calls Net.TLS loads OpenSSL 3's libssl and libcrypto. On Linux they
are libssl.so.3 and libcrypto.so.3, and nothing is read to write them. On a
Mac, turkey reads each library's install name from libssl.3.dylib (and so
on), found in the directories of $TURKEY_DYLIB_PATH, separated by colons,
then /opt/homebrew/lib and /usr/local/lib, then each Homebrew package's
opt/*/lib; so brew install openssl@3 is enough. Writing a Mac executable
that loads such a library on any other machine needs $TURKEY_DYLIB_PATH,
naming a directory that holds a copy of the library. Either executable
carries the unwind information and, with -g, the debug information a linked
one does (see "Debugging and profiling").
A program that imports Net.TLS needs OpenSSL 3 installed where it runs. On
Linux that is the system's (apt-get install libssl3 on Debian and Ubuntu,
or libssl-dev for the headers the tests compile against). On a Mac it is
Homebrew's (brew install openssl@3), since the system's own
/usr/lib/libcrypto.dylib ends any process that loads it. The tests find it
the same way, or under $TURKEY_OPENSSL if it is set, and
make their certificates with that installation's openssl.
check compiles as far as the last stage that can reject a program and
writes nothing. Either command takes --dump STAGE,... to print what a stage
produced: build/stages/turkey check --dump types rectangles.gob shows the
inferred types, and running the compiler with no arguments lists the stages.
build --timings reports on standard error how long each phase took, how the
backend's time is spread over functions, and how much of the optimizer's work
could run in parallel.
A program's tasks (System.Task, System.Parallel) run on one worker thread
per performance core -- every core on a Mac without performance levels; on
Linux, every CPU the program may run on, or its cgroup's CPU limit where that
is lower -- and the compiler is such a program: it compiles in parallel, and emits
the same bytes however many workers it has. TURKEY_WORKERS=N sets the number
of workers: how many tasks run at once. TURKEY_WORKERS=1 runs tasks
interleaved on the program's own thread, in a fixed order, unless a task waits
long enough in a call that cannot be polled, such as a file read or flock:
then another thread runs the rest meanwhile, as one does beside each worker
blocked in such a call. The test suite sets it to 1 for everything it runs
unless a test asks for more, since it runs a process per core already.
The suite also sets TURKEY_CHECK_BINDERS, which has the compiler check that
name resolution recorded a binder for every variable a program binds or reads;
a gap is an internal error. It costs a walk of the program, so it is off
otherwise.
The compiler that builds it is bootstrap/, which holds an earlier commit's
compiler as an executable for macOS and one for Linux, gzip'd, and the
commit they came from. scripts/build.sh checks their hashes, unpacks the
one for the host and builds with it. sh scripts/build.sh --fixpoint checks
the fixed point: the compiler built from today's source writes exactly the
executable it is. scripts/reproduce-bootstrap.sh checks the committed
executables themselves: the commit they name, built from its own bootstrap,
writes the same bytes. scripts/bump-bootstrap.sh replaces the committed
compiler, which is rare and deliberate. Each script explains itself at the
top.
build -g adds a line table and the DWARF a debugger needs to find it: a
compile unit for the program and an entry for each function. It changes no
code: a program built with -g runs the same instructions as one built
without.
build/stages/turkey build -g rectangles.gobOn a Mac, the executable carries the DWARF itself, in a __DWARF segment
that is never loaded, and lldb, atos, sample, Instruments and crash
reports read it there. There is nothing to keep beside it and nothing to run
afterwards. Do not run dsymutil on such an executable: it reads only a
linker's map, so it writes a .dSYM with no DWARF in it, which lldb then
prefers to the executable's own. strip leaves the DWARF in place; build
without -g for an executable without it.
On Linux, the DWARF goes in the ELF's debug sections, which are never loaded,
as a linker does: gdb reads them there, strip removes them and
objcopy --only-keep-debug copies them out.
-g is --debug=full. --debug=lines writes less: the line table, the
functions and the calls inlined into them, which is all a profiler or a
backtrace reads, and none of what a debugger needs to show a variable.
Then a debugger stops at a line and names the frames by function, file and line:
lldb ./rectangles -o 'breakpoint set --file rectangles.gob --line 4' -o run -o bt
gdb ./rectangles -ex 'break rectangles.gob:4' -ex run -ex btA debugger names a function by its display form, which spells the
compiler's separators the way a reader would: Main#area@Rectangle, area
specialized to Rectangle, is Main.area[Rectangle]; an instance's method,
%inst.Data.Hashable#Hash.Int#hashInto@FNV1a, is
Hash(Int).hashInto[FNV1a]; a lambda in makeRoom is
Turkey.Stdout.makeRoom.<lambda0>. src/Turkey/Demangle.gob has the rules.
The display form is also a breakpoint, and a call the optimizer inlined is
still a frame:
lldb ./rectangles -o 'breakpoint set --name Main.area[Rectangle]' -o run -o bt
gdb ./rectangles -ex "break 'Main.area[Rectangle]'" -ex run -ex btstops in Main.main where area's code was copied, and in area itself
where it was not, and bt shows area at its own line above main at the
line of the call. gdb needs the quotes around a name with brackets in it. A
breakpoint by symbol, breakpoint set --name Main#area@Rectangle or
break 'Main#area@Rectangle', stops only in the copy that has the symbol.
In lldb a breakpoint on every specialization of area, inlined copies
included, is a regular expression: breakpoint set --func-regex '^Main\.area\['. gdb's rbreak ^Main\.area\[ sets a breakpoint on each
specialization it matches, but each one stops only in the copy that has the
symbol, as a breakpoint by symbol does.
frame variable in lldb and info locals in gdb show a function's
parameters and locals wherever the code still holds them: in a register until
its last use, or in the frame slot the collector or the register allocator
keeps it in.
The debug information describes values as the compiled code holds them, so
without help a debugger shows a String as a pointer and a Vec as its
storage. The formatters in debugger/ show them as the source writes them --
a String as its text, an Array, a Vec or a Map as its elements, a sum
such as Option or Either as the constructor it holds, a record as its
fields:
scripts/turkey-lldb ./rectangles -o 'breakpoint set --file rectangles.gob --line 4' -o run -o 'frame variable'scripts/turkey-lldb is lldb with debugger/turkey_lldb.py imported; in a
session of your own, command script import debugger/turkey_lldb.py does the
same. On Linux, a program built with -g names turkey_gdb.py for gdb to
load. gdb looks for it along its source path, so it loads it once
~/.gdbinit adds the directory there and to the safe path:
directory /path/to/turkey/debugger
add-auto-load-safe-path /path/to/turkey/debugger
Profilers and backtraces need no -g to name functions. Every function keeps
a frame pointer, so sample PID and Instruments on a Mac, and
perf record --call-graph=fp on Linux, walk the stack and show the functions
by name. Every build also carries unwind information -- compact unwind on a
Mac, .eh_frame on Linux -- which lldb and gdb read to find a function's
caller from any instruction in it, its first and its ret included. A
backtrace inside a task or coroutine ends at the coroutine's base. With -g,
Instruments and perf report --sort srcline also show the lines samples fall
on, and Instruments shows inlined calls as frames. sample shows a sample in
inlined code at the line of the outermost call.
A profiler names a function by its symbol, which scripts/demangle.py
rewrites to the display form, in sample's and perf script's output and
in a crash report:
sample rectangles 5 -file report.txt && python3 scripts/demangle.py report.txt
perf script | python3 scripts/demangle.py-S -g writes the debug information into the assembly too, all but the line
table, which it leaves to the assembler as .loc rows. Assemble it in
DWARF 5, as the rest is: cc -gdwarf-5 -c rectangles.s.
Two environment variables choose the toolchain, for scripts/build.sh and for
the tests alike. Each is split into words the way a shell would split it.
TURKEY_CCis the C compiler that compiles the C files a few tests run beside a program, and assemblesturkey's assembly where a test checks it. Unset, it iscc. Buildingturkeyneeds none, but on a host that is not a target,scripts/build.shbuilds for the target it links for.TURKEY_RUNis a prefix for running a programturkeywrote, or a built compiler. Unset or empty, the program runs directly.
On x86-64 Linux, the arm64 output runs under qemu-user. Every executable
turkey writes, the committed compiler included, is dynamically linked
against glibc, which qemu finds in the cross toolchain's
/usr/aarch64-linux-gnu when QEMU_LD_PREFIX names it. Set up the machine
with:
apt-get update
apt-get install -y \
qemu-user-static \
gcc-aarch64-linux-gnu libc6-dev-arm64-cross \
python3-pytest python3-pytest-xdist
B=/proc/sys/fs/binfmt_misc
if [ -d $B ] && [ ! -e $B/register ]; then
mount -t binfmt_misc binfmt_misc $B 2>/dev/null
fi
if [ -w $B/register ]; then
cat /usr/lib/binfmt.d/qemu-aarch64.conf > $B/register 2>/dev/null || true
fiThen set TURKEY_CC="aarch64-linux-gnu-gcc -static" and
QEMU_LD_PREFIX=/usr/aarch64-linux-gnu, and leave TURKEY_RUN empty. The
last step of the setup registers qemu with the kernel's binfmt_misc, so an
arm64 binary runs as ./program, with no prefix, mounting binfmt_misc first
where the container has not. That registration is
lost when a machine is restored from a snapshot, so the repository's
.claude/settings.json runs the same line as a SessionStart hook. On macOS the
hook does nothing. Where binfmt_misc cannot be written, set
TURKEY_RUN=qemu-aarch64-static instead. pytest comes from apt here, because Ubuntu
24.04 refuses a system-wide pip install.
With those set, sh scripts/build.sh builds the compiler for arm64 Linux from
bootstrap/arm64-linux.gz, and --target arm64-linux makes a compiler on
any platform write Linux executables.
An executable for --target arm64-linux needs none of the cross toolchain:
turkey writes it, dynamically linked, on any host, with no linker and no arm64
libc. It runs on glibc 2.34 or later -- RHEL 9 and its rebuilds,
Ubuntu 22.04, Debian 12, and anything newer -- the first release with
pthread_create in libc.so.6. On an older glibc it stops before main
with symbol lookup error: undefined symbol. It names its loader
/lib/ld-linux-aarch64.so.1, as every glibc distribution installs it; on
NixOS or Guix, patchelf it as any prebuilt binary.
The goldens in tests/programs/ are the same on both platforms. Under qemu
the compiler runs many times slower than on an arm64 Mac, and the few tests
that compile the compiler's own source take most of the suite's time. Nothing
in CI runs this setup.
On an arm64 Linux machine none of that is needed: the compiler builds and
the programs run directly, with no C compiler. CI does this on GitHub's arm64
runners (.github/workflows/linux.yml), building from the bootstrap and
running the suite and the fixed point split across jobs by
scripts/ci-shard.sh.
tests/test_debug_info.py reads -g's DWARF with llvm-dwarfdump, and it
and tests/test_unwind.py run lldb on macOS and gdb on Linux; each skips a
check, saying which tool is missing, where one is not installed.
One group of tests depends on the C compiler, and skips, saying why, where it
cannot do what it needs: under
TURKEY_CC="clang --target=aarch64-linux-gnu -static", the UBSan probes in
test_allocators.py and test_runtime_gc.py. Linking -fsanitize=undefined
statically needs compiler-rt built for aarch64, which Ubuntu's clang does not
ship. gcc's cross toolchain has libubsan.a, so under gcc they run.
vim/ is a Vim and Neovim plugin for .gob files: filetype detection,
syntax highlighting and indentation. Add the directory to runtimepath, or
point a plugin manager at it (Plug '~/path/to/turkey/vim'). Its tests run
headless in whichever of vim and nvim are installed, and check that the
fixture parses when TURKEY_BOOT or build/stages/turkey is a compiler:
sh vim/test/run.shturkey doc FILE... checks the modules in the files and writes JSON describing
what each one exports. Every function, value, type, class, instance and
operator gets its type as the checker has it, its line, and its doc comment:
the --- comments directly above it (doc comments).
A module that re-exports something it imported directly from an undocumented
module -- the library's implementation, or a module not among the files --
shows it in full. A re-export of a documented module's copy stays a link to it.
turkey doc --html DIR FILE... writes the same description as a static
website in DIR: an index, one page per module, and a search over names,
types and comments. To build it for the whole library:
sh scripts/docs.shThat writes build/docs/index.html, which opens in a browser as a file,
alongside one page per module and the JSON. The same site is published to
https://p7g.github.io/turkey/ from main by .github/workflows/docs.yml.
Turkey is an experimental language under active development. The compiler is written in Turkey and compiles itself, with an arm64 backend that emits assembly directly. The standard library is written in Turkey over a small set of runtime primitives. A Python implementation served as the reference while the compiler was ported to Turkey, and was retired once the tests ran against the self-hosted one.
For more depth:
- Language reference: the syntax and meaning of every construct
- Compiler written in Turkey
The recorded programs in tests/programs/, the case archives in
tests/cases/ and the examples in docs/ref/ are run by a harness written in
Turkey, tests/harness/:
sh scripts/test.sh # every case, one per core at once
sh scripts/test.sh tests/programs/bf # the programs whose path starts so
sh scripts/test.sh tests/cases/placeholders.cases::condition # some of an archive's cases
sh scripts/test.sh docs/ref/types.md # one chapter's examples
sh scripts/test.sh -v --shard 2/4 # a quarter of them, passes listed
sh scripts/test.sh --selftest # the harness checked on its own cases
sh scripts/test.sh --bless PATH # PATH's goldens rewritten from its output
It builds turkey (or uses TURKEY_BOOT) and compiles itself with the
committed bootstrap compiler, both cached in $TMPDIR/turkey-test/, as are
compiled programs. A program's expected outcome is a directive in it: --@ error (it
must not compile), --@ panic, --@ exit: N, and otherwise exit 0. A case
that fails is shown with a diff, and every actual output is kept under
$TMPDIR/turkey-test/actual/. A reference example is named by its chapter and
the line of its fence, docs/ref/types.md:40, and checked against what the
chapter says of it (docs/ref/README.md); --bless never writes one.
A case archive holds many small cases in one text file, cut into sections by header lines:
-- shared Shapes.gob -- a module written beside every case (before the first case only)
-- case area_of_a_square -- starts a case; `--` comments and `--@` directives follow
--@ error as in a program, plus `check` and `matrix: VAR=1,4`
-- Main.gob -- the case's entry module; other `NAME.gob` sections sit beside it
-- stdout -- its exact stdout; also `stderr`, `error`, `panic`,
`types`, `kinds` and `classes`
A case with no stdout or stderr section must print nothing there. error
is the diagnostic without its place, panic the panic's message, and a dump
section holds only the case's own declarations. --@ matrix runs the case once
per value, with the variable set in its environment, as NAME[VAR=4]. Any
other header or directive is an error, so a line reading -- X -- inside a
module has to be reworded. tests/harness/Archive.gob gives the whole format.
--bless writes the selected programs' actual output over their .expected
files, and their dumps over the .types, .core, .opt and .mono files
they already have. In an archive it rewrites the case's expectation sections
in place, adding a missing stdout, stderr, error or panic section, and
leaves every other byte of the file alone. It refuses a case that crashed,
timed out, did not end as its directive says, printed nothing where its golden
had output, or printed what an archive cannot hold, and says why. When more than 5 are refused it writes nothing at all, since that
is what a broken compiler looks like. It never changes a directive.
The rest of the tests are Python. Install their dependencies with
python3 -m pip install -e '.[dev]', then run python3 -m pytest tests -q.
The tests compile their programs with turkey, which is built from the
committed bootstrap on first use; TURKEY_BOOT points them at one you built
yourself instead.
The suite runs in parallel by default, and three commands cover it:
python3 -m pytest tests -q # everything but the fixed point
python3 -m pytest tests -q -m bootstrap # the fixed point alone
python3 -m pytest tests -q -m '' # both, in one run
To run both, use the last one rather than the first two in turn. The fixed
point is a chain nothing can parallelize -- turkey writing the compiler, and
that writing itself again -- and in one run it overlaps the rest of the suite
instead of starting after it.
On a 16-core arm64 Mac, after a change to src/ (so turkey is rebuilt), the
combined run takes about nine minutes. The build of turkey and everything the tests
compute from it are cached in $TMPDIR by content hash, so a second run
with nothing changed is quicker; -n0 runs serially, for debugging.
To check the heap while debugging a program, compile it with
turkey build --gc-verify. Each collection independently checks object bounds,
each object's size class against the size its allocation recorded (objects
carry no size of their own, so such a build keeps a size table per region),
traced references, shadow-stack and native roots, marking completeness,
region bookkeeping before and after sweeping, and the generational
invariants: an old object holding a young one must have been remembered by
the write barrier. Failures report
heap verifier: and terminate the process with exit status 1 before proceeding
to the next collection phase.
Run it with TURKEY_GC_STRESS=1 to collect and verify at every allocation.
At the compiler's own scale that does not finish; TURKEY_GC_STRESS=N
collects at random intervals averaging N allocations instead, and
TURKEY_GC_STRESS_SEED picks the sequence (1 by default), so a failure can be
repeated and several seeds put the collections at different allocations.
Under stress one collection in eight is full and the rest are minor;
TURKEY_GC_GENERATIONAL=0 makes every collection full, to tell a collector
bug from a missed write barrier.
Verification scans the allocated heap and uses temporary native memory for a
region index. A program compiled without --gc-verify has no verifier in it
at all, and says so on stderr if it is run with TURKEY_GC_VERIFY set. It
checks the roots and layouts the compiler supplies, so behavioral stress tests
are still needed to catch references omitted from those descriptions.
turkey build --gc-stats compiles in the collector's accounting: a line per
collection and a summary at exit, on stderr. Counting sends every allocation
through the runtime rather than the code compiled in line for it, so a stats
build's times are slower than a plain one's.