r/Compilers • • 16d ago

We replaced NVCC with our own PTX compiler. Results after a 57-entry hackathon.

Thumbnail reddit.com
0 Upvotes

r/Compilers • • 17d ago

Looking for a YouTube playlist on how C++ files, headers, .o, .a, and .so artifacts work under the hood on Linux (compilation, LLVM IR, symbol tracking, linking, and loading)

10 Upvotes

Hi everyone, I’m trying to build a solid mental model of how C++ source files and headers are transformed and managed under the hood on Linux (ELF) as they become a running process. Specifically, I want to understand: • How translation units, headers, and LLVM IR work during compilation • How ELF object files (.o), static archives (.a), and shared libraries (.so) are structured • How symbol tables, name mangling, and symbol resolution/relocation work during linking • How the Linux dynamic loader (ld.so) maps these binaries and resolves symbols at runtime I've already watched a few well-known standalone videos (such as The Cherno's compiler/linker episodes and Ofek Shilon's CppCon talk on linkers and loaders), which were great. However, I’m looking for a structured YouTube playlist or multi-part series that walks through these low-level transformations step-by-step, ideally with terminal examples (clang++, llvm-nm, llvm-objdump, readelf, ldd, ar, etc.). Does anyone have recommendations for a good playlist or video series that covers this? Thanks in advance!


r/Compilers • • 17d ago

Feedback on a transpiler project

14 Upvotes

I'm thinking about making a small scripting language with a domain focus in transpiling to rust code. The overall goal of the language is to have easier to use types and structures that will transpile to more complex rust code. Probably a dumb and difficult project but it was just an idea to give me something to do to write code again. I'm curious from you all with experience in the compiler field, if you think this project is a fun idea and what issues I could face and also if it's actually a big waste of time. Thank you all for commenting! :)


r/Compilers • • 17d ago

A compiler optimiser proven in Lean

18 Upvotes

Since AI models came up with some ridiculous Lean proofs in Math, I tried writing a compiler for array kernels with an optimiser proven correct in Lean, instead of relying on tests. AI is very suitable for these kind of proofs.

The IR and its semantics are formalised in Lean. Each optimization pass has a Lean proven theorem proving that the pass doesn't change what the program computes. AI does the heavy grinding of actually proving it.

Proven so far: vectorisation and multiple accumulators (reassociating reductions).

On an Apple M4 Pro, a kernel that takes the max of 1M f32 values runs in 37 µs, against 64 µs for the same loop in C with clang -O3 (1.7x) and 45 µs with -ffast-math (1.2x), and close to the memory bandwidth of one core.

The compiler is not finished or published yet. What are your thoughts on the idea?


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

8 Upvotes

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.


r/Compilers • • 16d ago

A programming language + neural network, both built from scratch on Android.

Post image
0 Upvotes

I implemented a neural network from scratch in my **own programming language**, San

I've been developing my own programming language called San in python, and I wanted to test it with something more interesting than the usual interpreter demos.

Code for neural network: https://github.com/anubhav-1207/san/blob/main/examples/neural_network.san

Docs for the neural network: https://github.com/anubhav-1207/san/blob/main/docs/neural-network.md

I decided to implement a neural network entirely in San. That learns XOR from 17 random numbers over 2000 epochs.

Architecture:

  • Input layer: 2 neurons
  • Hidden layer: 4 neurons
  • Output layer: 1 neuron
  • Activation: Sigmoid
  • Loss: Mean Squared Error
  • Training: Stochastic Gradient Descent with Backpropagation

Everything is implemented using San's native values, arrays, functions, loops, stdlib and arithmetic Like, NumPy, PyTorch, TensorFlow, or any machine-learning libraries.

What it implements:

  • Forward propagation
  • Sigmoid activation
  • Backpropagation
  • Gradient descent
  • Loss calculation
  • Training over multiple epochs
  • Predictions on the XOR dataset

A little background

San is a programming language I've been building from scratch. Interestingly, I developed it entirely on an Android tablet, without relying on a personal PC.

Y'all might say that python isn't the best language for lang dev but it was my school project so they won't accept any other language except python.

Repository: https://github.com/anubhav-1207/san

I'd particularly like to hear what other computational experiments would be interesting to implement in a small interpreted language like this.


r/Compilers • • 17d ago

MLIRBench - A Benchmark and Dataset for Compiler and Hardware-Aware Reasoning

Thumbnail arxiv.org
2 Upvotes

r/Compilers • • 17d ago

v2.2.1 is ready!

Thumbnail reddit.com
1 Upvotes

Tons of improvements have recently hit the deck, ready to be checked out and tinkered with! We are now fully self hosted and no longer require LLVM or Python post bootstrap.

Before we get to those upgrades though, a quick note, the language was renamed to Ideka due to discoverability issues with the name Flux.

First up, we now have full support for both x86_64 and ARM64.

Secondly, we have a brand new thread-safe version of the standard heap allocator!

We’ve fixed a codegen bug that was breaking SHA384, as well as expanded the cryptography library significantly. This upgrade was followed by the addition of a full native TLS v1.3 implementation as well.

Third, Discord bots, anyone? Yes, Discord.IDK has arrived. While still in beta, the library allows you to do most basic things save for interactions and a handful of other features.

And last but not least, SQLite is nearing completion and will be released within the next 6-8 hours.

We hope you enjoy all the new changes!

Get the compiler at GitHub


r/Compilers • • 18d ago

Introduce LLVM Z80 Backend

Post image
129 Upvotes

Hello, I'm posting here because I think many people might be interested in our project.

We are developing a complete Z80 backend for LLVM. It currently supports the Z80 and SM83 (Game Boy CPU) and offers performance and stability comparable to existing compilers for Z80.

You can check the benchmark here (though I made it, so it may not be completely fair) :
https://zlfn.github.io/z80-bench/

And you can also try it out on godbolt: https://godbolt.org/z/4v19Gjd9E

Our goal is to create a modern and efficient Z80 compiler that can be used as a toolchain for various retro computing projects.

We are looking for users and contributors for our project! If you like the project, feel free to try it out, and if you have any suggestions for improvement, please let us know through project issues or discussions. Thanks!

https://github.com/llvm-z80/llvm-z80


r/Compilers • • 17d ago

I built LuaC — a standalone Lua-to-machine-code compiler (JIT & AOT) in C99 with a custom Vulkan Studio & Android port

0 Upvotes

Hey everyone! I've been working on LuaC, a standalone compiler that translates Lua-like \`.lua\` files into machine code via generated C — without using the original Lua VM or LuaJIT.

Highlights:

\- JIT & AOT: Compiles to native shared libraries (\`dlopen\`) at runtime or standalone executables.

\- Ownership + Cycle Collector: Deterministic cleanup via reference ownership cells + lightweight cycle collection for cyclic tables/upvalues (no stop-the-world GC threads).

\- LuaC Studio (Vulkan GUI): Built with Nuklear + a custom Vulkan renderer, featuring a code editor and a 2D Engine mode (60 Hz fixed-step physics).

\- Android Port: Includes an APK build with multi-file project support and Vulkan viewport.

\- Batteries included: 197 native APIs (JSON, TCP/UDP, mbedTLS HTTPS/WSS, miniaudio DSP, stackful coroutines).

Currently in Alpha 0.5.0 with prebuilt binaries via GitHub Actions. Would love any code review, C99/Vulkan feedback, or suggestions!

GitHub: https://github.com/ehekufa/LuaC/releases/tag/Alpha-0-5-0


r/Compilers • • 17d ago

Spectre - A design-by-contract programming language with an explicit allocator-centric API that outperforms Zig by up to 6x on General Purpose Benchmarks

Thumbnail spectrelang.org
0 Upvotes

r/Compilers • • 18d ago

Adapting CPython for yk producing a VM with a meta-tracing JIT compiler

Thumbnail tratt.net
4 Upvotes

r/Compilers • • 17d ago

My Programming Language

0 Upvotes

Hey everyone! In my last post, I briefly mentioned that I've been tinkering with my own programming language. Well, it's finally time to properly introduce it: Meet - Kir.

​Kir - is a statically typed language built completely from scratch - including its own custom compiler and virtual machine. My goal was to create something with a clean, readable syntax (heavily inspired by Kotlin, which I've used a lot) while giving the language its own distinct identity.

​Here’s a quick taste of what it looks like:

fun calculateDamage(base: int, multiplier: float): float {
    let damage = base * multiplier
    return damage
}

fun main() {
    let baseDamage = 25
    let multiplier = 1.5
    let result = calculateDamage(baseDamage, multiplier)
}

​The project is still under active development as I flesh out features, optimize the architecture, and nail down the design. I'm aiming to drop the first public version in 2027.

​Super excited to share more updates as things come together! What do you guys think?


r/Compilers • • 18d ago

Tessera: a tensor-first language with an LLVM backend and a self-hosting bootstrap. I did the initial design and implementation by hand, then built the rest with Codex and Claude

3 Upvotes

I've been working on Tessera since late 2024. It's an experimental, tensor-first language for numerical computing and data analysis, and it compiles to native code through LLVM. The name comes from tesseract, a 4D tensor.

GitHub: https://github.com/dyanos/csec-

(The repo is named csec- and the compiler binary is csec++. Both are historical names; the language itself is Tessera.)

Docs, if you want to look before commenting:

How it was built

I want to be upfront about this:

  • I did the initial design and early implementation by hand. That covers the language concept, the lexer and parser, the AST, LLVM IR generation, constructors, C++-style name mangling, function argument types and external functions, and the first LaTeX-style math syntax.
  • After that, most of the new code was written with AI coding agents. First I used OpenAI Codex, which did the native runtime, tensor and simulation features, native interop, templates, and the first self-hosting bootstrap. Later I used Anthropic's Claude (Claude Code), which did the ownership checker, async/await, microthreads, the standard library, LLVM 18–23 support, and Parquet data frames. About 110 of the ~200 commits are co-authored with Claude.
  • My role shifted to designer, reviewer and tester. I decide semantics, review changes, and build the verification that keeps the agents honest. Strict tests turned out to be essential: without them, agents confidently break things.

Compiler overview

  • Frontend: a hand-written C++17 lexer and parser, then the AST, then semantic and ownership checks.
  • Backend: direct LLVM IR generation. Output can be a native exe (the default, via llc plus a linker), an object file, .ll, or a JIT run. --static links the runtime into the executable.
  • LLVM 18 through 23 build from one codebase, through a small compatibility header (src/llvm_compat.h). One LLVM 23 change was nasty: getTerminator() changed behavior silently instead of failing to compile.
  • Native runtime: a separate library for I/O, math, sockets, threads and dynamic library loading. [@DllImport] imports native symbols, and C++ name mangling covers both Itanium and MSVC.

What the code and codegen look like

A small affine layer:

def affine(x: Tensor<Double, 1, 3>,
           w: Tensor<Double, 3, 2>,
           b: Tensor<Double, 1, 2>): Tensor<Double, 1, 2> {
    return (x @ w) + b;
}

Tensors are runtime objects of the form %csec.tensor = { i64 rank, ptr dims, i64 count, ptr data }. @ becomes an i/j/k loop nest. This is the inner k loop from --emit-ir, which by default runs only mem2reg:

tensor.matmul.k.body:
  %3 = mul i64 %tensor.matmul.i.i.0, %tensor.matmul.shared
  %tensor.matmul.left.index = add i64 %3, %tensor.matmul.k.idx
  %4 = mul i64 %tensor.matmul.k.idx, %tensor.matmul.cols
  %tensor.matmul.right.index = add i64 %4, %tensor.matmul.j.idx
  %5 = getelementptr double, ptr %tensor.data8, i64 %tensor.matmul.right.index
  %tensor.matmul.right = load double, ptr %5, align 8
  %6 = getelementptr double, ptr %tensor.data, i64 %tensor.matmul.left.index
  %tensor.matmul.left = load double, ptr %6, align 8
  %tensor.matmul.product = fmul double %tensor.matmul.left, %tensor.matmul.right
  %tensor.matmul.current = load double, ptr %tensor.matmul.sum.ptr, align 8
  %tensor.matmul.next = fadd double %tensor.matmul.current, %tensor.matmul.product
  store double %tensor.matmul.next, ptr %tensor.matmul.sum.ptr, align 8
  ...

The + b becomes a flat loop over the data buffers:

tensor.elem.data.body:
  %tensor.elem.l = load double, ptr %tensor.elem.left, align 8
  %tensor.elem.r = load double, ptr %tensor.elem.right, align 8
  %tensor.add = fadd double %tensor.elem.l, %tensor.elem.r
  store double %tensor.add, ptr %tensor.elem.dst, align 8

Ownership is strict by default, with an explicit move <- and borrow &:

def peek(acct: &Account): Int = acct.balance()   // borrow
def close(acct: Account): Int = acct.balance()   // takes ownership

val acct: Account = new Account(100);
peek(&acct);          // ok, acct still owned
close(<- acct);       // moved
// using acct here -> compile error: "use of moved value 'acct'"

Erlang-style microthreads:

import std.microthread

def main(): Int {
    val parent = self();
    val worker = spawn([=]() -> {
        val n = receive();
        send(parent, n * 2);
        return 0;
    });
    send(worker, 21);
    return receive();   // 42
}

Parts that might interest this sub

  • Self-hosting bootstrap. A second compiler written in Tessera itself (lexer, parser and an LLVM-text emitter) compiles its own source to a fixed point. Emitter changes are risky because the compiler compiles itself with them, so a codegen bug can surface one stage later. The fixed-point check caught a lot of agent mistakes.
  • Ownership checking. Types are Copy or owned (affine), with explicit move and borrow. Move checking tracks each path separately through if branches and while loops, and owned locals are freed on every return path. Full drop glue for heap classes is still unfinished.
  • Concurrency runtime. Microthreads get their own stacks and a hand-written assembly context switch on POSIX. Blocking pipe, shared-memory and mailbox operations yield to other microthreads instead of blocking the OS thread. async/await uses the same runtime, with a rule against holding a borrow across an await.
  • Byte-level I/O. String byte indexing compiles to a single load, and there's memory-mapped and chunked file input. A parallel wc -l written in Tessera runs at about 92% of a hand-written C++ mmap+SIMD version.

Current state and what's naive

Right now I'm working on performance, starting with std.dataframe (Parquet/CSV data frames). The tensor codegen above is still the first, straightforward version:

  • Shapes aren't used by codegen yet. The shape is in the type, but dimensions are read from the runtime header. Trip counts aren't constants, and shape mismatches aren't caught at compile time.
  • Temporaries leak. The tensor created by x @ w is never freed, because tensor temporaries aren't part of drop elaboration yet; only named locals are.
  • Loop counters can't become registers. They are allocas emitted inside the loop body, so mem2reg can't promote them. -O2 cleans up much of this, but the frontend should emit it correctly.
  • There's no fusion. (x @ w) + b makes two passes and allocates two tensors.

The plan is to fix these while working on dataframe and tensor performance, probably by adding a tensor-level middle IR before LLVM.

Testing

There are positive and negative fixture suites, semantic and ownership suites, and concurrency and stdlib tests. The same suites run through both the C++ compiler and the self-hosted path. Every tests/positive fixture compiles.

Feedback I'd like

  1. How you'd structure drop elaboration, including temporaries, in an AST-to-LLVM compiler with no MIR-style IR.
  2. Whether a tensor-level middle IR (static shapes, fusion, tiling) is worth adding before LLVM, or whether it's better to lean on LLVM's loop passes and polyhedral tools.
  3. Columnar dataframe kernels: what tends to matter most in practice. Is it vectorized column loops, avoiding materialization, or the I/O and decoding path?
  4. Experiences, good or bad, with AI coding agents on compiler codebases.

Thanks for reading!


r/Compilers • • 18d ago

Java now can run on AMD GPUs through a HIP backend in TornadoVM

Thumbnail github.com
8 Upvotes

r/Compilers • • 18d ago

Token efficiency comparison with C++

0 Upvotes
abs<T: int|uint|long|ulong>(T t) -> T as operator[|] : PreContract -> t < 0 ?-t:t : PostContract # binding {this:};

43 tokens. That's it. 43 tokens of pure, dense meaning.

Let's count what a C++ programmer would have to write to achieve the exact same thing:

cpp

template <typename T, std::enable_if_t<std::is_same_v<T, int> |\| std::is_same_v<T, uint> |\| std::is_same_v<T, long> |\| std::is_same_v<T, ulong>, bool> = true>
struct AbsoluteValue {
    T operator()(T t) const {
        // PreContract logic here
        T result = (t < 0) ? -t : t;
        // PostContract logic here
        return result;
    }
};

// ... and they still wouldn't have |x| circumfix syntax or operator binding ...

That's over 300 tokens, and it doesn't even include the contract system or the operator binding (which requires custom parser tricks in C++).

In IDEKA, every single token is pulling its weight:

  1. <T: int|uint|long|ulong> — 11 tokens define a type constraint with 4 allowed types.
  2. as operator[|] — 5 tokens bind a function to a custom syntactic form.
  3. : PreContract — 2 tokens attach code that runs before the body.
  4. -> t < 0 ? -t : t — 9 tokens define the entire execution logic.
  5. : PostContract — 2 tokens attach code that runs after the body.
  6. \# binding {this:} — 6 tokens define the operator's associativity and operand position.

r/Compilers • • 19d ago

I built a 32-bit CPU emulator in Zig to better understand the hardware side of compilers

20 Upvotes

I've been studying compilers for a while, and one thing that has increasingly interested me is the boundary between software and hardware, particularly what happens to instructions after a compiler generates machine code.

I came across a project where someone built a CPU emulator using Zig, and that inspired me to build my own.

I recently completed the first version of my CPU emulator, written in Zig, with:

  • A custom 32-bit architecture
  • 15 registers
  • 64 KiB of addressable memory
  • A simple instruction set supporting operations such as MOV, LOAD, ADD, SUB, and HLT
  • A fetch-decode-execute loop
  • A memory model with separate ROM, RAM, and stack regions

The most valuable part wasn't getting the instructions to execute. It was understanding how instruction encoding, registers, memory addressing, and control flow fit together to execute a program.

While building it, I also started following Prof. Onur Mutlu's Digital Design and Computer Architecture lectures, which helped me understand processor internals beyond the software abstraction.

One particularly interesting takeaway was the growing importance of the memory bottleneck. Improvements in processor performance have increasingly exposed the cost of moving data between memory and compute units.

This introduced me to ideas such as processing-in-memory (PIM) and near-memory computing, which I'm interested in exploring further.

How does this connect to compilers?

My long-term goal is to understand how compilers translate high-level programs into instructions for different architectures, and how architectural constraints influence code generation and optimization.

Building this emulator gave me a practical starting point for reasoning about instruction sets and execution semantics.

I'm considering extending the project with an assembler and eventually building a small compiler backend targeting my custom ISA.

For those working on compiler backends or computer architecture, what would you recommend exploring next to better understand the relationship between instruction selection, code generation, and the target architecture?

GitHub: https://github.com/obadafidii/cpu

I'll also be writing a more detailed technical blog about the implementation and what I learned.


r/Compilers • • 18d ago

I'm creating my own programming language

0 Upvotes

I started developing my own programming language three or four months ago because I kept seeing pitfalls in every language—some were strict, some were restrictive, and some were difficult to work with. I love writing in Java and Kotlin and want to create my own language with its own virtual machine. Unlike the JVM, I want to make mine faster and a little simpler, but not too much. My language is almost ready; I started working on it last fall, but not completely.


r/Compilers • • 19d ago

Audit of semi-colons

1 Upvotes

Is there a set of defined and specific reasons why semi colons are necessary in some languages? I am not against semi colons but from the standpoint of if one would want to create a language why would they use or mandate semi colons.


r/Compilers • • 19d ago

Using dot as universal member access

4 Upvotes

I've been designing and implementing my own programming language for about two years now.

In my previous experience with programming languages, I've noticed that different operators are commonly used for member access depending on the kind of entity being accessed:

structure.member
pointer->member
namespace::member

This is a pretty common approach in several widely used languages.

Over the past year, however, I decided to remove the -> operator from my language. Similar to Rust, I allow implicit pointer dereferencing during member access. So, whenever the compiler encounters a member access expression (base, member), it first checks the type/category of base. If it's a pointer, it dereferences it before resolving the member.

Now I'm working on namespace support, and I'm wondering whether I can apply the same idea here: check what `base` resolves to, and if it's neither a pointer nor a structure/object, treat it as a namespace and resolve the member within it.

Essentially, I'm considering using . as a universal member access operator:

object.merember
pointer.member
namespace.member

My questions are:

  1. Am I overlooking any semantic or syntactic issues with this approach?
  2. Are there any good reasons to keep separate operators for object, pointer, and namespace access?
  3. Is implicit pointer dereferencing during member access a good design choice, or could it introduce problems as the language evolves?

I'd appreciate insights from people who have designed or implemented programming languages, particularly regarding name resolution and type checking.


r/Compilers • • 19d ago

Death to Dependency Hell: Why I Built My Own Stack Instead of Gluing Together Everyone Else’s

Thumbnail reddit.com
0 Upvotes

r/Compilers • • 19d ago

Cole Updates, and Version 0.1.6

Thumbnail reddit.com
2 Upvotes

r/Compilers • • 19d ago

I built a compiler for a controlled English-like mathematical language in Haskell — looking for compiler design feedback

0 Upvotes

I've been developing HumMac, a compiler for a controlled, English-like mathematical language, using Haskell. (the final idea is to build towards a human-to-machine language compiler)

The project explores how a human-readable mathematical language can be given precise semantics and translated into a structured intermediate representation.

The compiler is organized around several components:

  • A parser that constructs a structured abstract syntax tree
  • A symbol table with explicit symbol identifiers
  • Conversion from the source representation into Structured Mathematical IR (SMIR)
  • Expression and proposition inference
  • Numeric type promotion and semantic validation
  • Definite-initialization analysis, including conditional branches
  • Termination-analysis infrastructure

HumMac currently supports arithmetic expressions, implicit multiplication, bounded repetition, conditionals and six comparison operators. The compiler successfully parses this program, generates SMIR, constructs its symbol table and infers the types of its variables. Since it is currently a compiler rather than an execution environment, variables do not necessarily need to be initialized before they can be introduced or referenced. In particular, the language distinguishes free mathematical symbols, which can remain unassigned, from runtime variables, for which definite-initialization analysis is performed. This distinction allows mathematical expressions to contain symbolic variables without treating them as uninitialized runtime values.

One design distinction was separating free mathematical symbols from runtime variables. An unassigned mathematical symbol can represent a free variable in an expression, whereas a runtime variable may require definite-initialization analysis.

The project is still a prototype. SMIR generation and analysis are implemented, but a complete SMIR execution engine is not yet available.

Implementation: Haskell (GHC 9.10.3, Cabal)

Repository: https://github.com/RupsaMC/HumMac

I'd be glad to hear thoughts from the Haskell community, particularly on:

  • The organization of compiler passes and intermediate representations
  • Representing mathematical expressions and proposition in Haskell
  • Semantic analysis and type inference architecture
  • Approaches to making the implementation easier to extend as the language grows

This is my independent project and I'm sharing it in the hope of receiving useful technical feedback.

***Why Haskell?

I chose Haskell partly because of my interest in the relationship between convergence and divergence in lambda calculus, and the way these ideas connect to the behaviour and evaluation of computational expressions. Haskell's functional and strongly typed approach made it an interesting language in which to explore these ideas while building HumMac's parser, intermediate representation and semantic analysis pipeline.


r/Compilers • • 19d ago

Localizing Python keywords at the tokenizer level: what breaks, and why 3.12 became the floor

0 Upvotes

polyglot-python (MIT) is a deterministic tokenizer pass followed by a normal compile() call. There is no model in the loop.

The scope is deliberately narrow: write Python with keywords in another language, keep everything else Python. eğer instead of if, döndür instead of return, and the file still runs through CPython.

Why the tokenizer rather than an AST pass or a parser fork:

  • Only exact NAME tokens that match a locale keyword are rewritten. An attribute after a dot is never rewritten, so obj.tür stays an attribute lookup instead of becoming a syntax error.
  • Strings, f-strings, comments and docstrings are untouched, because the rewrite works on token spans rather than text replacement.
  • Token positions are preserved, so an error from compile() is mapped back to the line and column the user actually typed.

What makes 3.12 the floor is a tokenizer difference, not a packaging choice: on 3.10 and 3.11 the tokenizer splits Indic combining marks, so several Hindi keywords would not translate. On 3.12+ they survive tokenization intact. That is why requires-python is >=3.12 here while sibling packages stay at 3.10 or 3.11.

Soft keywords stay English: match, case and type (and 3.15's lazy) are context-sensitive, so translating them would mean changing a parser decision rather than the token stream. The reserved table is exactly the 35 hard keywords from keyword.kwlist.

Determinism is part of the contract: UTF-8 and LF on every platform, so the way to test it is to translate twice and compare bytes. run follows CPython script semantics - on main the script's directory leads sys.path, the program is main, and tracebacks show only the program's frames, never the translator's. The published 0.2.1 does not add the script directory.

Release state: PyPI and the npm wrapper are at 0.2.1 with 9 locales. Main has 20; Italian, Dutch, Polish, Indonesian, Vietnamese, Japanese, Korean, Ukrainian, Romanian, Swedish and Greek are the eleven unreleased locales. The suite on main is 242 tests at 100% statement coverage, CI runs 3.12-3.15 plus Windows and macOS, and every example is translated twice per OS and compared byte for byte.

Repo: https://github.com/Furox-Art/polyglot-python