A while ago I've started working on a compiler and now the code is ready for the first release :
https://github.com/dfrunza/hoc/archive/0.1.zip
HoC is a simple C clone and the main goal is to learn about the anatomy of a compiler.
v0.1 implements the minimum set of features that allows to write basic yet functional programs.
Implemented in this release are :
- built-in types - int, float, bool and char
- arrays and pointer types
- procedures
- flow control statements - if, else, while
- evaluation of expressions
- arithmetic and boolean operators
- explicit and implicit type conversions
- a simple "standard" library, which includes routines for :
- printing (to stdout) of strings, ints and floats
- math functions like abs(), min(), pow()
- sorting of arrays of integers using quicksort and insertion sort algorithms
A short tutorial
Variable declarations
1 2 3 4 5 | var float f = 1.23; var int i = 66; var [20]char buf; /* array of 20 chars allocated on the stack */ var char* str = "Hello World!"; var char* str = new(char, 20); /* array of 20 chars allocated on the heap */ |
Procedures
1 2 3 4 | proc int add(int a, int b) { return a + b; } |
Importation of code from another file
1 2 3 4 5 6 | include "str.hoc"; proc void hello_world() { print_str("Hello World!"); } |
A complete program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | include "str.hoc"; /* For all integers from 1 to 'n' print: fizz if it's divisible by 3 buzz if it's divisible by 5 fizzbuzz if it's divisible by 15 else print the integer itself */ proc void fizzbuzz(int n) { if(n > 0) { var int i = 1; while(i <= n) { if((i % 15) == 0) print_str("fizzbuzz"); else if((i % 3) == 0) print_str("buzz"); else if((i % 5) == 0) print_str("fizz"); else print_int(i); print_str("\n"); i = i + 1; } } } proc int main() { fizzbuzz(100); return 0; } |
Compile a HoC source file
1 | cmd$ hocc.exe my_program.hoc |
If there are no errors in the source file, then the output executable `my_program.exe` will be created, otherwise the first error will be reported.
Included in the release package is a `test.hoc` file which can be compiled and run.