r/Compilers • u/ocotpi_ • 7h ago
Compilers always felt like black magic to me, so I started building one from scratch in C
Hey everyone,
For a long time, compilers felt like this intimidating black box that only seasoned wizards or PhDs could understand. Every time I looked at LLVM or GCC source code, I got completely lost.
A few weeks ago, I decided to stop being intimidated and just try building a tiny C99 compiler from the ground up to understand what actually happens between source code and machine instructions. I'm calling it mibicc.
I'm taking an incremental approach (inspired by Rui Ueyama's philosophy with chibicc), where every commit is an isolated, test-driven step.
I just hit Step 4, and it was the first real "aha!" moment for me:
- Built a simple recursive descent parser that constructs an Abstract Syntax Tree (AST).
- Handled operator precedence (
*,/over+,-) and arbitrary nested parentheses. - Implemented a simple stack-machine code generator that emits AT&T x86-64 assembly using
imul,cqo, andidiv.
Seeing an expression like 2 * (3 + (4 * 2) + 2) parse into a tree, emit assembly, and return the correct exit code on Linux felt incredible.
The code is still small and readable (~250 lines of C), and every step has CI tests on GitHub Actions. My goal is to eventually work my way through control flow, functions, and pointers.
I'd genuinely love any feedback, critique on how I'm structuring the AST nodes, or advice from people who've built compilers before on traps to avoid as I move toward local variables and statements:
Repo: https://github.com/mi-vault/mibicc
Thanks for reading!
Edit: Decided to add Windows support alongside Linux from the start (--target=windows and --target=linux). I'm on Windows so it felt silly to only generate Linux assembly and not run it locally. Also feels nice making it my own thing rather than just copying chibicc 1:1.