isuckatcs/how-to-compile-your-language
About
An introduction to language design through building a compiler frontend on top of LLVM.
Languages & RuntimesMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Original
Build a compiler from scratch for Your Language, a small programming language designed to explore how modern compilers work.
What You'll Learn
- 🚀 Native code generation with LLVM
- 🧠 Hindley–Milner type inference
- 🏷️ Traits and type extensions
- ♻️ Tracing garbage collection
- 📸 Heap-allocated closures
- 🖨️ Monomorphized generics
- 🗺️ Virtual dispatch
- 🌊 Data-flow analysis
- 💻 Compile time expression evaluation
- 🔍 Visualized internals
📖 Read the Guide, or Get Started
🚧 The guide is currently being updated to match the main branch. 🚧
Your Language
A small example combining traits, type extensions, generics, closures, and type inference:
trait Shape {
fn area(self: &Self): number;
}
struct Rectangle {
width: number,
length: number,
}
extension Rectangle : Shape {
fn area(self: &Self): number {
return self.width * self.length;
}
}
fn map<T, U>(value: T, transform: (T) -> U): U {
return transform(value);
}
fn main() {
let r = Rectangle { width: 4.0, length: 5.0 };
let areaSquared = map(r.area(), ->(area) {
return area * area;
});
println(areaSquared);
}
$ compiler example.yl -o example
$ ./example
400
Getting Started
Your Language currently only supports POSIX systems. The steps below will get the compiler up and running on Ubuntu Linux*. Equivalent commands are available for other POSIX systems as well.
Clone the repository:
git clone https://github.com/isuckatcs/how-to-compile-your-language.git cd how-to-compile-your-languageInstall CMake 3.20 or newer:
sudo apt install cmakeInstall LLVM and Clang. For Ubuntu Linux it is recommended to use the
llvm.shscript from apt.llvm.org.wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 20📝 The project was originally built for LLVM 20.1.0. Other versions are not guaranteed to work.
Create and enter the build directory:
mkdir build cd buildConfigure CMake and build the project:
cmake .. cmake --build .Verify that the build was successful:
./bin/compiler -h
To run the tests, install the additional dependencies and run the check target.
Install Python 3.10 or newer:
sudo apt install python3Install the required dependencies:
python3 -m pip install -r ./test/requirements.txtRun the
checktarget with CMake:cmake --build . --target check
* Tested on Ubuntu 22.04.5 LTS
Topics Covered
🚀 Native Code Generation
Run your program directly on your machine. The source file is first compiled to LLVM IR, which is then passed to the host-platform-specific LLVM backend to generate a native executable.
fn main() {
println(123);
}
$ compiler main.yl -o main
$ ./main
123
🧠 Hindley-Milner Type Inference
Write generic code without annotating every type. The compiler infers types using a Hindley–Milner style type system and Algorithm J.
fn map<T, U>(value: T, transform: (T) -> U): U {
return transform(value);
}
fn boolToNumber(b: bool): number {
if b { return 1; }
return 0;
}
fn main() {
println(map(true, boolToNumber));
}
$ compiler type_inference.yl -o type_inference
$ ./type_inference
1
🏷️ Traits and Type Extensions
Extend types without modifying their definitions. Traits provide shared behavior, while type extensions attach implementations to existing types.
trait Explorable {
fn explore(self: &Self, year: number);
}
struct Planet {}
extension Planet : Explorable {
fn explore(self: &Self, year: number) {
println(year);
}
}
fn main() {
let mars = Planet {};
mars.explore(2148);
}
$ compiler traits_and_type_extensions.yl -o traits_and_type_extensions
$ ./traits_and_type_extensions
2148
♻️ Tracing Garbage Collection
Allocate objects on the heap without manually managing their lifetime. A stop-the-world mark-and-sweep garbage collector, built on LLVM's shadow stack strategy, manages those allocations automatically.
struct Box<T> {
ptr: *T
}
fn main() {
let box = Box { ptr: gc 123 };
gcCollect();
println(*box.ptr);
}
💡 Use the
YL_GC_DUMPenvironment variable to enable logging the actions the collector performs.
$ compiler gc.yl -o gc
$ YL_GC_DUMP=1 ./gc
[0] alloc (123.header) data: (123.data) (8 B) {heap: 32 B, threshold: 96 B}
[0] mark (123.header) data: (123.data) (8 B) {heap: 32 B, threshold: 96 B}
[0] sweep {heap: 32 B, threshold: 96 B}
123
[1] sweep (123.header) data: (123.data) (8 B) {heap: 0 B, threshold: 96 B}
[1] sweep {heap: 0 B, threshold: 96 B}
Understanding the GC log format
[0] alloc (123.header) data: (123.data) (8 B) {heap: 32 B, threshold: 96 B}
- [0]: GC cycle, incremented after sweeping
- alloc: operation the GC performed
- (123.header): address of the allocation header
- (123.data): address of the storage returned to the program
- (8 B): size of the requested storage
- {heap: 32 B, threshold: 96 B}: total heap usage with the limit before the next cycle
📸 Heap-Allocated Closures
Work with higher-order functions seamlessly. Heap-allocated closures allow functions and lambdas to be passed around interchangeably.
fn apply<T, U, V>(t: T, u: U, f: (T, U) -> V): V {
return f(t, u);
}
fn main() {
let sum = apply(1, 2, ->(a, b) {
return a + b;
});
println(sum);
}
$ compiler heap_allocated_closures.yl -o heap_allocated_closures
$ ./heap_allocated_closures
3
🖨️ Monomorphized Generics
See how generics become concrete at compile time. In Your Language generics are instantiated lazily during LLVM IR generation.
fn generic<T>() {}
fn main() {
generic@<unit>();
generic@<number>();
generic@<() -> unit>();
}
💡 Use the
-mono-dumpflag to see how each instance was created.
$ compiler main.yl -mono-dump
(generic, [T = unit]) -> _Y7genericGuE
(generic, [T = number]) -> _Y7genericGnE
(generic, [T = () -> unit]) -> _Y7genericGFRuE
🗺️ Virtual Dispatch
Call trait methods without knowing the concrete type. Associated functions on trait objects are looked up from a vtable when called.
trait Printable {
fn print(self: &Self);
}
extension number : Printable {
fn print(self: &Self) {
println(self);
}
}
fn virtualDispatch(p: &any Printable) {
p.print();
}
fn main() {
let n = 123;
virtualDispatch(n);
}
$ compiler virtual_dispatch.yl -o virtual_dispatch
$ ./virtual_dispatch
123
🌊 Data-Flow Analysis
Catch uninitialized variables before your program runs. Data-flow analysis tracks variable initialization across control-flow paths.
fn dataFlowAnalysis(n: number) {
let uninit;
if n > 3 {
uninit = n;
}
println(uninit);
}
fn main() {
dataFlowAnalysis(1);
}
$ compiler data_flow_analysis.yl
data_flow_analysis.yl:8:11: error: 'uninit' is not initialized
8 | println(uninit);
| ^
💻 Compile-Time Expression Evaluation
Implement an interpreter inside the compiler. Expressions are evaluated by a tree-walk interpreter during compilation if possible.
fn main() {
let x = (1 + 2) * 3 - -4;
println(x);
}
$ compiler main.yl -res-dump
FunctionDecl @(main.addr) main {() -> unit}
Block
...
CallExpr {unit}
DeclRefExpr @(println.addr) println {(number) -> unit}
DeclRefExpr @(x.addr) x {number}
| value: 13
🔍 Visualized Internals
See what the compiler sees. Dump the AST, resolved AST, CFG and the generated LLVM IR module on demand.
fn main() {
println(123);
}
$ compiler main.yl -ast-dump
FunctionDecl 'main'
Block
CallExpr
PathExpr
DeclRefExpr 'println'
NumberLiteral '123'
$ compiler main.yl -res-dump
FunctionDecl @(main.addr) main {() -> unit}
Block
CallExpr {unit}
DeclRefExpr @(println.addr) println {(number) -> unit}
NumberLiteral '123' {number}
| value: 123
$ compiler main.yl -cfg-dump
fn main(...) {
bb2:
preds:
succs: 1
bb1:
preds: 2
$1 = 123
$2 = println
$3 = $2($1)
succs: 0
bb0:
preds: 1
succs:
}
$ compiler main.yl -mono-dump
(println, []) -> _Y7println
(main, []) -> _Y4main
$ compiler main.yl -llvm-dump
define void @_Y4main(ptr %closure) {
entry:
call void @_Y7println(double 1.230000e+02, ptr null)
ret void
}
📝 The
numbertype in Your Language is represented as adouble.
Explore related projects
Loading…