man k/ngn-k-source
Reading ngn/k's C: how a tiny interpreter is written
How small can the interpreter for a whole programming language be, and what does its source look like when it is written in the style of the language it implements?
ngn/k is an interpreter for K, an array language in which most primitives are
one character and a program is often one line. Its C source is written the
same way. At commit
b9eeb91
(2026-07-21) the whole interpreter is 2,099 lines in 24 .c and .h files,
119,403 bytes, with lines up to 210 characters long. 629 of those lines are
g.h, which is generated, so 1,470 are written by hand. That covers a parser, a
bytecode compiler and virtual machine, a memory manager, every primitive
with variants for each storage type, file and socket I/O, JSON, and a
REPL. This is a tour of how it fits.
The map
The readme lists what each file holds. The core:
0.c main() k.h embedding api
m.c memory manager and repl a.h common header
p.c parser g.h header generated by g.k
b.c bytecode compiler and vm t/ unit tests
a.c eval, apply, amend: . @
h.c shape-related: x#y ,x x,y
o.c order and equivalence
f.c find
main is one line
(0.c line 21):
initialise, store the command-line arguments, then either start the REPL or
load the file named as the first argument.
A dialect of C
Reading any function means learning the macros first. a.h defines dozens
of one- and two-letter ones, and these carry most of the weight
(a.h lines 6 to 27):
#define _(a...) {return({a;});}
#define P(x,a...) I(x,_(a))
#define I(x,a...) if(x){a;}
#define X(a...) S(xt,a)
#define R(x,a...) case x:_(a)
#define R_(a...) default:_(a)
_ turns a body into a function body that returns its last expression,
using GCC’s statement expressions. P is an early return: “if x, return a”.
X switches on the type of the argument x, and R is a case that
returns. Type-set macros such as Ril (an int or long atom) and RMT
(any list or table) expand to several case labels. They live in g.h,
629 lines with 73 R macros among them, and g.h is not written by hand. It is generated by g.k, a K
program, from compact descriptions of type sets
(g.k).
With those, here is grade down, the whole function (o.c line 38):
X1(dsc,RMT(x=rev(asc(rev(x)));sub(ai(xN-1),x))Rm(grdm(x,dsc))Ril(cls(gl(x)))R_(et(x)))
Expanded by hand, it reads:
A dsc(A x) {
switch (type(x)) {
case /* any list or table */:
x = rev(asc(rev(x))); // reverse, grade up, reverse
return sub(ai(len(x) - 1), x); // n-1 minus each index
case tm: return grdm(x, dsc); // dictionary: grade values, return keys
case ti: case tl: return cls(gl(x)); // integer atom: close that file handle
default: return et(x); // type error
}
}
So grade down is stable by construction: grading the reversed list up puts
equal items in reverse order, and the second reverse restores theirs. And >
applied to a number closes a file descriptor, because each character carries
every meaning K gives it.
One more macro appears everywhere: x(a) evaluates a, drops one reference
to x, and returns a
(g.h line 490).
Reference counting is manual, and this is how a function releases its
argument once it has the result.
A value is a 64-bit word
Every K value has the C type A, an unsigned 64-bit integer. A comment in
a.h gives the layouts
(a.h lines 115 to 130):
//header bytes: b....... XXXXXXXX ....OEkt rrrrnnnn
//tagged value bits (t=type,v=value,o=srcoffset,k=arity,x=ptr):
// tttttttt........................vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv tc,ti,tu,tv,tw
// tttttttt................oooooooovvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ts
// tttttttt....kkkkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx tx
// ................xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx00000 other(pointer)
A character, a 32-bit integer, a symbol or a primitive verb is packed into
the word itself, with its type in the top byte. Anything else is a pointer
whose top byte is zero, and the type lives in a 32-byte header just before
the data: a size-class byte b, a free-list link, the type t, a
reference count r and a length n.
The list types come in widths. The type enum and its width table
(a.h lines 103 to 107)
give integer lists five storage types: tB (bits), tG (1 byte), tH (2),
tI (4) and tL (8). The programmer sees one type, `I. Results are
squeezed to the narrowest width that holds every item: sqz ORs the items
together and tZ picks a width from the count of leading zero bits
(c.c lines 30 to 35,
m.c line 59).
The widths show in the process’s peak memory, for a list of 100 million
items made by repeating a short list:
for e in '1 2' '1000 2000' '100000 2' '10000000000 2' '1'; do
echo "x:100000000#$e;#x" > w.k
printf '%-16s %s\n' "$e" "$(/usr/bin/time -l k w.k 2>&1 | awk '/maximum resident/{print $1}')"
done
How to read the K part: 100000000#y repeats y until it has 100 million
items (# is take), x: names the result, ; separates statements, and
#x is its length.
1 2 102187008
1000 2000 202194944
100000 2 402210816
10000000000 2 802209792
1 402210816
1, 2, 4 and 8 bytes per item. The last line is the exception: a single number is an atom, and repeating an atom makes a 4-byte list without squeezing it.
There is one more list type, tE, labelled !i in the table. !n (the
numbers 0 to n−1) doesn’t allocate n numbers. It stores the two ends of the
range
(m.c line 57),
and a few primitives use the ends directly. Sum over a range is the
triangle-number formula
(3.c line 34):
\t +/!1000000000
+/!1000000000
\t +/100000000#1
How to read it: \t is an interpreter command that runs the expression and
prints the time in milliseconds. +/ is sum (/ puts + between the
items), and !1000000000 is the first billion natural numbers.
$ k sum.k
0
499999999500000000
76
Summing a billion numbers takes no measurable time. Making a real list of 100 million ones and summing it takes 76 ms.
Primitives are table entries
The parser turns each primitive character into an index. vc lists the
characters in order, and two arrays of function pointers, v1 for one
argument and v2 for two, hold the implementations at the same index
(a.h lines 151 to 154):
vc: : + - * % ! & | < > = ...
v1: sam flp neg fir sqr til whr rev asc dsc grp ...
v2: dex add sub mul dvd exc mnm mxm ltn gtn eql ...
= with one argument is grp, group; with two it is eql, equal. The
compiler emits a one-byte opcode per primitive call: monads start at opcode 0
and dyads at 32, so the opcode minus the base is the table index. The
virtual machine in b.c is a switch over those bytes with a stack of A
values, and each case carries a comment with its stack effect
(b.c lines 14 to 35):
C32(bu,U(*s=v1[c-bu](*s))) //monad |bu+m |.. x -> monads[m][x] |
C32(bv,A x=*s++;U(*s=x(v2[c-bv](x,*s)))) //dyad |bv+d |.. y x -> dyads[d][x;y]|
Some primitives are written in K
a.h has macros K, K1 and K2 that take a string of K source and
arguments
(a.h lines 164 to 166).
Each use declares a static slot; the first call compiles the string and
keeps the function there, and later calls reuse it
(a.c lines 94 to 97).
There are 30 of these in the C files. Group on a list of 4-byte integers is
one
(o.c line 42):
RI(K1("{$[x;x[*'g]!g@:<g:(&~(~*s)=':s:x i)_i:<x;x!0#,!0]}",x))
How to read the K: grade x (i:<x), index to get the sorted values
(s:x i), mark where each value differs from the one before (=': is
equal each-prior, ~ not, & where), cut the positions there (_), sort
the groups (g@:<g), and pair the first value of each group (x[*'g]) with
the groups (! makes a dictionary). $[c;a;b] is if-then-else, for the
empty list.
The same file does 1- and 2-byte lists in C, with counting tables of 256 and
65,536 entries
(o.c lines 40 and 41).
Writing the wider case in K costs speed where the K does more work than it
needs. g@:<g grades a list of lists with the generic merge sort only to
restore first-appearance order, and on 100,000 random integers below 100,000
that stage took 14.5 ms of the 21.6 ms that all of =x took, timed once with
the microsecond clock `t 0.
Sorting picks an algorithm per width
Grade up is a few lines of o.c, and each storage type gets its own
algorithm
(o.c lines 28 to 37):
- 1-byte lists and strings: a counting sort. Count each of the 256 values, take running totals, place each index.
- Wider integers: subtract the minimum, then an LSD radix sort one byte at a time. Every byte position is counted, but where all items share the same byte the placement pass is skipped, so small values move fewer times.
- Floats: their bits are mapped to integers that sort in the same order (o.c lines 15 to 18), then graded as integers.
- General lists: a merge sort that switches to binary insertion sort
below 17 items, comparing with the generic
qA.
All four are stable, and grade down inherits that through the reverses shown above.
Memory in power-of-two blocks
m.c allocates every object as a power-of-two block, header included, from
64 bytes up. There is one free list per size, 24 of them. When a list is
empty, a block of the next size is split in half; freed blocks go back on
their list and are never merged. Blocks of 512 MiB and up come straight from
mmap
(m.c lines 23 to 26,
line 34).
The size-class byte b in each header is the index of its free list.
Curious facts
- A script must end with a newline. The file loader checks the last byte
(m.c line 89):
printf '1+1' > nonl.k; k nonl.kprints'eoleofand exits with 1. 1:0reads stdin in 1,024-byte chunks and returns at the first short read (i.c line 22). With a fileone.kholding#1:0(the length of what one read returned),(printf ab; sleep 1; printf cd) | k one.kprints 2. The converge loop#{x,1:0}/""keeps reading until a read adds nothing, and prints 4.- Splitting a string on newlines,
"\n"\s, drops one empty piece at the end and no other separator does (w.c line 4), so a file’s final newline doesn’t produce an empty last line. - For the WebAssembly build,
0.cbrings its ownmemcpy,memset,strlen,strcmpand other C library string functions, each written in one line (0.c lines 25 to 78).
History
The K wiki calls ngn/k “an implementation of K6 created by ngn” that borrows
ideas from Arthur Whitney’s other Ks, and dates the start of development to
April 9, 2017. The same page says the code moved to Codeberg (announced May
21, 2021), was “indefinitely frozen” on May 24, 2022, and was announced as no
longer supported in January 2024. The readme at commit b9eeb91 opens with
“this k implementation is no longer supported” and points to a maintained
fork at codeberg.org/growler/k. Every source file’s header reads “(c)
2019-2024 ngn”, and the license is the GNU AGPL, version 3 only.
Sources
ngn/k at commit b9eeb91e0343ef6029f59d55dd98f82667b9bd59:
- readme.txt
- a.h lines 6 to 27, control macros;
lines 103 to 107, types and widths;
lines 115 to 130, value layout;
lines 151 to 154, dispatch tables;
lines 164 to 166,
K,K1andK2 - g.h line 490,
x(a); g.k - 0.c line 21,
main; lines 25 to 78, WebAssembly libc - a.c lines 94 to 97, compiling K strings
- b.c lines 14 to 35, the virtual machine
- c.c lines 30 to 35,
sqz - m.c lines 23 to 26 and 34, allocator;
line 57, ranges;
line 59,
tZ; line 89, script loader - o.c lines 15 to 18, float keys; lines 28 to 37, grade up; line 38, grade down; lines 40 to 42, group
- 3.c line 34, sum of a range
- i.c line 22, reading a stream
- w.c line 4, splitting
Other documentation: the K wiki, ngn/k.
grep -rl /lib/k/ngn-k-source/
ls k/
- draft Dictionaries and grouping in KWhat a K dictionary is inside ngn/k, why looking a key up scans a list, what happens when you update a key that isn't there, and how group keeps keys in first-appearance order.