Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,26 @@ env:

jobs:
coverage:
runs-on: ubuntu-latest

runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
flag: linux
- os: macos-latest
flag: macos

steps:
- uses: actions/checkout@v4
with:
submodules: recursive


# ncc emits x86-64 machine code; on arm64 macOS runners the test binaries run under Rosetta.
- name: Install Rosetta
if: matrix.os == 'macos-latest'
run: softwareupdate --install-rosetta --agree-to-license

- name: Cache cargo and build
uses: actions/cache@v4
with:
Expand All @@ -25,18 +38,17 @@ jobs:
~/.cargo/git
~/.cargo/bin
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
key: ${{ runner.os }}-cargo-coverage-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-coverage-

- uses: dtolnay/rust-toolchain@stable
with:
components: llvm-tools-preview

# Generate code coverage with llvm-cov

- name: Install cargo-llvm-cov
run: if ! command -v cargo-llvm-cov >/dev/null; then cargo install cargo-llvm-cov; fi
uses: taiki-e/install-action@cargo-llvm-cov

- name: Run tests with coverage
working-directory: ${{ github.workspace }}
run: cargo llvm-cov --ignore-filename-regex pretty.rs --lcov --output-path lcov.info --workspace --all-features --no-fail-fast
Expand All @@ -46,5 +58,6 @@ jobs:
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./lcov.info
flags: ${{ matrix.flag }}
verbose: true
slug: johnhringiv/NCC-Rust
7 changes: 4 additions & 3 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Cache cargo
- name: Cache cargo and build
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
~/.cargo/bin
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
target
key: ${{ runner.os }}-cargo-lint-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
${{ runner.os }}-cargo-lint-

- uses: dtolnay/rust-toolchain@stable
with:
Expand Down
167 changes: 167 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Working Principles

**This is a hobby/learning project.** The user wants to implement features themselves—do not implement core compiler logic or new features unless explicitly requested.

**What to do:**
- Answer questions about C and Rust related to features the user is working on
- Proactively suggest more performant or idiomatic Rust code when reviewing changes
- Suggest related features or improvements (e.g., new warnings, edge cases, test coverage) as the user works—but don't implement them
- Implement test cases (in `tests/` only, ensure they add value and don't overlap with existing tests)
- Make simple updates, write documentation, and implement pretty printing
- Confirm existing documentation (README.md, CLAUDE.md, comments) stays in sync with code changes
- When the user asks about a specific part of the codebase, focus on that part and ignore surrounding compilation errors (feature additions often break things temporarily)

**What NOT to do:**
- Do not implement core compiler logic (lexer, parser, validator, tackifier, codegen, emitter logic)
- Do not add new language features or compiler passes
- Push back if a task involves writing substantial feature logic—the user wants to learn by doing it themselves

**Test Case Guidelines:**
- User's custom tests: `tests/c_programs/` (with `tests/c_programs/expected_results.json`)
- Sandler's book tests: `writing-a-c-compiler-tests/tests/`
- **Always add new tests to `tests/c_programs/`**, never to the book's test directory
- New tests should add value and not overlap with existing tests in either location
- Follow the directory structure: `invalid_lex/`, `invalid_parse/`, `invalid_semantics/` for error tests

## Build & Development Commands

### Building
```bash
cargo build --release # Production build
cargo build # Debug build
```

### Testing
```bash
cargo test # Run all tests
cargo test test_custom_programs # Run only custom test suite
cargo test test_all_sandler # Run Sandler test suite
cargo test -- --nocapture # Show test output
```

The test runner (`tests/runner.rs`) compiles and executes C programs, comparing exit codes and stdout. Tests are auto-discovered from:
- `writing-a-c-compiler-tests/tests/chapter_*/` (Sandler's test suite)
- `tests/c_programs/` (custom tests)

Test classification by directory:
- `invalid_lex/` → expects exit code 10 (lexer error)
- `invalid_parse/` → expects exit code 20 (parser error)
- `invalid_semantics/` → expects exit code 30 (validation error)
- All others → expects successful compilation + runtime return code from `expected_results.json`

Library tests (`*_client.c` files) run cross-compilation tests to validate ABI compliance by linking ncc-compiled code with gcc-compiled code in both directions.

### Code Quality
```bash
make quality # Run all checks (fmt, sort, clippy, test, machete)
make fix # Auto-fix formatting and dependency order
make clippy # Run clippy with warnings as errors
```

### Running NCC
```bash
# Compile and run
cargo run -- examples/program.c --run

# Debug compiler passes
cargo run -- file.c --lex # Tokenize only
cargo run -- file.c --parse # Parse to AST
cargo run -- file.c --validate # Semantic analysis
cargo run -- file.c --tacky # Emit TACKY IR
cargo run -- file.c --codegen # Generate assembly AST
cargo run -- file.c -S # Emit x86-64 assembly

# Compilation options
cargo run -- file.c -c # Emit object file only
cargo run -- file.c -o binary # Custom output name
cargo run -- file.c --static # Static linking (Linux only)
cargo run -- file.c --external-linker # Use system ld instead of libwild
cargo run -- file.c --no-iced # Use deprecated text-based assembler
```

## Compiler Architecture

NCC is a multi-pass C compiler that generates x86-64 machine code. The pipeline:

```
Source .c → Lexer → Parser → Validator → Tackifier → Codegen → Emitter → Linker → Executable
tokens AST typed AST TACKY IR asm AST object binary
```

### Core Passes (src/)

**Lexer** (`lexer.rs`): Tokenizes source using regex patterns with maximal munch. Each token carries a `Span` (file, line, column) for error reporting. Exit code 10 on error.

**Parser** (`parser.rs`): Recursive descent parser with precedence climbing. Builds an abstract AST representing C syntax. No semantic analysis yet—identifiers are just strings, types are not checked. Exit code 20 on error.

**Validator** (`validate.rs`): Two-pass semantic analysis:
1. **Resolution pass**: Renames variables to unique identifiers, labels loops/switches for break/continue, validates goto targets
2. **Type checking pass**: Builds symbol table, checks types, evaluates constant expressions (for static initializers and case labels)

Both passes emit developer-friendly warnings; see the README's "Compile-Time Warnings" section for the catalog. **Warning conventions**: each `-W` warning is emitted through a single `warn_*` helper (so its wording/format lives in one place), and any function that emits one says "emits `-W…`" in its doc comment (keeps `grep -i emit` an accurate audit).

Returns `(NameGenerator, SymbolTable)` needed by subsequent passes. Exit code 30 on error.

**Tackifier** (`tacky.rs`): Converts typed AST to TACKY (three-address code IR). Flattens nested expressions into sequences of simple operations. Makes control flow explicit with jumps/labels. Pseudo-registers used instead of x86 registers.

**Codegen** (`codegen.rs`): Lowers TACKY to x86-64 assembly AST. Assigns pseudo-registers to stack slots, fixes invalid instruction operands (x86 restrictions), implements System V AMD64 calling convention (arguments in RDI, RSI, RDX, RCX, R8, R9, then stack).

**Emitter** (`emit_iced.rs`): Primary emitter using [iced-x86](https://github.com/icedland/iced) to encode instructions to machine code and [object](https://github.com/gimli-rs/object) crate to write ELF (Linux) or Mach-O (macOS) object files. No external assembler needed.

Alternative: `emit.rs` (deprecated `--no-iced` flag) generates text assembly for `as`.

**Linker** (`main.rs`): On Linux, uses [wild](https://github.com/wild-linker/wild) for in-process linking. On macOS, shells out to system `ld`. Locates CRT files and libc via the `cc` compiler.

### Key Data Structures

**AST Evolution**:
- Parser AST: Untyped, identifiers are strings
- Validator AST: Adds type information (`TypedExpression`), renames identifiers uniquely
- TACKY IR: Flattened three-address code with explicit control flow
- Assembly AST: x86-64 instructions with pseudo-registers
- Machine code: Final encoded bytes

**Symbol Table**: Maps identifiers to their type, storage class, and initial value. Built during validation, used by tackifier.

**NameGenerator**: Produces unique names for temporaries, labels, and renamed variables. Threaded through validation and tackification.

### Pretty Printing

The `pretty.rs` module provides tree-view debug output via the `ItfDisplay` trait. Use `--parse`, `--tacky`, or `--codegen` flags to visualize intermediate representations.

## Platform Support

- **Linux**: Full support with libwild linker and static linking
- **macOS**: Intel and Apple Silicon (arm64), requires system `ld` linker. NCC emits x86-64, so on
Apple Silicon the external assembler/linker are invoked with `-arch x86_64` and binaries run under Rosetta 2
- **Windows**: Not supported (WSL works)

## Testing Strategy

Tests validate both successful compilation and error handling:
- Valid programs check exit codes and stdout
- Invalid programs verify correct error detection with proper exit codes
- Library tests validate ABI compliance via cross-compilation
- Assembly output tests (`test_label_printing_with_iced`, `test_data_symbol_resolution_with_iced`) verify correct label generation and symbol resolution
- Warning tests ensure diagnostics are emitted correctly

## Language Implementation Notes

**Type System**: Currently supports `int` (32-bit) and `long` (64-bit). Type conversions follow two's complement truncation.

**Integer Arithmetic**: Deterministic wrapping behavior (non-standard C extension). Shift amounts are masked to prevent undefined behavior.

**Evaluation Order**: Left-to-right (non-standard, eliminates UB).

**Constant Expressions**: Evaluated at compile time using the same rules as runtime expressions. Used for static initializers and case labels.

**Storage Classes**:
- `static` → internal linkage (file-local)
- `extern` → external linkage (visible to other files)
- No specifier → functions default to extern, variables default to auto (local) or tentative (global)

**ABI Compliance**: Implements System V AMD64 calling convention. Validated by linking ncc-compiled code with gcc-compiled code.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ name = "ncc"
version = "0.1.0"
edition = "2024"

# All tests live in tests/ (integration). The binary has no unit tests, so skip its
# (empty) test harness to avoid a redundant "running 0 tests" summary under `cargo test`.
[[bin]]
name = "ncc"
path = "src/main.rs"
test = false

[dependencies]
clap = { version = "4.5.39", features = ["derive"] }
colored = "3.0.0"
Expand All @@ -13,4 +20,5 @@ regex = "1.11.1"

[dev-dependencies]
glob = "0.3.2"
rayon = "1.10"
serde_json = "1.0"
50 changes: 39 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ A (**N**ot **C**ompletely) **C** compiler written in Rust, inspired by Sandler's
NCC is a full pipeline compiler, going from lexing all the way down to x86-64 machine code emission and linking.
Machine code is encoded directly using [iced-x86](https://github.com/icedland/iced) and emitted to ELF/Mach-O
object files via the [object](https://github.com/gimli-rs/object) crate—no external assembler required.
A substantial subset of C is supported, including functions, static variables, all control flow statements, and
bitwise operations. Additionally, NCC supports developer-friendly warnings and pretty-printing of each compiler pass.
Runs on Linux and macOS (Intel).
A substantial subset of C is supported, including `int` and `long` types, functions, static variables, all control
flow statements, and bitwise operations. Additionally, NCC supports developer-friendly warnings and pretty-printing
of each compiler pass.
Runs on Linux and macOS.

## Example

Expand Down Expand Up @@ -211,8 +212,9 @@ The compiler currently implements a subset of C with the following grammar:
<declaration> ::= <variable-declaration> | <function-declaration>
<variable-declaration> ::= { <specifier> }+ <identifier> [ "=" <exp> ] ";"
<function-declaration> ::= { <specifier> }+ <identifier> "(" <param-list> ")" ( <block> | ";" )
<param-list> ::= "void" | "int" <identifier> { "," "int" <identifier> }
<specifier> ::= "int" | "static" | "extern"
<param-list> ::= "void" | <type> <identifier> { "," <type> <identifier> }
<type> ::= "int" | "long"
<specifier> ::= <type> | "static" | "extern"
<block> ::= "{" { <block-item> } "}"
<block-item> ::= <statement> | <declaration>
<for-init> ::= <variable-declaration> | [ <exp> ] ";"
Expand All @@ -233,15 +235,17 @@ The compiler currently implements a subset of C with the following grammar:
| ";"
<exp> ::= <factor> | <exp> <binop> <exp> | <exp> <assign-op> <exp>
| <exp> "?" <exp> ":" <exp> | <exp> "++" | <exp> "--"
<factor> ::= <int> | <identifier> | <unop> <factor> | "++" <factor> | "--" <factor> | "(" <exp> ")"
<factor> ::= <int> | <long> | <identifier> | <unop> <factor> | "++" <factor> | "--" <factor>
| "(" <type> ")" <factor> | "(" <exp> ")"
| <identifier> "(" [ <argument-list> ] ")"
<argument-list> ::= <exp> { "," <exp> }
<unop> ::= "-" | "~" | "!"
<binop> ::= "-" | "+" | "*" | "/" | "%" | "&" | "|" | "^" | "<<" | ">>" | "&&" | "||"
| "==" | "!=" | "<" | "<=" | ">" | ">="
<assign-op> ::= "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>="
<identifier> ::= ? An identifier token ?
<int> ::= ? A constant token ?
<int> ::= ? An integer constant token ?
<long> ::= ? A long integer constant token (suffix 'l' or 'L') ?
```

### Supported Features
Expand All @@ -257,6 +261,7 @@ The compiler supports:
functions
- **Compound statements (blocks)**: `{ ... }` with proper scoping
- **Variable scoping**: Block-local variables with shadowing support
- **Type system**: `int` (32-bit) and `long` (64-bit) with implicit conversions and explicit casts
- **Integer arithmetic**: addition, subtraction, multiplication, division, modulo
- **Bitwise operations**: AND (`&`), OR (`|`), XOR (`^`), complement (`~`), left/right shift (`<<`, `>>`)
- **Logical operations**: AND (`&&`), OR (`||`), NOT (`!`) with short-circuit evaluation
Expand All @@ -282,19 +287,42 @@ NCC provides several safety features and guarantees to help developers write mor

#### Guaranteed Behaviors

- **Deterministic integer overflow**: Integer arithmetic uses two's complement wrapping (32-bit). For example,
`INT_MAX + 1` reliably wraps to `INT_MIN`.
- **Deterministic integer overflow**: Integer arithmetic uses two's complement wrapping (`int`: 32-bit, `long`: 64-bit).
For example, `INT_MAX + 1` reliably wraps to `INT_MIN`.
- **Left-to-right evaluation**: Binary operations are evaluated left to right, eliminating undefined behavior from
evaluation order.
- **Type conversions**: Converting `long` to `int` truncates to the lower 32 bits using two's complement representation,
equivalent to repeatedly subtracting 2^32 until the value fits in an `int` range.
For example, `2147483650L` (INT_MAX + 3) converts to `-2147483646`.
- **Shift masking**: Left and right shifts mask the shift amount to prevent undefined behavior. For `int` types,
the shift amount is masked with `& 31` (modulo 32); for `long` types, masked with `& 63` (modulo 64).
For example, `1 << 32` evaluates to `1 << 0 = 1`, matching x86 hardware behavior.
- **Consistent compile-time and runtime behavior**: Constant expressions (static initializers, case labels) follow
the same arithmetic and type conversion rules as runtime expressions, ensuring predictable behavior.

#### Compile-Time Warnings

- **Variable shadowing** (`-Wshadow`): Warns when a variable declaration shadows a previous declaration in an outer
scope
- **Duplicate switch cases** (`-Wswitch-unreachable`): Detects and reports duplicate case values in switch statements,
including those from constant expressions
- **Unreachable switch code** (`-Wswitch-unreachable`): Warns about statements before the first `case` label in a
switch, which can never be executed
- **Unused parameters** (`-Wunused-parameter`): Warns when a function parameter is declared but never used in the
function body
- **Division by zero** (`-Wdiv-by-zero`): Warns when `/` or `%`, including the compound forms `/=` and `%=`, has
a constant zero divisor (e.g. `x / 0`, `x % 0`, `x /= 0`, `x %= 0`). A constant zero divisor in a context that
requires a constant expression (such as a static initializer) is a hard error instead
- **Out-of-range shift count** (`-Wshift-count-overflow`, `-Wshift-count-negative`): Warns when a `<<` or `>>`
(including `<<=` / `>>=`) has a constant shift count that is negative or `>=` the width of the left operand's type
(32 for `int`, 64 for `long`), e.g. `1 << 32` or `1 << -1`
- **Integer overflow in a constant expression** (`-Woverflow`): Warns when folding a constant expression in a static
initializer or case label leaves the result type (e.g. `int x = 2147483647 + 1;`). NCC wraps deterministically
(two's complement) rather than treating it as undefined, so this flags non-portable code instead of erroring
- **Constant changed by an implicit conversion** (`-Wconstant-conversion`): Warns when a constant initializer is
implicitly narrowed to a type that can't hold it (e.g. `int x = 2147483648;`, which truncates to `-2147483648`).
An explicit cast (`int x = (int)2147483648;`) silences it
- **Unsequenced modification** (`-Wsequence-point`): Warns when the same object is modified more than once between
sequence points (e.g. `i = i++`, `i++ + i++`, `f(i++, i++)`) — undefined in standard C. NCC evaluates left-to-right
so the result is well-defined, but the code is non-portable

#### Developer Experience

Expand Down
Loading
Loading