https://github.com/rui314/chibicc Skip to content Toggle navigation Sign up * Product + Actions Automate any workflow + Packages Host and manage packages + Security Find and fix vulnerabilities + Codespaces Instant dev environments + Copilot Write better code with AI + Code review Manage code changes + Issues Plan and track work + Discussions Collaborate outside of code + Explore + All features + Documentation + GitHub Skills + Blog * Solutions + By Plan + Enterprise + Teams + Compare all + By Solution + CI/CD & Automation + DevOps + DevSecOps + Case Studies + Customer Stories + Resources * Open Source + GitHub Sponsors Fund open source developers + The ReadME Project GitHub community articles + Repositories + Topics + Trending + Collections * Pricing [ ] * # In this repository All GitHub | Jump to | * No suggested jump to results * # In this repository All GitHub | Jump to | * # In this user All GitHub | Jump to | * # In this repository All GitHub | Jump to | Sign in Sign up {{ message }} rui314 / chibicc Public * Notifications * Fork 619 * Star 6.7k A small C compiler License MIT license 6.7k stars 619 forks Star Notifications * Code * Issues 62 * Pull requests 20 * Actions * Projects 0 * Wiki * Security * Insights More * Code * Issues * Pull requests * Actions * Projects * Wiki * Security * Insights rui314/chibicc This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. main Switch branches/tags [ ] Branches Tags Could not load branches Nothing to show {{ refName }} default View all branches Could not load tags Nothing to show {{ refName }} default View all tags Name already in use A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch? Cancel Create 4 branches 0 tags Code * Local * Codespaces * Clone HTTPS GitHub CLI [https://github.com/r] Use Git or checkout with SVN using the web URL. [gh repo clone rui314] Work fast with our official CLI. Learn more. * Open with GitHub Desktop * Download ZIP * Codespaces is rolling out You don't have access just yet, but in the meantime, you can learn about Codespaces Launching GitHub Desktop If nothing happens, download GitHub Desktop and try again. Launching GitHub Desktop If nothing happens, download GitHub Desktop and try again. Launching Xcode If nothing happens, download Xcode and try again. Launching Visual Studio Code Your codespace will open once ready. There was a problem preparing your codespace, please try again. Latest commit @rui314 rui314 Make struct member access to work with = and ?: ... 90d1f7f Dec 7, 2020 Make struct member access to work with `=` and `?:` 90d1f7f Git stats * 316 commits Files Permalink Failed to load latest commit information. Type Name Latest commit message Commit time include Complete stdatomic.h Dec 7, 2020 test Make struct member access to work with = and ?: Dec 7, 2020 .gitignore Add scripts to test third-party apps Dec 7, 2020 LICENSE Add LICENSE and README.md Oct 7, 2020 Makefile Add thread-local variable Dec 7, 2020 README.md Update README Dec 7, 2020 chibicc.h Add __attribute__((packed)) Dec 7, 2020 codegen.c Make struct member access to work with = and ?: Dec 7, 2020 hashmap.c Add string hashmap Dec 7, 2020 main.c Add -Xlinker option Dec 7, 2020 parse.c Add __attribute__((aligned(N)) for struct declaration Dec 7, 2020 preprocess.c Complete stdatomic.h Dec 7, 2020 strings.c Run "as" command unless -S is given Dec 7, 2020 tokenize.c Add __attribute__((packed)) Dec 7, 2020 type.c Add atomic_exchange Dec 7, 2020 unicode.c Improve error message for multibyte characters Dec 7, 2020 View code chibicc: A Small C Compiler Status Internals Contributing Design principles About the Author References README.md chibicc: A Small C Compiler (The old master has moved to historical/old branch. This is a new one uploaded in September 2020.) chibicc is yet another small C compiler that implements most C11 features. Even though it still probably falls into the "toy compilers" category just like other small compilers do, chibicc can compile several real-world programs, including Git, SQLite, libpng and chibicc itself, without making modifications to the compiled programs. Generated executables of these programs pass their corresponding test suites. So, chibicc actually supports a wide variety of C11 features and is able to compile hundreds of thousands of lines of real-world C code correctly. chibicc is developed as the reference implementation for a book I'm currently writing about the C compiler and the low-level programming. The book covers the vast topic with an incremental approach; in the first chapter, readers will implement a "compiler" that accepts just a single number as a "language", which will then gain one feature at a time in each section of the book until the language that the compiler accepts matches what the C11 spec specifies. I took this incremental approach from the paper by Abdulaziz Ghuloum. Each commit of this project corresponds to a section of the book. For this purpose, not only the final state of the project but each commit was carefully written with readability in mind. Readers should be able to learn how a C language feature can be implemented just by reading one or a few commits of this project. For example, this is how while, [], ?:, and thread-local variable are implemented. If you have plenty of spare time, it might be fun to read it from the first commit. If you like this project, please consider purchasing a copy of the book when it becomes available! I publish the source code here to give people early access to it, because I was planing to do that anyway with a permissive open-source license after publishing the book. If I don't charge for the source code, it doesn't make much sense to me to keep it private. I hope to publish the book in 2021. You can sign up here to receive a notification when a free chapter is available online or the book is published. I pronounce chibicc as chee bee cee cee. "chibi" means "mini" or "small" in Japanese. "cc" stands for C compiler. Status chibicc supports almost all mandatory features and most optional features of C11 as well as a few GCC language extensions. Features that are often missing in a small compiler but supported by chibicc include (but not limited to): * Preprocessor * float, double and long double (x87 80-bit floating point numbers) * Bit-fields * alloca() * Variable-length arrays * Compound literals * Thread-local variables * Atomic variables * Common symbols * Designated initializers * L, u, U and u8 string literals * Functions that take or return structs as values, as specified by the x86-64 SystemV ABI chibicc does not support complex numbers, K&R-style function prototypes and GCC-style inline assembly. Digraphs and trigraphs are intentionally left out. chibicc outputs a simple but nice error message when it finds an error in source code. There's no optimization pass. chibicc emits terrible code which is probably twice or more slower than GCC's output. I have a plan to add an optimization pass once the frontend is done. I'm using Ubuntu 20.04 for x86-64 as a development platform. I made a few small changes so that chibicc works on Ubuntu 18.04, Fedora 32 and Gentoo 2.6, but portability is not my goal at this moment. It may or may not work on systems other than Ubuntu 20.04. Internals chibicc consists of the following stages: * Tokenize: A tokenizer takes a string as an input, breaks it into a list of tokens and returns them. * Preprocess: A preprocessor takes as an input a list of tokens and output a new list of macro-expanded tokens. It interprets preprocessor directives while expanding macros. * Parse: A recursive descendent parser constructs abstract syntax trees from the output of the preprocessor. It also adds a type to each AST node. * Codegen: A code generator emits an assembly text for given AST nodes. Contributing When I find a bug in this compiler, I go back to the original commit that introduced the bug and rewrite the commit history as if there were no such bug from the beginning. This is an unusual way of fixing bugs, but as a part of a book, it is important to keep every commit bug-free. Thus, I do not take pull requests in this repo. You can send me a pull request if you find a bug, but it is very likely that I will read your patch and then apply that to my previous commits by rewriting history. I'll credit your name somewhere, but your changes will be rewritten by me before submitted to this repository. Also, please assume that I will occasionally force-push my local repository to this public one to rewrite history. If you clone this project and make local commits on top of it, your changes will have to be rebased by hand when I force-push new commits. Design principles chibicc's core value is its simplicity and the reability of its source code. To achieve this goal, I was careful not to be too clever when writing code. Let me explain what that means. Oftentimes, as you get used to the code base, you are tempted to improve the code using more abstractions and clever tricks. But that kind of improvements don't always improve readability for first-time readers and can actually hurts it. I tried to avoid the pitfall as much as possible. I wrote this code not for me but for first-time readers. If you take a look at the source code, you'll find a couple of dumb-looking pieces of code. These are written intentionally that way (but at some places I might be actually missing something, though). Here is a few notable examples: * The recursive descendent parser contains many similar-looking functions for similar-looking generative grammar rules. You might be tempted to improve it to reduce the duplication using higher-order functions or macros, but I thought that that's too complicated. It's better to allow small duplications instead. * chibicc doesn't try too hard to save memory. An entire input source file is read to memory first before the tokenizer kicks in, for example. * Slow algorithms are fine if we know that n isn't too big. For example, we use a linked list as a set in the preprocessor, so the membership check takes O(n) where n is the size of the set. But that's fine because we know n is usually very small. And even if n can be very big, I stick with a simple slow algorithm until it is proved by benchmarks that that's a bottleneck. * Each AST node type uses only a few members of the Node struct members. Other unused Node members are just a waste of memory at runtime. We could save memory using unions, but I decided to simply put everything in the same struct instead. I believe the inefficiency is negligible. Even if it matters, we can always change the code to use unions at any time. I wanted to avoid premature optimization. * chibicc always allocates heap memory using calloc, which is a variant of malloc that clears memory with zero. calloc is slightly slower than malloc, but that should be neligible. * Last but not least, chibicc allocates memory using calloc but never calls free. Allocated heap memory is not freed until the process exits. I'm sure that this memory management policy (or lack thereof) looks very odd, but it makes sense for short-lived programs such as compilers. DMD, a compiler for the D programming language, uses the same memory management scheme for the same reason, for example [1]. About the Author I'm Rui Ueyama. I'm the creator of 8cc, which is a hobby C compiler, and also the original creator of the current version of LLVM lld linker, which is a production-quality linker used by various operating systems and large-scale build systems. References * tcc: A small C compiler written by Fabrice Bellard. I learned a lot from this compiler, but the design of tcc and chibicc are different. In particular, tcc is a one-pass compiler, while chibicc is a multi-pass one. * lcc: Another small C compiler. The creators wrote a book about the internals of lcc, which I found a good resource to see how a compiler is implemented. * An Incremental Approach to Compiler Construction * Rob Pike's 5 Rules of Programming [1] https://www.drdobbs.com/cpp/increasing-compiler-speed-by-over-75/ 240158941 DMD does memory allocation in a bit of a sneaky way. Since compilers are short-lived programs, and speed is of the essence, DMD just mallocs away, and never frees. About A small C compiler Resources Readme License MIT license Stars 6.7k stars Watchers 158 watching Forks 619 forks Releases No releases published Packages 0 No packages published Languages * C 96.9% * Shell 2.8% * Other 0.3% Footer (c) 2022 GitHub, Inc. Footer navigation * Terms * Privacy * Security * Status * Docs * Contact GitHub * Pricing * API * Training * Blog * About You can't perform that action at this time. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.