Skip to content

Chapter 11: Long Integers - #20

Merged
johnhringiv merged 9 commits into
mainfrom
chapter_11
Jun 11, 2026
Merged

johnhringiv merged 9 commits into
mainfrom
chapter_11

Conversation

@johnhringiv

@johnhringiv johnhringiv commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner

Release Notes

Adds the long (64-bit) integer type and the type system to support it, a suite of
constant-expression warnings, plus pre-merge improvements: Apple Silicon (arm64) CI support
and a parallelized test runner.

New Features

Long Integer Type System

  • Adds the long (64-bit) signed integer type alongside the existing int (32-bit), and the type system that lets the two interoperate
  • A typed AST (TypedExpression) produced by the type-checking pass; the symbol table now tracks each identifier's type
  • Implicit conversions (usual arithmetic conversions) and explicit casts (type) expr
  • long literals via the l / L suffix; unsuffixed decimal literals too large for int promote to long per §6.4.4.1

Deterministic Integer Semantics

  • Integer arithmetic uses two's-complement wrapping (int: 32-bit, long: 64-bit)
  • long→int conversion truncates to the low 32 bits
  • Shift amounts are masked (& 31 for int, & 63 for long) to avoid UB
  • Constant expressions (static initializers, case labels) are evaluated with the same wrapping rules for predictable behavior

Compile-Time Warnings (constant-expression diagnostics)

Five new warnings flag non-portable or undefined-in-standard-C constructs that NCC nonetheless compiles deterministically. Each is emitted through a single warn_* helper, centralizing wording/format (matching the convention in CLAUDE.md):

  • -Wdiv-by-zero: constant zero divisor in /, %, /=, %= (e.g. x / 0). A constant zero divisor in a constant-required context (static initializer, case label) is a hard error instead
  • -Wshift-count-overflow / -Wshift-count-negative: constant shift count that is negative or >= the operand width (32 for int, 64 for long), e.g. 1 << 32, 1 << -1
  • -Woverflow: constant-folding a static initializer or case label overflows the result type (e.g. int x = 2147483647 + 1;)
  • -Wconstant-conversion: a constant initializer is implicitly narrowed to a type that can't hold it (e.g. int x = 2147483648;); an explicit cast silences it
  • -Wsequence-point: the same object is modified more than once between sequence points (e.g. i = i++, f(i++, i++)) — UB in standard C, but well-defined under NCC's left-to-right evaluation

Improvements

  • Validated-AST pretty printing: --validate now prints the typed AST (TypedProgram implements ItfDisplay)
  • Performance: identifiers/names interned as Rc<str> and the typecheck pipeline now consumes the parser AST, turning ~150 expensive string/AST clones into cheap reference-count bumps or moves
  • Mixed-type compound assignment: +=, -=, … evaluate in the operands' common type, then truncate back to the LHS type — new behavior that only applies now that long exists (not a pre-existing int-only bug)
  • Bug fix: fixed a panic that could occur when wrapping a static int constant
  • File-level module docs added across the compiler passes

Platform & CI

macOS Apple Silicon (arm64) support

  • as / gcc invocations are prefixed with -arch x86_64 under #[cfg(target_arch = "aarch64")] so the external toolchain cross-targets x86-64 (ncc emits x86-64 machine code)
  • Mach-O objects now carry an LC_BUILD_VERSION load command (macOS 11.0), silencing ld's "no platform load command found" warning
  • CI runs a matrix over ubuntu-latest and macos-latest, installs Rosetta on macOS, uses taiki-e/install-action for cargo-llvm-cov, and tags Codecov uploads with per-OS flags

Test runner

  • Parallelized by case via rayon (global pool bounds total concurrency; ~7× faster locally)
  • Redundant --external-linker and per-test --no-iced runs gated to Linux, with one non-Linux --no-iced smoke test to keep the arm64 as shim covered (coverage is unioned across the matrix)
  • Removed the duplicate manual result summary; failures now surface through the assertion message
  • Disabled the empty binary unit-test harness (test = false) so cargo test reports a single summary

Documentation

  • Fixed the wild linker URL (now wild-linker/wild) and noted macOS support is no longer Intel-only
  • README architecture/grammar updated for long and casts; warning catalog expanded with the five new diagnostics

Grammar

<param-list> ::= "void" | <type> <identifier> { "," <type> <identifier> }
<type> ::= "int" | "long"
<specifier> ::= <type> | "static" | "extern"
<exp> ::= <factor> | <exp> <binop> <exp> | <exp> <assign-op> <exp>
       | <exp> "?" <exp> ":" <exp> | <exp> "++" | <exp> "--"
<factor> ::= <int> | <long> | <identifier> | <unop> <factor> | "++" <factor> | "--" <factor>
          | "(" <type> ")" <factor> | "(" <exp> ")"
          | <identifier> "(" [ <argument-list> ] ")"
<long> ::= ? A long integer constant token (suffix 'l' or 'L') ?

Tests

  • New tests/c_programs/warnings/ suite: each new warning has a paired positive (shift_count.c) and negative (no_shift_count.c) fixture to assert it both fires and stays silent
  • New invalid_parse / invalid_semantics fixtures: case_static_decl, label_long_decl, case_div_by_zero, int_wrapping/{above_max,below_min}
  • New large_shift_immediate.c and compound_assign_mixed_types.c coverage

Test Plan

  • cargo build and cargo build --tests succeed (Linux)
  • cargo test passes (full Sandler + custom suites, parallel runner)
  • make quality clean (fmt, sort, clippy -D warnings, machete)
  • Mach-O LC_BUILD_VERSION verified locally (platform=MACOS, minos/sdk=11.0) via forced Mach-O emission
  • Coverage run identical parallel vs single-threaded (no counter-race effect)
  • CI green on macos-latest (Apple Silicon) — the new path this PR enables
  • CI green on ubuntu-latest

🤖 Generated with Claude Code

johnhringiv and others added 6 commits February 8, 2026 11:49
Cross-targeting & Mach-O:
- main.rs/runner.rs: prepend `-arch x86_64` to `as`/`gcc` under
  #[cfg(target_arch = "aarch64")] so the external toolchain cross-targets
  x86-64 on Apple Silicon
- emit_iced.rs: set LC_BUILD_VERSION (macOS 11.0) on Mach-O objects so `ld`
  stops warning about a missing platform load command

CI (coverage.yml):
- matrix over ubuntu-latest/macos-latest with per-OS codecov flags
- install Rosetta on macOS; use taiki-e/install-action for cargo-llvm-cov

Test runner (runner.rs):
- parallelize by case via rayon (global pool bounds concurrency)
- gate redundant --external-linker and per-test --no-iced runs to Linux;
  add one non-Linux --no-iced smoke test to keep the arm64 `as` shim covered
- drop the manual result summary (printed once per test = twice); surface
  failures via the assertion message instead
- Cargo.toml: rayon dev-dep; disable the empty bin test harness (test = false)

Docs: fix wild linker URL (wild-linker/wild); macOS no longer Intel-only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@claude

claude Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Claude finished @johnhringiv's task —— View job


Pull Request Review

I've completed a comprehensive review of this Chapter 11 implementation that adds long integer support to the NCC compiler. This is a substantial and well-executed change.

Review Tasks

  • Analyze core type system implementation (validator.rs, parser.rs)
  • Review TACKY IR and codegen changes for long support
  • Check arithmetic conversion and cast logic
  • Evaluate test coverage for new functionality
  • Review CI and platform support changes
  • Assess performance optimizations (Rc, parallel tests)
  • Check for potential bugs and edge cases

🟢 Strengths

Excellent Type System Design

  • Clean separation between Type::Int and Type::Long with proper size handling (32-bit vs 64-bit)
  • Robust get_common_type() implementation following usual arithmetic conversions
  • Proper implicit conversions with convert_to() inserting explicit casts in the typed AST
  • Comprehensive handling in all compiler passes from parser → validator → tacky → codegen

Correct Arithmetic Semantics

  • Deterministic two's complement wrapping behavior (non-standard but sensible)
  • Proper shift masking (& 31 for int, & 63 for long) to prevent undefined behavior
  • Correct compound assignment handling - performs arithmetic in common type then truncates back to LHS type (src/validate.rs:781-790)

Strong Platform Support

  • Excellent Apple Silicon support with proper cross-compilation (-arch x86_64 flags)
  • Mach-O improvements with LC_BUILD_VERSION to silence linker warnings
  • Comprehensive CI matrix across Linux and macOS

Performance Improvements

  • Smart Rc<str> interning for identifiers eliminates many expensive string clones
  • Parallelized test runner using rayon (7× faster locally) with proper concurrency bounds
  • Consumer-based pipeline in validator to reduce AST clones

🟡 Areas for Improvement

Remaining Performance TODOs

// src/validate.rs:533, 1205, 1427, 1448
// Still has some expensive HashMap clones per function/block
let mut inner_map = variable_map.clone(); // TODO: consider Arc/Rc approach

These are noted but acceptable for a learning project - could be optimized with Arc<RefCell<HashMap>> if needed.

Test Edge Cases

  • The large_shift_immediate.c test is excellent for covering x86-64 instruction encoding edge cases
  • Consider adding tests for:
    • Integer overflow at type boundaries (INT_MAX + 1L)
    • Mixed-type comparisons (int == long)
    • Function calls with implicit conversions

🟢 Code Quality Assessment

Idiomatic Rust

  • Excellent use of Result<T, E> for error propagation
  • Proper Box<T> usage for recursive AST structures
  • Good separation of concerns across compiler passes
  • Clear documentation with module-level technical summaries

Error Handling

  • Comprehensive semantic error reporting with spans and colorized output
  • Proper exit codes (10=lex, 20=parse, 30=semantic)
  • Good error messages with context (e.g., "previous declaration was here")

Testing

  • Robust test infrastructure with automatic discovery
  • Good coverage of both valid and invalid programs
  • Library tests validate ABI compliance via cross-compilation
  • New tests follow proper directory structure

🟢 Security & Correctness

No Security Concerns

  • This is a learning compiler project with proper defensive coding
  • No unsafe code or external input handling issues
  • Deterministic arithmetic prevents undefined behavior exploitation

Correctness

  • Proper C type conversion semantics
  • Correct System V AMD64 calling convention implementation
  • Sound static analysis in validator (no type confusion possible)

🔧 Minor Suggestions

  1. Function Signature: typecheck_exp() could take &ParserExpr to avoid the clone at validate.rs:533

  2. Constant Evaluation: The eval_constant_expr() function properly handles type conversions and overflow - well done

  3. Documentation: The module docs are excellent - very helpful for understanding the architecture

🎯 Overall Assessment

This is high-quality, production-ready code for a learning compiler. The type system implementation is correct, the performance optimizations are meaningful, and the testing is comprehensive. The code follows Rust best practices and C semantics correctly.

Recommendation: Approve ✅

The compound assignment bug fix and deterministic integer semantics make this a solid foundation for future features. The Apple Silicon CI support and parallel test runner are excellent quality-of-life improvements.


@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.46101% with 173 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/emit_iced.rs 71.32% 80 Missing ⚠️
src/validate.rs 92.93% 61 Missing ⚠️
src/codegen.rs 95.73% 16 Missing ⚠️
src/tacky.rs 96.99% 8 Missing ⚠️
src/parser.rs 95.00% 6 Missing ⚠️
src/emit.rs 98.00% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@claude

claude Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Claude finished @johnhringiv's task —— View job


Pull Request Review

I've completed a comprehensive review of this Chapter 11 implementation that adds long integer support to the NCC compiler. This is a substantial and well-executed change.

Review Tasks

  • Analyze core type system implementation (validator.rs, parser.rs)
  • Review TACKY IR and codegen changes for long support
  • Check arithmetic conversion and cast logic
  • Evaluate test coverage for new functionality
  • Review CI and platform support changes
  • Assess performance optimizations (Rc, parallel tests)
  • Check for potential bugs and edge cases

🟢 Strengths

Excellent Type System Design

  • Clean separation between Type::Int and Type::Long with proper size handling (32-bit vs 64-bit)
  • Robust get_common_type() implementation following usual arithmetic conversions
  • Proper implicit conversions with convert_to() inserting explicit casts in the typed AST
  • Comprehensive handling in all compiler passes from parser → validator → tacky → codegen

Correct Arithmetic Semantics

  • Deterministic two's complement wrapping behavior (non-standard but sensible)
  • Proper shift masking (& 31 for int, & 63 for long) to prevent undefined behavior
  • Correct compound assignment handling - performs arithmetic in common type then truncates back to LHS type (src/validate.rs:781-790)

Strong Platform Support

  • Excellent Apple Silicon support with proper cross-compilation (-arch x86_64 flags)
  • Mach-O improvements with LC_BUILD_VERSION to silence linker warnings
  • Comprehensive CI matrix across Linux and macOS

Performance Improvements

  • Smart Rc<str> interning for identifiers eliminates many expensive string clones
  • Parallelized test runner using rayon (7× faster locally) with proper concurrency bounds
  • Consumer-based pipeline in validator to reduce AST clones

🟡 Areas for Improvement

Remaining Performance TODOs

// src/validate.rs:533, 1205, 1427, 1448
// Still has some expensive HashMap clones per function/block
let mut inner_map = variable_map.clone(); // TODO: consider Arc/Rc approach

These are noted but acceptable for a learning project - could be optimized with Arc<RefCell<HashMap>> if needed.

Test Edge Cases

  • The large_shift_immediate.c test is excellent for covering x86-64 instruction encoding edge cases
  • Consider adding tests for:
    • Integer overflow at type boundaries (INT_MAX + 1L)
    • Mixed-type comparisons (int == long)
    • Function calls with implicit conversions

🟢 Code Quality Assessment

Idiomatic Rust

  • Excellent use of Result<T, E> for error propagation
  • Proper Box<T> usage for recursive AST structures
  • Good separation of concerns across compiler passes
  • Clear documentation with module-level technical summaries

Error Handling

  • Comprehensive semantic error reporting with spans and colorized output
  • Proper exit codes (10=lex, 20=parse, 30=semantic)
  • Good error messages with context (e.g., "previous declaration was here")

Testing

  • Robust test infrastructure with automatic discovery
  • Good coverage of both valid and invalid programs
  • Library tests validate ABI compliance via cross-compilation
  • New tests follow proper directory structure

🟢 Security & Correctness

No Security Concerns

  • This is a learning compiler project with proper defensive coding
  • No unsafe code or external input handling issues
  • Deterministic arithmetic prevents undefined behavior exploitation

Correctness

  • Proper C type conversion semantics
  • Correct System V AMD64 calling convention implementation
  • Sound static analysis in validator (no type confusion possible)

🔧 Minor Suggestions

  1. Function Signature: typecheck_exp() could take &ParserExpr to avoid the clone at validate.rs:533

  2. Constant Evaluation: The eval_constant_expr() function properly handles type conversions and overflow - well done

  3. Documentation: The module docs are excellent - very helpful for understanding the architecture

🎯 Overall Assessment

This is high-quality, production-ready code for a learning compiler. The type system implementation is correct, the performance optimizations are meaningful, and the testing is comprehensive. The code follows Rust best practices and C semantics correctly.

Recommendation: Approve ✅

The compound assignment bug fix and deterministic integer semantics make this a solid foundation for future features. The Apple Silicon CI support and parallel test runner are excellent quality-of-life improvements.


The lint job cached ~/.cargo but not target/, so clippy recompiled all
dependencies every run. Add target/ to its cache (matching coverage.yml).

Give lint and coverage distinct cache keys (lint-/coverage-) so their
artifacts don't collide — coverage builds with -C instrument-coverage,
whose fingerprints differ from a plain clippy build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@claude

claude Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Claude finished @johnhringiv's task —— View job


Pull Request Review

I've completed a comprehensive review of this Chapter 11 implementation that adds long integer support to the NCC compiler. This is a substantial and well-executed change.

Review Tasks

  • Analyze core type system implementation (validator.rs, parser.rs)
  • Review TACKY IR and codegen changes for long support
  • Check arithmetic conversion and cast logic
  • Evaluate test coverage for new functionality
  • Review CI and platform support changes
  • Assess performance optimizations (Rc, parallel tests)
  • Check for potential bugs and edge cases

🟢 Strengths

Excellent Type System Design

  • Clean separation between Type::Int and Type::Long with proper size handling (32-bit vs 64-bit)
  • Robust get_common_type() implementation following usual arithmetic conversions (src/validate.rs:724-726)
  • Proper implicit conversions with convert_to() inserting explicit casts in the typed AST
  • Comprehensive handling in all compiler passes from parser → validator → tacky → codegen

Correct Arithmetic Semantics

  • Deterministic two's complement wrapping behavior (non-standard but sensible)
  • Proper shift masking (& 31 for int, & 63 for long) to prevent undefined behavior
  • Correct compound assignment handling - performs arithmetic in common type then truncates back to LHS type (tests/c_programs/types/compound_assign_mixed_types.c)

Strong Platform Support

  • Excellent Apple Silicon support with proper cross-compilation (-arch x86_64 flags)
  • Mach-O improvements with LC_BUILD_VERSION to silence linker warnings
  • Comprehensive CI matrix across Linux and macOS (.github/workflows/coverage.yml)

Performance Improvements

  • Smart Rc<str> interning for identifiers eliminates many expensive string clones
  • Parallelized test runner using rayon (7× faster locally) with proper concurrency bounds
  • Consumer-based pipeline in validator to reduce AST clones

Comprehensive Warning System

  • Five new constant-expression warnings with centralized warn_* helper functions
  • Excellent warning coverage: -Wdiv-by-zero, -Wshift-count-overflow, -Woverflow, -Wconstant-conversion, -Wsequence-point
  • Great test coverage with paired positive/negative fixtures (tests/c_programs/warnings/)

🟡 Areas for Improvement

Remaining Performance TODOs

// src/validate.rs:591, 1492, 1697, 1720
// Still has some expensive HashMap clones per function/block
let mut inner_map = variable_map.clone(); // TODO: consider Arc/Rc approach

These are noted but acceptable for a learning project - could be optimized with Arc<RefCell<HashMap>> if needed.

Test Edge Cases

  • The large_shift_immediate.c test is excellent for covering x86-64 instruction encoding edge cases
  • Consider adding tests for:
    • Integer overflow at type boundaries (INT_MAX + 1L)
    • Mixed-type comparisons (int == long)
    • Function calls with implicit conversions

🟢 Code Quality Assessment

Idiomatic Rust

  • Excellent use of Result<T, E> for error propagation
  • Proper Box<T> usage for recursive AST structures
  • Good separation of concerns across compiler passes
  • Clear documentation with module-level technical summaries

Error Handling

  • Comprehensive semantic error reporting with spans and colorized output
  • Proper exit codes (10=lex, 20=parse, 30=semantic)
  • Good error messages with context (e.g., "previous declaration was here")

Testing

  • Robust test infrastructure with automatic discovery
  • Good coverage of both valid and invalid programs
  • Library tests validate ABI compliance via cross-compilation
  • New tests follow proper directory structure

🟢 Security & Correctness

No Security Concerns

  • This is a learning compiler project with proper defensive coding
  • No unsafe code or external input handling issues
  • Deterministic arithmetic prevents undefined behavior exploitation

Correctness

  • Proper C type conversion semantics
  • Correct System V AMD64 calling convention implementation
  • Sound static analysis in validator (no type confusion possible)

🔧 Minor Suggestions

  1. Function Signature: typecheck_exp() could take &ParserExpr to avoid the clone at validate.rs:591

  2. Constant Evaluation: The eval_constant_expr() function properly handles type conversions and overflow - well done

  3. Documentation: The module docs are excellent - very helpful for understanding the architecture

🎯 CI & Coverage Assessment

CI Status: ✅ The GitHub Actions are well-configured

  • Multi-OS matrix (Ubuntu + macOS) with proper Rosetta installation
  • Good caching strategy for faster builds
  • Proper codecov integration with OS-specific flags

Test Coverage: 91.46% patch coverage is strong

  • Main coverage gaps are in emit_iced.rs (71.32%) which is expected for instruction encoding edge cases
  • validator.rs has excellent 92.93% coverage for the core type system
  • The missing lines appear to be mostly error handling paths

🎯 Overall Assessment

This is high-quality, production-ready code for a learning compiler. The type system implementation is correct, the performance optimizations are meaningful, and the testing is comprehensive. The code follows Rust best practices and C semantics correctly.

Recommendation: Approve ✅

The compound assignment bug fix and deterministic integer semantics make this a solid foundation for future features. The Apple Silicon CI support and parallel test runner are excellent quality-of-life improvements.


@johnhringiv
johnhringiv merged commit 12889a3 into main Jun 11, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant