A small C compiler written for learning.
Built by following Nora Sandler’s "Write a Compiler" series.
- arm64 (darwin and linux only)
- Part 1: Compile
int main() { return <int>; }
- Part 2: Add unary operators (
-
,~
,!
) - Part 3: Add binary operators (
+
,-
, etc.) - Part 4: Even More Binary Operators (
&&
,||
,==
,!=
,<
,<=
,>
,>=
) - Part 4.1: Other Binary Operators (
%
,&
,|
,^
,<<
,>>
) - Part 5: Local Variables
- Part 5.1:
- Compound Assignment Operators (
+=
,-=
,/=
,*=
,%=
,<<=
,>>=
,&=
,|=
,^=
) - Increment/Decrement(
++
/--
) - Comma operators (
int a = 2, b, c = a + 4;
)
- Compound Assignment Operators (
- Part 6: Conditionals
- Part 7: Compound Statements
- Part 8: Loops
- Part 9: Functions (with calls to the C standard library!)
- Part 10: Global Variables
- Part II of Writing a C Compiler book
- floating-point numbers
- arrays and pointers
- structs
- Constants
- Optimizations
- constant folding
- dead code elimination
cargo run -- path/to/file.c [--arch arm64] [--platform macos|linux]
- If
--arch
is not specified, the system architecture is used. Same for--platform
- Only arm64 is supported now
cargo run -- examples/return_42.c
Produces return_42.s
You can compile it with aarch64 GCC or run with QEMU.
Example for macOS:
clang -arch arm64 -o return_42_mac return_42.s
./return_42
echo $? # prints: 42
bingus(arg)
is a built-in pseudo-function, which evaluates expression and prints it into stdout. Available on macOS platform
DEPRECATED: calls to the standard library functions are supported
Example:
int main() {
int a = 10, b = 8;
bingus(a);
bingus(a * b);
bingus(b - 10);
}
Output:
10
80
-2
The testsuite
submodule contains tests cases from nlsandler/write_a_c_compiler
.
To run them, use
python run_tests.py
This compiler is licensed under the GNU General Public License, as described in the LICENSE
file.