r/Compilers • • 17d ago

Kairo v0.2.3: Self-Hosted, General Purpose Systems Language, with Bi-directional C++ Interop, Cross compiles to ~48 Targets, and ships with an LSP

Hi r/Compilers!

Kairo (previously called Helix) is a statically typed, self-hosted systems language and compiler toolchain, built around full two-way C and C++ interop, that we have been working on for the past ~3 years.

Some stats about the codebase:

  • Compiler compiles ~420,000 lines of Kairo code found in Compiler/ Analyzer/ Linker/ Extras/
  • ~2,500 tests checked with LLVM lit, including parity suites that use clang as the oracle
  • Documentation
  • Compiler specification
  • Native LSP server
  • kld, a cross-targeting wrapper around LLVM’s lld that checks ABI-relevant compiler metadata at link time
  • kcc, a drop-in clang replacement that cross-compiles C/C++ out of the box to 48 targets
  • Formatter using the Wadler/Lindig pretty-printing algorithm
  • Native debugger support (GDB, LLDB, WinDbg)
  • LLVM is cross-compiled for 14 targets using kcc

I’ll start with Kairo. It’s a pragmatic language that supports many features, Two-way C++ interop, and 5 different paradigms: procedural imperative systems, Object-oriented, generic trait-based, Functional, and Compile-time metaprogramming. The main goal of Kairo was a readable language with varying levels of expressiveness, allowing developers to write code that is both clear and interacts directly with the lowest level of hardware. Kairo will have a formal memory safety proof model. However, as of now, that is still only spec’d and will not start until we have real users of the language, real bugs, and stabilization work complete - we want the foundation to be solid before formalizing the safety guarantees.

On the middle end of the language, The compiler has about 87 scheduled semantic passes as of writing this (why so many, you may ask? Kairo is a really large language with a lot of feature-interaction complexity). The compiler performs almost all the resolution logic itself, even for code being imported from C++. Kairo's Sema passes handle name lookup, ADL, overload resolution, conversions, specialization choice, constraint checking, SFINAE, and access checking. Clang is only used to get layout info (size, alignment, scope, members) and for completing an instance of an imported class template, and deducing the template arguments of an imported function template that Kairo’s overload resolution is considering. Though, Kairo isn’t fully semantically independent from clang yet. Some clang-generated errors ([CL001]) still come through, but we’re burning down that list, and the v1.0 goal is complete semantic independence.

Kairo can also cross-compile out of the box to 48 targets and freestanding environments, but the builtins don't support freestanding yet.

Here are 3 examples:

class Buf {
    var n: i32 = 7
    fn Buf(self) {}
    @move fn Buf(self, other: Self) { self.n = other.n }
}
fn take(b: Buf) -> i32 { return b.n }
fn main() -> i32 {
    var b = Buf()
    return take(b) + b.n  // error [SC052E]: 'b' is used after being moved
}

Using C++ in Kairo:

ffi "c++" import "vector"
ffi "c++" import "algorithm"

fn main() -> i32 {
    var v = cxx::std::vector<i32>()  v.push_back(3)  v.push_back(1)
    cxx::std::sort(v.begin(), v.end())  // the overload and the template chosen by Kairo
    return v[0] + (v.size() as i32)  // exit with code 3
}

Using Kairo in C++:

/* geo.k
pub class <T> Vec2 {
    pub var x: T  pub var y: T
    pub fn Vec2(self, x: T, y: T) { self.x = x  self.y = y }
    pub fn flip(const self) -> Vec2<T> { return Vec2<T>(self.y, self.x) }
}
*/

#include "geo.k"

int main() {
    geo::Vec2<int>    a(1, 2);    // a Kairo generic, instantiated from C++
    geo::Vec2<double> b(0.5, 4.0); // and again, at another type
    return a.flip().x + static_cast<int>(b.flip().x); // 2 + 4 = 6
}

Kairo also tries to remove a lot of the UB surface found in C++. In Kairo TUs, many things implicitly allowed in C++ are not. Nothing changes if you compile C++ with kcc or use it through interop; the rules apply at the .k boundary.

Now about Kcc, it’s a clang replacement that can cross-compile out of the box. The first time you pass --target, kcc (and kairo) build that target’s C library and C++ runtimes (libc++, libc++abi, libunwind, compiler-rt) from sources that ship in the archive and cache them. That takes about 10 to 30 seconds, once. glibc is built from source too, any version from 2.17 up (--target x86_64-linux-gnu.2.17), so your binary runs on that glibc or newer. MSVC works without Visual Studio: a script pulls the MSVC runtime and Windows SDK straight from Microsoft through xwin, after you accept their license. It ships 17 LLVM backends, so with --freestanding it also covers microcontrollers, eBPF and GPU object code.

kcc also allows a really nice feature to work cleanly:

    #include "my_kairo.k"

The direct inclusion of a Kairo file in C++, without generated headers being stored anywhere on disk (kcc never writes a header when invoked), allows a C++ codebase to be migrated incrementally, one file at a time. We had to make one small (~55-line) patch to clang’s preprocessor for this to work. When clang enters a .k file, it’s handed a module’s interface as pre-lexed tokens located in the .k file itself. Nothing else about the preprocessor changes, so the include can be under an #if, after a #pragma, or even inside a function, and it is respected the same as any other include. Errors that involve the Kairo code point at the .k source. kcc takes normal clang arguments and also compiles Kairo code; kcc foo.k and kcc foo.cpp both work.

We also used kcc to cross-compile LLVM/clang/lld itself (changed the C++ compiler to kcc), which is how the toolchain ships for 14 hosts:

  • Linux (musl, static): x86_64, i686, aarch64, armv7, riscv64
  • Windows (MinGW): x86_64, i686, aarch64, armv7
  • macOS: x86_64 (10.15+), arm64 (11.0+)
  • FreeBSD: x86_64, aarch64
  • NetBSD: x86_64

Each host can cross-compile to all 48 targets.

On the LSP, Kals provides end-to-end latency: p50 of 100 ms and p95 of 350 ms. To avoid patching clangd, it writes temporary headers to disk for all Kairo files that aren't used in any compilation process, and passes stock clangd an -ivfsoverlay that maps them. This means clangd keeps full LSP and autocomplete support in a C++ file that includes a Kairo file.

What’s not done yet: lifetime/escape analysis, virtual interfaces and async aren’t implemented, and the compiler’s own source is still migrating from raw pointers to Kairo’s safe pointers. The test suite runs on x86_64 Linux; the other hosts build and are tested working, but haven't had full suite runs yet. There's still quite a long way ahead to go still.

We’d love feedback on the compiler and toolchain docs, or anything else. Contributions are welcome. Feel free to try out the Kairo compiler and toolchain.

P.S. Hello from u/Lord_Mystic12 - I am the other dev on the project, and logo designer for Kairo. We are really proud to have come this far into this project, I will also be responding in the comments.

7 Upvotes

14 comments sorted by

3

u/Discordbothost 15d ago

The interop docs say Kairo frames default to noexcept. I'd flag that next to the vector example: a thrown C++ exception can terminate unless each Kairo frame it crosses permits unwinding. That's a useful gotcha for an incremental port.

1

u/Ze7111 15d ago

I agree; we'll make the documentation on exception semantics through interop much clearer on the exception-handling side, though you can catch a C++ exception in a Kairo try/catch and re-propagate it into Kairo's error system. A small example in default mode without adding @unwind:

/* exceptions.hpp
#include <stdexcept>

inline void throws_something() {
    throw std::runtime_error("Something went wrong");
}
*/

ffi "c++" import "exceptions.hpp"
import std::io::println

fn panics_something() panic {
    panic "Something went wrong"
}

fn runs_something() panic {
    try {
        panics_something() // using the Kairo panic system
        throws_something() // if this is not in a try-catch, it will terminate the program on this line
    } catch e: cxx::std::runtime_error {
        panic e //re-propagate the error into Kairo's panic system
    } catch e: string {
        println(f"caught a string error: {e}")
    }
}

the thing is without @unwind, if c++ throws and you dont handle or repropagate, it will terminate.

Thanks for pointing that out, btw!

2

u/KATO-Kanryu 16d ago

The approach of directly modifying the Clang compilation toolchain to implement an original language is interesting, but from a software engineering perspective, it has a fundamental flaw.

Ultimately, this language seems to fall into the category of a transpiled language—essentially no different than translating your code into C++ and running it through Clang, just done in-memory via AST hooking.

The biggest issue with your approach is that you now have to continuously track and adapt to the massive, often breaking changes in Clang's upstream codebase every year. It is highly unrealistic for a personal or small-team project to sustainably shoulder such a heavy maintenance cost over the long term.

In that sense, this architectural direction seems fundamentally problematic.

0

u/Ze7111 16d ago edited 16d ago

I'd push back one that since:

Kairo doesn't heavily modify Clang internals. We carry two patches: one buys #include "foo.k" (~55 added lines), and the other buys 128-bit int/float support across every arch. Rebasing onto a new LLVM version is about 5–10 minutes of work; compiling it for all 14 hosts is what takes an hour.

We don't do AST hooking either. We don't hook into Clang's Sema or AST. Kairo's codegen builds an in-memory token stream, one thing we followed religiously is to stick to long-standing public APIs (Token, EnterTokenStream, etc), and Clang consumes it like any other file. It just isn't on disk and doesn't need #line directives or a generated C++ file to accurately point into kairo.

I'd also push back most on calling Kairo a transpiler. A transpiler delegates semantics to its target language; Kairo doesn't. Its ~87 semantic-analysis passes (~180K lines) handle nearly all resolution and lowering. Calling Kairo a transpiler because it emits Clang tokens is like calling any language that emits LLVM IR instead of raw ASM a transpiler. Kairo's semantics also differ from C++'s:

  • Use-after-move is legal in ISO C++, so a transpiler would emit it and a C++ compiler would accept it. Kairo has a Sema pass that rejects it.
  • A Kairo file #included into C++ shares one Clang TU, yet Kairo ints wrap (a single instruction at -O2 and up, with no -fwrapv passed anywhere) while the C++ side keeps normal overflow semantics.

The only architectural difference from a language that lowers to LLVM IR, like Rust, is our IR is a clang token stream that is fully resolved and fully qualified, and leaves clang no resolution to do for Kairo code.

Because of that, emitting LLVM IR directly is a fairly small step for Kairo, and we plan to. The hard part is what Clang’s backend does implicitly for C++ interop: vtables, VTTs, virtual base offsets, Itanium/MSVC RTTI, and psABI struct-passing conventions. Going through tokens lets us build that LLVM path in parallel, with a working compiler as the baseline to diff against. Carbon is spending years reimplementing that same ABI logic before it can compile real interop code.

3

u/KATO-Kanryu 16d ago

I appreciate the detailed clarification on your implementation, but from an architectural standpoint, your explanation actually confirms my initial critique.

First, you state that you generate an in-memory Clang token stream rather than doing AST hooking. However, outputting a stream of C++ tokens (lexical representations of C++ source code) to be consumed by Clang is the very definition of an in-memory transpiler. The only difference is that you bypass the file system. You are still compiling your language down to C++.

Second, equating the emission of Clang tokens to the emission of LLVM IR is a false equivalence. LLVM IR is a language-agnostic, low-level intermediate representation. Clang tokens represent a highly specific, high-level language (C++). Translating to a high-level language to leverage its compiler is what makes it a transpiler.

Finally, your point about relying on Clang to implicitly handle vtables, RTTI, and psABI struct-passing conventions highlights the exact dependency issue I mentioned. Because you rely on Clang to handle these complex C++ ABI details, your emitted token stream must strictly conform to what Clang accepts as valid C++. No matter how many semantic passes Kairo performs internally, your language's ultimate behavior and expressiveness are inherently bounded by C++ semantics and Clang's parser.

You are treating Clang as a very heavy backend to avoid the immense difficulty of implementing C++ ABI compatibility from scratch (which, as you noted, Carbon is struggling with). While this is a practical shortcut for a small team to achieve C++ interop quickly, architecturally, it leaves Kairo shackled to C++ as its host language.

3

u/Ze7111 16d ago edited 16d ago

I think we actually agree on the mechanics; we view the architectural trade-off through different lenses.

On backend emitting tokens instead of LLVM IR: How low level an IR isn't what makes something a transpiler, by the short definition of a transpiler "takes in some source and converts it into equivalent source in another language" you'd be right, but the deeper versed definition of a transpiler also states: it stays as an almost 1:1 mapping, or semantic agreement, as you stated "bounded" but I'd say Kairo doesnt fit that term for one reason and one reason only, kairo translates semantics the same way a high level language would go to LLVM IR, rather than translating syntax, Rachit Nigam's "Transpiler, a meaningless word" makes the same case well, once you are at that point, you're doing exactly what a compiler does.

On expressiveness: every language is bounded by what its IR can express. LLVM IR bounds rust. But the key distinction is that being bounded by what C++ can express isn't the same as inheriting C++ semantics. Kairo has features that native C++ can't express, structural interface composition (Sub + Add - Closable), guaranteed left-to-right evaluation for operators and arguments, an inferred zero-cost error model (that micro-benched 10x faster than C++ exceptions on the error path, and even 2x faster than Rust's Result type), the list goes on.

Kairo also rejects things C++ accepts, as stated previously. Sema lowers all of that into a smaller core before codegen, the same way rustc's MIR desugars if let into match. Kairo doesn't 1:1 map to C++'s surface; it maps higher-level Kairo into its own IR surface before emitting fully resolved, C++-interoperable tokens. That's also why moving to direct LLVM IR later is a small step, minus the ABI lowering.

Furthermore, being bounded to what Clang accepts at the ABI level is our explicit design goal; that's precisely what buys us seamless, zero-cost 2-way interop with C++23. For that goal, this path let a team of basically two university students ship a self-hosted toolchain that cross-compiles LLVM for 14 hosts today, instead of leaving it as a paper design.

2

u/KATO-Kanryu 16d ago

It is perfectly fine if you operate under the premise that there is no strict definition of the word "transpiler". However, generally speaking, a transpiler refers to a super-high-level language that compiles down to a widely used high-level language like C or C++. Technically, your language falls into this category, and by transpiling to C++, specific constraints inevitably emerge.

For example, you cannot use your language to develop the Linux Kernel. The Linux Kernel project explicitly forbids merging C++ code. The context of the kernel demands code whose execution is ultimately deterministic and intuitive to humans, making the hidden behaviors of complex template engines and internal vtables entirely unsuitable.

On the other hand, I am independently developing a lightweight and fast language called "Hike". It features a Go-like syntax, outputs LLVM IR, and generates native code that is 100% compatible with the C ABI. Because of these characteristics, I found it has a very high affinity with WASM, so I also added native support for WAT (WebAssembly Text format), the official assembly format for WASM. Thus, Hike natively supports two backend formats: LLVM IR and WAT.

As this shows, every programming language has its own ideal application domain, and I think it is perfectly fine for your language to aim for its own specific niche.

When Bjarne Stroustrup released the very first C++ compiler, it was essentially a transpiler that output standard C source code. This was because, at the time, C was the only general-purpose language capable of producing fast native code. Decades later, we have inherited the overwhelming applicability and massive software legacy of C++.

I look forward to seeing your new language carve out its own niche and establish a new domain of applicability.

1

u/Ze7111 17d ago

Since the post is a lot, here's a shorter TLDR about how Kairo resolves calls into C++ without being bound by C++ semantics.

When Kairo's Sema sees a C++ call such as sort(v.begin(), v.end()), Kairo builds the candidate set itself: ADL over the imported decls, its own conversion ranking, SFINAE by asking Clang to deduce and substituting into the signature, then constraint checking.

Clang is called for exactly three things:
- record layout
- completing a class template instantiation
- and template argument deduction for a candidate Kairo is considering.

-7

u/nian2326076 17d ago

Kairo's interoperability and compiler tools are impressive. If you're involved in systems languages or compiler development, it's a good idea to refine your technical skills. You can use PracHub to practice coding problems relevant to compiler design and systems programming, which can help you prepare for potential technical interviews in this field.

6

u/FloweyTheFlower420 17d ago

Holy shit the moderators are actually just completely dead on this subreddit. Why do we have a bot shilling some bullshit??

3

u/Maleficent-Nose-9844 16d ago

for real though, laughed at this shit so hard

-3

u/realrealvantheman 16d ago

Holy slop bro

1

u/Lord_Mystic12 16d ago

Could you clarify? We have been working on kairo for the last 3 years