Contents

Internals

How the compiler and the runtime of Koji are made, for those who work on them. Each decision says what was done, why, and what was considered instead. The decisions about the language and its standard library, which its users see, are in design.md.

The compiler and its bootstrap

How the compiler is built, and checked.

The compiler is written in Koji, from a seed of its own executables

Decision: kojic is written in Koji (compiler/). It is built from the seed, an executable of the compiler for each platform its native backend reaches (bootstrap/seed/kojic-linux-x64.gz, kojic-linux-arm64.gz, kojic-macos-x64.gz, kojic-macos-arm64.gz, kojic-windows-x64.gz, compressed): the seed builds the runtime library (kojic library) and, with it, the compiler of compiler/ (bootstrap/build.sh), machine code and linking included, with no C compiler; building Koji needs gzip (PowerShell on Windows, bootstrap\build.cmd) and the seed of its platform. The seeds are the compiler built by itself (the fixed point: bootstrap/build.sh --seed writes them again, the same byte for byte from one generation to the next), all of them from one machine (the native backend builds for each platform). They are written again only when the compiler needs a feature the seed does not compile, as Rust updates its stage 0, so that the history does not grow by megabytes with each change.

Why: the compiler is the largest Koji program, and writing it in Koji tests the language and shows what it lacks. A seed of its own executables needs nothing to build Koji but the seed itself: no C compiler, no other language; and the compiler can use any feature of the language once the seed is written again with it.

Alternatives: keeping the compiler in Rust, a second implementation to maintain along with the one in Koji; a seed in C, which needs a C compiler (and so a C backend to write it); a seed in the intermediate representation, which would need an interpreter of it; a chain of releases to build from (like Go, which needs an earlier Go), the seed here being the one release in the repository.

The tests of Koji are written in Koji

Decision: the test suite is written in Koji and run by kojic test (build/kojic test test/*.kj, after bootstrap/build.sh): the programs that only print are cases in files of text (test/cases/: a program, its input, what it must print, the error that must end it, the other files it needs), run several at a time by tasks; the rest are test blocks (servers, pipes, foreign functions, the cryptography of the library called by its names, the snapshots of the stages, the fixed point). Like the generators of the tables of the library (bootstrap/generate/, which read the files of their sources: the Unicode Character Database, Mozilla's authorities), nothing of Koji is in another language.

Why: building and testing Koji then needs Koji alone: no cargo, no Rust, no C compiler (the tests of the cryptography were programs of C). The tests use the language as its programs do, and what they need of it (running programs with an input, TCP for the servers of the tests) became the standard library and foreign functions. The cases as text are read at a glance, need no quoting of their programs, and are what the tests in Rust gave the compiler (they were recorded from them, the same programs and results).

Alternatives: keeping the tests in Rust, which needs cargo to contribute; each case a test block with its program in a string, which would need its quotes escaped; a file per case, hundreds of small files.

The runtime

The library every program is linked with, and the lowest level of the standard library.

A runtime of its own, written in Koji

Decision: the runtime and the standard library are written in Koji, not in another language. What Koji cannot express yet (raw memory, calls to the operating system) comes from an internal module, koji:unsafe, with an address type, reads and writes of bytes and words, and extern function declarations of C functions of the system's library; only the standard library imports it at first. Its modules are in std/, and the compiler carries them (compiler/stdlib.kj, generated from std/): import json compiles std/json.kj like any module. HTTPS uses a TLS written in Koji. What stays outside Koji is the system's C library (on Windows, its DLLs), as for nearly every language; what the operations of the language cannot express (switching stacks, the threads of the runtime, a few instructions) is machine code that the compiler writes itself (see "The library of the runtime built by the compiler").

Why: a serious language should not need another one to run its programs: the standard library is then Koji's to read, change and optimize, and Koji is tested on it. The low-level part stays small and out of the users' sight, as unsafe does in Go, so the language stays safe.

Alternatives: the runtime in Rust (as it was), which needs cargo and libraries of others; the runtime in C, which is not Koji either; TLS from the system (OpenSSL), as Python or Node do, which depends on a library in C.

koji:unsafe: the lowest level of the standard library

Decision: a module of the standard library may import koji:unsafe, which has Address (a place in memory, of its own type), CInt (the 32-bit int of C, for extern declarations only: an int in Koji), CSize (the size_t of C, likewise), CVariadic (the last parameter of a variadic function of C, fcntl: where the arguments of ... start), U128 (an unsigned integer of 128 bits, unsigned __int128 in C: +, - and * wrap around, /, % and the shifts beyond 127 panic, the comparisons are unsigned, a literal is one where a U128 is expected; wide(low, high), lowWord, highWord and leadingZeros; floatBits and floatOfBits, the 64 bits of a float and back; decimalLow, decimalHigh and decimalOf give the words of a decimal and back: what the decimals in Koji are made of), Location (the place of a call, main.kj:12, for panics: a last parameter of this type is given by the compiler, so f.read() calls File.read(f, here)), Never (the type of a function that does not return: exit of C, a function for C that ends the program), locationAddress (the text of a Location, as C has it), offset, distance, nullAddress and isNull (arithmetic of addresses, and the address 0), stringBytes, stringSize and newString (the UTF-8 bytes of a string, and a string from bytes; the address of the bytes does not keep the string alive, which is dropped after its last use, so a function that reads them takes the string), blankString, stringReferences, stringCapacity and setStringSize (a string to fill, and growing one in place), reserve, listItems and setListLength (room for more items in a list that is not shared, the address of its items, a word each, and how many of them were written), allocate, free, read and write (of an int, a float, a boolean, a char, a byte or an Address, with its size: immut n: int = read(address, 8), the type read being the one expected) and panicAt(here, message) (a panic at that place); and it may declare extern function name(...): type, a function of the system's C library or of the runtime, with values of C only: int, CInt, CSize, float, decimal, boolean, char, byte, Address and Location, a U128 or a string it reads (a string it returns is a new reference), and Never for a function that does not return. Other programs can use neither.

Why: the standard library is written in Koji, but some of it must reach the system (clocks, files, processes) or memory; this keeps that part small, visible and out of the users' sight, as unsafe does in Go.

Alternatives: these functions in the runtime in Rust (as they were); an FFI for every program, postponed until the language needs it.

Built-in methods written in Koji: koji:core

Decision: methods of the built-in types can be written in Koji, in the internal module koji:core (std/koji/core.kj), which programs cannot import. The checker keeps their signatures; a call (text.trim()) is one of the function of the same name, with the value first (trim(text)) and, for a method that may panic, the Location of the call last. The module is checked only when a program uses one of them, and it has no top-level variables (it is never initialized). The methods of strings work on the bytes of the string (stringBytes, stringSize and newString in koji:unsafe), with memcmp and memmem of the C library for the searches.

The modules of the standard library may import koji:core too (system uses textOf, which reads bytes from the system as UTF-8, each invalid sequence becoming U+FFFD as Rust's from_utf8_lossy does).

Why: the built-in methods are Koji like the rest of the library, without changing the language or its messages: the same mechanism as math, for methods.

Alternatives: functions of Koji compiled under the C names of the runtime, which the generated code would call as it calls the runtime (the conventions of references of the runtime and of Koji would have to match at that border); a module of Koji imported by every program (compiled for each program, even one that never uses it).

The library of the runtime written in Koji

Decision: the runtime is a library: the internal modules of std/koji/ but koji:core, compiled once (kojic library) into the archive of the runtime (libkoji_runtime.a), which every program links, and which the generated code calls. Its functions are declared extern function name(...) { ... }: a function of Koji, given to C under its name (with values of C only, as for extern declarations). The library has no main: koji_library_init runs its modules, and the runtime calls it first. A program cannot import its modules: it calls their functions by their names of C. A function for C reads the strings it is given; one it declares take is given by C, and released after the call (a function of Koji does not take the reference of a string it is given, and shares the one it returns). Its modules are compiled together, so one may import another (koji:list uses mixed of koji:text). A function for C may return Never (koji_std_panic). The functions given to the library, such as those of the type of the items of a list (KojiElementType: retain, release, equal...), are called through their addresses, with the types that extern declarations of Koji give. The tables of Unicode of upper, lower and the is... methods (std/koji/unicode.kj) were first written from the methods of char of Rust, so that the methods give what they gave when the runtime was in Rust; they are now written by a program of Koji, bootstrap/generate/unicode.kj, from the files of the Unicode Character Database, with the same tables, byte for byte, for Unicode 17.0.0 (Rust's properties are those of the database: Alphabetic, Lowercase, Uppercase, Cased and Case_Ignorable of DerivedCoreProperties.txt, the mappings of SpecialCasing.txt without conditions over those of UnicodeData.txt). Likewise, the tables of powers of 5 with which koji:decimal finds the shortest decimal of a float (Ryu, std/koji/ryu.kj) are written by bootstrap/generate/ryu.kj, and the authorities built in (std/koji/roots.kj) by bootstrap/generate/roots.kj: no generator is in another language.

Why: as the runtime of other languages, it is compiled once, not with each program: a program compiles only its own code.

Alternatives: the functions compiled into each program (as koji:core), which makes every compilation slower as the runtime moves; a library built by the tests and bootstrap/build.sh with the compiler just built (the seed would need a library before the compiler that makes it).

The library of the runtime built by the compiler

Decision: the native backend compiles the library of the runtime (kojic library): its object alone, in the archive that programs link, with no C compiled. What the C prelude of the C backend wrote in C is Koji in the library (koji:prelude, std/koji/prelude.kj, a module only kojic library compiles), and machine code the backend writes itself: the switch between the stacks of tasks, where a task starts, the heads of the pool, the descriptions of the items of the built-in types, and the few functions that call through an address (of a description, of the type of a record, of a closure), and the threads of the runtime (see "The threads of the runtime"). The seed of the bootstrap is the compiler's own executables (see "The compiler is written in Koji"), which build the library natively before the compiler.

Why: the library is Koji: building it with the compiler takes the C compiler away from it, as the backend did for programs; the archive is written by the compiler too (see "A linker of Koji's own").

Alternatives: committing the object of the library (a binary in the repository, one for each platform); keeping the library compiled through C.

The mathematics of floats written in Koji

Decision: the functions of floats that C has in libm and strtod are in the library of the runtime, in Koji (std/koji/floats.kj), and all of them give the correctly rounded result (the float nearest to the exact one), as IEEE 754 asks of sqrt: math.floor, ceil, round, abs and int(f) from the bits of the float; % exact, as C's fmod, from the mantissas as integers; math.sqrt from the integer square root of the mantissa (in a U128); the logarithm in double-double, about 2^-70 (x = 2^k m, log m = 2 atanh((m - 1) / (m + 1)), its first terms in double-double), whose high part is log and which times 1 / ln 10 is log10 (the decimals estimate their powers and roots with them); ** and math.pow by fdlibm, the library of Sun on which most C libraries build theirs (e_pow.c: within 1 ulp, its result r off by one in about 7% of cases), then corrected by what it is off by, y log x - log r, in double-double: r + r (y log x - log r) rounds once; and the float of a decimal text (float('0.1'), the literals of floats, decimals made floats): Clinger's fast path when the digits and the power of ten are floats exactly, or the digits as a big integer (at most 800 of them, then one that stands for those left out), times the power of ten or divided by it, rounded half to even. Their constants are written in hexadecimal, exactly. The results beyond the floats are infinities made from their bits, which the callers check (an operation of Koji that gives one panics). floatBits and floatOfBits of koji:unsafe move the bits of a float to an int and back, between registers. Tested against the exact results, computed with 60 digits, on thousands of values (subnormals, halfway cases, texts of hundreds of digits), where they were all correctly rounded; a power or a logarithm could still miss in rare cases, by an ulp, when the exact result is within about 2^-70 of the middle of two floats.

Why: a program gives the same floats on every system: libm differs between systems (glibc's log10 is off by up to 2 ulps, others round otherwise), and Koji keeps the results of a program above the machine, as with decimals. Correctly rounded results are also what a float prints as: 2 ** 0.5 shows the same digits as in other languages, and the last digit is never a matter of the library. The runtime then needs the C library only for the operating system (memory, files, sockets, threads), and programs on Linux no longer link libm.so.6. The cost is speed: a power takes about 400 ns (two logarithms in double-double, each operation of floats checked), where glibc's takes 20.

Alternatives: keeping libm (results that differ between systems, and one more library of C); fdlibm's power and logarithms alone (off by an ulp in a few percent of the results); the power of glibc and musl (ARM's optimized routines), correctly rounded nearly always and fast, but with tables of hundreds of constants; correctly rounded functions that are proven so, as CORE-MATH writes them (much more code for the last cases); strtod by Eisel-Lemire before the big integers (faster for long texts, which floats seldom come from).

The threads of the runtime

Decision: the threads that help with the calls that block, and the one that ticks for preemption, run machine code that the native backend writes into the library (as it writes the switch between stacks): their loops, the job of each call that blocks, and running a job; no Koji runs on them, and all the Koji of a program runs on its one thread. What runs on that thread (making their pipes, starting them, giving them jobs, starting and stopping the clock) is Koji (koji:prelude).

Why: in Koji they would need code of Koji that runs on another thread, where it must neither allocate nor count references, with nothing to check it; written by the backend, they are a few loops around calls of the system, with no Koji in them, and the library needs no C compiler.

Alternatives: functions of koji:unsafe for the address of a function and a call through an address, with the rule, unchecked, that the code of other threads allocates nothing; keeping them in C (as at first: the library then needed a C compiler for them).

Instructions of the processor: functions of koji:unsafe that the compiler knows

Decision: the few things of the runtime that are instructions of the processor and nothing else (switching between the stacks of tasks, the rounds of AES and the products without carries of GHASH, the requests to valgrind) are functions of koji:unsafe that the compiler knows, a small and closed set (switchStacks, taskEntry, floatControl, valgrind, aesRound, aesLastRound, carrylessProduct, reverseBytes and aesAvailable so far): the native backend writes their instructions as machine code, inline (but the switch between stacks, a function of the library it writes), for each processor.

Why: they cannot be written with the operations of the language, and they are few; functions keep their uses checked by types and portable, each instruction written once for each processor in the compiler.

Alternatives: blocks of assembly in Koji (asm), which can do anything but are checked by nothing and written in the syntax of each processor; leaving them in C or in files of assembly, which keeps a language other than Koji in the runtime.

Machine code

How the compiler writes and links executables.

Machine code: the compiler writes the object file itself

Decision: the native backend (compiler/native.kj, the only backend of kojic build and kojic run) generates the machine code of the IR and writes the object file itself (ELF, Mach-O or COFF), which Koji's linker links with the runtime library (see "A linker of Koji's own"): no C is generated nor compiled. It grew in steps, each checked against the C backend (the same output and panics, under valgrind): the integers, booleans, chars and strings, control flow, calls and globals first; then every type (records, lists, maps, closures, decimals, floats); then the allocation of registers; then arm64 and Mach-O; then the library of the runtime itself, whose C (the prelude) became Koji, foreign declarations of the system and code of the generator; then a linker of Koji's own. It became the default once it covered the language, its code within 1.4 times the instructions of gcc's, so that Koji stops needing C as soon as it can; the C backend stayed for the platforms the native one did not reach yet, and to compare the two. The C backend is retired: once the native backend reached Linux, macOS and Windows on their processors and the seed was executables, cgen.kj, the C prelude (runtime/prelude.h) and the seed in C went; a platform the native backend does not reach is an error of kojic build, never a wrong program. The native backend calls the functions of the runtime, the library exporting the descriptions of the items of lists; it inlines them where speed asks for it (the counts of references, a borrowed parameter that is neither retained nor released, a record made from the pool), and inlines the small functions of the program itself.

Why: Koji depends on no other language, C included: the compiler is written in Koji, and with its own code generation and linker it needs nothing of C to build a program. Writing the object file (rather than assembly for an assembler) keeps the whole path in Koji. Growing it under the C backend kept Koji usable and correct at each step, with the C backend as the reference of every behavior.

Alternatives: LLVM (excellent code, but a large dependency in C++); a backend of assembly text for the system's assembler, one tool more; replacing the C backend at once, which would leave Koji broken for months.

A machine IR between the IR and the processors

Decision: the native backend is split in three. The lowering to machine code (compiler/mir.kj and what lowers to it) turns the IR into a machine IR that knows no processor: virtual registers without number, of words and of floats; loads and stores of 1, 4 or 8 bytes at a register plus an offset; operations of two operands (a register or a constant), checked ones that panic on an overflow; comparisons and branches; calls by the System V and AAPCS64 conventions, which the machine IR states as arguments and results in registers of each class; slots of the frame; and the few instructions of the processor of koji:unsafe. All of the semantics of Koji (counts of references, moves, borrowing, records, lists, the pool) is decided there, once. A register allocator (linear scan over the ranges of liveness, the registers that calls keep for the values alive across a call, the others first, spills to slots of the frame) gives each virtual register a register of the processor. Then an emitter for each processor (x86-64, arm64) encodes the instructions, with the relocations of its objects; the object file of ELF (and later Mach-O) is written for either.

Why: the first native backend wrote the bytes of x86-64 in some 400 places, the semantics of Koji between them; arm64 would have meant a second copy of all of it, and its allocation of registers (5 registers kept across calls, the rest of the values through rax and the frame) leaves the code at 1.3 to 1.7 times the instructions of gcc's. With a machine IR, the semantics is written once, the allocator works for both processors, and an emitter is a small closed job (each instruction of the machine IR, a few encodings).

Counting references: a managed value is a word in a virtual register, like an int. The lowering keeps the rules of ownership of the language (see "Ownership and value semantics" in design.md): which locals a function owns (all managed ones but the borrowed), where each is read for the last time (liveness.kj), and, forwards over the blocks, which may hold a reference at each point. A local is released only where it may hold one (at its last read, when it is given another value, when the function returns), and set to none at the end of the paths where it holds none when they meet others where it does, so the function zeroes nothing when it starts but the locals a TakeIns empties. MRetain and MRelease are instructions of the machine IR (a test, an increment or a decrement, and the call that frees at the last reference, which keeps every register like the check of preemption), so that the allocator keeps the values alive across them in any register.

Windows: for Windows on x86-64 (KOJI_TARGET=windows-x64), the code of Koji keeps the convention of System V among its own functions (both sides are Koji's), and only a call of a function of C, of a DLL, follows the convention of Windows (MVariadic with all its arguments fixed: the first four in rcx, rdx, r8 and r9 or xmm0 to xmm3 by their positions, 32 bytes above the arguments for the callee): Windows keeps across calls every register System V keeps and more (rsi, rdi, xmm6 to xmm15), so the allocator need not know. The few places where Windows calls Koji (the start of a thread) go through an adapter that saves what Windows keeps. A frame of a page or more touches its pages in order (the stack grows through a guard page), and the switch between the stacks of tasks saves the limits of the stack in the block of the thread (StackBase, StackLimit), which the functions of the system check. The objects are of COFF (compiler/coff.kj), and Koji's linker writes the executable of PE (compiler/pelink.kj: the imports of ucrtbase, kernel32, ws2_32 and bcrypt, stubs jmp [rip + entry], the relocations of the data for the loader), from the entry koji_windows_start (the arguments from the C library). The library has branches of Windows where POSIX is not there (koji:windows, and match (system.os) elsewhere): the stacks by VirtualAlloc, the clock by QueryPerformanceCounter, sleeps by Sleep, the threads by CreateThread, the pipes and files by the C library of Windows, the directories by _findfirst64, programs run by CreateProcessA, the sockets by Winsock (which never wait, its own errors), the poller by WSAPoll (the pipe of the jobs looked at between short waits), random bytes by BCryptGenRandom, and the authorities of TLS from the list built in. A comparison with system.os known on the platform is a constant, so that nothing of the global is read before the modules start. Checked by running the programs under Wine: every test of the language (KOJI_TEST_WINDOWS=1 cargo test --test language), tasks, threads that help, TLS 1.3; and the compiler itself: built for Windows, it builds itself there the same, byte for byte, as the compiler on Linux builds it for Windows, so that Windows has a seed too (bootstrap\build.cmd). The names of POSIX that the C library of Windows has with an underscore (getcwd, _getcwd) are imported so, for the foreign blocks; std/path.kj takes \ and drives (C:\) as well.

Values of two words: a decimal or a U128 is a pair of virtual registers (low, high), passed as two words by the convention; MPairs tells the emitter which arguments of a call start a pair, so that one that does not fit whole in the registers goes on the stack whole, as System V wants. MWide computes the arithmetic of 128 bits (an add with its carry, the product, the shifts, the unsigned comparisons), which each processor encodes in a few instructions.

Calls of cold blocks: a value alive across a call needs a register that calls keep (5 on x86-64) or the frame. The panics and the slow paths of an instruction (a list shared when an item is set, a string without room, the pool empty) are blocks of their own laid out after the block of the IR they come from, so inside its loop: had their calls counted, every value alive in the loop would cross a call, and most of them would go to the frame. They do not count for the allocator; such a call saves the registers that calls do not keep and that hold a value alive across it (not its results) around itself, as the check of preemption does: the cost is on the path rarely taken.

Alternatives: a second backend for arm64 copying the first one (the semantics in two places that drift apart); improving the allocation inside the first backend (x86-64 only).

A linker of Koji's own

Decision: kojic links the executables of the native backend itself (compiler/linker.kj): the object of the program and the objects of the runtime library (an archive of ar, which kojic library writes too, with the table of its symbols), into an executable of ELF that is not position-independent and that the dynamic loader links with the C library of the system (libc.so.6; its functions through stubs and a table of addresses filled when the program starts, BIND_NOW), its entry calling __libc_start_main with main as the start files of C do. A symbol that neither the objects nor those libraries define (read from the libraries of the system) is an error of linking. The shared libraries of foreign blocks are linked the same way: foreign 'sqlite3' is libsqlite3.so, found in the directories of libraries of the system or of LIBRARY_PATH (through the script of the linker it may be, as libc.so is), named for the dynamic loader by its own name (its DT_SONAME, libsqlite3.so.0), its symbols read to check the program's. For Windows, the functions of a foreign block are imported from the DLL of its library (foreign 'user32': user32.dll), which need not be there when the program is built. For macOS, a foreign block loads its dynamic library by its install name (LC_LOAD_DYLIB): that of the file (libsqlite3.dylib, in LIBRARY_PATH or where Homebrew puts them, a universal file included), or, for a library of the system, whose file is only in the cache of the dynamic loader, that of its stub in the SDK (libz.tbd: /usr/lib/libz.1.dylib); its functions are bound to it by their ordinals, and not checked (the dynamic loader names one that is missing). The linker of the system (KOJI_CC, cc) stays for what Koji's does not do: a library found only as an archive (libfoo.a), a library of macOS found neither as a file nor in an SDK, and KOJI_LINKER=system; KOJI_LINKER=koji makes a failure of Koji's linker an error rather than a fallback.

Why: with it, building a program on Linux needs nothing of the toolchain of C: no compiler, no linker, no ar; only the shared C library, which every program of the system uses. Linking the objects Koji makes, with the few relocations it uses, is a small and closed job; the executable also comes faster (no process for the linker), the same from the same program.

Alternatives: static executables (the C library of the system is not made to be linked statically everywhere, and its loader and its locales want a dynamic one); a position-independent executable (relocations of its own data at the start, for nothing an executable of Koji needs); keeping the linker of the system (one more program of C to build anything).

Edit this page on GitHub