r/C_Programming • • 14d ago

Building a small C99 compiler to get better at low-level C and x86-64 assembly

Hey everyone,

I've been trying to deepen my understanding of C and x86-64, and instead of just doing LeetCode or toy projects, I decided to try writing a tiny, self-contained C compiler in C99.

I wanted zero external dependencies just standard C library headers (stdio, stdlib, string, ctype).

I just reached the milestone where it handles operator precedence and nested parentheses:

  • Tokenizer: A linked-list tokenizer with character pointers that skips whitespace and formats visual Clang-style ^ caret error diagnostics.
  • Parser & AST: A recursive descent parser that allocates binary AST nodes for operators and numbers.
  • Code Generation: A stack-based code generator that recurses through the AST and emits x86-64 assembly (using push/pop for expressions, imul for multiplication, and cqo + idiv for signed 64-bit division).

Writing this has already taught me so much about memory layout, pointer arithmetic, and how the Linux ABI handles return values in %rax.

I have a test script with automated GitHub Actions CI verifying each arithmetic edge case against GCC.

I'd really appreciate any C veterans taking a look at my C style, error handling, or memory management in src/main.c:

https://github.com/mi-vault/mibicc

Any tips or feedback are very welcome!

Edit: Decided to add Windows support alongside Linux from the start (--target=windows and --target=linux). I'm on Windows myself so it felt silly to only target Linux System V and not be able to test it locally. Also feels nice putting my own stamp on it rather than just following chibicc 1:1.

(Had some great discussions over on r/Compilers about ABI quirks and stack architectures if anyone is interested in that side of things!)

17 Upvotes

11 comments sorted by

•

u/mikeblas 14d ago

What role did AI have in the creation of your project?

5

u/tempestpdwn 13d ago

I am currently writing an assembler and do have plans to start with a c compiler sometime soon after im done with this.
Can you point me to any resources that you've found useful or the ones that you are following if any?

2

u/ocotpi_ 12d ago

That's awesome! Writing an assembler first is actually the best prep work you could have done, since codegen will feel way more natural to you.

The resources that helped me the most:

  1. Rui Ueyama's chibicc git history: Rui built it in tiny, incremental commits where every single commit adds one feature plus its tests. Stepping through his early commits commit-by-commit is easily the best practical guide out there.
  2. Nora Sandler's book ("Writing a C Compiler"): Super modern (No Starch Press) and takes the same incremental, test-driven approach. Highly recommend it.
  3. The System V AMD64 & Microsoft x64 ABI docs: Helpful once you get to registers and calling conventions.

I also had a really good discussion going on r/Compilers where a few compiler devs shared some neat architecture references too if you want to check that thread out! Good luck with the assembler!

2

u/tempestpdwn 12d ago

Thanks :-)

3

u/AutoModerator 14d ago

Hi /u/ocotpi_,

Your submission in r/C_Programming was filtered because it links to a git project.

You must edit the submission or respond to this comment with an explanation about how AI was involved in the creation of your project.

While AI-generated code is not disallowed, low-effort "slop" projects may be removed and it's likely that other users push back strongly on substantially AI-generated projects.

You can read more at How do I post my Project?


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

6

u/ocotpi_ 14d ago

No AI generated code or automated copy paste was used to build this project.

I have been studying Rui Ueyama's chibicc and compiler resources to learn compiler construction from first principles. I used AI as an interactive tutor/rubber-duck to explain x86-64 assembly nuances (like cqo sign-extension and idiv register pairs) and discuss grammar edge cases, but the C code, recursive descent parser, AST node structures, and test suites are all written and tested incrementally by hand.

This is a genuine educational effort to learn systems programming and understand what happens between C source code and machine instructions.

4

u/mikeblas 13d ago

Thank you. I have approved your post.

2

u/Hoshiqua 12d ago

I also have worked on my own C99 compiler, I switched to a different project since then but I want to come back to it sometimes soon. Github link. The current level of advancement is full tokenization, parsing, and nearly full solving / "integration" (as I've called it) of the C99 standard, with a few exceptions like gotos and switch statements which I wanted to handle later for some reason. It does manage stuff like typedefs and whatnot, which made me completely rewrite the AST logic multiple times as I got a more and more "pure" understanding of how the C standard works conceptually and thus how my compiler "should" read it. The main takeaway was that C is made up of object declarations, which always start with:
- Whether the objects are typedefs / aliases or actual objects
- A type (var types and function return types), in the form of a primitive type, a typedef'ed object name, or a defined struct / enum.

The start of an objects declaration statement is followed by a comma separate list of objects that use that type. They can be variables (N stars for pointer / indirection levels, a name, and N array sizes), functions (a name with parameters in parenthesis with comma-separate parameters) or function pointers (a hybrid of the two: a variable with parameters and the well-known weird syntax).

It ends when either a function definition or a semicolon is encountered.

A lot of the time in actual code, we don't tend to mix type definitions and declaring objects, but it's all the same really. It's only for readability. This means you can write something like:

typedef enum
{
  VAL_1,
  VAL_2
} array_of_anonymous_enum[25];

struct foo 
{
  int result,
  const char* str_because_why_not;
  array_of_anonymous_enum array;
} bar(int a, int b)
{
  return { a + b, "wtf is this" };
}

// I mean you CAN write this (I think ?) but I would get you fired from the team if you did :)

And that's pretty much the entire langage right there, not counting pre-processor stuff.

Maybe that's obvious but it certainly wasn't to me even though I have years of experience in C / C++... that realization made the langage click to me as a compiler developer: my parsing stage which used to be this complicated tree of possibilities depending on the sort of statement I was facing violently collapsed to only being a single comparatively simple state machine, with the main "branch" being whether you're inside a function or not.

As for your code...

I like the way you're going with this, and that's something I've been thinking I should have done with mine - try to get the whole chain working for a small subset of features, rather than building the FULL AST then the FULL solver and later (not started yet) the FULL code generation.

However, I guess one drawback of that approach is that if you make a bad choice of architecture, it will bite you in the buttox over multiple stages instead of a single one at a time. And I think this is something that will create a bunch of work down the road - so far what you have is an expression parser, which is actually a big thing to build in pure C99 already so great job. However, I think you will find that, for example, defining your AST Nodes as the different operand / operator types will not be the right granularity.

For now the simplicity / size of the program makes it so putting it all in one file and separating the stages by function calls only is fine, but the reason I personally didn't do that is because I wanted to conceptually build the stage-based pipeline right away, allowing me to better separate the concerns of each stage, handle their errors with their own codes, encapsulate the code / symbols, etc...

2

u/ocotpi_ 12d ago

That cursed snippet with the anonymous enum and struct declared right inside the function signature made me laugh. C declaration syntax is honestly wild once you look under the hood. That point about everything fundamentally being an object declaration collapsing the parser into a simple state machine is great. Definitely keeping that mental model in mind for when I get to structs and typedefs.

You are spot on about the vertical slice tradeoff. Rewriting across multiple stages whenever an abstraction shifts is definitely the price you pay for doing it incrementally. But coming into this wanting to learn assembly and ABIs, getting each step to emit real x86 assembly and run tests end to end gives a really nice feedback loop. It also forced me to handle calling conventions and ABI quirks like Windows 32 byte shadow space early on instead of leaving codegen as a scary mystery for the end. We have been having some fun discussions around these tradeoffs over in r/Compilers as well.

I completely agree on the single file approach and AST node granularity hitting a wall down the road. Right now at step 7 where I just added basic locals and assignment, having everything in one file makes rapid testing easy. Once types, pointer indirection, and scopes land, I will definitely split it into proper lexer, parser, and codegen stages.

Your breakdown was so helpful that I actually logged your notes on declaration grammar and the horizontal versus vertical tradeoffs directly into my repo lab notebook in DEVLOG.md. I also starred your C compiler repo so I can follow along whenever you jump back into it, the integration stage looks super clean. Really appreciate you taking the time to share all of that. :>

1

u/Hoshiqua 12d ago

Wow thanks, actually giving me some motivation to get back on it 😁 I'll star yours in return it's only fair !

And yeah your logic makes sense. I can tell you that with my approach every new stage feels a little scary to break ground in...

2

u/ocotpi_ 12d ago

Thanks for the star. That feeling of each new stage being intimidating to break ground in is so real. What helps me is just writing one tiny failing test at a time so the mountain feels smaller. Definitely drop an update whenever you pick yours back up, would be cool to see how your codegen phase comes together.