Skip to content

AdamHameed/RCC

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RCC

RCC is a small Rust-based C compiler project for a minimal subset of C. It lexes, parses, builds an AST, lowers that AST to LLVM IR with inkwell, and then invokes clang or gcc to produce an executable.

Supported C Subset

Current support is intentionally small:

  • int main() { return <expr>; }
  • integer literals
  • binary arithmetic:
    • +
    • -
    • *
    • /
  • parentheses for grouping

Examples:

int main() { return 5; }
int main() { return 2 + 3; }
int main() { return 4 * (2 + 1); }

Project Layout

src/
  ast/
  codegen/
  lexer/
  parser/
  main.rs
tests/
samples/

Requirements

  • Rust and Cargo
  • clang or gcc
  • LLVM 17 for inkwell

This repo is currently configured for Homebrew LLVM 17 on macOS in .cargo/config.toml:

[env]
LLVM_SYS_170_PREFIX = "/opt/homebrew/opt/llvm@17"

If you use a different LLVM install location, update that path.

Build

cargo build

The compiler binary is named compiler.

Usage

Compile a C file:

cargo run --bin compiler -- samples/return_5.c

This produces:

  • output.ll - generated LLVM IR
  • output - compiled executable

Run the produced executable and inspect its return code:

./output
echo $?

Sample Programs

Sample inputs live in the samples directory:

Testing

Run all tests:

cargo test

The test suite includes:

  • unit tests for the lexer, parser, AST, and codegen
  • end-to-end tests that compile small C programs, run them, and check the exit code

How It Works

The compiler pipeline is:

  1. Lex source code into tokens
  2. Parse tokens into an AST
  3. Lower the AST into LLVM IR
  4. Write LLVM IR to output.ll
  5. Invoke the system compiler to build output

For example, this AST:

int main() { return 4 * (2 + 1); }

can lower to LLVM IR equivalent to:

define i32 @main() {
entry:
  ret i32 12
}

LLVM may fold constant expressions during IR construction, so simple arithmetic can appear already simplified in the generated IR.

About

a C compiler written in RUST

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages