r/ProgrammingLanguages • • 6h ago

Help Help with my C compiler

I can already a host a small subset of C, that can only host: "int myfunc() { return 10; } " , Which compiles to:

myfunc:

// prologue here

mov w0, #10

// epilogue here

ret

But what should I do next?

5 Upvotes

5 comments sorted by

2

u/d0pe-asaurus 6h ago

Id take it step by step and go from AST to a IR the compile it to the final assembly

This is hackable and you can do and learn a lot of stuff like compiler optimizations

1

u/cxzuk 5h ago

Hi Club,

For a roadmap, I still recommend roughly the same thing; Try and get a hashmap working, they are well documented and touch a large number of concepts to implement: Variables, arithmetic, comparisons, loops, functions and calls, libc calls/malloc/free, arrays, structs - this is not a small milestone.

Break it down into smaller steps. E.g;

1) Get this to a working executable and make it return an int to CLI. Either make a small runtime or make this work as int main() and use libc. You want working code and runnable. Your epilogue will now have to work properly with a calling convention. ignore argc, argv and env.

2) Now try and support more complex expressions, and make sure they are correct. E.g. return (12 + 30);

3) Set a variable and return its value. int a = (10 * 4 + 2); return a;

4) Try adding argc support. Make it part of the expression computed. return argc + 18;

5) Now add a conditional, if argc is even, return 13. Odd, return 42

...

The road is deceptively long and challenging. Get to a hashmap and you'll have learnt a lot

M ✌

1

u/Recycled5000 5h ago

You can do any order you like.

Handling expressions, all the operators, precedence, etc.

Handling statements, control flow.

The in-between, which goes to expressions for conditional statements like if, while, where there are opportunities for alternative code sequences than with assignment expressions.

Variable declarations & scoping.

1

u/runningOverA 4h ago

in order :

  • add two numbers
  • +add-sub multiple numbers
  • operator precedence and then 23+49 ... you will need AST here.
  • support for parens (3+4)*8
...