Skip to content

Commit 327a2c3

Browse files
authored
Update README.md
1 parent 55dd90a commit 327a2c3

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

README.md

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,49 @@
1-
# tinycompiler
2-
Writing a compiler in a week-end
1+
# tinycompiler - a 500-ish lines of code compiler in a weekend
2+
Have you ever wondered how a compiler works? If so, this project is for you.
3+
4+
This weekend I'll write a compiler that translates a code written in a very simple programming language Wend (short for a week-end) into GNU assembly.
5+
This repository, however, will contain more than the final code. It will tell you a story about compilers.
6+
7+
So behold, here is a program that uses virtually all concepts in Wend:
8+
```cpp
9+
fun main() {
10+
// square root of a fixed-point number
11+
// stored in a 32 bit integer variable, shift is the precision
12+
13+
fun sqrt(n:int, shift:int) : int {
14+
var x:int;
15+
var x_old:int;
16+
var n_one:int;
17+
18+
if n > 65535 { // pay attention to potential overflows
19+
return 2 * sqrt(n / 4, shift);
20+
}
21+
x = shift; // initial guess 1.0, can do better, but oh well
22+
n_one = n * shift; // need to compensate for fixp division
23+
while true {
24+
x_old = x;
25+
x = (x + n_one / x) / 2;
26+
if abs(x - x_old) <= 1 {
27+
return x;
28+
}
29+
}
30+
}
31+
32+
fun abs(x:int) : int {
33+
if x < 0 {
34+
return -x;
35+
} else {
36+
return x;
37+
}
38+
}
39+
40+
// 25735 is approximately equal to pi * 8192;
41+
// expected value of the output is sqrt(pi) * 8192 approx 14519
42+
43+
println sqrt(25735, 8192);
44+
}
45+
```
46+
47+
There will no be dynamic memory allocation, no pointers, no garbage collection. There will be nested functions, function overloading and type checking.
48+
49+
And as usual, there will be a program with a raytracer :)

0 commit comments

Comments
 (0)