diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 231924d..e340c2f 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -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: @@ -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 @@ -46,5 +58,6 @@ jobs: with: token: ${{ secrets.CODECOV_TOKEN }} files: ./lcov.info + flags: ${{ matrix.flag }} verbose: true slug: johnhringiv/NCC-Rust \ No newline at end of file diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index e602c01..3d8d551 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -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: diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..3be0b80 --- /dev/null +++ b/CLAUDE.md @@ -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. diff --git a/Cargo.lock b/Cargo.lock index e46a5cc..19c330f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -731,6 +731,7 @@ dependencies = [ "iced-x86", "libwild", "object 0.38.0", + "rayon", "regex", "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index ab966a9..2966860 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" @@ -13,4 +20,5 @@ regex = "1.11.1" [dev-dependencies] glob = "0.3.2" +rayon = "1.10" serde_json = "1.0" diff --git a/README.md b/README.md index ec5596b..6e11243 100644 --- a/README.md +++ b/README.md @@ -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 @@ -211,8 +212,9 @@ The compiler currently implements a subset of C with the following grammar: ::= | ::= { }+ [ "=" ] ";" ::= { }+ "(" ")" ( | ";" ) - ::= "void" | "int" { "," "int" } - ::= "int" | "static" | "extern" + ::= "void" | { "," } + ::= "int" | "long" + ::= | "static" | "extern" ::= "{" { } "}" ::= | ::= | [ ] ";" @@ -233,7 +235,8 @@ The compiler currently implements a subset of C with the following grammar: | ";" ::= | | | "?" ":" | "++" | "--" - ::= | | | "++" | "--" | "(" ")" + ::= | | | | "++" | "--" + | "(" ")" | "(" ")" | "(" [ ] ")" ::= { "," } ::= "-" | "~" | "!" @@ -241,7 +244,8 @@ The compiler currently implements a subset of C with the following grammar: | "==" | "!=" | "<" | "<=" | ">" | ">=" ::= "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ::= ? An identifier token ? - ::= ? A constant token ? + ::= ? An integer constant token ? + ::= ? A long integer constant token (suffix 'l' or 'L') ? ``` ### Supported Features @@ -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 @@ -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 diff --git a/src/codegen.rs b/src/codegen.rs index 4764ff3..6d96439 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -1,10 +1,72 @@ +//! # Codegen — TACKY IR to x86-64 Assembly AST +//! +//! Lowers TACKY three-address code into an x86-64 assembly AST through a four-step +//! pipeline, producing valid instruction sequences ready for machine code emission. +//! +//! ## Technical Approach +//! +//! The lowering runs four sequential passes, each refining the representation: +//! +//! 1. **Instruction selection** ([`convert_instruction`]) — pattern-matches each TACKY +//! instruction into one or more assembly instructions using pseudo-registers +//! 2. **Pseudo-register replacement** ([`replace_pseudo_registers`]) — assigns stack +//! slots (negative RBP offsets) to locals, and RIP-relative [`Operand::Data`] +//! references to static/extern variables +//! 3. **Instruction fix-up** ([`fix_invalid`]) — rewrites operand combinations that +//! violate x86-64 encoding rules (e.g. memory-to-memory moves) using scratch +//! registers R10/R11/CX, and inserts the stack allocation prologue +//! 4. **Label coalescing** ([`coalesce_labels`]) — merges consecutive labels to reduce +//! redundant jump targets +//! +//! ## What This Pass Accomplishes +//! +//! - Translates all TACKY operations to concrete x86-64 instructions +//! - Implements the System V AMD64 calling convention: +//! - Arguments 1-6 in RDI, RSI, RDX, RCX, R8, R9; remainder on stack +//! - 16-byte stack alignment before `call` +//! - Return value in RAX +//! - Allocates stack frames: locals grow downward from RBP, 16-byte aligned +//! - Produces a [`Program`] of [`FunctionDefinition`]s and [`StaticVariable`]s +//! - Produces a [`BackendSymbolTable`] mapping names to assembly types +//! +//! ## Call Order +//! +//! ```text +//! generate() — public entry point, orchestrates all 4 passes +//! ├─ build_backend_symbol_table() — map all vars/fns to assembly types +//! ├─ convert_function() — per function: lower params + body +//! │ └─ convert_instruction() — per instruction: TACKY -> assembly +//! │ └─ convert_function_call() — System V ABI argument passing +//! ├─ convert_static_var() — per static variable +//! ├─ replace_pseudo_registers() — assign stack slots / data operands +//! ├─ fix_invalid() — rewrite illegal operand combos, add prologue +//! └─ coalesce_labels() — merge consecutive labels +//! ``` +//! +//! ## Stack Frame Layout +//! +//! ```text +//! ┌──────────────────┐ higher addresses +//! │ 8th+ arg (caller)│ RBP + 24, +32, ... +//! │ 7th arg (caller) │ RBP + 16 +//! │ return address │ RBP + 8 +//! │ saved RBP │ RBP + 0 <── RBP +//! │ local var (int) │ RBP - 4 +//! │ local var (long) │ RBP - 12 +//! │ ... │ ... grows downward +//! │ (16-byte aligned)│ <── RSP +//! └──────────────────┘ lower addresses +//! ``` + use crate::parser; -use crate::parser::Identifier; +use crate::parser::{Const, Identifier, Type}; use crate::tacky; -use crate::tacky::{BinOp, StaticVariable, Val}; +use crate::tacky::{BinOp, StaticVariable as TackyStaticVariable, Val, VarInit}; +use crate::validate::SymbolTable; use std::collections::{HashMap, HashSet}; +use std::rc::Rc; -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum Reg { AX, CX, @@ -15,15 +77,57 @@ pub enum Reg { R9, R10, R11, + SP, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum AssemblyType { + Longword, + Quadword, +} + +impl AssemblyType { + pub fn size(&self) -> u64 { + match self { + AssemblyType::Longword => 4, + AssemblyType::Quadword => 8, + } + } +} + +impl From<&Type> for AssemblyType { + fn from(ty: &Type) -> Self { + match ty { + Type::Int => AssemblyType::Longword, + Type::Long => AssemblyType::Quadword, + Type::FunType { .. } => { + panic!("Cannot convert function type to assembly type") + } + } + } +} + +impl From for AssemblyType { + fn from(ty: Type) -> Self { + AssemblyType::from(&ty) + } +} + +#[derive(Debug)] +pub struct StaticVariable { + pub name: Rc, + pub global: bool, + pub alignment: u64, + pub init: VarInit, } #[derive(Clone, Debug, PartialEq)] pub enum Operand { - Imm(i32), + Imm(i64), Reg(Reg), - Pseudo(String), + Pseudo(Rc), Stack(i32), - Data(String), + Data(Rc), } impl Operand { @@ -32,13 +136,23 @@ impl Operand { } } -#[derive(Clone, Debug, PartialEq)] +impl From<&Val> for Operand { + fn from(val: &Val) -> Self { + match val { + Val::Constant(Const::ConstInt(i)) => Operand::Imm(*i as i64), + Val::Constant(Const::ConstLong(l)) => Operand::Imm(*l), + Val::Var(s) => Operand::Pseudo(s.clone()), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] pub enum UnaryOp { Neg, Not, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum BinaryOp { Add, Sub, @@ -52,24 +166,49 @@ pub enum BinaryOp { #[derive(Clone, Debug, PartialEq)] pub enum Instruction { - Mov { src: Operand, dst: Operand }, - Unary { op: UnaryOp, dst: Operand }, - Binary { op: BinaryOp, src: Operand, dst: Operand }, - Cmp { v1: Operand, v2: Operand }, - Idiv(Operand), - Cdq, + Mov { + src: Operand, + dst: Operand, + size: AssemblyType, + }, + Movsx { + src: Operand, + dst: Operand, + }, + Unary { + op: UnaryOp, + dst: Operand, + size: AssemblyType, + }, + Binary { + op: BinaryOp, + src: Operand, + dst: Operand, + size: AssemblyType, + }, + Cmp { + v1: Operand, + v2: Operand, + size: AssemblyType, + }, + Idiv(Operand, AssemblyType), + Cdq(AssemblyType), Jmp(Identifier), - JmpCC { code: CondCode, label: Identifier }, - SetCC { code: CondCode, op: Operand }, + JmpCC { + code: CondCode, + label: Identifier, + }, + SetCC { + code: CondCode, + op: Operand, + }, Label(Identifier), - AllocateStack(i32), - DeallocateStack(i32), Push(Operand), Call(Identifier), Ret, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum CondCode { E, NE, @@ -94,7 +233,7 @@ impl CondCode { #[derive(Debug)] pub struct FunctionDefinition { - pub name: String, + pub name: Rc, pub body: Vec, pub global: bool, } @@ -105,59 +244,93 @@ pub struct Program { pub static_vars: Vec, } -fn convert_function_call(fun_name: &Identifier, args: &[Val], dst: &Val) -> Vec { +fn get_assembly_type(val: &Val, symbols: &BackendSymbolTable) -> AssemblyType { + match val { + Val::Constant(Const::ConstInt(_)) => AssemblyType::Longword, + Val::Constant(Const::ConstLong(_)) => AssemblyType::Quadword, + Val::Var(name) => match symbols.get(name).expect("Variable should be in backend symbol table") { + AsmSymbolEntry::Obj { asm_type, .. } => *asm_type, + AsmSymbolEntry::Fun { .. } => unreachable!("Cannot use function as value"), + }, + } +} + +/// Emits instructions for a function call following the System V AMD64 ABI. +/// +/// First 6 integer arguments go in registers (RDI, RSI, RDX, RCX, R8, R9). +/// Remaining arguments are pushed onto the stack in reverse order. +/// Stack is padded to maintain 16-byte alignment before the call. +/// The return value is moved from RAX to the destination. +fn convert_function_call( + fun_name: &Identifier, + args: &[Val], + dst: &Val, + symbols: &BackendSymbolTable, +) -> Vec { let arg_registers = [Reg::DI, Reg::SI, Reg::DX, Reg::CX, Reg::R8, Reg::R9]; let (register_args, stack_args) = args.split_at(args.len().min(6)); let mut instructions = Vec::new(); let stack_padding = if stack_args.len() % 2 != 0 { - instructions.push(Instruction::AllocateStack(8)); + instructions.push(Instruction::Binary { + op: BinaryOp::Sub, + src: Operand::Imm(8), + dst: Operand::Reg(Reg::SP), + size: AssemblyType::Quadword, + }); 8 } else { 0 }; for (tacky_arg, reg) in register_args.iter().zip(arg_registers) { - let assembly_arg = convert_val(tacky_arg); instructions.push(Instruction::Mov { - src: assembly_arg, + src: tacky_arg.into(), dst: Operand::Reg(reg), + size: get_assembly_type(tacky_arg, symbols), }); } for tacky_arg in stack_args.iter().rev() { - let assembly_arg = convert_val(tacky_arg); - match assembly_arg { - Operand::Imm(_) | Operand::Reg(_) => instructions.push(Instruction::Push(assembly_arg)), - Operand::Stack(_) | Operand::Pseudo(_) | Operand::Data(_) => { - instructions.push(Instruction::Mov { - src: assembly_arg, - dst: Operand::Reg(Reg::AX), - }); - instructions.push(Instruction::Push(Operand::Reg(Reg::AX))) - } + let assembly_arg = tacky_arg.into(); + let asm_type = get_assembly_type(tacky_arg, symbols); + if asm_type == AssemblyType::Quadword || matches!(assembly_arg, Operand::Imm(_) | Operand::Reg(_)) { + instructions.push(Instruction::Push(assembly_arg)); + } else { + instructions.push(Instruction::Mov { + src: assembly_arg, + dst: Operand::Reg(Reg::AX), + size: AssemblyType::Longword, + }); + instructions.push(Instruction::Push(Operand::Reg(Reg::AX))) } } instructions.push(Instruction::Call(fun_name.clone())); - let bytes_to_remove = 8 * stack_args.len() as i32 + stack_padding; + let bytes_to_remove = 8 * stack_args.len() as i64 + stack_padding; if bytes_to_remove > 0 { - instructions.push(Instruction::DeallocateStack(bytes_to_remove)); + instructions.push(Instruction::Binary { + op: BinaryOp::Add, + src: Operand::Imm(bytes_to_remove), + dst: Operand::Reg(Reg::SP), + size: AssemblyType::Quadword, + }); } - let assembly_dst = convert_val(dst); instructions.push(Instruction::Mov { src: Operand::Reg(Reg::AX), - dst: assembly_dst, + dst: dst.into(), + size: get_assembly_type(dst, symbols), }); instructions } -fn convert_instruction(instruction: &tacky::Instruction) -> Vec { +fn convert_instruction(instruction: &tacky::Instruction, symbols: &BackendSymbolTable) -> Vec { match instruction { tacky::Instruction::Return(x) => { - let val = convert_val(&x.clone()); + let size = get_assembly_type(x, symbols); vec![ Instruction::Mov { - src: val, + src: x.into(), dst: Operand::Reg(Reg::AX), + size, }, Instruction::Ret, ] @@ -167,36 +340,42 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { src, dst, } => { - let src = convert_val(src); - let dst = convert_val(dst); + let size = get_assembly_type(src, symbols); vec![ Instruction::Cmp { v1: Operand::Imm(0), - v2: src, + v2: src.into(), + size, }, Instruction::Mov { src: Operand::Imm(0), - dst: dst.clone(), + dst: dst.into(), + size, }, Instruction::SetCC { code: CondCode::E, - op: dst, + op: dst.into(), }, ] } tacky::Instruction::Unary { op, src, dst } => { - let src = convert_val(src); - let dst = convert_val(dst); + let size = get_assembly_type(src, symbols); let op = convert_unary_op(op); vec![ - Instruction::Mov { src, dst: dst.clone() }, - Instruction::Unary { op, dst }, + Instruction::Mov { + src: src.into(), + dst: dst.into(), + size, + }, + Instruction::Unary { + op, + dst: dst.into(), + size, + }, ] } tacky::Instruction::Binary { op, src1, src2, dst } => { - let src1 = convert_val(src1); - let src2 = convert_val(src2); - let dst = convert_val(dst); + let size = get_assembly_type(src1, symbols); match op { BinOp::Add | BinOp::Subtract @@ -208,13 +387,15 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { | BinOp::BitwiseRightShift => { vec![ Instruction::Mov { - src: src1, - dst: dst.clone(), + src: src1.into(), + dst: dst.into(), + size, }, Instruction::Binary { op: BinaryOp::from(op), - src: src2, - dst, + src: src2.into(), + dst: dst.into(), + size, }, ] } @@ -222,14 +403,16 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { let result_reg = if *op == BinOp::Divide { Reg::AX } else { Reg::DX }; vec![ Instruction::Mov { - src: src1, + src: src1.into(), dst: Operand::Reg(Reg::AX), + size, }, - Instruction::Cdq, - Instruction::Idiv(src2), + Instruction::Cdq(size), + Instruction::Idiv(src2.into(), size), Instruction::Mov { src: Operand::Reg(result_reg), - dst, + dst: dst.into(), + size, }, ] } @@ -249,21 +432,28 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { _ => unreachable!(), }; vec![ - Instruction::Cmp { v1: src2, v2: src1 }, + Instruction::Cmp { + v1: src2.into(), + v2: src1.into(), + size, + }, Instruction::Mov { src: Operand::Imm(0), - dst: dst.clone(), + dst: dst.into(), + size, }, - Instruction::SetCC { code, op: dst }, + Instruction::SetCC { code, op: dst.into() }, ] } } } tacky::Instruction::JumpIfZero { condition, target } => { + let size = get_assembly_type(condition, symbols); vec![ Instruction::Cmp { v1: Operand::Imm(0), - v2: convert_val(condition), + v2: condition.into(), + size, }, Instruction::JmpCC { code: CondCode::E, @@ -272,10 +462,12 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { ] } tacky::Instruction::JumpIfNotZero { condition, target } => { + let size = get_assembly_type(condition, symbols); vec![ Instruction::Cmp { v1: Operand::Imm(0), - v2: convert_val(condition), + v2: condition.into(), + size, }, Instruction::JmpCC { code: CondCode::NE, @@ -290,11 +482,27 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { vec![Instruction::Label(label.clone())] } tacky::Instruction::Copy { src, dst } => { - let src = convert_val(src); - let dst = convert_val(dst); - vec![Instruction::Mov { src, dst }] + let size = get_assembly_type(src, symbols); + vec![Instruction::Mov { + src: src.into(), + dst: dst.into(), + size, + }] + } + tacky::Instruction::FunCall { fun_name, args, dst } => convert_function_call(fun_name, args, dst, symbols), + tacky::Instruction::SignExtend { src, dst } => { + vec![Instruction::Movsx { + src: src.into(), + dst: dst.into(), + }] + } + tacky::Instruction::Truncate { src, dst } => { + vec![Instruction::Mov { + src: src.into(), + dst: dst.into(), + size: AssemblyType::Longword, + }] } - tacky::Instruction::FunCall { fun_name, args, dst } => convert_function_call(fun_name, args, dst), } } @@ -330,80 +538,168 @@ fn convert_unary_op(op: &parser::UnaryOp) -> UnaryOp { } } -fn convert_val(ast: &tacky::Val) -> Operand { - match ast { - tacky::Val::Constant(value) => Operand::Imm(*value), - tacky::Val::Var(s) => Operand::Pseudo(s.clone()), - } -} - -fn convert_function(ast: &tacky::FunctionDefinition) -> FunctionDefinition { +/// Converts a TACKY function definition to x86-64 assembly instructions. +/// +/// Emits parameter moves (from registers/stack to pseudo-registers) followed +/// by the converted body instructions. First 6 params come from registers, +/// the rest from stack positions above the saved RBP and return address. +//todo should this consume FunctionDefination +fn convert_function(ast: &tacky::FunctionDefinition, symbols: &BackendSymbolTable) -> FunctionDefinition { let tacky::FunctionDefinition { name, params, body, global, + temp_types: _, } = ast; let arg_registers = [Reg::DI, Reg::SI, Reg::DX, Reg::CX, Reg::R8, Reg::R9]; let mut instructions = vec![]; for (Identifier(param), reg) in params.iter().zip(arg_registers) { + let param_ty = symbols.get_obj_type(param); + instructions.push(Instruction::Mov { src: Operand::Reg(reg), dst: Operand::Pseudo(param.clone()), + size: *param_ty, }); } for (i, Identifier(param)) in params.iter().skip(6).enumerate() { let stack_offset = 16 + (i as i32 * 8); // +16 for saved RBP and return address + let param_ty = symbols.get_obj_type(param); instructions.push(Instruction::Mov { src: Operand::Stack(stack_offset), dst: Operand::Pseudo(param.clone()), + size: *param_ty, }); } - instructions.extend(body.iter().flat_map(convert_instruction)); + instructions.extend(body.iter().flat_map(|ins| convert_instruction(ins, symbols))); { FunctionDefinition { - name: name.to_string(), + name: name.clone(), body: instructions, global: *global, } } } -/// Converts TACKY IR to x86-64 assembly AST. +/// Backend symbol table entry mapping identifiers to their assembly-level properties. +/// +/// Tracks whether a symbol is an object (variable) or function, along with +/// the assembly type (Longword/Quadword) needed for instruction sizing. +pub enum AsmSymbolEntry { + // `is_static` and `defined` are tracked for future use (e.g. RIP-relative + // addressing decisions, link-time checks) but not yet read. + Obj { + asm_type: AssemblyType, + #[allow(dead_code)] + is_static: bool, + }, + Fun { + #[allow(dead_code)] + defined: bool, + }, +} + +pub type BackendSymbolTable = HashMap, AsmSymbolEntry>; + +pub trait BackendSymbolTableExt { + fn get_obj_type(&self, name: &str) -> &AssemblyType; +} + +impl BackendSymbolTableExt for BackendSymbolTable { + fn get_obj_type(&self, name: &str) -> &AssemblyType { + match self.get(name).unwrap() { + AsmSymbolEntry::Obj { asm_type, .. } => asm_type, + AsmSymbolEntry::Fun { .. } => panic!("Expected object type, found function: {}", name), + } + } +} + +/// Builds the backend symbol table from the frontend symbol table and TACKY IR. /// -/// Performs several passes: converts TACKY to assembly instructions, -/// replaces pseudo-registers with stack slots (or Data operands for statics), -/// fixes invalid instruction operand combinations, and coalesces consecutive labels. -pub fn generate(ast: &tacky::Program) -> Program { - let mut functions = vec![]; - let mut static_vars = vec![]; - - for decl in &ast.top_level { - match decl { - tacky::TopLevel::Function(function) => functions.push(convert_function(function)), - tacky::TopLevel::StaticVariable(s) => static_vars.push(s.clone()), +/// Maps all symbols to their assembly types: frontend symbols (variables and functions) +/// from the validator's symbol table, plus TACKY temporaries from each function definition. +fn build_backend_symbol_table(ast: &tacky::Program, symbols: &SymbolTable) -> BackendSymbolTable { + let mut backend = BackendSymbolTable::new(); + let static_names: HashSet<&str> = ast.static_vars.iter().map(|sv| &*sv.name).collect(); + + for (name, symbol) in symbols.iter() { + let backend_entry = match &symbol.symbol_type { + Type::FunType { defined, .. } => AsmSymbolEntry::Fun { defined: *defined }, + ty => AsmSymbolEntry::Obj { + asm_type: ty.into(), + is_static: static_names.contains(&**name), + }, + }; + backend.insert(name.clone(), backend_entry); + } + + for func in &ast.function_defs { + for (temp_name, temp_type) in &func.temp_types { + backend.insert( + temp_name.clone(), + AsmSymbolEntry::Obj { + asm_type: temp_type.into(), + is_static: false, + }, + ); } } + + backend +} + +fn convert_static_var(static_var: TackyStaticVariable) -> StaticVariable { + let TackyStaticVariable { + name, + global, + init, + var_type, + } = static_var; + StaticVariable { + name, + global, + alignment: AssemblyType::from(&var_type).size(), + init, + } +} + +/// Converts TACKY IR to x86-64 assembly AST. +/// +/// Performs four passes: +/// 1. Instruction selection: converts TACKY instructions to assembly +/// 2. Pseudo-register replacement: assigns stack slots to locals, Data operands to statics +/// 3. Fix-up: rewrites invalid x86-64 operand combinations (e.g., memory-to-memory) +/// 4. Label coalescing: merges consecutive labels to reduce jump targets +pub fn generate(ast: tacky::Program, symbols: &SymbolTable) -> (Program, BackendSymbolTable) { + let backend_symbol_table = build_backend_symbol_table(&ast, symbols); + let functions = ast + .function_defs + .iter() + .map(|f| convert_function(f, &backend_symbol_table)) + .collect(); + let static_vars = ast.static_vars.into_iter().map(convert_static_var).collect(); + let mut p = Program { functions, static_vars }; - let stack_offsets = replace_pseudo_registers(&mut p); + let stack_offsets = replace_pseudo_registers(&mut p, &backend_symbol_table); fix_invalid(&mut p, &stack_offsets); coalesce_labels(&mut p); - p + (p, backend_symbol_table) } struct StackMapping<'a> { - stack_mapping: HashMap, + stack_mapping: HashMap, i32>, offset: i32, /// Names of variables that should use Data operands (RIP-relative addressing). /// Includes both static variables defined in this file and extern variables. - data_vars: &'a HashSet, + data_vars: &'a HashSet>, } impl<'a> StackMapping<'a> { - fn from_data_vars(data_vars: &'a HashSet) -> Self { + fn from_data_vars(data_vars: &'a HashSet>) -> Self { StackMapping { stack_mapping: HashMap::new(), offset: 0, @@ -411,13 +707,16 @@ impl<'a> StackMapping<'a> { } } - fn get_stack_location(&mut self, pseudo: &str) -> Operand { + /// Returns the stack operand for a pseudo-register, allocating a new slot if needed. + /// + /// Stack grows downward: each new allocation decrements the offset by the type's size. + fn get_stack_location(&mut self, pseudo: &str, asm_type: AssemblyType) -> Operand { let offset_option = self.stack_mapping.get(pseudo); let offset = match offset_option { Some(offset) => offset, None => { - self.offset -= 4; - self.stack_mapping.insert(pseudo.to_string(), self.offset); + self.offset -= asm_type.size() as i32; + self.stack_mapping.insert(Rc::from(pseudo), self.offset); &self.offset } }; @@ -428,13 +727,13 @@ impl<'a> StackMapping<'a> { /// /// Static/extern variables become `Data` operands (RIP-relative addressing). /// Local variables become `Stack` operands (RBP-relative addressing). - fn replace_pseudo(&mut self, operand: &Operand) -> Operand { + fn replace_pseudo(&mut self, operand: &Operand, asm_type: AssemblyType) -> Operand { match operand { Operand::Pseudo(pseudo) => { if self.data_vars.contains(pseudo) { Operand::Data(pseudo.clone()) } else { - self.get_stack_location(pseudo) + self.get_stack_location(pseudo, asm_type) } } _ => operand.clone(), @@ -447,9 +746,9 @@ impl<'a> StackMapping<'a> { /// For each function, assigns stack slots to local variables and converts /// static variable references to Data operands. Returns a map of function /// names to their total stack space used (as negative offsets from RBP). -pub fn replace_pseudo_registers(program: &mut Program) -> HashMap { +fn replace_pseudo_registers(program: &mut Program, symbols: &BackendSymbolTable) -> HashMap, i32> { // Collect data vars (static + extern) upfront to avoid borrow conflict in the loop - let data_vars: HashSet = program.static_vars.iter().map(|v| v.name.clone()).collect(); + let data_vars: HashSet> = program.static_vars.iter().map(|v| v.name.clone()).collect(); let mut offsets = HashMap::new(); for FunctionDefinition { name, body, global: _ } in program.functions.iter_mut() { @@ -457,25 +756,33 @@ pub fn replace_pseudo_registers(program: &mut Program) -> HashMap { for ins in body.iter_mut() { match ins { - Instruction::Mov { src, dst } | Instruction::Binary { op: _, src, dst } => { - *src = stack_mapping.replace_pseudo(src); - *dst = stack_mapping.replace_pseudo(dst); + Instruction::Mov { src, dst, size } | Instruction::Binary { op: _, src, dst, size } => { + *src = stack_mapping.replace_pseudo(src, *size); + *dst = stack_mapping.replace_pseudo(dst, *size); + } + Instruction::Unary { op: _, dst, size } => *dst = stack_mapping.replace_pseudo(dst, *size), + Instruction::Movsx { src, dst } => { + *src = stack_mapping.replace_pseudo(src, AssemblyType::Longword); + *dst = stack_mapping.replace_pseudo(dst, AssemblyType::Quadword); } - Instruction::Unary { op: _, dst } => *dst = stack_mapping.replace_pseudo(dst), - Instruction::Idiv(src) => { - *src = stack_mapping.replace_pseudo(src); + Instruction::Idiv(src, size) => { + *src = stack_mapping.replace_pseudo(src, *size); } - Instruction::Cmp { v1, v2 } => { - *v1 = stack_mapping.replace_pseudo(v1); - *v2 = stack_mapping.replace_pseudo(v2); + Instruction::Cmp { v1, v2, size } => { + *v1 = stack_mapping.replace_pseudo(v1, *size); + *v2 = stack_mapping.replace_pseudo(v2, *size); } - Instruction::SetCC { op, .. } | Instruction::Push(op) => { - *op = stack_mapping.replace_pseudo(op); + Instruction::SetCC { op, .. } => { + if let Operand::Pseudo(name) = op { + let size = *symbols.get_obj_type(name); + *op = stack_mapping.replace_pseudo(op, size); + } } + Instruction::Push(op) => *op = stack_mapping.replace_pseudo(op, AssemblyType::Quadword), _ => {} } } - offsets.insert(name.to_string(), stack_mapping.offset); + offsets.insert(name.clone(), stack_mapping.offset); } offsets } @@ -488,109 +795,261 @@ pub fn replace_pseudo_registers(program: &mut Program) -> HashMap { /// - imul with memory destination (uses R11 as intermediate) /// - Binary ops with both operands in memory (uses R10) /// - Shift with memory source (moves count to CX) -/// - Compare with both operands in memory or immediate second operand +/// - Compare with immediate as destination operand (v2), or both operands in memory, or large immediates +/// - Large immediates that don't fit in i32 for quadword operations +/// - Movsx with immediate source or pseudo-register destination /// /// Also inserts stack allocation at the start of each function. -pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) { +fn fix_invalid(program: &mut Program, stack_offsets: &HashMap, i32>) { for FunctionDefinition { name, body, global: _ } in program.functions.iter_mut() { // stack_offset is negative, so convert to positive, round up to 16, then negate for AllocateStack let mut positive_offset = -stack_offsets[name]; if positive_offset % 16 != 0 { positive_offset = ((positive_offset / 16) + 1) * 16; } - let mut new_ins = vec![Instruction::AllocateStack(positive_offset)]; - for ins in body.iter() { + let mut new_ins = vec![]; + if positive_offset > 0 { + new_ins.push(Instruction::Binary { + op: BinaryOp::Sub, + src: Operand::Imm(positive_offset as i64), + dst: Operand::Reg(Reg::SP), + size: AssemblyType::Quadword, + }) + } + for ins in body.drain(..) { match ins { - Instruction::Mov { src, dst } if src.is_memory() && dst.is_memory() => { + Instruction::Mov { ref src, ref dst, size } if src.is_memory() && dst.is_memory() => { new_ins.push(Instruction::Mov { src: src.clone(), dst: Operand::Reg(Reg::R10), + size, + }); + new_ins.push(Instruction::Mov { + src: Operand::Reg(Reg::R10), + dst: dst.clone(), + size, + }); + } + Instruction::Mov { + src: Operand::Imm(val), + dst, + size: AssemblyType::Longword, + } if val < i32::MIN as i64 || val > i32::MAX as i64 => { + // handle case where quadwords imm are being moved into longword. Avoids linker warnings + new_ins.push(Instruction::Mov { + src: Operand::Imm(val as i32 as i64), + dst, + size: AssemblyType::Longword, + }); + } + Instruction::Mov { + // iced caught this missing case, can't mov imm quadword to memory + src: Operand::Imm(val), + ref dst, + size: AssemblyType::Quadword, + } if matches!(dst, Operand::Stack(_) | Operand::Data(_)) + && (val < i32::MIN as i64 || val > i32::MAX as i64) => + { + new_ins.push(Instruction::Mov { + src: Operand::Imm(val), + dst: Operand::Reg(Reg::R10), + size: AssemblyType::Quadword, }); new_ins.push(Instruction::Mov { src: Operand::Reg(Reg::R10), dst: dst.clone(), + size: AssemblyType::Quadword, }); } - Instruction::Idiv(Operand::Imm(c)) => { + Instruction::Idiv(Operand::Imm(c), size) => { new_ins.push(Instruction::Mov { - src: Operand::Imm(*c), + src: Operand::Imm(c), dst: Operand::Reg(Reg::R10), + size, }); - new_ins.push(Instruction::Idiv(Operand::Reg(Reg::R10))); + new_ins.push(Instruction::Idiv(Operand::Reg(Reg::R10), size)); } Instruction::Binary { op: BinaryOp::Mult, - src, - dst, + ref src, + ref dst, + size, } if dst.is_memory() => { + let new_src = if matches!(src, Operand::Imm(val) if *val < i32::MIN as i64 || *val > i32::MAX as i64) + { + new_ins.push(Instruction::Mov { + src: src.clone(), + dst: Operand::Reg(Reg::R10), + size: AssemblyType::Quadword, + }); + Operand::Reg(Reg::R10) + } else { + src.clone() + }; + new_ins.push(Instruction::Mov { src: dst.clone(), dst: Operand::Reg(Reg::R11), + size, }); new_ins.push(Instruction::Binary { op: BinaryOp::Mult, - src: src.clone(), + src: new_src, dst: Operand::Reg(Reg::R11), + size, }); new_ins.push(Instruction::Mov { src: Operand::Reg(Reg::R11), dst: dst.clone(), + size, }); } Instruction::Binary { op: op @ (BinaryOp::Add | BinaryOp::Sub | BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXOr), src, - dst, + ref dst, + size, } if src.is_memory() && dst.is_memory() => { new_ins.push(Instruction::Mov { - src: src.clone(), + src, dst: Operand::Reg(Reg::R10), + size, }); new_ins.push(Instruction::Binary { - op: op.clone(), + op, src: Operand::Reg(Reg::R10), dst: dst.clone(), + size, }); } Instruction::Binary { op: op @ (BinaryOp::BitShl | BinaryOp::BitSar), src, dst, - } if src.is_memory() => { + size, + } if src.is_memory() || matches!(src, Operand::Imm(val) if !(0..=255).contains(&val)) => { new_ins.push(Instruction::Mov { - src: src.clone(), + src, dst: Operand::Reg(Reg::CX), + size, }); new_ins.push(Instruction::Binary { - op: op.clone(), + op, src: Operand::Reg(Reg::CX), - dst: dst.clone(), + dst, + size, }); } - Instruction::Cmp { v1, v2 } if v1.is_memory() && v2.is_memory() => { + Instruction::Binary { + op, + src: Operand::Imm(val), + dst, + size: AssemblyType::Quadword, + } if matches!( + op, + BinaryOp::Add + | BinaryOp::Sub + | BinaryOp::Mult + | BinaryOp::BitAnd + | BinaryOp::BitOr + | BinaryOp::BitXOr + ) && (val < i32::MIN as i64 || val > i32::MAX as i64) => + { new_ins.push(Instruction::Mov { - src: v1.clone(), + src: Operand::Imm(val), dst: Operand::Reg(Reg::R10), + size: AssemblyType::Quadword, }); + new_ins.push(Instruction::Binary { + op, + src: Operand::Reg(Reg::R10), + dst, + size: AssemblyType::Quadword, + }) + } + Instruction::Cmp { ref v1, ref v2, size } => { + let new_v1 = if (v1.is_memory() && v2.is_memory()) + || matches!((v1, size), (Operand::Imm(c), AssemblyType::Quadword) if *c < i32::MIN as i64 || *c > i32::MAX as i64) + { + new_ins.push(Instruction::Mov { + src: v1.clone(), + dst: Operand::Reg(Reg::R10), + size, + }); + Operand::Reg(Reg::R10) + } else { + v1.clone() + }; + + let new_v2 = if matches!(v2, Operand::Imm(_)) { + new_ins.push(Instruction::Mov { + src: v2.clone(), + dst: Operand::Reg(Reg::R11), + size, + }); + Operand::Reg(Reg::R11) + } else { + v2.clone() + }; + new_ins.push(Instruction::Cmp { - v1: Operand::Reg(Reg::R10), - v2: v2.clone(), + v1: new_v1, + v2: new_v2, + size, }); } - Instruction::Cmp { - v1, - v2: Operand::Imm(c), - } => { + Instruction::Push(Operand::Imm(c)) if c < i32::MIN as i64 || c > i32::MAX as i64 => { new_ins.push(Instruction::Mov { - src: Operand::Imm(*c), - dst: Operand::Reg(Reg::R11), - }); - new_ins.push(Instruction::Cmp { - v1: v1.clone(), - v2: Operand::Reg(Reg::R11), + src: Operand::Imm(c), + dst: Operand::Reg(Reg::R10), + size: AssemblyType::Quadword, }); + new_ins.push(Instruction::Push(Operand::Reg(Reg::R10))); + } + Instruction::Movsx { ref src, ref dst } => { + //extends longword src to quadword dst + if let &Operand::Imm(val) = src { + new_ins.push(Instruction::Mov { + // move src to r10 + src: Operand::Imm(val), + dst: Operand::Reg(Reg::R10), + size: AssemblyType::Longword, + }); + if dst.is_memory() { + // src and dst are invalid + new_ins.push(Instruction::Movsx { + src: Operand::Reg(Reg::R10), + dst: Operand::Reg(Reg::R11), + }); + new_ins.push(Instruction::Mov { + src: Operand::Reg(Reg::R11), + dst: dst.clone(), + size: AssemblyType::Quadword, + }) + } else { + // just src is invalid + new_ins.push(Instruction::Movsx { + src: Operand::Reg(Reg::R10), + dst: dst.clone(), + }); + } + } else if dst.is_memory() { + // just dst is invalid, put result in r10 then mov to dst + new_ins.push(Instruction::Movsx { + src: src.clone(), + dst: Operand::Reg(Reg::R11), + }); + new_ins.push(Instruction::Mov { + src: Operand::Reg(Reg::R11), + dst: dst.clone(), + size: AssemblyType::Quadword, + }); + } else { + // valid + new_ins.push(ins); + } } - _ => new_ins.push(ins.clone()), + _ => new_ins.push(ins), } } *body = new_ins; @@ -598,19 +1057,19 @@ pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) } /// Coalesces consecutive labels by mapping subsequent labels to the first one -pub fn coalesce_labels(program: &mut Program) { +fn coalesce_labels(program: &mut Program) { for FunctionDefinition { name: _name, body, global: _, } in program.functions.iter_mut() { - let mut label_map: std::collections::HashMap = std::collections::HashMap::new(); + let mut label_map: std::collections::HashMap, Rc> = std::collections::HashMap::new(); let mut new_ins = Vec::new(); - let mut current_label: Option = None; + let mut current_label: Option> = None; // First pass: build label mapping - for ins in body.iter() { - match ins { + for ins in body.drain(..) { + match &ins { Instruction::Label(Identifier(label)) => { if let Some(first_label) = ¤t_label { // Map this label to the first label in the sequence @@ -619,13 +1078,13 @@ pub fn coalesce_labels(program: &mut Program) { } else { // This is the first label in a potential sequence current_label = Some(label.clone()); - new_ins.push(ins.clone()); + new_ins.push(ins); } } _ => { // Non-label instruction, reset the sequence current_label = None; - new_ins.push(ins.clone()); + new_ins.push(ins); } } } diff --git a/src/emit.rs b/src/emit.rs index 7fc9710..2940d08 100644 --- a/src/emit.rs +++ b/src/emit.rs @@ -1,5 +1,24 @@ -use crate::codegen::{BinaryOp, FunctionDefinition, Instruction, Operand, Program, Reg, UnaryOp}; -use crate::tacky::{StaticVariable, VarInit}; +//! # Emitter (text) — Assembly AST to AT&T-Syntax Text Assembly +//! +//! Deprecated text-based emitter (enabled via `--no-iced`). Generates AT&T-syntax +//! x86-64 assembly as a [`String`], intended to be written to a `.s` file and +//! assembled by the system `as` assembler. +//! +//! ## Call Order +//! +//! ```text +//! emit_program() — public entry point, returns full assembly text +//! ├─ emit_function() — .globl directive, prologue, instruction loop +//! │ └─ emit_instruction() — single instruction to AT&T syntax +//! │ └─ emit_operand() — register/immediate/stack/data operand formatting +//! └─ emit_static_variable() — .data/.bss directives for static vars +//! ``` + +use crate::codegen::{ + AssemblyType, BinaryOp, FunctionDefinition, Instruction, Operand, Program, Reg, StaticVariable, UnaryOp, +}; +use crate::tacky::VarInit; +use crate::validate; enum RegWidth { Byte, @@ -7,6 +26,22 @@ enum RegWidth { QWord, } +impl RegWidth { + fn from_size(size: &AssemblyType) -> Self { + match size { + AssemblyType::Longword => RegWidth::DWord, + AssemblyType::Quadword => RegWidth::QWord, + } + } +} + +fn size_suffix(size: &AssemblyType) -> &'static str { + match size { + AssemblyType::Longword => "l", + AssemblyType::Quadword => "q", + } +} + fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> &'static str { match reg_width { RegWidth::Byte => match reg { @@ -19,6 +54,7 @@ fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> &'static str { Reg::R9 => "r9b", Reg::R10 => "r10b", Reg::R11 => "r11b", + Reg::SP => "spl", }, RegWidth::DWord => match reg { Reg::AX => "eax", @@ -30,6 +66,7 @@ fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> &'static str { Reg::R9 => "r9d", Reg::R10 => "r10d", Reg::R11 => "r11d", + Reg::SP => "esp", }, RegWidth::QWord => match reg { Reg::AX => "rax", @@ -41,27 +78,30 @@ fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> &'static str { Reg::R9 => "r9", Reg::R10 => "r10", Reg::R11 => "r11", + Reg::SP => "rsp", }, } } -fn emit_unaryop(op: &UnaryOp) -> &'static str { +fn emit_unaryop(op: &UnaryOp, size: &AssemblyType) -> String { + let suffix = size_suffix(size); match op { - UnaryOp::Neg => "negl", - UnaryOp::Not => "notl", + UnaryOp::Neg => format!("neg{suffix}"), + UnaryOp::Not => format!("not{suffix}"), } } -fn emit_binaryop(op: &BinaryOp) -> &'static str { +fn emit_binaryop(op: &BinaryOp, size: &AssemblyType) -> String { + let suffix = size_suffix(size); match op { - BinaryOp::Add => "addl", - BinaryOp::Sub => "subl", - BinaryOp::Mult => "imull", - BinaryOp::BitAnd => "andl", - BinaryOp::BitOr => "orl", - BinaryOp::BitXOr => "xorl", - BinaryOp::BitShl => "shll", - BinaryOp::BitSar => "sarl", + BinaryOp::Add => format!("add{suffix}"), + BinaryOp::Sub => format!("sub{suffix}"), + BinaryOp::Mult => format!("imul{suffix}"), + BinaryOp::BitAnd => format!("and{suffix}"), + BinaryOp::BitOr => format!("or{suffix}"), + BinaryOp::BitXOr => format!("xor{suffix}"), + BinaryOp::BitShl => format!("shl{suffix}"), + BinaryOp::BitSar => format!("sar{suffix}"), } } @@ -90,65 +130,91 @@ fn emit_operand(operand: &Operand, reg_width: &RegWidth) -> String { output } +/// Emits AT&T-syntax x86-64 assembly text for a single instruction. +/// +/// `fn_name` is used to prefix labels and jump targets, ensuring they are scoped +/// to the enclosing function (e.g., `main.label0`). fn emit_instruction(ins: &Instruction, fn_name: &str) -> String { - fn emit_operand_dw(operand: &Operand) -> String { - emit_operand(operand, &RegWidth::DWord) - } let mut output = String::new(); match ins { - Instruction::Mov { src, dst } => { - output.push_str(&format!("movl {}, {}", emit_operand_dw(src), emit_operand_dw(dst))); + Instruction::Mov { src, dst, size } => { + let suffix = size_suffix(size); + let width = RegWidth::from_size(size); + output.push_str(&format!( + "mov{suffix} {}, {}", + emit_operand(src, &width), + emit_operand(dst, &width) + )); + } + Instruction::Movsx { src, dst } => { + // movslq - sign-extend 32-bit to 64-bit + output.push_str(&format!( + "movslq {}, {}", + emit_operand(src, &RegWidth::DWord), + emit_operand(dst, &RegWidth::QWord) + )); } Instruction::Ret => { output.push_str("movq %rbp, %rsp\n"); output.push_str("\tpopq %rbp\n"); output.push_str("\tret"); } - Instruction::Unary { op, dst } => { - output.push_str(&format!("{} {}\n", emit_unaryop(op), emit_operand_dw(dst))); - } - Instruction::AllocateStack(offset) => { - output.push_str(&format!("subq ${}, %rsp", offset)); + Instruction::Unary { op, dst, size } => { + let width = RegWidth::from_size(size); + output.push_str(&format!("{} {}\n", emit_unaryop(op, size), emit_operand(dst, &width))); } Instruction::Binary { op: op @ (BinaryOp::BitShl | BinaryOp::BitSar), src, dst, + size, } => { - // shr and sar always use an immediate or cl register as the source operand + // shl and sar always use an immediate or cl register as the source operand + let width = RegWidth::from_size(size); output.push_str(&format!( "{} {}, {}", - emit_binaryop(op), + emit_binaryop(op, size), emit_operand(src, &RegWidth::Byte), - emit_operand_dw(dst) + emit_operand(dst, &width) )); } - Instruction::Binary { op, src, dst } => { + Instruction::Binary { op, src, dst, size } => { + let width = RegWidth::from_size(size); output.push_str(&format!( "{} {}, {}", - emit_binaryop(op), - emit_operand_dw(src), - emit_operand_dw(dst) + emit_binaryop(op, size), + emit_operand(src, &width), + emit_operand(dst, &width) )); } - Instruction::Idiv(op) => { - output.push_str(&format!("idivl {} ", emit_operand_dw(op))); + Instruction::Idiv(op, size) => { + let suffix = size_suffix(size); + let width = RegWidth::from_size(size); + output.push_str(&format!("idiv{suffix} {} ", emit_operand(op, &width))); } - Instruction::Cdq => { - output.push_str("cdq"); + Instruction::Cdq(size) => { + let ins = match size { + AssemblyType::Longword => "cdq", + AssemblyType::Quadword => "cqo", + }; + output.push_str(ins); } - Instruction::Cmp { v1, v2 } => { - output.push_str(&format!("cmpl {}, {}", emit_operand_dw(v1), emit_operand_dw(v2))); + Instruction::Cmp { v1, v2, size } => { + let suffix = size_suffix(size); + let width = RegWidth::from_size(size); + output.push_str(&format!( + "cmp{suffix} {}, {}", + emit_operand(v1, &width), + emit_operand(v2, &width) + )); } Instruction::Jmp(target) => { - // Use raw label name with function prefix for uniqueness output.push_str(&format!("jmp {}.{}", fn_name, target.0)); } Instruction::JmpCC { code, label } => { output.push_str(&format!("j{} {}.{}", code.ins_suffix(), fn_name, label.0)); } Instruction::Label(label) => { - // Use raw label name with function prefix for uniqueness output.push_str(&format!("{}.{}:", fn_name, label.0)); } Instruction::SetCC { code, op } => { @@ -158,15 +224,10 @@ fn emit_instruction(ins: &Instruction, fn_name: &str) -> String { emit_operand(op, &RegWidth::Byte) )); } - Instruction::DeallocateStack(offset) => { - output.push_str(&format!("addq ${}, %rsp", offset)); - } Instruction::Push(op) => { output.push_str(&format!("pushq {}", emit_operand(op, &RegWidth::QWord))); } Instruction::Call(name) => { - // Use name.0 to get raw function name without .L prefix - // On Linux, use @PLT for external function calls if cfg!(target_os = "macos") { output.push_str(&format!("call _{}", name.0)); } else { @@ -197,9 +258,20 @@ fn emit_function(fun_def: &FunctionDefinition) -> String { output } +/// Emits a static variable as AT&T-syntax assembly directives. +/// +/// Places zero-initialized variables in `.bss` and non-zero variables in `.data`, +/// with appropriate alignment and size directives (`.long` for int, `.quad` for long). +/// Extern variables (unresolved by the linker) produce no output. +/// On macOS, symbol names are prefixed with `_`. fn emit_static_variable(sv: &StaticVariable) -> String { let mut output = String::new(); - let StaticVariable { name, global, init } = sv; + let StaticVariable { + name, + global, + init, + alignment, + } = sv; let processed_name = if cfg!(target_os = "macos") { format!("_{name}") } else { @@ -215,18 +287,28 @@ fn emit_static_variable(sv: &StaticVariable) -> String { output.push_str(&format!("\t.globl {processed_name}\n")); } - if *init_val == 0 { - // BSS section for zero-initialized data - output.push_str("\t.bss\n"); - output.push_str("\t.align 4\n"); - output.push_str(&format!("{processed_name}:\n")); - output.push_str("\t.zero 4\n"); - } else { - // Data section for initialized data - output.push_str("\t.data\n"); - output.push_str("\t.align 4\n"); - output.push_str(&format!("{processed_name}:\n")); - output.push_str(&format!("\t.long {init_val}\n")); + match init_val { + validate::StaticInt::IntInit(0) | validate::StaticInt::LongInit(0) => { + // BSS section for zero-initialized data + output.push_str("\t.bss\n"); + output.push_str(&format!("\t.align {alignment}\n")); + output.push_str(&format!("{processed_name}:\n")); + output.push_str(&format!("\t.zero {alignment}\n")); + } + validate::StaticInt::IntInit(val) => { + // Data section for initialized int + output.push_str("\t.data\n"); + output.push_str("\t.align 4\n"); + output.push_str(&format!("{processed_name}:\n")); + output.push_str(&format!("\t.long {val}\n")); + } + validate::StaticInt::LongInit(val) => { + // Data section for initialized long + output.push_str("\t.data\n"); + output.push_str("\t.align 8\n"); + output.push_str(&format!("{processed_name}:\n")); + output.push_str(&format!("\t.quad {val}\n")); + } } output diff --git a/src/emit_iced.rs b/src/emit_iced.rs index 1a79c9d..a2f8fc9 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -1,6 +1,45 @@ -// Simple emitter using iced-x86 to generate machine code at runtime -use crate::codegen::{self, BinaryOp, CondCode, Instruction, Operand, Reg, UnaryOp}; -use crate::tacky::{StaticVariable, VarInit}; +//! # Emitter (iced-x86) — Assembly AST to Relocatable Object File +//! +//! Primary emitter that encodes the assembly AST into machine code using +//! [iced-x86](https://github.com/icedland/iced) and writes ELF (Linux) or +//! Mach-O (macOS) object files using the [object](https://github.com/gimli-rs/object) crate. +//! +//! ## Technical Approach +//! +//! Labels are pre-created for all functions and static variables so that forward +//! references resolve naturally. The [`CodeAssembler`] accumulates instructions, then +//! the block encoder resolves label addresses and produces a flat code buffer with +//! instruction-offset metadata. Relocations for external calls (`E8` + placeholder) +//! and RIP-relative data accesses are computed from the offset metadata and added to +//! the object file for the linker to patch. +//! +//! ## What This Pass Accomplishes +//! +//! - Encodes all x86-64 instructions to machine code (no external assembler needed) +//! - Builds a complete object file with `.text`, `.data`, and `.bss` sections +//! - Emits symbol table entries with correct scope (global vs file-local) +//! - Emits relocations for external function calls and static variable references +//! - Handles platform differences (ELF vs Mach-O implicit addend patching) +//! - Provides [`get_instructions`] for disassembly/pretty-printing with symbol names +//! +//! ## Call Order +//! +//! ```text +//! emit_object() — public entry point (returns object bytes) +//! └─ emit_object_with_labels() — core: assemble + build object file +//! └─ emit_function_body() — prologue + instruction loop +//! └─ emit_instruction() — encode one instruction, track relocations +//! ├─ gpr32() / gpr64_reg() — register mapping helpers +//! ├─ mem_rbp() — [rbp+offset] memory operands +//! └─ make_lbl_ptr() — [label] RIP-relative operands +//! +//! get_instructions() — public (for pretty-printing) +//! └─ emit_object_with_labels() — generate object, then decode back +//! ``` + +use crate::codegen::{self, AssemblyType, BinaryOp, CondCode, Instruction, Operand, Reg, StaticVariable, UnaryOp}; +use crate::tacky::VarInit; +use crate::validate::StaticInt; use iced_x86::{BlockEncoderOptions, IcedError, SymbolResolver, SymbolResult, code_asm::*}; use object::write::{ Object, Relocation, RelocationFlags, StandardSection, StandardSegment, Symbol, SymbolFlags, SymbolId, SymbolKind, @@ -11,6 +50,7 @@ use object::{ RelocationKind, SectionKind, }; use std::collections::HashMap; +use std::rc::Rc; /// Creates an undefined symbol (resolved by linker at link time). fn undefined_symbol(name: &str, kind: SymbolKind) -> Symbol { @@ -32,12 +72,12 @@ fn undefined_symbol(name: &str, kind: SymbolKind) -> Symbol { /// - `symbols`: Direct address-to-name mapping for functions and internal labels /// - `reloc_symbols`: Instruction IP to symbol name for RIP-relative data references pub struct MySymbolResolver { - symbols: HashMap, - reloc_symbols: HashMap, + symbols: HashMap>, + reloc_symbols: HashMap>, } impl MySymbolResolver { - fn new(symbols: HashMap, reloc_symbols: HashMap) -> Self { + fn new(symbols: HashMap>, reloc_symbols: HashMap>) -> Self { Self { symbols, reloc_symbols } } } @@ -53,11 +93,11 @@ impl SymbolResolver for MySymbolResolver { ) -> Option> { // First check direct address mapping (functions, internal labels) if let Some(name) = self.symbols.get(&address) { - return Some(SymbolResult::with_str(address, name.as_str())); + return Some(SymbolResult::with_str(address, name)); } // Then check relocation-based symbols (data references) if let Some(name) = self.reloc_symbols.get(&instruction.ip()) { - return Some(SymbolResult::with_str(address, name.as_str())); + return Some(SymbolResult::with_str(address, name)); } None } @@ -66,7 +106,7 @@ impl SymbolResolver for MySymbolResolver { #[allow(clippy::type_complexity)] pub fn get_instructions( program: &codegen::Program, -) -> Result<(Vec, MySymbolResolver, HashMap), Box> { +) -> Result<(Vec, MySymbolResolver, HashMap>), Box> { use object::read::RelocationTarget; let (obj_bytes, internal_labels) = emit_object_with_labels(program)?; @@ -79,23 +119,24 @@ pub fn get_instructions( let code = text_section.data()?; // Build symbol index to name map - let mut symbol_names: HashMap = HashMap::new(); + let mut symbol_names: HashMap> = HashMap::new(); for symbol in obj.symbols() { if let Ok(name) = symbol.name() { - symbol_names.insert(symbol.index(), name.to_string()); + symbol_names.insert(symbol.index(), Rc::from(name)); } } // Build symbol resolver from object file symbols - let mut address_map = HashMap::new(); - let mut function_offsets = HashMap::new(); + let mut address_map: HashMap> = HashMap::new(); + let mut function_offsets: HashMap, u64> = HashMap::new(); for symbol in obj.symbols() { if let Ok(name) = symbol.name() && !name.is_empty() && symbol.kind() == object::SymbolKind::Text { - address_map.insert(symbol.address(), name.to_string()); - function_offsets.insert(name.to_string(), symbol.address()); + let name: Rc = Rc::from(name); + address_map.insert(symbol.address(), name.clone()); + function_offsets.insert(name, symbol.address()); } } @@ -135,7 +176,7 @@ pub fn get_instructions( // Build relocation-based symbol map: instruction IP -> symbol name // This allows the symbol resolver to show data symbol names for RIP-relative accesses - let mut reloc_symbols: HashMap = HashMap::new(); + let mut reloc_symbols: HashMap> = HashMap::new(); for (reloc_offset, reloc) in text_section.relocations() { if let RelocationTarget::Symbol(sym_idx) = reloc.target() && let Some(symbol_name) = symbol_names.get(&sym_idx) @@ -186,27 +227,27 @@ pub fn emit_object(program: &codegen::Program) -> Result, Box Result<(Vec, HashMap), Box> { +) -> Result<(Vec, HashMap>), Box> { let mut a = CodeAssembler::new(64)?; // Create labels for all functions upfront - let mut fn_labels: HashMap = HashMap::new(); + let mut fn_labels: HashMap, CodeLabel> = HashMap::new(); for fun_def in &program.functions { fn_labels.insert(fun_def.name.clone(), a.create_label()); } // Create labels for static variables (including extern) to get RIP-relative addressing - let mut data_labels: HashMap = HashMap::new(); + let mut data_labels: HashMap, CodeLabel> = HashMap::new(); for sv in &program.static_vars { data_labels.insert(sv.name.clone(), a.create_label()); } // Track external function calls (instruction index, function name) - let mut external_calls: Vec<(usize, String)> = Vec::new(); - let mut data_relocs: Vec<(usize, String)> = Vec::new(); + let mut external_calls: Vec<(usize, Rc)> = Vec::new(); + let mut data_relocs: Vec<(usize, Rc)> = Vec::new(); // Track all internal labels across all functions - let mut all_label_idx: HashMap = HashMap::new(); + let mut all_label_idx: HashMap> = HashMap::new(); // Emit all functions for fun_def in &program.functions { @@ -236,7 +277,7 @@ fn emit_object_with_labels( )?; // Get function offsets before moving the code buffer - let mut func_offsets: Vec<(String, u64, bool)> = Vec::new(); + let mut func_offsets: Vec<(Rc, u64, bool)> = Vec::new(); for fun_def in &program.functions { let func_off = result.label_ip(fn_labels.get(&fun_def.name).unwrap())?; func_offsets.push((fun_def.name.clone(), func_off, fun_def.global)); @@ -278,7 +319,17 @@ fn emit_object_with_labels( obj.append_section_data(note_stack, &[], 1); obj } else { - Object::new(BinaryFormat::MachO, Architecture::X86_64, Endianness::Little) + let mut obj = Object::new(BinaryFormat::MachO, Architecture::X86_64, Endianness::Little); + // Without an LC_BUILD_VERSION load command, macOS `ld` warns + // "no platform load command found ... assuming: macOS". Emit one targeting + // macOS 11.0. MachOBuildVersion is #[non_exhaustive], so build via Default + // then set fields. minos/sdk use the nibble-packed XXXX.YY.ZZ form (11.0 = 11 << 16). + let mut build_version = object::write::MachOBuildVersion::default(); + build_version.platform = object::macho::PLATFORM_MACOS; + build_version.minos = 11 << 16; + build_version.sdk = 11 << 16; + obj.set_macho_build_version(build_version); + obj }; obj.add_file_symbol(b"ncc".to_vec()); @@ -310,28 +361,44 @@ fn emit_object_with_labels( let bss = obj.section_id(StandardSection::UninitializedData); let mut data_offset: u64 = 0; let mut bss_offset: u64 = 0; - let mut static_var_symbols: HashMap = HashMap::new(); - for StaticVariable { name, global, init } in &program.static_vars { + let mut static_var_symbols: HashMap, SymbolId> = HashMap::new(); + for StaticVariable { + name, + global, + init, + alignment, + } in &program.static_vars + { let sym_id = match init { // Defined variable - allocate storage in .data or .bss VarInit::Defined(init_val) => { - let (offset, section) = if *init_val == 0 { - obj.append_section_bss(bss, 4, 4); - let offset = bss_offset; - bss_offset += 4; - (offset, &bss) - } else { - let init_bytes = init_val.to_le_bytes(); - obj.append_section_data(data, &init_bytes, 4); - let offset = data_offset; - data_offset += 4; - (offset, &data) + let (offset, section) = match init_val { + StaticInt::IntInit(0) | StaticInt::LongInit(0) => { + obj.append_section_bss(bss, *alignment, *alignment); + let offset = bss_offset; + bss_offset += alignment; + (offset, &bss) + } + StaticInt::IntInit(val) => { + let init_bytes = val.to_le_bytes(); + obj.append_section_data(data, &init_bytes, *alignment); + let offset = data_offset; + data_offset += alignment; + (offset, &data) + } + StaticInt::LongInit(val) => { + let init_bytes = val.to_le_bytes(); + obj.append_section_data(data, &init_bytes, *alignment); + let offset = data_offset; + data_offset += alignment; + (offset, &data) + } }; obj.add_symbol(Symbol { name: name.as_bytes().to_vec(), value: offset, - size: 4, + size: *alignment, kind: SymbolKind::Data, scope: if *global { SymbolScope::Dynamic @@ -350,7 +417,7 @@ fn emit_object_with_labels( } // Add external function symbols and relocations - let mut external_symbols: HashMap = HashMap::new(); + let mut external_symbols: HashMap, SymbolId> = HashMap::new(); for (_ins_idx, func_name) in &external_calls { if !external_symbols.contains_key(func_name) { let symbol_id = obj.add_symbol(undefined_symbol(func_name, SymbolKind::Text)); @@ -438,12 +505,12 @@ fn emit_object_with_labels( fn emit_function_body( a: &mut CodeAssembler, fun_def: &codegen::FunctionDefinition, - fn_labels: &HashMap, - data_labels: &HashMap, - external_calls: &mut Vec<(usize, String)>, - data_relocs: &mut Vec<(usize, String)>, - labels: &mut HashMap, - label_idx: &mut HashMap, + fn_labels: &HashMap, CodeLabel>, + data_labels: &HashMap, CodeLabel>, + external_calls: &mut Vec<(usize, Rc)>, + data_relocs: &mut Vec<(usize, Rc)>, + labels: &mut HashMap, CodeLabel>, + label_idx: &mut HashMap>, ) -> Result<(), IcedError> { a.push(gpr64::rbp)?; a.mov(gpr64::rbp, gpr64::rsp)?; @@ -474,6 +541,7 @@ fn gpr32(reg: &Reg) -> AsmRegister32 { SI => registers::gpr32::esi, R8 => registers::gpr32::r8d, R9 => registers::gpr32::r9d, + SP => registers::gpr32::esp, } } @@ -489,14 +557,30 @@ fn gpr64_reg(reg: &Reg) -> AsmRegister64 { SI => gpr64::rsi, R8 => gpr64::r8, R9 => gpr64::r9, + SP => gpr64::rsp, } } -fn mem_rbp(offset: i32) -> AsmMemoryOperand { - if offset >= 0 { - dword_ptr(gpr64::rbp + offset) +/// Constructs a sized memory operand for a stack slot at `[rbp + offset]`. +/// +/// Returns a `dword ptr` (Longword) or `qword ptr` (Quadword) memory reference. +/// Handles negative offsets via subtraction to satisfy iced-x86's operand API. +fn mem_rbp(offset: i32, asm_ty: AssemblyType) -> AsmMemoryOperand { + let pos = if offset >= 0 { + gpr64::rbp + offset } else { - dword_ptr(gpr64::rbp - (-offset)) + gpr64::rbp - (-offset) + }; + match asm_ty { + AssemblyType::Longword => dword_ptr(pos), + AssemblyType::Quadword => qword_ptr(pos), + } +} + +fn make_lbl_ptr(lbl: &CodeLabel, asm_ty: &AssemblyType) -> AsmMemoryOperand { + match asm_ty { + AssemblyType::Longword => dword_ptr(*lbl), + AssemblyType::Quadword => qword_ptr(*lbl), } } @@ -510,224 +594,354 @@ fn mem_rbp(offset: i32) -> AsmMemoryOperand { fn emit_instruction( a: &mut CodeAssembler, ins: &Instruction, - labels: &mut HashMap, - label_idx: &mut HashMap, - fn_labels: &HashMap, - data_labels: &HashMap, - external_calls: &mut Vec<(usize, String)>, - data_relocs: &mut Vec<(usize, String)>, + labels: &mut HashMap, CodeLabel>, + label_idx: &mut HashMap>, + fn_labels: &HashMap, CodeLabel>, + data_labels: &HashMap, CodeLabel>, + external_calls: &mut Vec<(usize, Rc)>, + data_relocs: &mut Vec<(usize, Rc)>, ) -> Result<(), IcedError> { match ins { - Instruction::Mov { src, dst } => match (src, dst) { - (Operand::Imm(v), Operand::Reg(r)) => a.mov(gpr32(r), *v)?, - (Operand::Reg(s), Operand::Reg(d)) => a.mov(gpr32(d), gpr32(s))?, - (Operand::Reg(s), Operand::Stack(off)) => a.mov(mem_rbp(*off), gpr32(s))?, - (Operand::Stack(off), Operand::Reg(d)) => a.mov(gpr32(d), mem_rbp(*off))?, - (Operand::Data(name), Operand::Reg(d)) => { + Instruction::Mov { src, dst, size } => match (src, dst, size) { + (Operand::Imm(v), Operand::Reg(r), AssemblyType::Longword) => a.mov(gpr32(r), *v as i32)?, + (Operand::Imm(v), Operand::Reg(r), AssemblyType::Quadword) => a.mov(gpr64_reg(r), *v)?, + + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.mov(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.mov(gpr64_reg(d), gpr64_reg(s))?, + + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => a.mov(mem_rbp(*off, *size), gpr32(s))?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.mov(mem_rbp(*off, *size), gpr64_reg(s))? + } + + (Operand::Stack(off), Operand::Reg(d), AssemblyType::Longword) => a.mov(gpr32(d), mem_rbp(*off, *size))?, + (Operand::Stack(off), Operand::Reg(d), AssemblyType::Quadword) => { + a.mov(gpr64_reg(d), mem_rbp(*off, *size))? + } + (Operand::Data(name), Operand::Reg(d), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.mov(gpr32(d), dword_ptr(*lbl))? + match size { + AssemblyType::Longword => a.mov(gpr32(d), dword_ptr(*lbl))?, + AssemblyType::Quadword => a.mov(gpr64_reg(d), qword_ptr(*lbl))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.mov(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm to memory is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Stack(off), _) => a.mov(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), size) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.mov(dword_ptr(*lbl), *v)? + a.mov(make_lbl_ptr(lbl, size), *v as i32)? } - (Operand::Reg(s), Operand::Data(name)) => { + + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.mov(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.mov(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.mov(qword_ptr(*lbl), gpr64_reg(s))?, + } } - _ => unreachable!("unsupported mov combination"), + _ => unreachable!("unsupported mov combination: {:?}", ins), }, - Instruction::Unary { op, dst } => match op { - UnaryOp::Neg => match dst { - Operand::Reg(r) => a.neg(gpr32(r))?, - Operand::Stack(off) => a.neg(mem_rbp(*off))?, - Operand::Data(name) => { + Instruction::Movsx { src, dst } => match (src, dst) { + (Operand::Reg(s), Operand::Reg(d)) => a.movsxd(gpr64_reg(d), gpr32(s))?, + (Operand::Stack(off), Operand::Reg(d)) => a.movsxd(gpr64_reg(d), mem_rbp(*off, AssemblyType::Longword))?, + (Operand::Data(name), Operand::Reg(d)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.movsxd(gpr64_reg(d), dword_ptr(*lbl))?; + } + _ => unreachable!("unsupported movsx combination: {:?}", ins), + }, + Instruction::Unary { op, dst, size } => match op { + UnaryOp::Neg => match (dst, size) { + (Operand::Reg(r), AssemblyType::Longword) => a.neg(gpr32(r))?, + (Operand::Reg(r), AssemblyType::Quadword) => a.neg(gpr64_reg(r))?, + (Operand::Stack(off), _) => a.neg(mem_rbp(*off, *size))?, + (Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.neg(dword_ptr(*lbl))? + a.neg(make_lbl_ptr(lbl, size))? } _ => unreachable!(), }, - UnaryOp::Not => match dst { - Operand::Reg(r) => a.not(gpr32(r))?, - Operand::Stack(off) => a.not(mem_rbp(*off))?, - Operand::Data(name) => { + UnaryOp::Not => match (dst, size) { + (Operand::Reg(r), AssemblyType::Longword) => a.not(gpr32(r))?, + (Operand::Reg(r), AssemblyType::Quadword) => a.not(gpr64_reg(r))?, + (Operand::Stack(off), _) => a.not(mem_rbp(*off, *size))?, + (Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.not(dword_ptr(*lbl))? + a.not(make_lbl_ptr(lbl, size))? } _ => unreachable!(), }, }, - Instruction::Binary { op, src, dst } => match op { - BinaryOp::Add => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.add(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.add(gpr32(d), *v)?, - (Operand::Reg(s), Operand::Stack(off)) => a.add(mem_rbp(*off), gpr32(s))?, - (Operand::Reg(s), Operand::Data(name)) => { + Instruction::Binary { op, src, dst, size } => match op { + BinaryOp::Add => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.add(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.add(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.add(gpr32(d), *v as i32)?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => { + a.add(mem_rbp(*off, *size), gpr32(s))? + } + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.add(mem_rbp(*off, *size), gpr64_reg(s))? + } + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.add(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.add(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.add(qword_ptr(*lbl), gpr64_reg(s))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.add(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.add(gpr64_reg(d), *v as i32)?, + (Operand::Imm(v), Operand::Stack(off), _) => a.add(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.add(dword_ptr(*lbl), *v)? + a.add(make_lbl_ptr(lbl, size), *v as i32)? } _ => unreachable!(), }, - BinaryOp::Sub => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.sub(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.sub(gpr32(d), *v)?, - (Operand::Reg(s), Operand::Stack(off)) => a.sub(mem_rbp(*off), gpr32(s))?, - (Operand::Reg(s), Operand::Data(name)) => { + BinaryOp::Sub => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.sub(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.sub(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.sub(gpr32(d), *v as i32)?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => { + a.sub(mem_rbp(*off, *size), gpr32(s))? + } + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.sub(mem_rbp(*off, *size), gpr64_reg(s))? + } + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.sub(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.sub(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.sub(qword_ptr(*lbl), gpr64_reg(s))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.sub(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.sub(gpr64_reg(d), *v as i32)?, + (Operand::Imm(v), Operand::Stack(off), _) => a.sub(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.sub(dword_ptr(*lbl), *v)? + a.sub(make_lbl_ptr(lbl, size), *v as i32)? } _ => unreachable!(), }, - BinaryOp::Mult => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.imul_2(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.imul_3(gpr32(d), gpr32(d), *v)?, - (Operand::Stack(off), Operand::Reg(d)) => a.imul_2(gpr32(d), mem_rbp(*off))?, - (Operand::Data(name), Operand::Reg(d)) => { + BinaryOp::Mult => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.imul_2(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.imul_2(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Stack(off), Operand::Reg(d), AssemblyType::Longword) => { + a.imul_2(gpr32(d), mem_rbp(*off, *size))? + } + (Operand::Stack(off), Operand::Reg(d), AssemblyType::Quadword) => { + a.imul_2(gpr64_reg(d), mem_rbp(*off, *size))? + } + (Operand::Data(name), Operand::Reg(d), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.imul_2(gpr32(d), dword_ptr(*lbl))? + match size { + AssemblyType::Longword => a.imul_2(gpr32(d), dword_ptr(*lbl))?, + AssemblyType::Quadword => a.imul_2(gpr64_reg(d), qword_ptr(*lbl))?, + } + } + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => { + a.imul_3(gpr32(d), gpr32(d), *v as i32)? + } + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => { + a.imul_3(gpr64_reg(d), gpr64_reg(d), *v as i32)? } _ => unreachable!("Mult {:?}, {:?}", src, dst), }, - BinaryOp::BitAnd => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.and(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.and(gpr32(d), *v)?, - (Operand::Reg(s), Operand::Stack(off)) => a.and(mem_rbp(*off), gpr32(s))?, - (Operand::Reg(s), Operand::Data(name)) => { + BinaryOp::BitAnd => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.and(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.and(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.and(gpr32(d), *v as i32)?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.and(gpr64_reg(d), *v as i32)?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => { + a.and(mem_rbp(*off, *size), gpr32(s))? + } + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.and(mem_rbp(*off, *size), gpr64_reg(s))? + } + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.and(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.and(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.and(qword_ptr(*lbl), gpr64_reg(s))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.and(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Stack(off), _) => a.and(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.and(dword_ptr(*lbl), *v)? + a.and(make_lbl_ptr(lbl, size), *v as i32)? } _ => unreachable!(), }, - BinaryOp::BitOr => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.or(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.or(gpr32(d), *v)?, - (Operand::Reg(s), Operand::Stack(off)) => a.or(mem_rbp(*off), gpr32(s))?, - (Operand::Reg(s), Operand::Data(name)) => { + BinaryOp::BitOr => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.or(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.or(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.or(gpr32(d), *v as i32)?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.or(gpr64_reg(d), *v as i32)?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => { + a.or(mem_rbp(*off, *size), gpr32(s))? + } + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.or(mem_rbp(*off, *size), gpr64_reg(s))? + } + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.or(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.or(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.or(qword_ptr(*lbl), gpr64_reg(s))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.or(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Stack(off), _) => a.or(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.or(dword_ptr(*lbl), *v)? + a.or(make_lbl_ptr(lbl, size), *v as i32)? } _ => unreachable!(), }, - BinaryOp::BitXOr => match (src, dst) { - (Operand::Reg(s), Operand::Reg(d)) => a.xor(gpr32(d), gpr32(s))?, - (Operand::Imm(v), Operand::Reg(d)) => a.xor(gpr32(d), *v)?, - (Operand::Reg(s), Operand::Stack(off)) => a.xor(mem_rbp(*off), gpr32(s))?, - (Operand::Reg(s), Operand::Data(name)) => { + BinaryOp::BitXOr => match (src, dst, size) { + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Longword) => a.xor(gpr32(d), gpr32(s))?, + (Operand::Reg(s), Operand::Reg(d), AssemblyType::Quadword) => a.xor(gpr64_reg(d), gpr64_reg(s))?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.xor(gpr32(d), *v as i32)?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.xor(gpr64_reg(d), *v as i32)?, + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Longword) => { + a.xor(mem_rbp(*off, *size), gpr32(s))? + } + (Operand::Reg(s), Operand::Stack(off), AssemblyType::Quadword) => { + a.xor(mem_rbp(*off, *size), gpr64_reg(s))? + } + (Operand::Reg(s), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.xor(dword_ptr(*lbl), gpr32(s))? + match size { + AssemblyType::Longword => a.xor(dword_ptr(*lbl), gpr32(s))?, + AssemblyType::Quadword => a.xor(qword_ptr(*lbl), gpr64_reg(s))?, + } } - (Operand::Imm(v), Operand::Stack(off)) => a.xor(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + + // large imm is rewritten in fix_invalid, downcast is safe + (Operand::Imm(v), Operand::Stack(off), _) => a.xor(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.xor(dword_ptr(*lbl), *v)? + a.xor(make_lbl_ptr(lbl, size), *v as i32)? } _ => unreachable!(), }, - BinaryOp::BitShl => match (src, dst) { - (Operand::Imm(v), Operand::Reg(d)) => a.shl(gpr32(d), *v)?, - (Operand::Reg(Reg::CX), Operand::Reg(d)) => a.shl(gpr32(d), gpr8::cl)?, - (Operand::Imm(v), Operand::Stack(off)) => a.shl(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + BinaryOp::BitShl => match (src, dst, size) { + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.shl(gpr32(d), *v as i32)?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.shl(gpr64_reg(d), *v as i32)?, + (Operand::Reg(Reg::CX), Operand::Reg(d), AssemblyType::Longword) => a.shl(gpr32(d), gpr8::cl)?, + (Operand::Reg(Reg::CX), Operand::Reg(d), AssemblyType::Quadword) => a.shl(gpr64_reg(d), gpr8::cl)?, + (Operand::Imm(v), Operand::Stack(off), _) => a.shl(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.shl(dword_ptr(*lbl), *v)? + a.shl(make_lbl_ptr(lbl, size), *v as i32)? } - (Operand::Reg(Reg::CX), Operand::Stack(off)) => a.shl(mem_rbp(*off), gpr8::cl)?, - (Operand::Reg(Reg::CX), Operand::Data(name)) => { + (Operand::Reg(Reg::CX), Operand::Stack(off), _) => a.shl(mem_rbp(*off, *size), gpr8::cl)?, + (Operand::Reg(Reg::CX), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.shl(dword_ptr(*lbl), gpr8::cl)? + a.shl(make_lbl_ptr(lbl, size), gpr8::cl)? } _ => unreachable!(), }, - BinaryOp::BitSar => match (src, dst) { - (Operand::Imm(v), Operand::Reg(d)) => a.sar(gpr32(d), *v)?, - (Operand::Reg(Reg::CX), Operand::Reg(d)) => a.sar(gpr32(d), cl)?, - (Operand::Imm(v), Operand::Stack(off)) => a.sar(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + BinaryOp::BitSar => match (src, dst, size) { + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Longword) => a.sar(gpr32(d), *v as i32)?, + (Operand::Imm(v), Operand::Reg(d), AssemblyType::Quadword) => a.sar(gpr64_reg(d), *v as i32)?, + (Operand::Reg(Reg::CX), Operand::Reg(d), AssemblyType::Longword) => a.sar(gpr32(d), gpr8::cl)?, + (Operand::Reg(Reg::CX), Operand::Reg(d), AssemblyType::Quadword) => a.sar(gpr64_reg(d), gpr8::cl)?, + (Operand::Imm(v), Operand::Stack(off), _) => a.sar(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.sar(dword_ptr(*lbl), *v)? + a.sar(make_lbl_ptr(lbl, size), *v as i32)? } - (Operand::Reg(Reg::CX), Operand::Stack(off)) => a.sar(mem_rbp(*off), gpr8::cl)?, - (Operand::Reg(Reg::CX), Operand::Data(name)) => { + (Operand::Reg(Reg::CX), Operand::Stack(off), _) => a.sar(mem_rbp(*off, *size), gpr8::cl)?, + (Operand::Reg(Reg::CX), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.sar(dword_ptr(*lbl), gpr8::cl)? + a.sar(make_lbl_ptr(lbl, size), gpr8::cl)? } _ => unreachable!(), }, }, - Instruction::Cmp { v1, v2 } => match (v1, v2) { - (Operand::Reg(r1), Operand::Reg(r2)) => a.cmp(gpr32(r2), gpr32(r1))?, - (Operand::Reg(r1), Operand::Stack(off)) => a.cmp(mem_rbp(*off), gpr32(r1))?, - (Operand::Reg(r1), Operand::Data(name)) => { + Instruction::Cmp { v1, v2, size } => match (v1, v2, size) { + (Operand::Reg(r1), Operand::Reg(r2), AssemblyType::Longword) => a.cmp(gpr32(r2), gpr32(r1))?, + (Operand::Reg(r1), Operand::Reg(r2), AssemblyType::Quadword) => a.cmp(gpr64_reg(r2), gpr64_reg(r1))?, + (Operand::Reg(r1), Operand::Stack(off), AssemblyType::Longword) => { + a.cmp(mem_rbp(*off, *size), gpr32(r1))? + } + (Operand::Reg(r1), Operand::Stack(off), AssemblyType::Quadword) => { + a.cmp(mem_rbp(*off, *size), gpr64_reg(r1))? + } + (Operand::Reg(r1), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.cmp(dword_ptr(*lbl), gpr32(r1))? + match size { + AssemblyType::Longword => a.cmp(dword_ptr(*lbl), gpr32(r1))?, + AssemblyType::Quadword => a.cmp(qword_ptr(*lbl), gpr64_reg(r1))?, + } } - (Operand::Stack(off), Operand::Reg(r)) => a.cmp(gpr32(r), mem_rbp(*off))?, - (Operand::Data(name), Operand::Reg(r)) => { + (Operand::Stack(off), Operand::Reg(r), AssemblyType::Longword) => a.cmp(gpr32(r), mem_rbp(*off, *size))?, + (Operand::Stack(off), Operand::Reg(r), AssemblyType::Quadword) => { + a.cmp(gpr64_reg(r), mem_rbp(*off, *size))? + } + (Operand::Data(name), Operand::Reg(r), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.cmp(gpr32(r), dword_ptr(*lbl))? + match size { + AssemblyType::Longword => a.cmp(gpr32(r), dword_ptr(*lbl))?, + AssemblyType::Quadword => a.cmp(gpr64_reg(r), qword_ptr(*lbl))?, + } } - (Operand::Imm(v), Operand::Reg(r)) => a.cmp(gpr32(r), *v)?, - (Operand::Imm(v), Operand::Stack(off)) => a.cmp(mem_rbp(*off), *v)?, - (Operand::Imm(v), Operand::Data(name)) => { + (Operand::Imm(v), Operand::Reg(r), AssemblyType::Longword) => a.cmp(gpr32(r), *v as i32)?, + (Operand::Imm(v), Operand::Reg(r), AssemblyType::Quadword) => a.cmp(gpr64_reg(r), *v as i32)?, + (Operand::Imm(v), Operand::Stack(off), _) => a.cmp(mem_rbp(*off, *size), *v as i32)?, + (Operand::Imm(v), Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.cmp(dword_ptr(*lbl), *v)? + a.cmp(make_lbl_ptr(lbl, size), *v as i32)? } - _ => unreachable!(), + _ => unreachable!("unsupported cmp combination: v1={:?}, v2={:?}, size={:?}", v1, v2, size), }, - Instruction::Cdq => { - a.cdq()?; - } - Instruction::Idiv(op) => match op { - Operand::Reg(r) => a.idiv(gpr32(r))?, - Operand::Stack(off) => a.idiv(mem_rbp(*off))?, - Operand::Data(name) => { + Instruction::Cdq(size) => match size { + AssemblyType::Longword => a.cdq()?, + AssemblyType::Quadword => a.cqo()?, + }, + Instruction::Idiv(op, size) => match (op, size) { + (Operand::Reg(r), AssemblyType::Longword) => a.idiv(gpr32(r))?, + (Operand::Reg(r), AssemblyType::Quadword) => a.idiv(gpr64_reg(r))?, + (Operand::Stack(off), _) => a.idiv(mem_rbp(*off, *size))?, + (Operand::Data(name), _) => { let lbl = data_labels.get(name).unwrap(); data_relocs.push((a.instructions().len(), name.clone())); - a.idiv(dword_ptr(*lbl))? + a.idiv(make_lbl_ptr(lbl, size))? } _ => unreachable!(), }, @@ -756,12 +970,12 @@ fn emit_instruction( CondCode::LE => a.setle(gpr8::al)?, }, Operand::Stack(off) => match code { - CondCode::E => a.sete(mem_rbp(*off))?, - CondCode::NE => a.setne(mem_rbp(*off))?, - CondCode::G => a.setg(mem_rbp(*off))?, - CondCode::GE => a.setge(mem_rbp(*off))?, - CondCode::L => a.setl(mem_rbp(*off))?, - CondCode::LE => a.setle(mem_rbp(*off))?, + CondCode::E => a.sete(byte_ptr(gpr64::rbp - (-*off)))?, + CondCode::NE => a.setne(byte_ptr(gpr64::rbp - (-*off)))?, + CondCode::G => a.setg(byte_ptr(gpr64::rbp - (-*off)))?, + CondCode::GE => a.setge(byte_ptr(gpr64::rbp - (-*off)))?, + CondCode::L => a.setl(byte_ptr(gpr64::rbp - (-*off)))?, + CondCode::LE => a.setle(byte_ptr(gpr64::rbp - (-*off)))?, }, Operand::Data(name) => { let lbl = data_labels.get(name).unwrap(); @@ -782,21 +996,13 @@ fn emit_instruction( a.set_label(l)?; label_idx.insert(a.instructions().len(), lbl.0.clone()); } - Instruction::AllocateStack(off) => { - if *off != 0 { - a.sub(gpr64::rsp, *off)?; - } - } Instruction::Ret => { a.mov(gpr64::rsp, gpr64::rbp)?; a.pop(gpr64::rbp)?; a.ret()?; } - Instruction::DeallocateStack(off) => { - a.add(gpr64::rsp, *off)?; - } Instruction::Push(op) => match op { - Operand::Imm(c) => a.push(*c)?, + Operand::Imm(c) => a.push(*c as i32)?, // i64 handled in fix_invalid Operand::Reg(reg) => a.push(gpr64_reg(reg))?, Operand::Stack(off) => a.push(qword_ptr(gpr64::rbp - (-*off)))?, Operand::Pseudo(_) | Operand::Data(_) => unreachable!(), diff --git a/src/lexer.rs b/src/lexer.rs index 1437722..1ab1845 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -1,3 +1,30 @@ +//! # Lexer — Source Text to Tokens +//! +//! Converts raw C source text into a stream of [`SpannedToken`]s using regex-based +//! pattern matching with maximal munch disambiguation. +//! +//! ## Technical Approach +//! +//! Token patterns are pre-compiled into regexes at startup via [`LazyLock`] and anchored +//! with `^` so they match only at the current scan position. On each iteration the lexer +//! tries every pattern, collects all matches, and picks the longest (maximal munch). +//! This avoids keyword/identifier ambiguity (e.g. `int` vs `integer`) without reserved-word +//! tables. +//! +//! ## What This Pass Accomplishes +//! +//! - Strips comments (`//`, `/* */`, `#` line directives) +//! - Produces a [`VecDeque`] carrying line/column [`Span`]s for error reporting +//! - Detects lexer errors (unexpected characters, unterminated comments) and exits with code 10 +//! - Promotes integer literals with an `L`/`l` suffix to [`Token::ConstantLong`] +//! +//! ## Call Order +//! +//! ```text +//! tokenizer() — public entry point, drives the scan loop +//! └─ next_token() — tries all TOKEN_DEFS, returns longest match +//! ``` + // todo: we should stream tokens to parser in a future refactor use colored::*; use regex::Regex; @@ -9,6 +36,7 @@ use std::sync::LazyLock; pub enum Token { Identifier(String), ConstantInt(String), + ConstantLong(String), IntKeyword, // int VoidKeyword, // void ReturnKeyword, // return @@ -66,12 +94,14 @@ pub enum Token { Comma, // , StaticKeyword, // static ExternKeyword, // extern + LongKeyword, // long } const TOKEN_PATTERNS: &[(&str, Token)] = &[ // Special handling tokens (handled differently in next_token) (r"^[a-zA-Z_]\w*\b", Token::Identifier(String::new())), (r"^[0-9]+\b", Token::ConstantInt(String::new())), + (r"^[0-9]++[lL]\b", Token::ConstantLong(String::new())), // Keywords (r"^int\b", Token::IntKeyword), (r"^void\b", Token::VoidKeyword), @@ -137,6 +167,7 @@ const TOKEN_PATTERNS: &[(&str, Token)] = &[ (r"^case\b", Token::CaseKeyword), (r"^static\b", Token::StaticKeyword), (r"^extern\b", Token::ExternKeyword), + (r"^long\b", Token::LongKeyword), ]; static TOKEN_DEFS: LazyLock, fn() -> Vec> = LazyLock::new(|| { @@ -201,6 +232,10 @@ fn next_token(input: &str, span: Span) -> Result { let token = match variant { Token::Identifier(_) => Token::Identifier(mat.as_str().to_string()), Token::ConstantInt(_) => Token::ConstantInt(mat.as_str().to_string()), + Token::ConstantLong(_) => { + let s = mat.as_str(); + Token::ConstantLong(s[..s.len() - 1].to_string()) + } other => other.clone(), }; matches.push(TokenMatch { diff --git a/src/main.rs b/src/main.rs index d7afa4c..ae1f394 100644 --- a/src/main.rs +++ b/src/main.rs @@ -289,27 +289,25 @@ fn main() { std::process::exit(0); } - let mut ast = ast; - let validated_result = validate::resolve_program(&mut ast).unwrap_or_else(|e| { + let validated_result = validate::resolve_program(ast).unwrap_or_else(|e| { eprintln!("{e:?}"); std::process::exit(30); }); + let (mut name_gen, typed_program, symbols) = validated_result; + if args.validate { - println!("Program Valid"); - println!("{}", ast.itf_string()); + println!("{}", typed_program.itf_string()); std::process::exit(0); } - - let (mut name_gen, symbols) = validated_result; - let tacky_ast = tacky::tackify_program(&ast, &mut name_gen, &symbols); + let tacky_ast = tacky::tackify_program(typed_program, &mut name_gen, &symbols); if args.tacky { println!("{}", tacky_ast.itf_string()); std::process::exit(0); } - let code_ast = codegen::generate(&tacky_ast); + let (code_ast, _backend_symbols) = codegen::generate(tacky_ast, &symbols); if args.codegen { println!("{}", code_ast.itf_string()); std::process::exit(0); @@ -361,16 +359,20 @@ fn main() { if defined_vars.peek().is_some() { println!(); for (sv, init_val) in defined_vars { - let section = if init_val == 0 { ".bss" } else { ".data" }; + let is_zero = matches!( + init_val, + validate::StaticInt::IntInit(0) | validate::StaticInt::LongInit(0) + ); + let section = if is_zero { ".bss" } else { ".data" }; println!("{}", section.cyan()); if sv.global { println!(" {}", format!(".globl {}", sv.name).dimmed()); } println!("{}:", sv.name.green()); - if init_val == 0 { + if is_zero { println!(" {}", ".zero 4".yellow()); } else { - println!(" {} {}", ".long".yellow(), init_val.to_string().cyan()); + println!(" {} {:?}", ".long".yellow(), init_val); } } } @@ -399,15 +401,14 @@ fn main() { std::process::exit(20) }); - let mut ast = ast; - let validated_result = validate::resolve_program(&mut ast).unwrap_or_else(|e| { + let validated_result = validate::resolve_program(ast).unwrap_or_else(|e| { eprintln!("{e:?}"); std::process::exit(30); }); - let (mut name_gen, symbols) = validated_result; - let tacky_ast = tacky::tackify_program(&ast, &mut name_gen, &symbols); - let code_ast = codegen::generate(&tacky_ast); + let (mut name_gen, typed_program, symbols) = validated_result; + let tacky_ast = tacky::tackify_program(typed_program, &mut name_gen, &symbols); + let (code_ast, _backend_symbols) = codegen::generate(tacky_ast, &symbols); let path = Path::new(c_file); let obj_file = path.with_extension("o").to_string_lossy().to_string(); @@ -417,7 +418,11 @@ fn main() { let asm_file = path.with_extension("s").to_string_lossy().to_string(); fs::write(&asm_file, asm).expect("Failed to write assembly file"); - let status = std::process::Command::new("as") + let mut cmd = std::process::Command::new("as"); + // On arm64 hosts the system assembler must be told to target x86_64. + #[cfg(target_arch = "aarch64")] + cmd.args(["-arch", "x86_64"]); + let status = cmd .arg(&asm_file) .arg("-o") .arg(&obj_file) @@ -442,7 +447,11 @@ fn main() { let path = Path::new(asm_file); let obj_file = path.with_extension("o").to_string_lossy().to_string(); - let status = std::process::Command::new("as") + let mut cmd = std::process::Command::new("as"); + // On arm64 hosts the system assembler must be told to target x86_64. + #[cfg(target_arch = "aarch64")] + cmd.args(["-arch", "x86_64"]); + let status = cmd .arg(asm_file) .arg("-o") .arg(&obj_file) diff --git a/src/parser.rs b/src/parser.rs index c543767..6348259 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,23 +1,49 @@ -//! Parser for a subset of C using recursive descent with operator precedence climbing. +//! # Parser — Tokens to Untyped AST //! -//! The parser combines recursive descent for statement and declaration parsing with -//! precedence climbing for expression parsing. This hybrid approach provides good -//! performance while keeping the implementation straightforward. +//! Recursive descent parser with precedence climbing for expressions. +//! Consumes a [`VecDeque`] and produces an untyped AST ([`Program`]). //! -//! # Architecture +//! ## Technical Approach //! -//! - [`parse_factor`] handles primary expressions and unary operators -//! - [`parse_exp`] handles binary operators using precedence climbing -//! - Assignment operators are treated as binary operators for parsing simplicity -//! but generate distinct AST nodes +//! Statements, declarations, and top-level structure use classic recursive descent. +//! Expressions use Pratt-style precedence climbing ([`parse_exp`]) with a minimum +//! precedence parameter, which naturally handles left-associativity and precedence +//! without separate functions per level. Assignment and compound-assignment operators +//! are parsed as right-associative binary operators but produce distinct AST nodes. +//! +//! ## What This Pass Accomplishes +//! +//! - Builds a complete untyped AST: declarations, statements, and expressions +//! - Validates syntactic structure (balanced braces, expected semicolons, etc.) +//! - Resolves type specifier combinations order-independently (`long int` == `int long`) +//! - Separates storage-class specifiers (`static`, `extern`) from type specifiers +//! - Detects syntactic errors and exits with code 20 +//! +//! ## Call Order +//! +//! ```text +//! parse_program() — public entry point +//! ├─ parse_declaration() — try declaration first (type specifier lookahead) +//! │ ├─ parse_type_and_storage_class() +//! │ ├─ parse_function_params() — if '(' follows identifier +//! │ └─ parse_exp() — variable initializer +//! └─ parse_statement() — if not a declaration +//! ├─ parse_exp() — expression statements, conditions +//! │ ├─ parse_factor() — literals, unary, casts, postfix, calls +//! │ │ └─ parse_constant() — int/long literal with overflow promotion +//! │ └─ parse_exp() (recursive) — binary operators via precedence climbing +//! └─ parse_block_item() — compound statements (recursive) +//! ``` //! use crate::lexer::{Span, SpannedToken, Token}; use colored::*; -use std::collections::{HashSet, VecDeque}; +use std::collections::VecDeque; use std::fmt; +use std::hash::Hash; +use std::rc::Rc; -#[derive(Clone, Debug, PartialEq)] -pub struct Identifier(pub String); +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Identifier(pub Rc); impl fmt::Display for Identifier { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -26,14 +52,14 @@ impl fmt::Display for Identifier { } } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum UnaryOp { BitwiseComplement, Negate, Not, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum AssignOp { Add, Subtract, @@ -70,10 +96,11 @@ impl From<&Token> for AssignOp { #[derive(Clone, Debug, PartialEq)] pub enum Expr { - Constant(i32), + Constant(Const), Var(Identifier, Span), + Cast(Type, Box), Unary(UnaryOp, Box), - Binary(BinOp, Box, Box), + Binary(BinOp, Box, Box, Span), Assignment(Box, Box, Span), CompoundAssignment(AssignOp, Box, Box, Span), PostFixOp(IncDec, Box, Span), @@ -82,13 +109,19 @@ pub enum Expr { FunctionCall(Identifier, Vec, Span), } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Const { + ConstInt(i32), + ConstLong(i64), +} + +#[derive(Clone, Copy, Debug, PartialEq)] pub enum IncDec { Increment, Decrement, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub enum BinOp { Subtract, Add, @@ -133,13 +166,48 @@ impl BinOp { } } -#[derive(Eq, Hash, PartialEq, Debug, Clone)] +/// Represents case label values in switch statements. +/// +/// # Duplicate Case Detection +/// +/// In C, case labels are compared by their numeric value after conversion to the +/// switch expression's type. This implementation normalizes case values using the +/// `as_i64` method during semantic analysis to properly handle overflow/truncation: +/// +/// ```c +/// switch (x) { // x is int +/// case 0: return 0; +/// case 17179869184: return 1; // 2^34 truncates to 0 - detected as duplicate +/// } +/// ``` +#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum SwitchIntType { Int(i32), + Long(i64), Default, } impl SwitchIntType { + /// Normalize case value to the switch expression's type. + /// + /// This handles overflow/truncation when the case constant's type differs + /// from the switch expression's type. Used during semantic analysis for + /// duplicate case detection. + pub fn as_i64(&self, switch_type: &Type) -> Option { + match self { + SwitchIntType::Int(v) => match switch_type { + Type::Int | Type::Long => Some(*v as i64), + Type::FunType { .. } => unreachable!("Cannot switch on function type"), + }, + SwitchIntType::Long(v) => match switch_type { + Type::Int => Some((*v as i32) as i64), // Truncate to int, then extend + Type::Long => Some(*v), + Type::FunType { .. } => unreachable!("Cannot switch on function type"), + }, + SwitchIntType::Default => None, + } + } + pub fn label_str(&self, switch_num: u64) -> String { match self { SwitchIntType::Int(val) => { @@ -150,6 +218,14 @@ impl SwitchIntType { format!("switch.{switch_num}_case.neg{c_str}") } } + SwitchIntType::Long(val) => { + if *val >= 0 { + format!("switch.{switch_num}_case.{val}L") + } else { + let c_str = &val.to_string()[1..]; + format!("switch.{switch_num}_case.neg{c_str}L") + } + } SwitchIntType::Default => { format!("switch.{switch_num}_default") } @@ -157,6 +233,28 @@ impl SwitchIntType { } } +#[derive(Clone, PartialEq, Debug)] +#[allow(clippy::enum_variant_names)] // `FunType` reads clearly despite the `Type` suffix +pub enum Type { + Int, + Long, + FunType { + params: Vec, + ret: Box, + defined: bool, + }, +} + +impl Type { + pub fn get_1(&self) -> Const { + match self { + Type::Int => Const::ConstInt(1), + Type::Long => Const::ConstLong(1), + Type::FunType { .. } => unreachable!("Cannot increment function type"), + } + } +} + #[derive(Debug, Clone)] pub struct SpannedStmt { pub stmt: Stmt, @@ -175,7 +273,7 @@ pub enum Stmt { While(Expr, Box, u64), // while(condition, body, label) DoWhile(Box, Expr, u64), // dowhile(body, condition, label) For(ForInit, Option, Option, Box, u64), // for(init, condition, post, body, label) - Switch(Expr, Box, u64, HashSet), + Switch(Expr, Box, u64, Vec<(SwitchIntType, Span)>), Case(Expr, Box, Identifier), Default(Box, Identifier), Null, @@ -193,14 +291,11 @@ pub enum StorageClass { Extern, } -enum TypeClass { - Int, -} - #[derive(PartialEq, Clone)] pub struct VarDeclaration { pub name: Identifier, pub init: Option, + pub var_type: Type, pub storage_class: Option, pub span: Span, } @@ -210,6 +305,7 @@ pub struct FunDeclaration { pub name: Identifier, pub params: Vec, pub body: Option, + pub fun_type: Type, pub storage_class: Option, pub span: Span, } @@ -327,33 +423,61 @@ fn expect(expected: &Token, tokens: &mut VecDeque) -> Result Result { + match &token.token { + Token::ConstantInt(value_str) => match value_str.parse::() { + Ok(val) => Ok(Expr::Constant(Const::ConstInt(val))), + Err(_) => parse_constant(&SpannedToken { + token: Token::ConstantLong(value_str.clone()), + span: token.span, + }), + }, + Token::ConstantLong(value_str) => match value_str.parse::() { + Ok(val) => Ok(Expr::Constant(Const::ConstLong(val))), + Err(_) => Err(SyntaxError::with_span( + format!("Integer constant '{}' does not fit in 64-bit int", value_str.bold()), + Some(token.span), + )), + }, + _ => unreachable!(), + } +} + /// Parses primary expressions and operators with precedence higher than any binary operator. /// /// Handles: /// - Constants and identifiers /// - Prefix unary operators (`-`, `~`, `!`, `++`, `--`) -/// - Parenthesized expressions +/// - Cast expressions (`(type) expr`) +/// - Parenthesized expressions (`(expr)`) /// - Postfix operators (`++`, `--`) +/// - Function calls /// /// # Implementation Notes /// +/// **Cast vs Parenthesized Expression:** +/// When encountering `(`, the parser looks ahead to distinguish between casts and +/// parenthesized expressions. If type keywords follow, it's a cast; otherwise, it's +/// a parenthesized expression. Crucially: +/// - Casts call `parse_factor` for their operand (unary precedence, e.g., `(int) -x`) +/// - Parenthesized expressions call `parse_exp` (can contain binary operators, e.g., `(a + b)`) +/// +/// **Postfix operators:** /// Postfix operators are parsed in a loop after the primary expression to handle /// cases like `x++++` (though this would fail validation). The loop structure -/// also makes it easy to extend with other postfix operators like array subscripts -/// or function calls in the future. +/// also makes it easy to extend with other postfix operators like array subscripts. fn parse_factor(tokens: &mut VecDeque) -> Result { let next_token = tokens.front().cloned(); let mut expr = match next_token { Some(ref spanned) => match &spanned.token { - Token::ConstantInt(value_str) => { + Token::ConstantInt(_) | Token::ConstantLong(_) => { tokens.pop_front(); - match value_str.parse::() { - Ok(val) => Ok(Expr::Constant(val)), - Err(_) => Err(SyntaxError::with_span( - format!("Integer constant '{}' does not fit in 32-bit int", value_str.bold()), - Some(spanned.span), - )), - } + parse_constant(spanned) } Token::Negation => { // simply treating negation as an unop cases a panic when unwrapping int min @@ -388,9 +512,24 @@ fn parse_factor(tokens: &mut VecDeque) -> Result { tokens.pop_front(); - let inner_exp = parse_exp(tokens, 0)?; - expect(&Token::CloseParen, tokens)?; - Ok(inner_exp) + let mut type_specifiers = vec![]; + while matches!( + tokens.front().map(|t| &t.token), + Some(Token::LongKeyword | Token::IntKeyword) + ) { + type_specifiers.push(tokens.front().unwrap().token.clone()); + tokens.pop_front(); + } + if !type_specifiers.is_empty() { + let cast_type = parse_type(&type_specifiers, &Some(spanned.span))?; + expect(&Token::CloseParen, tokens)?; + let inner_exp = parse_factor(tokens)?; + Ok(Expr::Cast(cast_type, Box::from(inner_exp))) + } else { + let inner_exp = parse_exp(tokens, 0)?; + expect(&Token::CloseParen, tokens)?; + Ok(inner_exp) + } } Token::Identifier(name) => { tokens.pop_front(); @@ -399,9 +538,13 @@ fn parse_factor(tokens: &mut VecDeque) -> Result, min_prec: u64) -> Result { - tokens.pop_front(); + let span = tokens.pop_front().unwrap().span; let right = parse_exp(tokens, prec + 1)?; - left = Expr::Binary(operator, Box::from(left), Box::from(right)); + left = Expr::Binary(operator, Box::from(left), Box::from(right), span); } } } else { @@ -488,22 +631,37 @@ fn parse_exp(tokens: &mut VecDeque, min_prec: u64) -> Result, err_span: &Option) -> Result { + match specifier_list.as_slice() { + [Token::IntKeyword] => Ok(Type::Int), + [Token::LongKeyword] | [Token::IntKeyword, Token::LongKeyword] | [Token::LongKeyword, Token::IntKeyword] => { + Ok(Type::Long) + } + [] => Err(SyntaxError::with_span("Missing type specifier".to_string(), *err_span)), + _ => Err(SyntaxError::with_span( + "Invalid type specifier combination".to_string(), + *err_span, + )), + } +} + +/// Splits a declaration's specifier list into a `Type` and an optional `StorageClass`. +/// +/// Separates type specifiers (`int`, `long`) from storage-class specifiers (`static`, `extern`), +/// then delegates to `parse_type` for type resolution. Errors on duplicate storage classes. fn parse_type_and_storage_class( specifier_list: &Vec, -) -> Result<(TypeClass, Option), SyntaxError> { - let mut type_specifier = None; +) -> Result<(Type, Option), SyntaxError> { + let mut types = Vec::new(); let mut storage_class = None; for token in specifier_list { match token.token { - Token::IntKeyword => { - if type_specifier.is_none() { - type_specifier = Some(TypeClass::Int); - } else { - return Err(SyntaxError::with_span( - "Duplicate type specifier".to_string(), - Option::from(token.span), - )); - } + Token::IntKeyword | Token::LongKeyword => { + types.push(token.token.clone()); } Token::StaticKeyword | Token::ExternKeyword => { let sc = if token.token == Token::StaticKeyword { @@ -523,11 +681,8 @@ fn parse_type_and_storage_class( _ => unreachable!("Already matched on type specifier"), } } - if let Some(type_specifier) = type_specifier { - Ok((type_specifier, storage_class)) - } else { - Err(SyntaxError::with_span("Missing type specifier".to_string(), None)) - } + let err_span = specifier_list.first().map(|s| s.span); + Ok((parse_type(&types, &err_span)?, storage_class)) } fn parse_conditional_middle(tokens: &mut VecDeque) -> Result { @@ -590,7 +745,7 @@ fn parse_identifier(tokens: &mut VecDeque) -> Result<(Identifier, Some(SpannedToken { token: Token::Identifier(value), span, - }) => Ok((Identifier(value), span)), + }) => Ok((Identifier(Rc::from(value)), span)), x => Err(SyntaxError::new(Some(Token::Identifier("whatever".to_string())), x)), } } @@ -639,7 +794,7 @@ fn parse_statement(tokens: &mut VecDeque) -> Result { // Check if it's a label (identifier followed by colon) if tokens.get(1).map(|t| &t.token) == Some(&Token::Colon) { - let label = Identifier(label_name); + let label = Identifier(Rc::from(label_name)); let span = tokens.pop_front().unwrap().span; // consume identifier tokens.pop_front(); // consume colon declaration_check(tokens)?; @@ -666,7 +821,7 @@ fn parse_statement(tokens: &mut VecDeque) -> Result) -> Result) -> Result) -> Result) -> Result) -> Result {} Stmt::Compound(block) => { if let Some(BlockItem::Statement(s)) = block.first() { - switch_unreachable_check(s) + warn_switch_unreachable(s) } } _ => eprintln!( @@ -788,8 +945,15 @@ fn switch_unreachable_check(stmt: &SpannedStmt) { } } +/// Guards against declarations appearing where only statements are allowed. +/// +/// Peeks at the next token and returns an error if it starts a declaration (type or +/// storage-class keyword). Used after labels, where C requires a statement, not a declaration. fn declaration_check(tokens: &VecDeque) -> Result<(), SyntaxError> { - if tokens.front().map(|t| &t.token) == Some(&Token::IntKeyword) { + if matches!( + tokens.front().map(|t| &t.token), + Some(&Token::IntKeyword | &Token::LongKeyword | &Token::StaticKeyword | &Token::ExternKeyword) + ) { Err(SyntaxError::with_span( "A label can only be part of a statement and a declaration is not a statement. Add a statement or ';' before the declaration.".to_string(), Some(tokens.front().unwrap().span), @@ -822,7 +986,7 @@ fn parse_declaration( let mut specifier_list = Vec::new(); while let Some(front) = tokens.front() { match front.token { - Token::IntKeyword | Token::StaticKeyword | Token::ExternKeyword => { + Token::IntKeyword | Token::StaticKeyword | Token::ExternKeyword | Token::LongKeyword => { specifier_list.push(tokens.pop_front().unwrap()); } _ => break, @@ -831,21 +995,27 @@ fn parse_declaration( if specifier_list.is_empty() { return Ok(None); // no declaration } - let (_type_class, storage_class) = parse_type_and_storage_class(&specifier_list)?; + let (type_class, storage_class) = parse_type_and_storage_class(&specifier_list)?; let (name, span) = parse_identifier(tokens)?; if let Some(front) = tokens.front() { if tokens.front().map(|t| &t.token) == Some(&Token::OpenParen) { // function declaration tokens.pop_front(); - let params = parse_function_params(tokens, &Some(span))?; + let (params, types) = parse_function_params(tokens, &Some(span))?; let body = parse_function_body(tokens)?; + let defined = body.is_some(); Ok(Some(Declaration::FunDeclaration(FunDeclaration { name, params, body, + fun_type: Type::FunType { + params: types, + ret: Box::from(type_class), + defined, + }, storage_class, span, }))) @@ -859,6 +1029,7 @@ fn parse_declaration( Ok(Some(Declaration::VarDeclaration(VarDeclaration { name, init, + var_type: type_class, storage_class, span, }))) @@ -886,11 +1057,16 @@ fn parse_arg_comma(tokens: &mut VecDeque) -> Result<(), SyntaxErro Ok(()) } +/// Parses a function's parameter list (after the opening parenthesis). +/// +/// Handles `void` for no parameters, or a comma-separated list of typed parameters. +/// Consumes the closing `)`. Returns parallel vecs of parameter names and their types. fn parse_function_params( tokens: &mut VecDeque, err_span: &Option, -) -> Result, SyntaxError> { +) -> Result<(Vec, Vec), SyntaxError> { let mut params = vec![]; + let mut types = vec![]; if let Some(front) = tokens.front().cloned() { if front.token == Token::VoidKeyword { tokens.pop_front(); @@ -899,14 +1075,31 @@ fn parse_function_params( if tokens.front().map(|t| &t.token) == Some(&Token::CloseParen) { break; } - expect(&Token::IntKeyword, tokens)?; + let mut type_tokens = Vec::new(); + while let Some(front) = tokens.front() { + match front.token { + Token::IntKeyword | Token::LongKeyword => { + type_tokens.push(front.token.clone()); + tokens.pop_front(); + } + _ => break, + } + } + let err_span = tokens.front().map(|t| t.span); + if type_tokens.is_empty() { + return Err(SyntaxError::with_span( + "Expected type specifier in function parameter".to_string(), + err_span, + )); + } + types.push(parse_type(&type_tokens, &err_span)?); let (name, _span) = parse_identifier(tokens)?; params.push(name.clone()); parse_arg_comma(tokens)?; } } expect(&Token::CloseParen, tokens)?; - Ok(params) + Ok((params, types)) } else { Err(SyntaxError::with_span( "EOF when parsing function parameters".to_string(), diff --git a/src/pretty.rs b/src/pretty.rs index 1250027..0d9aad4 100644 --- a/src/pretty.rs +++ b/src/pretty.rs @@ -3,16 +3,21 @@ use std::fmt; use colored::Colorize; use crate::codegen::{ - BinaryOp, CondCode, FunctionDefinition as CodegenFunctionDefinition, Instruction as CodegenInstruction, Operand, - Program as CodegenProgram, Reg, UnaryOp, + AssemblyType, BinaryOp, CondCode, FunctionDefinition as CodegenFunctionDefinition, + Instruction as CodegenInstruction, Operand, Program as CodegenProgram, Reg, UnaryOp, }; use crate::parser::{ - AssignOp, BinOp as ParserBinOp, BlockItem, Declaration, Expr, ForInit, FunDeclaration, Identifier, IncDec, - Program as ParserProgram, SpannedStmt, Stmt, UnaryOp as ParserUnaryOp, VarDeclaration, + AssignOp, BinOp as ParserBinOp, BlockItem, Const, Declaration, Expr, ForInit, FunDeclaration, Identifier, IncDec, + Program as ParserProgram, SpannedStmt, Stmt, StorageClass, SwitchIntType, Type, UnaryOp as ParserUnaryOp, + VarDeclaration, }; use crate::tacky::{ BinOp, FunctionDefinition as TackyFunctionDefinition, Instruction as TackyInstruction, Program as TackyProgram, - StaticVariable, TopLevel, Val, VarInit, + StaticVariable, Val, VarInit, +}; +use crate::validate::{ + BlockItem as ValidatedBlockItem, Expr as ValidatedExpr, ForInit as ValidatedForInit, Stmt as ValidatedStmt, + TypedDeclaration, TypedExpression, TypedFunction, TypedProgram, TypedVarDeclaration, }; // ============================================================================= @@ -158,12 +163,29 @@ colored_node!( // TACKY function definition - compact format impl ItfDisplay for TackyFunctionDefinition { fn itf_node(&self) -> Node { + let global_str = if self.global { + String::new() + } else { + format!(", {}", "local".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2)) + }; + let params_str = if self.params.is_empty() { + String::new() + } else { + let names: Vec = self + .params + .iter() + .map(|p| p.0.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string()) + .collect(); + format!("({})", names.join(", ")) + }; let body_children: Vec = self.body.iter().map(|i| i.itf_node()).collect(); Node::branch( format!( - "{}: {}", + "{}: {}{}{}", "FunctionDefinition".truecolor(TEAL.0, TEAL.1, TEAL.2), - self.name + self.name.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2), + params_str, + global_str ), body_children, ) @@ -173,34 +195,32 @@ impl ItfDisplay for TackyFunctionDefinition { // Codegen function definition - compact format impl ItfDisplay for CodegenFunctionDefinition { fn itf_node(&self) -> Node { + let global_str = if self.global { + String::new() + } else { + format!(", {}", "local".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2)) + }; let body_children: Vec = self.body.iter().map(|i| i.itf_node()).collect(); Node::branch( format!( - "{}: {}", + "{}: {}{}", "FunctionDefinition".truecolor(TEAL.0, TEAL.1, TEAL.2), - self.name + self.name.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2), + global_str ), body_children, ) } } -// Macro for types with `top_level` field (Program pattern) -macro_rules! impl_program { - ($($ty:ty),* $(,)?) => { - $( - impl ItfDisplay for $ty { - fn itf_node(&self) -> Node { - let children: Vec = self.top_level.iter().map(|t| t.itf_node()).collect(); - Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) - } - } - )* - }; +impl ItfDisplay for TackyProgram { + fn itf_node(&self) -> Node { + let mut children: Vec = self.function_defs.iter().map(|f| f.itf_node()).collect(); + children.extend(self.static_vars.iter().map(|v| v.itf_node())); + Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) + } } -impl_program!(TackyProgram); - impl ItfDisplay for CodegenProgram { fn itf_node(&self) -> Node { let mut children: Vec = self.functions.iter().map(|f| f.itf_node()).collect(); @@ -234,10 +254,6 @@ delegate_variants!(Declaration { FunDeclaration }); delegate_variants!(BlockItem { Statement, Declaration }); -delegate_variants!(TopLevel { - Function, - StaticVariable -}); // Macro for wrapper types that delegate to a single field macro_rules! delegate_field { @@ -318,20 +334,67 @@ impl ItfDisplay for Identifier { } } +impl ItfDisplay for Type { + fn itf_node(&self) -> Node { + match self { + Type::Int => Node::leaf("Int".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string()), + Type::Long => Node::leaf("Long".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string()), + Type::FunType { params, ret, .. } => { + let param_types: Vec = params.iter().map(|t| t.itf_node()).collect(); + let mut children = vec![Node::branch("return:", vec![ret.itf_node()])]; + if !param_types.is_empty() { + children.push(Node::branch("params:", param_types)); + } + Node::branch( + "FunType".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string(), + children, + ) + } + } + } +} + +impl ItfDisplay for StorageClass { + fn itf_node(&self) -> Node { + let label = match self { + StorageClass::Static => "static", + StorageClass::Extern => "extern", + }; + Node::leaf( + format!("storage_class: {}", label) + .truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2) + .to_string(), + ) + } +} + impl ItfDisplay for Expr { fn itf_node(&self) -> Node { match self { - Expr::Constant(c) => Node::leaf( - format!("Constant({c})") - .truecolor(YELLOW_GOLD.0, YELLOW_GOLD.1, YELLOW_GOLD.2) - .to_string(), - ), + Expr::Constant(c) => { + let value_str = match c { + Const::ConstInt(val) => format!("Int({})", val), + Const::ConstLong(val) => format!("Long({})", val), + }; + Node::leaf( + format!("Constant({})", value_str) + .truecolor(YELLOW_GOLD.0, YELLOW_GOLD.1, YELLOW_GOLD.2) + .to_string(), + ) + } Expr::Var(id, _span) => id.itf_node(), + Expr::Cast(target_type, e) => Node::branch( + "Cast".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![ + Node::branch("target_type:", vec![target_type.itf_node()]), + Node::branch("expr:", vec![e.itf_node()]), + ], + ), Expr::Unary(op, e) => Node::branch( format!("Unary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), vec![e.itf_node()], ), - Expr::Binary(op, e1, e2) => Node::branch( + Expr::Binary(op, e1, e2, _span) => Node::branch( format!("Binary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), vec![e1.itf_node(), e2.itf_node()], ), @@ -487,17 +550,36 @@ impl ItfDisplay for Stmt { children, ) } - Stmt::Switch(expr, body, label, _) => Node::branch( - format!( - "{} [label: {}]", - "Switch".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), - label - ), - vec![ + Stmt::Switch(expr, body, label, cases) => { + let cases_str = cases + .iter() + .map(|(c, _span)| match c { + SwitchIntType::Int(v) => format!("{v}"), + SwitchIntType::Long(v) => format!("{v}L"), + SwitchIntType::Default => "default".to_string(), + }) + .collect::>() + .join(", "); + let mut children = vec![ Node::branch("expr:", vec![expr.itf_node()]), Node::branch("body:", vec![body.stmt.itf_node()]), - ], - ), + ]; + if !cases.is_empty() { + children.push(Node::leaf( + format!("cases: [{}]", cases_str) + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + )); + } + Node::branch( + format!( + "{} [label: {}]", + "Switch".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + children, + ) + } Stmt::Case(expr, stmt, label) => { let header = if label.0.is_empty() { "Case".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string() @@ -536,26 +618,29 @@ impl ItfDisplay for Stmt { impl ItfDisplay for VarDeclaration { fn itf_node(&self) -> Node { - let name_node = Node::leaf(format!("name: {}", self.name.itf_node().text)); - match &self.init { - Some(init_expr) => { - let init_node = Node::branch("init:", vec![init_expr.itf_node()]); - Node::branch( - "VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), - vec![name_node, init_node], - ) - } - None => Node::branch( - "VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), - vec![name_node], - ), + let mut children = vec![ + Node::leaf(format!("name: {}", self.name.itf_node().text)), + Node::branch("type:", vec![self.var_type.itf_node()]), + ]; + if let Some(sc) = &self.storage_class { + children.push(sc.itf_node()); + } + if let Some(init_expr) = &self.init { + children.push(Node::branch("init:", vec![init_expr.itf_node()])); } + Node::branch("VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } impl ItfDisplay for FunDeclaration { fn itf_node(&self) -> Node { - let mut children = vec![Node::leaf(format!("name: {}", self.name.itf_node().text))]; + let mut children = vec![ + Node::leaf(format!("name: {}", self.name.itf_node().text)), + Node::branch("type:", vec![self.fun_type.itf_node()]), + ]; + if let Some(sc) = &self.storage_class { + children.push(sc.itf_node()); + } if !self.params.is_empty() { let param_nodes: Vec = self.params.iter().map(|p| p.itf_node()).collect(); children.push(Node::branch("params:", param_nodes)); @@ -568,6 +653,345 @@ impl ItfDisplay for FunDeclaration { } } +// ============================================================================= +// Validated (typed) AST types +// ============================================================================= + +impl ItfDisplay for TypedProgram { + fn itf_node(&self) -> Node { + let children: Vec = self.declarations.iter().map(|d| d.itf_node()).collect(); + Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) + } +} + +impl ItfDisplay for TypedDeclaration { + fn itf_node(&self) -> Node { + match self { + TypedDeclaration::Function(f) => f.itf_node(), + TypedDeclaration::Variable(v) => v.itf_node(), + } + } +} + +impl ItfDisplay for TypedFunction { + fn itf_node(&self) -> Node { + let global_str = if self.global { + String::new() + } else { + format!(", {}", "local".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2)) + }; + let mut children = vec![ + Node::leaf(format!("name: {}", self.name.itf_node().text)), + Node::branch("type:", vec![self.fun_type.itf_node()]), + ]; + if !self.params.is_empty() { + let param_nodes: Vec = self.params.iter().map(|p| p.itf_node()).collect(); + children.push(Node::branch("params:", param_nodes)); + } + if let Some(body) = &self.body { + let body_nodes: Vec = body.iter().map(|b| b.itf_node()).collect(); + children.push(Node::branch("body:", body_nodes)); + } + Node::branch( + format!("{}{}", "FunDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2), global_str), + children, + ) + } +} + +impl ItfDisplay for TypedVarDeclaration { + fn itf_node(&self) -> Node { + let mut children = vec![ + Node::leaf(format!("name: {}", self.name.itf_node().text)), + Node::branch("type:", vec![self.var_type.itf_node()]), + ]; + if let Some(sc) = &self.storage_class { + children.push(sc.itf_node()); + } + if let Some(init_expr) = &self.init { + children.push(Node::branch("init:", vec![init_expr.itf_node()])); + } + Node::branch("VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) + } +} + +impl ItfDisplay for TypedExpression { + fn itf_node(&self) -> Node { + let type_str = format!("{:?}", self.exp_type).truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2); + let inner = self.exp.itf_node(); + Node::branch(format!("{}: {}", inner.text, type_str), inner.children) + } +} + +impl ItfDisplay for ValidatedExpr { + fn itf_node(&self) -> Node { + match self { + ValidatedExpr::Const(c) => { + let value_str = match c { + Const::ConstInt(val) => format!("Int({})", val), + Const::ConstLong(val) => format!("Long({})", val), + }; + Node::leaf( + format!("Constant({})", value_str) + .truecolor(YELLOW_GOLD.0, YELLOW_GOLD.1, YELLOW_GOLD.2) + .to_string(), + ) + } + ValidatedExpr::Var(id) => id.itf_node(), + ValidatedExpr::Cast(target_type, e) => Node::branch( + "Cast".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![ + Node::branch("target_type:", vec![target_type.itf_node()]), + Node::branch("expr:", vec![e.itf_node()]), + ], + ), + ValidatedExpr::Unary(op, e) => Node::branch( + format!("Unary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![e.itf_node()], + ), + ValidatedExpr::Binary(op, e1, e2) => Node::branch( + format!("Binary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![e1.itf_node(), e2.itf_node()], + ), + ValidatedExpr::Assignment(lhs, rhs) => Node::branch( + "Assignment".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![lhs.itf_node(), rhs.itf_node()], + ), + ValidatedExpr::CompoundAssignment(op, lhs, rhs, _inner_type) => Node::branch( + format!("CompoundAssignment ({op:?})") + .truecolor(TEAL.0, TEAL.1, TEAL.2) + .to_string(), + vec![lhs.itf_node(), rhs.itf_node()], + ), + ValidatedExpr::PostFixOp(op, e) => Node::branch( + format!("PostFix ({op:?})") + .truecolor(TEAL.0, TEAL.1, TEAL.2) + .to_string(), + vec![e.itf_node()], + ), + ValidatedExpr::PreFixOp(op, e) => Node::branch( + format!("PreFix ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![e.itf_node()], + ), + ValidatedExpr::Conditional(cond, then_expr, else_expr) => Node::branch( + "Conditional".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![ + Node::branch("condition:", vec![cond.itf_node()]), + Node::branch("then:", vec![then_expr.itf_node()]), + Node::branch("else:", vec![else_expr.itf_node()]), + ], + ), + ValidatedExpr::FunctionCall(name, args) => { + let mut children = vec![Node::leaf(format!("name: {}", name.itf_node().text))]; + if !args.is_empty() { + let arg_nodes: Vec = args.iter().map(|a| a.itf_node()).collect(); + children.push(Node::branch("args:", arg_nodes)); + } + Node::branch("FunctionCall".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) + } + } + } +} + +impl ItfDisplay for ValidatedStmt { + fn itf_node(&self) -> Node { + match self { + ValidatedStmt::Return(expr) => Node::branch( + "Return".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + vec![expr.itf_node()], + ), + ValidatedStmt::Expression(expr) => Node::branch( + "Expression" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + vec![expr.itf_node()], + ), + ValidatedStmt::If(condition, then_stmt, else_stmt) => { + let mut children = vec![ + Node::branch("condition:", vec![condition.itf_node()]), + Node::branch("then:", vec![then_stmt.itf_node()]), + ]; + if let Some(else_s) = else_stmt { + children.push(Node::branch("else:", vec![else_s.itf_node()])); + } + Node::branch( + "If".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + children, + ) + } + ValidatedStmt::Null => Node::leaf("Null".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string()), + ValidatedStmt::Goto(label) => Node::branch( + "Goto".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + vec![label.itf_node()], + ), + ValidatedStmt::Labeled(label, stmt) => Node::branch( + "Labeled" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + vec![label.itf_node(), stmt.itf_node()], + ), + ValidatedStmt::Compound(block) => { + let children: Vec = block.iter().map(|item| item.itf_node()).collect(); + Node::branch( + "Compound" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + children, + ) + } + ValidatedStmt::Break(target) => { + let label_str = if target.0.is_empty() { + "Break".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string() + } else { + format!( + "{} [{}]", + "Break".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + target.0 + ) + }; + Node::leaf(label_str) + } + ValidatedStmt::Continue(target) => { + let label_str = if target.0.is_empty() { + "Continue" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string() + } else { + format!( + "{} [{}]", + "Continue".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + target.0 + ) + }; + Node::leaf(label_str) + } + ValidatedStmt::While(condition, body, label) => Node::branch( + format!( + "{} [label: {}]", + "While".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + vec![ + Node::branch("condition:", vec![condition.itf_node()]), + Node::branch("body:", vec![body.itf_node()]), + ], + ), + ValidatedStmt::DoWhile(body, condition, label) => Node::branch( + format!( + "{} [label: {}]", + "DoWhile".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + vec![ + Node::branch("body:", vec![body.itf_node()]), + Node::branch("condition:", vec![condition.itf_node()]), + ], + ), + ValidatedStmt::For(init, condition, post, body, label) => { + let mut children = vec![Node::branch("init:", vec![init.itf_node()])]; + if let Some(cond) = condition { + children.push(Node::branch("condition:", vec![cond.itf_node()])); + } + if let Some(post_expr) = post { + children.push(Node::branch("post:", vec![post_expr.itf_node()])); + } + children.push(Node::branch("body:", vec![body.itf_node()])); + Node::branch( + format!( + "{} [label: {}]", + "For".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + children, + ) + } + ValidatedStmt::Switch(expr, body, label, cases) => { + let mut case_vals: Vec = cases + .iter() + .map(|c| match c { + SwitchIntType::Int(v) => format!("{v}"), + SwitchIntType::Long(v) => format!("{v}L"), + SwitchIntType::Default => "default".to_string(), + }) + .collect(); + case_vals.sort(); + let mut children = vec![ + Node::branch("expr:", vec![expr.itf_node()]), + Node::branch("body:", vec![body.itf_node()]), + ]; + if !cases.is_empty() { + children.push(Node::leaf( + format!("cases: [{}]", case_vals.join(", ")) + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + )); + } + Node::branch( + format!( + "{} [label: {}]", + "Switch".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + children, + ) + } + ValidatedStmt::Case(expr, stmt, label) => { + let header = if label.0.is_empty() { + "Case".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string() + } else { + format!( + "{} [{}]", + "Case".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label.0 + ) + }; + Node::branch( + header, + vec![ + Node::branch("expr:", vec![expr.itf_node()]), + Node::branch("stmt:", vec![stmt.itf_node()]), + ], + ) + } + ValidatedStmt::Default(stmt, label) => { + let header = if label.0.is_empty() { + "Default" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string() + } else { + format!( + "{} [{}]", + "Default".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label.0 + ) + }; + Node::branch(header, vec![stmt.itf_node()]) + } + } + } +} + +impl ItfDisplay for ValidatedBlockItem { + fn itf_node(&self) -> Node { + match self { + ValidatedBlockItem::Statement(s) => s.itf_node(), + ValidatedBlockItem::Declaration(d) => d.itf_node(), + } + } +} + +impl ItfDisplay for ValidatedForInit { + fn itf_node(&self) -> Node { + match self { + ValidatedForInit::InitDecl(decl) => decl.itf_node(), + ValidatedForInit::InitExp(opt_expr) => match opt_expr { + Some(expr) => expr.itf_node(), + None => Node::leaf("None".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), + }, + } + } +} + // ============================================================================= // Tacky types // ============================================================================= @@ -576,7 +1000,7 @@ impl ItfDisplay for Val { fn itf_node(&self) -> Node { match self { Val::Constant(c) => Node::leaf( - c.to_string() + format!("{:?}", c) .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) .to_string(), ), @@ -588,8 +1012,7 @@ impl ItfDisplay for Val { // Helper to format Val compactly as string fn val_str(v: &Val) -> String { match v { - Val::Constant(c) => c - .to_string() + Val::Constant(c) => format!("{:?}", c) .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) .to_string(), Val::Var(s) => s.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string(), @@ -655,21 +1078,67 @@ impl ItfDisplay for TackyInstruction { val_str(dst) )) } + TackyInstruction::SignExtend { src, dst } => Node::leaf(format!( + "{} {} -> {}", + "SignExtend".truecolor(TEAL.0, TEAL.1, TEAL.2), + val_str(src), + val_str(dst) + )), + TackyInstruction::Truncate { src, dst } => Node::leaf(format!( + "{} {} -> {}", + "Truncate".truecolor(TEAL.0, TEAL.1, TEAL.2), + val_str(src), + val_str(dst) + )), } } } impl ItfDisplay for StaticVariable { fn itf_node(&self) -> Node { + let type_str = format!("{:?}", self.var_type).truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2); let init_str = match &self.init { - VarInit::Defined(v) => format!("init: {}", v), - VarInit::Extern => "extern".to_string(), + VarInit::Defined(v) => format!("init: {:?}", v) + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + VarInit::Extern => "extern".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string(), + }; + let global_str = if self.global { + format!(", {}", "global".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2)) + } else { + String::new() }; - let global_str = if self.global { ", global" } else { "" }; Node::leaf(format!( - "{}: {} ({}{})", + "{}: {} ({}, {}{})", "StaticVariable".truecolor(TEAL.0, TEAL.1, TEAL.2), - self.name, + self.name.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2), + type_str, + init_str, + global_str + )) + } +} + +impl ItfDisplay for crate::codegen::StaticVariable { + fn itf_node(&self) -> Node { + let init_str = match &self.init { + VarInit::Defined(v) => format!("init: {:?}", v) + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + VarInit::Extern => "extern".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string(), + }; + let global_str = if self.global { + format!(", {}", "global".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2)) + } else { + String::new() + }; + Node::leaf(format!( + "{}: {} (align: {}, {}{})", + "StaticVariable".truecolor(TEAL.0, TEAL.1, TEAL.2), + self.name.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2), + self.alignment + .to_string() + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2), init_str, global_str )) @@ -680,6 +1149,14 @@ impl ItfDisplay for StaticVariable { // Codegen types // ============================================================================= +// Helper to format AssemblyType compactly as string +fn size_str(size: &AssemblyType) -> String { + match size { + AssemblyType::Longword => "L".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string(), + AssemblyType::Quadword => "Q".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2).to_string(), + } +} + // Helper to format Operand compactly as string fn operand_str(op: &Operand) -> String { match op { @@ -718,37 +1195,52 @@ impl ItfDisplay for Operand { impl ItfDisplay for CodegenInstruction { fn itf_node(&self) -> Node { match self { - CodegenInstruction::Mov { src, dst } => Node::leaf(format!( - "{} {} -> {}", + CodegenInstruction::Mov { src, dst, size } => Node::leaf(format!( + "{}<{}> {} -> {}", "Mov".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size), operand_str(src), operand_str(dst) )), - CodegenInstruction::Unary { op, dst } => Node::leaf(format!( - "{} {:?} {}", + CodegenInstruction::Movsx { src, dst } => Node::leaf(format!( + "{} {} -> {}", + "Movsx".truecolor(TEAL.0, TEAL.1, TEAL.2), + operand_str(src), + operand_str(dst) + )), + CodegenInstruction::Unary { op, dst, size } => Node::leaf(format!( + "{}<{}> {:?} {}", "Unary".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size), op, operand_str(dst) )), - CodegenInstruction::Binary { op, src, dst } => Node::leaf(format!( - "{} {:?} {} -> {}", + CodegenInstruction::Binary { op, src, dst, size } => Node::leaf(format!( + "{}<{}> {:?} {} -> {}", "Binary".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size), op, operand_str(src), operand_str(dst) )), - CodegenInstruction::Cmp { v1, v2 } => Node::leaf(format!( - "{} {}, {}", + CodegenInstruction::Cmp { v1, v2, size } => Node::leaf(format!( + "{}<{}> {}, {}", "Cmp".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size), operand_str(v1), operand_str(v2) )), - CodegenInstruction::Idiv(op) => Node::leaf(format!( - "{} {}", + CodegenInstruction::Idiv(op, size) => Node::leaf(format!( + "{}<{}> {}", "Idiv".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size), operand_str(op) )), - CodegenInstruction::Cdq => Node::leaf("Cdq".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), + CodegenInstruction::Cdq(size) => Node::leaf(format!( + "{}<{}>", + "Cdq".truecolor(TEAL.0, TEAL.1, TEAL.2), + size_str(size) + )), CodegenInstruction::Jmp(label) => Node::leaf(format!( "{} -> {}", "Jmp".truecolor(TEAL.0, TEAL.1, TEAL.2), @@ -771,17 +1263,7 @@ impl ItfDisplay for CodegenInstruction { "Label".truecolor(TEAL.0, TEAL.1, TEAL.2), l.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) )), - CodegenInstruction::AllocateStack(off) => Node::leaf(format!( - "{} {}", - "AllocateStack".truecolor(TEAL.0, TEAL.1, TEAL.2), - off.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) - )), CodegenInstruction::Ret => Node::leaf("Ret".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), - CodegenInstruction::DeallocateStack(off) => Node::leaf(format!( - "{} {}", - "DeallocateStack".truecolor(TEAL.0, TEAL.1, TEAL.2), - off.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) - )), CodegenInstruction::Push(op) => Node::leaf(format!( "{} {}", "Push".truecolor(TEAL.0, TEAL.1, TEAL.2), diff --git a/src/tacky.rs b/src/tacky.rs index 5a9ef6d..bdbbd66 100644 --- a/src/tacky.rs +++ b/src/tacky.rs @@ -1,12 +1,53 @@ +//! # Tackifier — Typed AST to Three-Address Code IR (TACKY) +//! +//! Flattens the typed AST into TACKY, a linear three-address code intermediate +//! representation with explicit control flow via jumps and labels. +//! +//! ## Technical Approach +//! +//! Each nested expression is recursively decomposed into a sequence of simple +//! [`Instruction`]s that operate on at most two source [`Val`]s and one destination. +//! Temporaries are generated via [`NameGenerator`] and tracked in `temp_types` for +//! downstream passes. Control flow (if/while/for/switch) is lowered to conditional +//! and unconditional jumps with generated labels. +//! +//! ## What This Pass Accomplishes +//! +//! - Flattens nested expressions into linear instruction sequences +//! - Makes all control flow explicit (no structured if/while/for in output) +//! - Implements short-circuit evaluation for `&&` and `||` +//! - Implements left-to-right evaluation by capturing operands to temporaries +//! - Lowers switch statements to cascading equality comparisons with jumps +//! - Extracts static variables from the [`SymbolTable`] into [`StaticVariable`] entries +//! - Ensures every function ends with a `Return` (inserts default `return 0` if missing) +//! +//! ## Call Order +//! +//! ```text +//! tackify_program() — public entry point +//! ├─ tackify_function() — per function (with body only) +//! │ └─ tackify_block() — process compound statements +//! │ ├─ tackify_var_declaration() — emit local var initializers (skip static/extern) +//! │ └─ tackify_stmt() — lower statements to jumps/labels +//! │ └─ tackify_expr() — core: flatten expressions to instructions +//! │ └─ emit_cast() — int<->long conversion instructions +//! └─ convert_symbols_to_tacky() — extract static vars from symbol table +//! ``` + use crate::parser; -use crate::parser::{Block, BlockItem, Declaration, Expr, ForInit, Identifier, IncDec, Stmt, UnaryOp, VarDeclaration}; -use crate::tacky::Instruction::{JumpIfNotZero, JumpIfZero}; -use crate::validate::{InitialValue, NameGenerator, SymbolTable, SymbolType}; +use crate::parser::{Const, Identifier, IncDec, SwitchIntType, Type, UnaryOp}; +use crate::validate::{ + Block, BlockItem, Expr, ForInit, InitialValue, NameGenerator, StaticInt, Stmt, SymbolTable, TypedDeclaration, + TypedExpression, TypedFunction, TypedProgram, TypedVarDeclaration, +}; +use std::cmp::PartialEq; +use std::collections::HashMap; +use std::rc::Rc; #[derive(Clone, Debug)] pub enum Val { - Constant(i32), - Var(String), + Constant(Const), + Var(Rc), } #[derive(Clone, Debug, PartialEq)] @@ -82,6 +123,14 @@ impl From<&parser::AssignOp> for BinOp { #[derive(Clone, Debug)] pub enum Instruction { Return(Val), + SignExtend { + src: Val, + dst: Val, + }, + Truncate { + src: Val, + dst: Val, + }, Unary { op: UnaryOp, src: Val, @@ -118,37 +167,42 @@ pub enum Instruction { #[derive(Debug)] pub struct FunctionDefinition { - pub name: String, + pub name: Rc, pub params: Vec, pub body: Vec, pub global: bool, + pub temp_types: HashMap, Type>, } /// Storage initialization for static variables. #[derive(Debug, Clone)] pub enum VarInit { /// Variable defined here with initial value (0 = .bss, non-zero = .data) - Defined(i32), + Defined(StaticInt), /// Extern variable - no storage allocated, resolved by linker Extern, } #[derive(Debug, Clone)] pub struct StaticVariable { - pub name: String, + pub name: Rc, pub global: bool, pub init: VarInit, + pub var_type: Type, } #[derive(Debug)] -pub enum TopLevel { - Function(FunctionDefinition), - StaticVariable(StaticVariable), +pub struct Program { + pub function_defs: Vec, + pub static_vars: Vec, } -#[derive(Debug)] -pub struct Program { - pub top_level: Vec, +fn emit_cast(src: Val, dst: Val, src_type: &Type, dst_type: &Type, instructions: &mut Vec) { + match (src_type, dst_type) { + (Type::Int, Type::Long) => instructions.push(Instruction::SignExtend { src, dst }), + (Type::Long, Type::Int) => instructions.push(Instruction::Truncate { src, dst }), + _ => unreachable!("Unsupported cast: {:?} -> {:?}", src_type, dst_type), + } } /// Converts AST expressions into TACKY IR instructions. @@ -164,34 +218,56 @@ pub struct Program { /// - Postfix operators return the original value before modification /// - Prefix operators return the new value after modification /// - Lvalue expressions are currently limited to simple variables -fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_generator: &mut NameGenerator) -> Val { - match e { - parser::Expr::Constant(c) => Val::Constant(*c), - parser::Expr::Unary(op, inner) => { - let src = tackify_expr(inner, instructions, name_generator); - let dst = Val::Var(name_generator.next("temp")); +fn tackify_expr( + e: &TypedExpression, + instructions: &mut Vec, + name_generator: &mut NameGenerator, + temp_types: &mut HashMap, Type>, +) -> Val { + let e_type = e.exp_type.clone(); + match &e.exp { + Expr::Const(c) => Val::Constant(*c), + Expr::Cast(target_type, inner) => { + let source_type = inner.exp_type.clone(); + let result = tackify_expr(inner, instructions, name_generator, temp_types); + if *target_type == source_type { + return result; + } + let dst_name = name_generator.next("temp"); + temp_types.insert(dst_name.clone(), target_type.clone()); + let dst = Val::Var(dst_name); + emit_cast(result, dst.clone(), &source_type, target_type, instructions); + dst + } + Expr::Unary(op, inner) => { + let src = tackify_expr(inner, instructions, name_generator, temp_types); + let dst_name = name_generator.next("temp"); + temp_types.insert(dst_name.clone(), e.exp_type.clone()); + let dst = Val::Var(dst_name); instructions.push(Instruction::Unary { - op: op.clone(), + op: *op, src, dst: dst.clone(), }); dst } - parser::Expr::Binary(parser::BinOp::And, e1, e2) => { - let src1 = tackify_expr(e1, instructions, name_generator); + Expr::Binary(parser::BinOp::And, e1, e2) => { + let src1 = tackify_expr(e1, instructions, name_generator, temp_types); let false_label = Identifier(name_generator.next("and_false")); instructions.push(Instruction::JumpIfZero { condition: src1, target: false_label.clone(), }); - let src2 = tackify_expr(e2, instructions, name_generator); + let src2 = tackify_expr(e2, instructions, name_generator, temp_types); instructions.push(Instruction::JumpIfZero { condition: src2, target: false_label.clone(), }); - let result = Val::Var(name_generator.next("temp")); + let result_name = name_generator.next("temp"); + temp_types.insert(result_name.clone(), e.exp_type.clone()); + let result = Val::Var(result_name); instructions.push(Instruction::Copy { - src: Val::Constant(1), + src: Val::Constant(Const::ConstInt(1)), dst: result.clone(), }); let end_label = Identifier(name_generator.next("end")); @@ -200,27 +276,29 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene }); instructions.push(Instruction::Label(false_label)); instructions.push(Instruction::Copy { - src: Val::Constant(0), + src: Val::Constant(Const::ConstInt(0)), dst: result.clone(), }); instructions.push(Instruction::Label(end_label)); result } - parser::Expr::Binary(parser::BinOp::Or, e1, e2) => { - let src1 = tackify_expr(e1, instructions, name_generator); + Expr::Binary(parser::BinOp::Or, e1, e2) => { + let src1 = tackify_expr(e1, instructions, name_generator, temp_types); let false_label = Identifier(name_generator.next("or_false")); instructions.push(Instruction::JumpIfNotZero { condition: src1, target: false_label.clone(), }); - let src2 = tackify_expr(e2, instructions, name_generator); + let src2 = tackify_expr(e2, instructions, name_generator, temp_types); instructions.push(Instruction::JumpIfNotZero { condition: src2, target: false_label.clone(), }); - let result = Val::Var(name_generator.next("temp")); + let result_name = name_generator.next("temp"); + temp_types.insert(result_name.clone(), e.exp_type.clone()); + let result = Val::Var(result_name); instructions.push(Instruction::Copy { - src: Val::Constant(0), + src: Val::Constant(Const::ConstInt(0)), dst: result.clone(), }); let end_label = Identifier(name_generator.next("end")); @@ -229,27 +307,31 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene }); instructions.push(Instruction::Label(false_label)); instructions.push(Instruction::Copy { - src: Val::Constant(1), + src: Val::Constant(Const::ConstInt(1)), dst: result.clone(), }); instructions.push(Instruction::Label(end_label)); result } - parser::Expr::Binary(op, e1, e2) => { + Expr::Binary(op, e1, e2) => { // Evaluate left-to-right and capture values immediately to avoid undefined behavior - let mut src1 = tackify_expr(e1, instructions, name_generator); + let mut src1 = tackify_expr(e1, instructions, name_generator, temp_types); // If src1 is a variable, copy it to a temp to capture its current value // before evaluating src2 (which might modify it) if let Val::Var(_) = &src1 { - let temp = Val::Var(name_generator.next("binary_left")); + let temp_name = name_generator.next("binary_left"); + temp_types.insert(temp_name.clone(), e1.exp_type.clone()); + let temp = Val::Var(temp_name); instructions.push(Instruction::Copy { src: src1.clone(), dst: temp.clone(), }); src1 = temp; } - let src2 = tackify_expr(e2, instructions, name_generator); - let dst = Val::Var(name_generator.next("temp")); + let src2 = tackify_expr(e2, instructions, name_generator, temp_types); + let dst_name = name_generator.next("temp"); + temp_types.insert(dst_name.clone(), e.exp_type.clone()); + let dst = Val::Var(dst_name); instructions.push(Instruction::Binary { op: BinOp::from(op), src1, @@ -258,10 +340,10 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene }); dst } - Expr::Var(Identifier(name), _span) => Val::Var(name.clone()), - Expr::Assignment(lhs, rhs, _span) => match lhs.as_ref() { - Expr::Var(Identifier(name), _) => { - let res = tackify_expr(rhs, instructions, name_generator); + Expr::Var(Identifier(name)) => Val::Var(name.clone()), + Expr::Assignment(lhs, rhs) => match &lhs.exp { + Expr::Var(Identifier(name)) => { + let res = tackify_expr(rhs, instructions, name_generator, temp_types); instructions.push(Instruction::Copy { src: res.clone(), dst: Val::Var(name.clone()), @@ -270,33 +352,69 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene } _ => unreachable!("Assignment to non-lvalue"), }, - Expr::CompoundAssignment(op, lhs, rhs, _span) => match lhs.as_ref() { - Expr::Var(Identifier(name), _) => { - let current_val = Val::Var(name.clone()); // get the original value - let rhs_val = tackify_expr(rhs, instructions, name_generator); - let dst = Val::Var(name_generator.next("compound_temp")); - // do the operation and store the result in a temporary variable - instructions.push(Instruction::Binary { - op: op.into(), - src1: current_val.clone(), - src2: rhs_val.clone(), - dst: dst.clone(), - }); + Expr::CompoundAssignment(op, lhs, rhs, op_type) => match &lhs.exp { + Expr::Var(Identifier(name)) => { + let current_val = Val::Var(name.clone()); + let rhs_val = tackify_expr(rhs, instructions, name_generator, temp_types); - // copy the result back to the original variable - instructions.push(Instruction::Copy { - src: dst.clone(), - dst: Val::Var(name.clone()), - }); - dst + // Promote RHS to op_type if needed + let src2 = if *op_type != rhs.exp_type { + let cast_name = name_generator.next("cast_tmp"); + temp_types.insert(cast_name.clone(), op_type.clone()); + let cast_dst = Val::Var(cast_name); + emit_cast(rhs_val, cast_dst.clone(), &rhs.exp_type, op_type, instructions); + cast_dst + } else { + rhs_val + }; + + // Promote LHS to op_type if needed + let src1 = if *op_type != lhs.exp_type { + let cast_name = name_generator.next("cast_tmp"); + temp_types.insert(cast_name.clone(), op_type.clone()); + let cast_dst = Val::Var(cast_name); + emit_cast( + current_val.clone(), + cast_dst.clone(), + &lhs.exp_type, + op_type, + instructions, + ); + cast_dst + } else { + current_val.clone() + }; + + // Perform operation; use temp if result needs truncation + if *op_type != lhs.exp_type { + let dst_name = name_generator.next("compound_temp"); + temp_types.insert(dst_name.clone(), op_type.clone()); + let dst = Val::Var(dst_name); + instructions.push(Instruction::Binary { + op: op.into(), + src1, + src2, + dst: dst.clone(), + }); + emit_cast(dst, current_val.clone(), op_type, &lhs.exp_type, instructions); + } else { + instructions.push(Instruction::Binary { + op: op.into(), + src1, + src2, + dst: current_val.clone(), + }); + } + current_val } _ => unreachable!("Compound assignment to non-lvalue"), }, - Expr::PostFixOp(op, e, _) => match e.as_ref() { - Expr::Var(Identifier(name), _) => { + Expr::PostFixOp(op, e) => match &e.exp { + Expr::Var(Identifier(name)) => { let current_val = Val::Var(name.clone()); // get the original value - let org_tmp = Val::Var(name_generator.next("postfix_org")); - let new_val = Val::Var(name_generator.next("postfix_new")); + let org_tmp_name = name_generator.next("postfix_org"); + temp_types.insert(org_tmp_name.clone(), e.exp_type.clone()); + let org_tmp = Val::Var(org_tmp_name); instructions.push(Instruction::Copy { src: current_val.clone(), dst: org_tmp.clone(), @@ -304,45 +422,46 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene instructions.push(Instruction::Binary { op: op.into(), src1: current_val.clone(), - src2: Val::Constant(1), - dst: new_val.clone(), + src2: Val::Constant(e_type.get_1()), + dst: current_val.clone(), }); instructions.push(Instruction::Copy { - src: new_val.clone(), + src: current_val.clone(), dst: Val::Var(name.clone()), }); org_tmp } _ => unreachable!("Postfix on non-lvalue"), }, - Expr::PreFixOp(op, e, _) => match e.as_ref() { - Expr::Var(Identifier(name), _) => { + Expr::PreFixOp(op, e) => match &e.exp { + Expr::Var(Identifier(name)) => { let current_val = Val::Var(name.clone()); // get the original value - let new_val = Val::Var(name_generator.next("prefix_new")); instructions.push(Instruction::Binary { op: op.into(), src1: current_val.clone(), - src2: Val::Constant(1), - dst: new_val.clone(), + src2: Val::Constant(e_type.get_1()), + dst: current_val.clone(), }); instructions.push(Instruction::Copy { - src: new_val.clone(), + src: current_val.clone(), dst: Val::Var(name.clone()), }); - new_val + current_val } _ => unreachable!("Prefix on non-lvalue"), }, Expr::Conditional(cond, e1, e2) => { - let c = tackify_expr(cond, instructions, name_generator); - let result = Val::Var(name_generator.next("temp")); + let c = tackify_expr(cond, instructions, name_generator, temp_types); + let result_name = name_generator.next("temp"); + temp_types.insert(result_name.clone(), e.exp_type.clone()); + let result = Val::Var(result_name); let cond_false = Identifier(name_generator.next("cond_false")); let cond_end = Identifier(name_generator.next("cond_end")); instructions.push(Instruction::JumpIfZero { condition: c, target: cond_false.clone(), }); - let left = tackify_expr(e1, instructions, name_generator); + let left = tackify_expr(e1, instructions, name_generator, temp_types); instructions.push(Instruction::Copy { src: left, dst: result.clone(), @@ -351,7 +470,7 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene target: cond_end.clone(), }); instructions.push(Instruction::Label(cond_false.clone())); - let right = tackify_expr(e2, instructions, name_generator); + let right = tackify_expr(e2, instructions, name_generator, temp_types); instructions.push(Instruction::Copy { src: right, dst: result.clone(), @@ -359,12 +478,14 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene instructions.push(Instruction::Label(cond_end.clone())); result } - Expr::FunctionCall(fun_name, params, _span) => { + Expr::FunctionCall(fun_name, params) => { let mut tacky_params = vec![]; for param in params { - let mut tacky_param = tackify_expr(param, instructions, name_generator); + let mut tacky_param = tackify_expr(param, instructions, name_generator, temp_types); if let Val::Var(_) = &tacky_param { - let temp = Val::Var(name_generator.next("arg")); + let temp_name = name_generator.next("arg"); + temp_types.insert(temp_name.clone(), param.exp_type.clone()); + let temp = Val::Var(temp_name); instructions.push(Instruction::Copy { src: tacky_param, dst: temp.clone(), @@ -373,7 +494,9 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene } tacky_params.push(tacky_param); } - let dst = Val::Var(name_generator.next("call")); + let dst_name = name_generator.next("call"); + temp_types.insert(dst_name.clone(), e.exp_type.clone()); + let dst = Val::Var(dst_name); instructions.push(Instruction::FunCall { fun_name: fun_name.clone(), args: tacky_params, @@ -384,130 +507,139 @@ fn tackify_expr(e: &parser::Expr, instructions: &mut Vec, name_gene } } -fn tackify_stmt(stmt: &parser::Stmt, instructions: &mut Vec, name_generator: &mut NameGenerator) { - match &stmt { - parser::Stmt::Return(expr) => { - let val = tackify_expr(expr, instructions, name_generator); +fn tackify_stmt( + stmt: &Stmt, + instructions: &mut Vec, + name_generator: &mut NameGenerator, + temp_types: &mut HashMap, Type>, +) { + match stmt { + Stmt::Return(expr) => { + let val = tackify_expr(expr, instructions, name_generator, temp_types); instructions.push(Instruction::Return(val)); } - parser::Stmt::Expression(e) => { - tackify_expr(e, instructions, name_generator); + Stmt::Expression(e) => { + tackify_expr(e, instructions, name_generator, temp_types); } - parser::Stmt::Null => (), - &parser::Stmt::If(cond, then_stmt, else_stmt) => { - let c = tackify_expr(cond, instructions, name_generator); + Stmt::Null => (), + Stmt::If(cond, then_stmt, else_stmt) => { + let c = tackify_expr(cond, instructions, name_generator, temp_types); let end_label = Identifier(name_generator.next("fi")); - if let Some(e) = &**else_stmt { + if let Some(e) = else_stmt { // if with else let else_label = Identifier(name_generator.next("if_else")); instructions.push(Instruction::JumpIfZero { condition: c, target: else_label.clone(), }); - tackify_stmt(&then_stmt.stmt, instructions, name_generator); + tackify_stmt(then_stmt, instructions, name_generator, temp_types); instructions.push(Instruction::Jump { target: end_label.clone(), }); instructions.push(Instruction::Label(else_label)); - tackify_stmt(&e.stmt, instructions, name_generator); + tackify_stmt(e, instructions, name_generator, temp_types); } else { // no else instructions.push(Instruction::JumpIfZero { condition: c, target: end_label.clone(), }); - tackify_stmt(&then_stmt.stmt, instructions, name_generator); + tackify_stmt(then_stmt, instructions, name_generator, temp_types); } instructions.push(Instruction::Label(end_label.clone())); } - &parser::Stmt::Labeled(label_name, stmt) => { - instructions.push(Instruction::Label(Identifier(label_name.to_string()))); - tackify_stmt(&stmt.stmt, instructions, name_generator) + Stmt::Labeled(label_name, stmt) => { + instructions.push(Instruction::Label(label_name.clone())); + tackify_stmt(stmt, instructions, name_generator, temp_types); } - &parser::Stmt::Goto(label_name) => instructions.push(Instruction::Jump { - target: Identifier(label_name.to_string()), + Stmt::Goto(label_name) => instructions.push(Instruction::Jump { + target: label_name.clone(), }), - &parser::Stmt::Compound(block) => tackify_block(block, instructions, name_generator), - parser::Stmt::Break(target) | parser::Stmt::Continue(target) => { - instructions.push(Instruction::Jump { target: target.clone() }) - } - parser::Stmt::While(condition, body, label) => { - let continue_label = Identifier(format!("continue_loop.{label}")); - let break_label = Identifier(format!("break_loop.{label}")); + Stmt::Compound(block) => tackify_block(block, instructions, name_generator, temp_types), + Stmt::Break(target) | Stmt::Continue(target) => instructions.push(Instruction::Jump { target: target.clone() }), + Stmt::While(condition, body, label) => { + let continue_label = Identifier(Rc::from(format!("continue_loop.{label}"))); + let break_label = Identifier(Rc::from(format!("break_loop.{label}"))); instructions.push(Instruction::Label(continue_label.clone())); - let c = tackify_expr(condition, instructions, name_generator); + let c = tackify_expr(condition, instructions, name_generator, temp_types); instructions.push(Instruction::JumpIfZero { condition: c, target: break_label.clone(), }); - tackify_stmt(&body.stmt, instructions, name_generator); + tackify_stmt(body, instructions, name_generator, temp_types); instructions.push(Instruction::Jump { target: continue_label }); instructions.push(Instruction::Label(break_label)); } - parser::Stmt::DoWhile(body, condition, label) => { - let start_label = Identifier(format!("start_loop.{label}")); - let continue_label = Identifier(format!("continue_loop.{label}")); - let break_label = Identifier(format!("break_loop.{label}")); + Stmt::DoWhile(body, condition, label) => { + let start_label = Identifier(Rc::from(format!("start_loop.{label}"))); + let continue_label = Identifier(Rc::from(format!("continue_loop.{label}"))); + let break_label = Identifier(Rc::from(format!("break_loop.{label}"))); instructions.push(Instruction::Label(start_label.clone())); - tackify_stmt(&body.stmt, instructions, name_generator); + tackify_stmt(body, instructions, name_generator, temp_types); instructions.push(Instruction::Label(continue_label)); - let c = tackify_expr(condition, instructions, name_generator); - instructions.push(JumpIfNotZero { + let c = tackify_expr(condition, instructions, name_generator, temp_types); + instructions.push(Instruction::JumpIfNotZero { condition: c, target: start_label, }); instructions.push(Instruction::Label(break_label)); } - parser::Stmt::For(init, condition, post, body, label) => { - match init { - ForInit::InitDecl(dec) => tackify_var_declaration(dec, instructions, name_generator), + Stmt::For(init, condition, post, body, label) => { + match init.as_ref() { + ForInit::InitDecl(dec) => tackify_var_declaration(dec, instructions, name_generator, temp_types), ForInit::InitExp(exp) => { if let Some(e) = exp { - tackify_expr(e, instructions, name_generator); + tackify_expr(e, instructions, name_generator, temp_types); } } } - let start_label = Identifier(format!("start_loop.{label}")); - let continue_label = Identifier(format!("continue_loop.{label}")); - let break_label = Identifier(format!("break_loop.{label}")); + let start_label = Identifier(Rc::from(format!("start_loop.{label}"))); + let continue_label = Identifier(Rc::from(format!("continue_loop.{label}"))); + let break_label = Identifier(Rc::from(format!("break_loop.{label}"))); instructions.push(Instruction::Label(start_label.clone())); if let Some(condition) = condition { - let c = tackify_expr(condition, instructions, name_generator); - instructions.push(JumpIfZero { + let c = tackify_expr(condition, instructions, name_generator, temp_types); + instructions.push(Instruction::JumpIfZero { condition: c, target: break_label.clone(), }) } - tackify_stmt(&body.stmt, instructions, name_generator); + tackify_stmt(body, instructions, name_generator, temp_types); instructions.push(Instruction::Label(continue_label)); if let Some(post) = post { - tackify_expr(post, instructions, name_generator); + tackify_expr(post, instructions, name_generator, temp_types); } instructions.push(Instruction::Jump { target: start_label }); instructions.push(Instruction::Label(break_label)); } Stmt::Switch(exp, stmt, switch_num, cases) => { - let end_label = Identifier(format!("break_switch.{switch_num}")); - let switch_val = tackify_expr(exp, instructions, name_generator); + let end_label = Identifier(Rc::from(format!("break_switch.{switch_num}"))); + let switch_val = tackify_expr(exp, instructions, name_generator, temp_types); // Build conditional jumps for each case // this can be optimized with binary search and/or jump tables let mut default_label = None; for case in cases { match case { - parser::SwitchIntType::Int(val) => { - let case_label = Identifier(case.label_str(*switch_num)); - let case_val = Val::Constant(*val); - let cond = Val::Var(name_generator.next("case_cond")); + SwitchIntType::Int(_) | SwitchIntType::Long(_) => { + let case_label = Identifier(Rc::from(case.label_str(*switch_num))); + let case_const = match case { + SwitchIntType::Int(c) => Const::ConstInt(*c), + SwitchIntType::Long(c) => Const::ConstLong(*c), + SwitchIntType::Default => unreachable!(), + }; + let cond_name = name_generator.next("case_cond"); + temp_types.insert(cond_name.clone(), Type::Int); + let cond = Val::Var(cond_name); instructions.push(Instruction::Binary { op: BinOp::Equal, src1: switch_val.clone(), - src2: case_val, + src2: Val::Constant(case_const), dst: cond.clone(), }); instructions.push(Instruction::JumpIfNotZero { @@ -515,8 +647,8 @@ fn tackify_stmt(stmt: &parser::Stmt, instructions: &mut Vec, name_g target: case_label, }); } - parser::SwitchIntType::Default => { - default_label = Some(Identifier(case.label_str(*switch_num))); + SwitchIntType::Default => { + default_label = Some(Identifier(Rc::from(case.label_str(*switch_num)))); } } } @@ -531,23 +663,30 @@ fn tackify_stmt(stmt: &parser::Stmt, instructions: &mut Vec, name_g }); } - tackify_stmt(&stmt.stmt, instructions, name_generator); + tackify_stmt(stmt, instructions, name_generator, temp_types); instructions.push(Instruction::Label(end_label)); } Stmt::Case(_, stmt, label) | Stmt::Default(stmt, label) => { instructions.push(Instruction::Label(label.clone())); - tackify_stmt(&stmt.stmt, instructions, name_generator); + tackify_stmt(stmt, instructions, name_generator, temp_types); } } } -fn tackify_block(block: &Block, instructions: &mut Vec, name_generator: &mut NameGenerator) { +fn tackify_block( + block: &Block, + instructions: &mut Vec, + name_generator: &mut NameGenerator, + temp_types: &mut HashMap, Type>, +) { for item in block { match item { - BlockItem::Statement(stmt) => tackify_stmt(&stmt.stmt, instructions, name_generator), + BlockItem::Statement(stmt) => tackify_stmt(stmt, instructions, name_generator, temp_types), BlockItem::Declaration(dec) => match dec { - Declaration::VarDeclaration(var) => tackify_var_declaration(var, instructions, name_generator), - Declaration::FunDeclaration(_) => {} + TypedDeclaration::Variable(var) => { + tackify_var_declaration(var, instructions, name_generator, temp_types) + } + TypedDeclaration::Function(_) => {} // Function declarations in blocks have no body }, } } @@ -558,81 +697,104 @@ fn tackify_block(block: &Block, instructions: &mut Vec, name_genera /// Static variables are initialized at compile time in the data section. /// Extern variables have no initialization code emitted. fn tackify_var_declaration( - declaration: &VarDeclaration, + declaration: &TypedVarDeclaration, instructions: &mut Vec, name_generator: &mut NameGenerator, + temp_types: &mut HashMap, Type>, ) { - if let VarDeclaration { - name, - init: Some(e), - span, - storage_class: None, - } = declaration + if declaration.storage_class.is_none() + && let Some(init_exp) = &declaration.init { - let ass = Expr::Assignment(Box::new(Expr::Var(name.clone(), *span)), Box::new(e.clone()), *span); - tackify_expr(&ass, instructions, name_generator); + let res = tackify_expr(init_exp, instructions, name_generator, temp_types); + instructions.push(Instruction::Copy { + src: res, + dst: Val::Var(declaration.name.0.clone()), + }); } } -fn tackify_function( - func: &parser::FunDeclaration, - name_generator: &mut NameGenerator, - symbols: &SymbolTable, -) -> FunctionDefinition { +fn tackify_function(func: &TypedFunction, name_generator: &mut NameGenerator) -> FunctionDefinition { let mut instructions = Vec::new(); - let parser::Identifier(name) = &func.name; + let mut temp_types = HashMap::new(); + let Identifier(name) = &func.name; if let Some(body) = &func.body { - tackify_block(body, &mut instructions, name_generator); + tackify_block(body, &mut instructions, name_generator, &mut temp_types); } - // Return 0 if the function has no return statement - // will not be reached if the function has a return statement - instructions.push(Instruction::Return(Val::Constant(0))); + if !matches!(instructions.last(), Some(Instruction::Return(_))) { + let ret_type = match &func.fun_type { + Type::FunType { ret, .. } => ret.as_ref(), + _ => unreachable!("Function must have FunType"), + }; + + let default_return = match ret_type { + Type::Int => Val::Constant(Const::ConstInt(0)), + Type::Long => Val::Constant(Const::ConstLong(0)), + _ => unreachable!("Function return type must be Int or Long"), + }; + instructions.push(Instruction::Return(default_return)); + } FunctionDefinition { name: name.clone(), params: func.params.clone(), body: instructions, - global: symbols.get(name).unwrap().global, + global: func.global, + temp_types, } } /// Converts static variables from the symbol table into TACKY IR definitions. /// -/// Iterates through all symbols and emits `StaticVariable` entries for variables -/// with static storage duration: -/// - `VarInit::Defined(value)` for defined variables (Initial or Tentative) -/// - `VarInit::Extern` for extern declarations (defined elsewhere) +/// Extracts static variables from the symbol table into TACKY IR `StaticVariable` entries. /// -/// Tentative definitions are initialized to 0. -fn convert_symbols_to_tacky(symbols: &SymbolTable) -> Vec { +/// - `Initial` → `VarInit::Defined(value)` +/// - `Tentative` → `VarInit::Defined(0)` (zero-initialized) +/// - `NoInitializer` → `VarInit::Extern` (resolved by linker), but only for file-scope +/// names (skips renamed locals like `i.1` which contain a dot) +fn convert_symbols_to_tacky(symbols: &SymbolTable) -> Vec { let mut tacky_defs = vec![]; for (name, entry) in symbols.iter() { - if let SymbolType::Int(init) = &entry.symbol_type { - match init { - InitialValue::Initial(i) => tacky_defs.push(TopLevel::StaticVariable(StaticVariable { - name: name.clone(), - global: entry.global, - init: VarInit::Defined(*i), - })), - InitialValue::Tentative => tacky_defs.push(TopLevel::StaticVariable(StaticVariable { - name: name.clone(), - global: entry.global, - init: VarInit::Defined(0), - })), - InitialValue::NoInitializer => { - // Only add extern vars if it's not a renamed local variable. - // Renamed locals have dots in their names (e.g., "i.1"). - // File-scope extern declarations keep their original names. - if !name.contains('.') { - tacky_defs.push(TopLevel::StaticVariable(StaticVariable { + match &entry.symbol_type { + Type::Int | Type::Long => { + match &entry.val { + InitialValue::Initial(static_val) => tacky_defs.push(StaticVariable { + name: name.clone(), + global: entry.global, + init: VarInit::Defined(*static_val), + var_type: entry.symbol_type.clone(), + }), + InitialValue::Tentative => { + let zero = match &entry.symbol_type { + Type::Int => StaticInt::IntInit(0), + Type::Long => StaticInt::LongInit(0), + Type::FunType { .. } => unreachable!("Tentative must be Int or Long"), + }; + tacky_defs.push(StaticVariable { name: name.clone(), global: entry.global, - init: VarInit::Extern, - })); + init: VarInit::Defined(zero), + var_type: entry.symbol_type.clone(), + }) + } + InitialValue::NoInitializer => { + // Only add extern vars if it's not a renamed local variable. + // Renamed locals have dots in their names (e.g., "i.1"). + // File-scope extern declarations keep their original names. + if !name.contains('.') { + tacky_defs.push(StaticVariable { + name: name.clone(), + global: entry.global, + init: VarInit::Extern, + var_type: entry.symbol_type.clone(), + }); + } } } } + Type::FunType { .. } => { + // Skip function types - they're handled separately + } } } tacky_defs @@ -642,21 +804,19 @@ fn convert_symbols_to_tacky(symbols: &SymbolTable) -> Vec { /// /// Processes all function definitions (skipping declarations without bodies) and /// combines them with static variable definitions from the symbol table. -pub fn tackify_program( - program: &parser::Program, - name_generator: &mut NameGenerator, - symbols: &SymbolTable, -) -> Program { - let mut top_level = Vec::new(); +pub fn tackify_program(program: TypedProgram, name_generator: &mut NameGenerator, symbols: &SymbolTable) -> Program { + let mut function_defs = Vec::new(); for decl in &program.declarations { - if let Declaration::FunDeclaration(func) = decl + if let TypedDeclaration::Function(func) = decl && func.body.is_some() { - top_level.push(TopLevel::Function(tackify_function(func, name_generator, symbols))); + function_defs.push(tackify_function(func, name_generator)); } } - let static_var_defs = convert_symbols_to_tacky(symbols); - top_level.extend(static_var_defs); - Program { top_level } + let static_vars = convert_symbols_to_tacky(symbols); + Program { + function_defs, + static_vars, + } } diff --git a/src/validate.rs b/src/validate.rs index 294dea5..4bf3823 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -1,17 +1,167 @@ +//! # Validator — Semantic Analysis (Resolution + Type Checking) +//! +//! Two-pass semantic analysis that transforms the untyped parser AST into a +//! [`TypedProgram`] with fully resolved names and types. +//! +//! ## Technical Approach +//! +//! The validator runs two sequential passes over the AST, both orchestrated by +//! [`resolve_program`] (the single public entry point called from `main`): +//! +//! **Pass 1 — Resolution** mutates the parser AST in place: +//! - Renames local variables to unique identifiers (`x` -> `x.1`) via [`NameGenerator`] +//! - Validates lvalue requirements (assignment/increment targets must be variables) +//! - Labels loops and switches with unique IDs for break/continue/case +//! - Validates goto targets exist, detects duplicate labels +//! - Emits `-Wshadow`, `-Wunused-parameter`, and `-Wsequence-point` warnings +//! +//! **Pass 2 — Type Checking** consumes the mutated AST and produces typed output: +//! - Builds the [`SymbolTable`] mapping identifiers to types, linkage, and initial values +//! - Inserts implicit casts via common-type promotion (`int` + `long` -> `long`) +//! - Validates function call arity and argument types +//! - Evaluates constant expressions for static initializers and case labels +//! - Emits `-Wdiv-by-zero` for `/` or `%` with a constant zero divisor +//! - Emits `-Wshift-count-overflow` / `-Wshift-count-negative` for an out-of-range constant shift count +//! - Emits `-Woverflow` when a constant fold leaves the result type (in static initializers / case labels) +//! - Emits `-Wconstant-conversion` when an implicit narrowing of a constant initializer changes its value +//! - Enforces declaration consistency (linkage, types, single-definition rule) +//! +//! ## What This Pass Accomplishes +//! +//! - Produces a [`TypedProgram`] where every expression carries its resolved type +//! - Produces a [`SymbolTable`] consumed by tackifier and codegen +//! - Produces a [`NameGenerator`] with counters for the tackifier to continue from +//! - Detects semantic errors and exits with code 30 +//! +//! ## Call Order +//! +//! ```text +//! resolve_program() — public entry point (Pass 1 + Pass 2) +//! │ +//! │ ── Pass 1: Resolution ── +//! ├─ label_block() — assign loop/switch IDs +//! │ └─ label_statement() — break/continue/case label generation +//! ├─ resolve_file_var_declaration() — register file-scope vars (no rename) +//! ├─ resolve_fun_decoration() — process each function +//! │ ├─ resolve_param() — rename parameters +//! │ └─ resolve_block() — process function body +//! │ ├─ resolve_local_var_decoration() — rename locals, check shadowing +//! │ └─ resolve_statement() — resolve expressions in statements +//! │ └─ resolve_exp() — replace var names with unique renames +//! │ +//! │ ── Pass 2: Type Checking ── +//! └─ typecheck_program() — called after resolution succeeds +//! ├─ typecheck_file_variable_declaration() — file-scope var rules +//! └─ typecheck_function_declaration() — function type consistency +//! └─ typecheck_block() — process function body +//! ├─ typecheck_local_variable_declaration() +//! └─ typecheck_stmt() — recursive statement typing +//! └─ typecheck_exp() — core: assign types, insert casts +//! ``` + use crate::lexer::Span; use crate::parser::{ - BinOp, Block, BlockItem, Declaration, Expr, ForInit, FunDeclaration, Identifier, Program, SpannedStmt, Stmt, - StorageClass, SwitchIntType, UnaryOp, VarDeclaration, + AssignOp, BinOp, Block as ParserBlock, BlockItem as ParserBlockItem, Const, Declaration, Expr as ParserExpr, + ForInit as ParserForInit, FunDeclaration, Identifier, IncDec, Program, SpannedStmt, Stmt as ParserStmt, + StorageClass, SwitchIntType, Type, UnaryOp, VarDeclaration, }; use colored::*; use std::collections::{HashMap, HashSet}; use std::fmt; +use std::rc::Rc; pub struct SemanticError { message: String, span: Option, } +#[derive(Clone)] +pub struct TypedExpression { + pub exp_type: Type, + pub exp: Expr, +} + +#[derive(Clone)] +pub enum Expr { + Const(Const), + Var(Identifier), + Cast(Type, Box), + Unary(UnaryOp, Box), + Binary(BinOp, Box, Box), + Assignment(Box, Box), + CompoundAssignment(AssignOp, Box, Box, Type), + PostFixOp(IncDec, Box), + PreFixOp(IncDec, Box), + Conditional(Box, Box, Box), + FunctionCall(Identifier, Vec), +} + +pub enum Stmt { + Return(TypedExpression), + Expression(TypedExpression), + If(TypedExpression, Box, Option>), + Goto(Identifier), + Labeled(Identifier, Box), + Compound(Block), + Break(Identifier), + Continue(Identifier), + While(TypedExpression, Box, u64), + DoWhile(Box, TypedExpression, u64), + For( + Box, + Option, + Option, + Box, + u64, + ), + Switch(TypedExpression, Box, u64, HashSet), + Case(TypedExpression, Box, Identifier), + Default(Box, Identifier), + Null, +} + +pub type Block = Vec; + +pub enum BlockItem { + Statement(Stmt), + Declaration(TypedDeclaration), +} + +pub enum ForInit { + InitDecl(TypedVarDeclaration), + InitExp(Option), +} + +impl Expr { + pub fn with_type(self, exp_type: Type) -> TypedExpression { + TypedExpression { exp_type, exp: self } + } +} + +pub struct TypedFunction { + pub name: Identifier, + pub params: Vec, + pub body: Option, + pub fun_type: Type, + pub global: bool, +} + +pub enum TypedDeclaration { + Function(TypedFunction), + Variable(TypedVarDeclaration), +} + +pub struct TypedProgram { + pub declarations: Vec, +} + +pub struct TypedVarDeclaration { + pub name: Identifier, + pub init: Option, + pub var_type: Type, + pub storage_class: Option, +} + impl SemanticError { fn with_span(message: String, span: Span) -> Self { SemanticError { @@ -24,41 +174,314 @@ impl SemanticError { impl fmt::Debug for SemanticError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.span { - Some(span) => write!(f, "{}: {}: {}", span, "SemanticError".red(), self.message), + Some(span) => write!(f, "{}: {}: {}", span, "error".red(), self.message), None => write!(f, "{}: {}", "error".red(), self.message), } } } -#[derive(Clone)] +#[derive(Clone, Copy)] pub enum InitialValue { Tentative, - Initial(i32), + Initial(StaticInt), NoInitializer, } -pub enum SymbolType { - Int(InitialValue), - FunType { param_cnt: usize, defined: bool }, +/// A compile-time integer value for static variable initializers. +/// +/// Carries both the value and its type so that zero-initialized `.bss` vs +/// initialized `.data` placement can be decided later in emission. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum StaticInt { + IntInit(i32), + LongInit(i64), } +impl StaticInt { + fn get_type(&self) -> Type { + match self { + StaticInt::IntInit(_) => Type::Int, + StaticInt::LongInit(_) => Type::Long, + } + } + + fn to_const(self) -> Const { + match self { + StaticInt::IntInit(i) => Const::ConstInt(i), + StaticInt::LongInit(l) => Const::ConstLong(l), + } + } + + pub fn get_common(self, other: Self) -> (Self, Self) { + let common_type = get_common_type(&self.get_type(), &other.get_type()); + // Promotion only widens to the common type, so it never truncates — ignore the flag. + let (left, _) = convert_to_type(self, &common_type); + let (right, _) = convert_to_type(other, &common_type); + (left, right) + } + + fn neg(self) -> (Self, bool) { + match self { + StaticInt::IntInit(v) => { + let (v, o) = v.overflowing_neg(); + (StaticInt::IntInit(v), o) + } + StaticInt::LongInit(v) => { + let (v, o) = v.overflowing_neg(); + (StaticInt::LongInit(v), o) + } + } + } + + fn add(self, other: Self) -> (Self, bool) { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => { + let (v, o) = a.overflowing_add(b); + (StaticInt::IntInit(v), o) + } + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => { + let (v, o) = a.overflowing_add(b); + (StaticInt::LongInit(v), o) + } + _ => unreachable!(), + } + } + + fn sub(self, other: Self) -> (Self, bool) { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => { + let (v, o) = a.overflowing_sub(b); + (StaticInt::IntInit(v), o) + } + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => { + let (v, o) = a.overflowing_sub(b); + (StaticInt::LongInit(v), o) + } + _ => unreachable!(), + } + } + + fn mul(self, other: Self) -> (Self, bool) { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => { + let (v, o) = a.overflowing_mul(b); + (StaticInt::IntInit(v), o) + } + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => { + let (v, o) = a.overflowing_mul(b); + (StaticInt::LongInit(v), o) + } + _ => unreachable!(), + } + } + + fn is_zero(&self) -> bool { + match self { + StaticInt::IntInit(v) => *v == 0, + StaticInt::LongInit(v) => *v == 0, + } + } + + fn as_i64(&self) -> i64 { + match *self { + StaticInt::IntInit(v) => v as i64, + StaticInt::LongInit(v) => v, + } + } + + fn div(self, other: Self) -> Result<(Self, bool), ConstEvalError> { + if other.is_zero() { + return Err(ConstEvalError::DivByZero); + } + let (left, right) = self.get_common(other); + Ok(match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => { + let (v, o) = a.overflowing_div(b); + (StaticInt::IntInit(v), o) + } + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => { + let (v, o) = a.overflowing_div(b); + (StaticInt::LongInit(v), o) + } + _ => unreachable!(), + }) + } + + fn rem(self, other: Self) -> Result<(Self, bool), ConstEvalError> { + if other.is_zero() { + return Err(ConstEvalError::DivByZero); + } + let (left, right) = self.get_common(other); + Ok(match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => { + let (v, o) = a.overflowing_rem(b); + (StaticInt::IntInit(v), o) + } + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => { + let (v, o) = a.overflowing_rem(b); + (StaticInt::LongInit(v), o) + } + _ => unreachable!(), + }) + } + + fn bitwise_and(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(a & b), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::LongInit(a & b), + _ => unreachable!(), + } + } + + fn bitwise_or(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(a | b), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::LongInit(a | b), + _ => unreachable!(), + } + } + + fn bitwise_xor(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(a ^ b), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::LongInit(a ^ b), + _ => unreachable!(), + } + } + + /// Left shift. Shift amount is masked (& 31 for int, & 63 for long) to prevent + /// undefined behavior, matching x86 hardware semantics. + fn shl(self, other: Self) -> Self { + let shift_amount = match other { + StaticInt::IntInit(v) => v as u32, + StaticInt::LongInit(v) => v as u32, + }; + + match self { + StaticInt::IntInit(a) => StaticInt::IntInit(a << (shift_amount & 31)), + StaticInt::LongInit(a) => StaticInt::LongInit(a << (shift_amount & 63)), + } + } + + /// Right shift (arithmetic). Shift amount is masked (& 31 for int, & 63 for long) + /// to prevent undefined behavior, matching x86 hardware semantics. + fn shr(self, other: Self) -> Self { + let shift_amount = match other { + StaticInt::IntInit(v) => v as u32, + StaticInt::LongInit(v) => v as u32, + }; + + match self { + StaticInt::IntInit(a) => StaticInt::IntInit(a >> (shift_amount & 31)), + StaticInt::LongInit(a) => StaticInt::LongInit(a >> (shift_amount & 63)), + } + } + + fn eq(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a == b { 1 } else { 0 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a == b { 1 } else { 0 }), + _ => unreachable!(), + } + } + + fn ne(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a == b { 0 } else { 1 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a == b { 0 } else { 1 }), + _ => unreachable!(), + } + } + + fn lt(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a < b { 1 } else { 0 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a < b { 1 } else { 0 }), + _ => unreachable!(), + } + } + + fn le(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a <= b { 1 } else { 0 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a <= b { 1 } else { 0 }), + _ => unreachable!(), + } + } + + fn gt(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a > b { 1 } else { 0 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a > b { 1 } else { 0 }), + _ => unreachable!(), + } + } + + fn ge(self, other: Self) -> Self { + let (left, right) = self.get_common(other); + match (left, right) { + (StaticInt::IntInit(a), StaticInt::IntInit(b)) => StaticInt::IntInit(if a >= b { 1 } else { 0 }), + (StaticInt::LongInit(a), StaticInt::LongInit(b)) => StaticInt::IntInit(if a >= b { 1 } else { 0 }), + _ => unreachable!(), + } + } + + fn and(self, other: Self) -> Self { + StaticInt::IntInit(if !self.is_zero() && !other.is_zero() { 1 } else { 0 }) + } + + fn or(self, other: Self) -> Self { + StaticInt::IntInit(if !self.is_zero() || !other.is_zero() { 1 } else { 0 }) + } +} + +/// Symbol table entry for variables and functions. +/// +/// # Fields +/// +/// - `symbol_type`: The type of the symbol (Int, Long, or FunType) +/// - For functions, `FunType.defined` tracks if the function has a body +/// +/// - `global`: Linkage scope +/// - `true` = external linkage (visible across translation units) +/// - `false` = internal linkage (static) or no linkage (local variables) +/// +/// - `val`: Initial value for **variables only** +/// - `Initial(value)` = has a constant initializer (definition) +/// - `Tentative` = file-scope without initializer (tentative definition) +/// - `NoInitializer` = extern declaration or local variable without initializer +/// - Unused for functions +/// +/// - `span`: Source location of the definition, or most recent declaration if never defined pub struct Symbol { - pub(crate) symbol_type: SymbolType, - pub(crate) global: bool, + pub symbol_type: Type, + pub global: bool, + pub val: InitialValue, span: Span, } -pub type SymbolTable = HashMap; +pub type SymbolTable = HashMap, Symbol>; #[derive(Clone)] struct VarInfo { - renamed: String, + renamed: Rc, span: Span, ext_link: bool, } pub struct NameGenerator { - counts: HashMap, + counts: HashMap, usize>, } impl NameGenerator { @@ -66,10 +489,10 @@ impl NameGenerator { NameGenerator { counts: HashMap::new() } } - pub fn next(&mut self, base: &str) -> String { - let count = self.counts.entry(base.to_string()).or_insert(0); + pub fn next(&mut self, base: &str) -> Rc { + let count = self.counts.entry(Rc::from(base)).or_insert(0); *count += 1; - format!("{base}.{count}") + Rc::from(format!("{base}.{count}")) } } @@ -79,16 +502,26 @@ impl NameGenerator { /// /// **extern**: References an external variable /// - Cannot have an initializer -/// - If not already in symbol table, adds with `NoInitializer` and `global: true` +/// - If not already in symbol table, adds with `NoInitializer`, `global: true` /// - If already exists, must be a variable (not a function) +/// - `defined: false` (no local storage allocated) /// /// **static**: Local variable with static storage duration -/// - Initializer must be a constant expression (or defaults to 0) +/// - Initializer evaluated as constant expression (not typechecked) and converted to variable's type +/// - If no initializer, defaults to 0 with appropriate type (int → IntInit(0), long → LongInit(0)) +/// - Added to symbol table with `global: false` +/// - `defined: true` (allocates static storage) +/// +/// **none (automatic)**: Regular local variable with automatic storage +/// - Initializer is typechecked and converted to variable's type /// - Added to symbol table with `global: false` +/// - `defined: true` (allocates stack storage) /// -/// **none (automatic)**: Regular local variable -/// - Added to symbol table, initializer typechecked if present -fn typecheck_local_variable_declaration(decl: &VarDeclaration, symbols: &mut SymbolTable) -> Result<(), SemanticError> { +/// The `defined` field is set to `decl.storage_class != Some(StorageClass::Extern)`. +fn typecheck_local_variable_declaration( + decl: &VarDeclaration, + symbols: &mut SymbolTable, +) -> Result { if decl.storage_class == Some(StorageClass::Extern) { if decl.init.is_some() { return Err(SemanticError::with_span( @@ -97,7 +530,7 @@ fn typecheck_local_variable_declaration(decl: &VarDeclaration, symbols: &mut Sym )); } if let Some(old_dec) = symbols.get(&decl.name.0) { - if !matches!(old_dec.symbol_type, SymbolType::Int(_)) { + if old_dec.symbol_type != decl.var_type { return Err(SemanticError::with_span( format!( "'{}' redeclared as different kind of symbol\n{}: {}: previous declaration was here", @@ -112,34 +545,30 @@ fn typecheck_local_variable_declaration(decl: &VarDeclaration, symbols: &mut Sym symbols.insert( decl.name.0.clone(), Symbol { - symbol_type: SymbolType::Int(InitialValue::NoInitializer), + symbol_type: decl.var_type.clone(), global: true, + val: InitialValue::NoInitializer, span: decl.span, }, ); } } else if decl.storage_class == Some(StorageClass::Static) { let initial_value = if let Some(expr) = decl.init.as_ref() { - match eval_constant_expr(expr) { - None => { - return Err(SemanticError::with_span( - format!( - "initializer for static variable '{}' is not a constant expression", - decl.name.0.bold() - ), - decl.span, - )); - } - Some(c) => InitialValue::Initial(c), - } + eval_static_initializer(expr, &decl.var_type, &decl.name, decl.span)? } else { - InitialValue::Initial(0) + let zero = match decl.var_type { + Type::Int => StaticInt::IntInit(0), + Type::Long => StaticInt::LongInit(0), + _ => unreachable!("static variable must be int or long"), + }; + InitialValue::Initial(zero) }; symbols.insert( decl.name.0.clone(), Symbol { - symbol_type: SymbolType::Int(initial_value), + symbol_type: decl.var_type.clone(), global: false, + val: initial_value, span: decl.span, }, ); @@ -148,16 +577,27 @@ fn typecheck_local_variable_declaration(decl: &VarDeclaration, symbols: &mut Sym symbols.insert( decl.name.0.clone(), Symbol { - symbol_type: SymbolType::Int(InitialValue::NoInitializer), + symbol_type: decl.var_type.clone(), global: false, + val: InitialValue::NoInitializer, span: decl.span, }, ); - if let Some(init) = &decl.init { - typecheck_exp(init, symbols)?; - } } - Ok(()) + // Convert init expression to typed form (typecheck happens once here for all branches) + let typed_init = decl + .init + .as_ref() + .map(|e| typecheck_exp(e.clone(), symbols)) // TODO: expensive clone of ParserExpr - refactor typecheck_exp to take &ParserExpr + .transpose()? + .map(|exp| convert_to(exp, &decl.var_type)); + + Ok(TypedVarDeclaration { + name: decl.name.clone(), + init: typed_init, + var_type: decl.var_type.clone(), + storage_class: decl.storage_class.clone(), + }) } /// Validates a file-scope variable declaration and updates the symbol table. @@ -174,17 +614,12 @@ fn typecheck_local_variable_declaration(decl: &VarDeclaration, symbols: &mut Sym /// - No initializer + not `extern` → `Tentative` /// /// The span stored is the location of the definition, or most recent declaration if never defined. -fn typecheck_file_variable_declaration(decl: &VarDeclaration, symbols: &mut SymbolTable) -> Result<(), SemanticError> { +fn typecheck_file_variable_declaration( + decl: VarDeclaration, + symbols: &mut SymbolTable, +) -> Result { let mut initial_value = if let Some(expr) = &decl.init { - match eval_constant_expr(expr) { - None => { - return Err(SemanticError::with_span( - format!("initializer for '{}' is not a constant expression", decl.name.0.bold()), - decl.span, - )); - } - Some(c) => InitialValue::Initial(c), - } + eval_static_initializer(expr, &decl.var_type, &decl.name, decl.span)? } else if decl.storage_class == Some(StorageClass::Extern) { InitialValue::NoInitializer } else { @@ -196,7 +631,7 @@ fn typecheck_file_variable_declaration(decl: &VarDeclaration, symbols: &mut Symb if let Some(old_dec) = symbols.get(&decl.name.0) { let old_init = match &old_dec.symbol_type { - SymbolType::FunType { .. } => { + Type::FunType { .. } => { return Err(SemanticError::with_span( format!( "'{}' redeclared as different kind of symbol\n{}: {}: previous declaration was here", @@ -207,7 +642,20 @@ fn typecheck_file_variable_declaration(decl: &VarDeclaration, symbols: &mut Symb decl.span, )); } - SymbolType::Int(old_init) => old_init.clone(), + Type::Int | Type::Long => { + if old_dec.symbol_type != decl.var_type { + return Err(SemanticError::with_span( + format!( + "conflicting types for '{}'\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + &old_dec.val + } }; if decl.storage_class == Some(StorageClass::Extern) { @@ -236,7 +684,7 @@ fn typecheck_file_variable_declaration(decl: &VarDeclaration, symbols: &mut Symb decl.span, )); } else { - initial_value = old_init; + initial_value = *old_init; saved_span = old_dec.span; } } else if !matches!(initial_value, InitialValue::Initial(_)) && matches!(old_init, InitialValue::Tentative) { @@ -247,71 +695,406 @@ fn typecheck_file_variable_declaration(decl: &VarDeclaration, symbols: &mut Symb symbols.insert( decl.name.0.clone(), Symbol { - symbol_type: SymbolType::Int(initial_value), + symbol_type: decl.var_type.clone(), global, + val: initial_value, span: saved_span, }, ); - Ok(()) + + let typed_init = match initial_value { + InitialValue::Initial(static_val) => { + let const_val = static_val.to_const(); + Some(TypedExpression { + exp_type: decl.var_type.clone(), + exp: Expr::Const(const_val), + }) + } + InitialValue::NoInitializer | InitialValue::Tentative => None, + }; + + Ok(TypedVarDeclaration { + name: decl.name, + init: typed_init, + var_type: decl.var_type, + storage_class: decl.storage_class, + }) +} + +pub(crate) fn get_common_type(t1: &Type, t2: &Type) -> Type { + if t1 == t2 { t1.clone() } else { Type::Long } +} + +fn convert_to(exp: TypedExpression, t: &Type) -> TypedExpression { + if exp.exp_type == *t { + exp + } else { + let cast_exp = Expr::Cast(t.clone(), Box::new(exp)); + cast_exp.with_type(t.clone()) + } +} + +/// `-Wsequence-point`: entry point for one *full* expression. Warns when the same object is +/// modified more than once with no sequence point in between — undefined in standard C (NCC itself +/// evaluates left-to-right, so the result is well-defined but the code is non-portable). +/// +/// Call once per full expression (expression statements, conditions, `return`, initializers) — NOT +/// on sub-expressions, or nested cases would be reported twice. +fn check_sequence_points(expr: &ParserExpr) { + let mut region: HashMap, Span> = HashMap::new(); + walk_region(expr, &mut region); } -fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticError> { +/// Walks `expr` within the current unsequenced region, recording modifications into `region`. +/// Sequence-point operators (`&&`, `||`, `?:`, and function-call arguments) start fresh regions +/// via [`check_sequence_points`]; everything else shares the region with its operands. +fn walk_region(expr: &ParserExpr, region: &mut HashMap, Span>) { + match expr { + ParserExpr::Assignment(lhs, rhs, span) | ParserExpr::CompoundAssignment(_, lhs, rhs, span) => { + warn_sequence_point(lhs, *span, region); + walk_region(rhs, region); + } + ParserExpr::PreFixOp(_, inner, span) | ParserExpr::PostFixOp(_, inner, span) => { + warn_sequence_point(inner, *span, region); + } + ParserExpr::Binary(op, lhs, rhs, _) => { + if matches!(op, BinOp::And | BinOp::Or) { + // sequence points + check_sequence_points(lhs); + check_sequence_points(rhs); + } else { + walk_region(lhs, region); + walk_region(rhs, region); + } + } + ParserExpr::Unary(_, e) | ParserExpr::Cast(_, e) => walk_region(e, region), + ParserExpr::Conditional(c, t, f) => { + check_sequence_points(c); + check_sequence_points(t); + check_sequence_points(f); + } + ParserExpr::FunctionCall(_, args, _) => { + // args have no sequence points between them + let mut arg_region = HashMap::new(); + for a in args { + walk_region(a, &mut arg_region); + } + } + ParserExpr::Var(..) | ParserExpr::Constant(..) => {} + } +} + +/// Records a modification of the object named by `target` (an lvalue, always a `Var` in this +/// subset). A second modification of the same object in the current region is an unsequenced +/// double-modification — emit `-Wsequence-point`. +fn warn_sequence_point(target: &ParserExpr, span: Span, region: &mut HashMap, Span>) { + if let ParserExpr::Var(Identifier(name), _) = target + && region.insert(name.clone(), span).is_some() + { + eprintln!( + "{}: {}: '{}' modified more than once between sequence points (undefined in standard C; NCC evaluates left-to-right) {}", + span, + "warning".purple(), + name, + "[-Wsequence-point]".purple() + ) + } +} + +/// `-Wdiv-by-zero`: warn if a `/` or `%` (or `/=` / `%=`) divisor folds to a constant 0. +/// `is_division` selects the message wording (division vs remainder). +fn warn_div_by_zero(is_division: bool, rhs: &ParserExpr, span: Span) { + if let Ok((v, _)) = eval_constant_expr(rhs) + && v.is_zero() + { + eprintln!( + "{}: {}: {} by zero {}", + span, + "warning".purple(), + if is_division { "division" } else { "remainder" }, + "[-Wdiv-by-zero]".purple() + ); + } +} + +/// `-Wshift-count-overflow` / `-Wshift-count-negative`: warn if a shift's constant count is +/// negative or `>=` the width of the left operand's type (`int` -> 32, `long` -> 64). +fn warn_shift_count(left_type: &Type, rhs: &ParserExpr, span: Span) { + if let Ok((v, _)) = eval_constant_expr(rhs) { + let width: i64 = match left_type { + Type::Long => 64, + _ => 32, + }; + let count = v.as_i64(); + if count < 0 { + eprintln!( + "{}: {}: shift count is negative {}", + span, + "warning".purple(), + "[-Wshift-count-negative]".purple() + ); + } else if count >= width { + eprintln!( + "{}: {}: shift count >= width of type ({}) {}", + span, + "warning".purple(), + width, + "[-Wshift-count-overflow]".purple() + ); + } + } +} + +/// `-Woverflow`: a constant fold whose result left the result type. NCC wraps deterministically +/// (two's complement), so this flags non-portable code rather than reporting UB. Only emitted in +/// constant contexts (static initializers, case labels), where `eval_constant_expr` folds. +fn warn_overflow(overflowed: bool, span: Span) { + if overflowed { + eprintln!( + "{}: {}: integer overflow in constant expression (result wraps) {}", + span, + "warning".purple(), + "[-Woverflow]".purple() + ); + } +} + +/// `-Wconstant-conversion`: an implicit narrowing conversion of a constant that changed its value +/// (e.g. `int x = 0x1FFFFFFFF;`). `changed` is the truncation flag from `convert_to_type`. Explicit +/// casts suppress this — the caller only invokes it for implicit conversions. +fn warn_constant_conversion(changed: bool, from: i64, to: i64, span: Span) { + if changed { + eprintln!( + "{}: {}: implicit conversion changes constant value from {} to {} {}", + span, + "warning".purple(), + from, + to, + "[-Wconstant-conversion]".purple() + ); + } +} + +/// `-Wshadow`: a declaration shadows one in an outer scope. `prev` is the shadowed entry's span +/// (the value returned when inserting into the scope map), or `None` if nothing was shadowed. +/// Emits the warning plus a note pointing at the previous declaration. +fn warn_shadow(name: &str, span: Span, prev: Option) { + if let Some(prev_span) = prev { + eprintln!( + "{}: {}: variable {} shadows previous declaration {}", + span, + "warning".purple(), + format!("'{}'", name).bold(), + "[-Wshadow]".purple() + ); + eprintln!( + "{}: {}: previous declaration of {} was here", + prev_span, + "note".cyan(), + format!("'{}'", name).bold() + ); + } +} + +/// `-Wunused-parameter`: a function parameter (in a function with a body) is never referenced. +/// `used` is whether the parameter appears in the body; `name` is the original source name. +fn warn_unused_parameter(used: bool, name: &str, span: Span) { + if !used { + eprintln!( + "{}: {}: unused parameter '{}' {}", + span, + "warning".purple(), + name.bold(), + "[-Wunused-parameter]".purple() + ); + } +} + +/// Type-checks an expression, returning a `TypedExpression` with a resolved type. +/// +/// Inserts implicit casts where operand types differ (using the common-type rule), +/// with special cases: logical ops always produce `Int`, bitshifts keep the left operand's +/// type, comparisons produce `Int`, and assignments convert the RHS to the LHS type. +/// Validates function call arity and argument types against the symbol table. +/// +/// Also emits warnings for constant operands that are valid but suspect: `-Wdiv-by-zero` +/// (constant zero divisor) and `-Wshift-count-overflow` / `-Wshift-count-negative` +/// (constant shift count outside `0..width`, where width comes from the left operand's type). +fn typecheck_exp(exp: ParserExpr, symbols: &mut SymbolTable) -> Result { match exp { - Expr::Constant(_) => Ok(()), - Expr::Var(Identifier(name), span) => { - if let Some(expected) = symbols.get(name) { - match expected.symbol_type { - SymbolType::FunType { .. } => Err(SemanticError::with_span( - format!("cannot use function '{}' as a variable", name.bold()), - *span, - )), - SymbolType::Int(_) => Ok(()), + ParserExpr::Var(Identifier(name), span) => { + let v_type = &symbols + .get(&name) + .expect("Undefined variable in typechecking") + .symbol_type; + match v_type { + Type::FunType { .. } => Err(SemanticError::with_span( + format!("cannot use function '{}' as a variable", name.bold()), + span, + )), + _ => { + let typed_var = Expr::Var(Identifier(name)); + Ok(typed_var.with_type(v_type.clone())) } - } else { - unreachable!("Undefined variable in typechecking") } } - Expr::Unary(_, e1) | Expr::PostFixOp(_, e1, _) | Expr::PreFixOp(_, e1, _) => typecheck_exp(e1, symbols), - Expr::Binary(_, e1, e2) | Expr::Assignment(e1, e2, _) | Expr::CompoundAssignment(_, e1, e2, _) => { - typecheck_exp(e1, symbols)?; - typecheck_exp(e2, symbols) - } - Expr::Conditional(e1, e2, e3) => { - typecheck_exp(e1, symbols)?; - typecheck_exp(e2, symbols)?; - typecheck_exp(e3, symbols) - } - Expr::FunctionCall(Identifier(name), args, span) => { - if let Some(expected) = symbols.get(name) { - match expected.symbol_type { - SymbolType::FunType { param_cnt, defined: _ } => { - if param_cnt != args.len() { - Err(SemanticError::with_span( - format!( - "function '{}' expects {} argument{} but {} {} provided", - name.bold(), - param_cnt, - if param_cnt == 1 { "" } else { "s" }, - args.len(), - if args.len() == 1 { "was" } else { "were" } - ), - *span, - )) - } else { - for arg in args { - typecheck_exp(arg, symbols)? - } - Ok(()) - } - } - SymbolType::Int(_) => Err(SemanticError::with_span( - format!("cannot call '{}' as a function: identifier is a variable", name.bold()), - *span, - )), + ParserExpr::Constant(c) => match c { + Const::ConstInt(_) => Ok(TypedExpression { + exp_type: Type::Int, + exp: Expr::Const(c), + }), + Const::ConstLong(_) => Ok(TypedExpression { + exp_type: Type::Long, + exp: Expr::Const(c), + }), + }, + ParserExpr::Cast(t, inner) => { + let typed_inner = typecheck_exp(*inner, symbols)?; + let cast_exp = Expr::Cast(t.clone(), Box::new(typed_inner)); + Ok(cast_exp.with_type(t)) + } + ParserExpr::Unary(op, inner) => { + let typed_inner = typecheck_exp(*inner, symbols)?; + let inner_type = typed_inner.exp_type.clone(); + let unary_exp = Expr::Unary(op, Box::new(typed_inner)); + match op { + UnaryOp::Not => Ok(unary_exp.with_type(Type::Int)), + _ => Ok(unary_exp.with_type(inner_type)), + } + } + ParserExpr::PreFixOp(incdec, inner, _) => { + let typed_inner = typecheck_exp(*inner, symbols)?; + let inner_type = typed_inner.exp_type.clone(); + Ok(Expr::PreFixOp(incdec, Box::new(typed_inner)).with_type(inner_type)) + } + ParserExpr::PostFixOp(incdec, inner, _) => { + let typed_inner = typecheck_exp(*inner, symbols)?; + let inner_type = typed_inner.exp_type.clone(); + Ok(Expr::PostFixOp(incdec, Box::new(typed_inner)).with_type(inner_type)) + } + ParserExpr::Binary(op, lhs, rhs, span) => { + // -Wdiv-by-zero: constant divisor of 0 (compiles, but SIGFPEs at runtime) + if matches!(op, BinOp::Divide | BinOp::Remainder) { + warn_div_by_zero(matches!(op, BinOp::Divide), &rhs, span); + } + let typed_lhs = typecheck_exp(*lhs, symbols)?; + // -Wshift-count-*: width comes from the left operand's type, so this must run after + // typecheck_lhs but before `rhs` is moved into typecheck_exp below. + if matches!(op, BinOp::BitwiseLeftShift | BinOp::BitwiseRightShift) { + warn_shift_count(&typed_lhs.exp_type, &rhs, span); + } + let typed_rhs = typecheck_exp(*rhs, symbols)?; + if matches!(op, BinOp::And | BinOp::Or) { + let binary_exp = Expr::Binary(op, Box::new(typed_lhs), Box::new(typed_rhs)); + return Ok(binary_exp.with_type(Type::Int)); + }; + + // Bitshift: result type is the type of left operand (not common type) + if matches!(op, BinOp::BitwiseLeftShift | BinOp::BitwiseRightShift) { + let result_type = typed_lhs.exp_type.clone(); + let binary_exp = Expr::Binary(op, Box::new(typed_lhs), Box::new(typed_rhs)); + return Ok(binary_exp.with_type(result_type)); + } + + let common_type = get_common_type(&typed_lhs.exp_type, &typed_rhs.exp_type); + let converted_lhs = convert_to(typed_lhs, &common_type); + let converted_rhs = convert_to(typed_rhs, &common_type); + let binary_exp = Expr::Binary(op, Box::new(converted_lhs), Box::new(converted_rhs)); + let result_type = match op { + BinOp::Add + | BinOp::Subtract + | BinOp::Multiply + | BinOp::Divide + | BinOp::Remainder + | BinOp::BitwiseAnd + | BinOp::BitwiseOr + | BinOp::BitwiseXOr => common_type, + BinOp::Equal + | BinOp::NotEqual + | BinOp::LessThan + | BinOp::LessOrEqual + | BinOp::GreaterThan + | BinOp::GreaterOrEqual => Type::Int, + _ => unreachable!(), + }; + Ok(binary_exp.with_type(result_type)) + } + ParserExpr::Assignment(lhs, rhs, _) => { + let typed_lhs = typecheck_exp(*lhs, symbols)?; + let typed_rhs = typecheck_exp(*rhs, symbols)?; + let left_type = typed_lhs.exp_type.clone(); + let converted_rhs = convert_to(typed_rhs, &left_type); + let assign_exp = Expr::Assignment(Box::new(typed_lhs), Box::new(converted_rhs)); + Ok(assign_exp.with_type(left_type)) + } + ParserExpr::Conditional(condition, then_exp, else_exp) => { + let typed_condition = typecheck_exp(*condition, symbols)?; + let typed_then_exp = typecheck_exp(*then_exp, symbols)?; + let typed_else_exp = typecheck_exp(*else_exp, symbols)?; + let common_type = get_common_type(&typed_then_exp.exp_type, &typed_else_exp.exp_type); + let converted_then = convert_to(typed_then_exp, &common_type); + let converted_else = convert_to(typed_else_exp, &common_type); + let conditional = Expr::Conditional( + Box::new(typed_condition), + Box::new(converted_then), + Box::new(converted_else), + ); + Ok(conditional.with_type(common_type)) + } + ParserExpr::CompoundAssignment(op, lhs, rhs, span) => { + if matches!(op, AssignOp::Divide | AssignOp::Remainder) { + warn_div_by_zero(matches!(op, AssignOp::Divide), &rhs, span); + } + let typed_lhs = typecheck_exp(*lhs, symbols)?; + if matches!(op, AssignOp::BitwiseLeftShift | AssignOp::BitwiseRightShift) { + warn_shift_count(&typed_lhs.exp_type, &rhs, span); + } + let typed_rhs = typecheck_exp(*rhs, symbols)?; + let left_type = typed_lhs.exp_type.clone(); + let op_type = match op { + AssignOp::BitwiseLeftShift | AssignOp::BitwiseRightShift => left_type.clone(), + _ => get_common_type(&typed_lhs.exp_type, &typed_rhs.exp_type), + }; + let compound = Expr::CompoundAssignment(op, Box::new(typed_lhs), Box::new(typed_rhs), op_type); + Ok(compound.with_type(left_type)) + } + ParserExpr::FunctionCall(Identifier(name), param_exps, span) => { + let f_type = &symbols + .get(&name) + .expect("Undefined function in typechecking") + .symbol_type; + let (param_types, ret_type) = match f_type { + Type::FunType { params, ret, .. } => (params.clone(), ret.clone()), + _ => { + return Err(SemanticError::with_span( + format!("'{}' is not a function", name.bold()), + span, + )); } - } else { - unreachable!("Undefined function call in typechecking") + }; + + if param_types.len() != param_exps.len() { + return Err(SemanticError::with_span( + format!( + "function '{}' expects {} argument{} but {} {} provided", + name.bold(), + param_types.len(), + if param_types.len() == 1 { "" } else { "s" }, + param_exps.len(), + if param_exps.len() == 1 { "was" } else { "were" } + ), + span, + )); } + + let mut converted_args = Vec::with_capacity(param_exps.len()); + for (arg, param_type) in param_exps.iter().zip(param_types.iter()) { + let typed_arg = typecheck_exp(arg.clone(), symbols)?; + let converted_arg = convert_to(typed_arg, param_type); + converted_args.push(converted_arg); + } + let call_exp = Expr::FunctionCall(Identifier(name), converted_args); + Ok(call_exp.with_type(*ret_type)) } } } @@ -324,20 +1107,33 @@ fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticEr /// - A `static` declaration cannot follow a non-static declaration /// - Global linkage is inherited from the first declaration /// +/// Returns `Some(TypedFunction)` if the function has a body (definition), +/// or `None` if it's just a declaration. +/// /// The span stored in the symbol table is the location of the function's /// definition (body), or the most recent declaration if never defined. -fn typecheck_function_declaration(decl: &FunDeclaration, symbols: &mut SymbolTable) -> Result<(), SemanticError> { - let param_cnt = decl.params.len(); +fn typecheck_function_declaration( + decl: FunDeclaration, + symbols: &mut SymbolTable, +) -> Result, SemanticError> { let mut global = decl.storage_class != Some(StorageClass::Static); let mut defined = decl.body.is_some(); let mut saved_span = decl.span; + let mut fun_type = decl.fun_type; + + let (new_param_types, new_ret_type) = match &fun_type { + Type::FunType { params, ret, .. } => (params.clone(), ret.clone()), + _ => unreachable!("Function declaration must have FunType"), + }; + if let Some(old_dec) = symbols.get(&decl.name.0) { - match old_dec.symbol_type { - SymbolType::FunType { - param_cnt: old_param_cnt, + match &old_dec.symbol_type { + Type::FunType { + params: old_params, + ret: old_ret_type, defined: old_defined, } => { - if old_param_cnt != param_cnt { + if *old_params != new_param_types || old_ret_type != &new_ret_type { return Err(SemanticError::with_span( format!( "incompatible declaration of function '{}'\n{}: {}: previous declaration was here", @@ -348,7 +1144,7 @@ fn typecheck_function_declaration(decl: &FunDeclaration, symbols: &mut SymbolTab decl.span, )); } - if old_defined { + if *old_defined { if decl.body.is_some() { return Err(SemanticError::with_span( format!( @@ -369,9 +1165,9 @@ fn typecheck_function_declaration(decl: &FunDeclaration, symbols: &mut SymbolTab )); } global = old_dec.global; - defined = defined || old_defined; + defined = defined || *old_defined; } - SymbolType::Int(_) => { + Type::Int | Type::Long => { return Err(SemanticError::with_span( format!( "redeclaration of '{}' as a function\n{}: {}: previous declaration was here", @@ -385,100 +1181,207 @@ fn typecheck_function_declaration(decl: &FunDeclaration, symbols: &mut SymbolTab } } + // Update the function type's defined field based on redeclarations + if let Type::FunType { defined: ref mut d, .. } = fun_type { + *d = defined; + } + symbols.insert( decl.name.0.clone(), Symbol { - symbol_type: SymbolType::FunType { param_cnt, defined }, + symbol_type: fun_type.clone(), global, + val: InitialValue::NoInitializer, span: saved_span, }, ); - if let Some(body) = decl.body.as_ref() { - for Identifier(name) in &decl.params { + // If function has a body, typecheck it and return TypedFunction + if let Some(body) = decl.body { + for (Identifier(name), param_type) in decl.params.iter().zip(new_param_types.iter()) { symbols.insert( name.clone(), Symbol { - symbol_type: SymbolType::Int(InitialValue::NoInitializer), + symbol_type: param_type.clone(), global: false, + val: InitialValue::NoInitializer, span: decl.span, }, ); } - typecheck_block(body, symbols) + let typed_body = typecheck_block(body, symbols, &new_ret_type)?; + + Ok(Some(TypedFunction { + name: decl.name, + params: decl.params, + body: Some(typed_body), + fun_type, + global, + })) } else { - Ok(()) + // Just a declaration, no body + Ok(None) } } -fn typecheck_block(block: &Block, symbols: &mut SymbolTable) -> Result<(), SemanticError> { +/// Type-checks a block (compound statement), processing declarations and statements in order. +/// +/// Variable declarations are type-checked as locals; function declarations in blocks +/// are validated but produce no output (bodies are forbidden, enforced in the resolve phase). +fn typecheck_block(block: ParserBlock, symbols: &mut SymbolTable, ret_type: &Type) -> Result { + let mut typed_items = Vec::with_capacity(block.len()); for item in block { match item { - BlockItem::Declaration(Declaration::VarDeclaration(var)) => { - typecheck_local_variable_declaration(var, symbols)?; + ParserBlockItem::Declaration(Declaration::VarDeclaration(var)) => { + let typed_var = typecheck_local_variable_declaration(&var, symbols)?; + typed_items.push(BlockItem::Declaration(TypedDeclaration::Variable(typed_var))); } - BlockItem::Declaration(Declaration::FunDeclaration(fun)) => { + ParserBlockItem::Declaration(Declaration::FunDeclaration(fun)) => { + // Function declarations in blocks cannot have bodies (already validated in resolve phase) typecheck_function_declaration(fun, symbols)?; } - BlockItem::Statement(stmt) => { - typecheck_stmt(&stmt.stmt, symbols)?; + ParserBlockItem::Statement(stmt) => { + let typed_stmt = typecheck_stmt(stmt.stmt, symbols, ret_type)?; + typed_items.push(BlockItem::Statement(typed_stmt)); } } } - Ok(()) + Ok(typed_items) } -fn typecheck_stmt(stmt: &Stmt, symbols: &mut SymbolTable) -> Result<(), SemanticError> { +/// Type-checks a statement, recursively processing nested expressions and sub-statements. +/// +/// `ret_type` is the enclosing function's return type, used to insert implicit casts +/// on `return` expressions. Switch statements normalize case values to the controlling +/// expression's type and check for duplicates. +fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) -> Result { match stmt { - Stmt::Return(e1) | Stmt::Expression(e1) => typecheck_exp(e1, symbols), - Stmt::If(cond, then_s, else_s) => { - typecheck_exp(cond, symbols)?; - typecheck_stmt(&then_s.stmt, symbols)?; - if let Some(e) = else_s.as_ref() { - typecheck_stmt(&e.stmt, symbols)?; + ParserStmt::Return(e1) => { + let typed_e1 = typecheck_exp(e1, symbols)?; + let converted = convert_to(typed_e1, ret_type); + Ok(Stmt::Return(converted)) + } + ParserStmt::Expression(e1) => { + let typed_e1 = typecheck_exp(e1, symbols)?; + Ok(Stmt::Expression(typed_e1)) + } + ParserStmt::If(cond, then_s, else_s) => { + let typed_cond = typecheck_exp(cond, symbols)?; + let converted_then = typecheck_stmt(then_s.stmt, symbols, ret_type)?; + let typed_else = (*else_s) + .map(|e| typecheck_stmt(e.stmt, symbols, ret_type)) + .transpose()? + .map(Box::new); + Ok(Stmt::If(typed_cond, Box::new(converted_then), typed_else)) + } + ParserStmt::Goto(lbl) => Ok(Stmt::Goto(lbl)), + ParserStmt::Null => Ok(Stmt::Null), + ParserStmt::Break(lbl) => Ok(Stmt::Break(lbl)), + ParserStmt::Continue(lbl) => Ok(Stmt::Continue(lbl)), + ParserStmt::Labeled(lbl, s) => { + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + Ok(Stmt::Labeled(lbl, Box::new(typed_s))) + } + ParserStmt::Default(s, lbl) => { + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + Ok(Stmt::Default(Box::new(typed_s), lbl)) + } + ParserStmt::Compound(block) => { + let typed_block = typecheck_block(block, symbols, ret_type)?; + Ok(Stmt::Compound(typed_block)) + } + ParserStmt::While(e, s, lbl) => { + let typed_e = typecheck_exp(e, symbols)?; + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + Ok(Stmt::While(typed_e, Box::new(typed_s), lbl)) + } + ParserStmt::DoWhile(s, e, lbl) => { + let typed_e = typecheck_exp(e, symbols)?; + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + Ok(Stmt::DoWhile(Box::new(typed_s), typed_e, lbl)) + } + ParserStmt::Switch(e, s, lbl, cases) => { + let typed_e = typecheck_exp(e, symbols)?; + let switch_type = &typed_e.exp_type; + + // Normalize cases and check for duplicates + let mut normalized: HashMap, Span> = HashMap::new(); + for (case, case_span) in cases.iter() { + let norm_value = case.as_i64(switch_type); + if let Some(previous_span) = normalized.insert(norm_value, *case_span) { + let (message, prev_note) = match norm_value { + Some(v) => ( + format!("duplicate case value '{}'", v.to_string().bold()), + "previous case was here", + ), + None => ( + "multiple default labels in one switch".to_string(), + "previous default was here", + ), + }; + return Err(SemanticError::with_span( + format!("{}\n{}: {}: {}", message, previous_span, "note".cyan(), prev_note), + *case_span, + )); + } } - Ok(()) + + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + // Convert Vec to HashSet for output (tacky doesn't need spans) + let cases_set = cases.iter().map(|(c, _span)| *c).collect(); + Ok(Stmt::Switch(typed_e, Box::new(typed_s), lbl, cases_set)) } - Stmt::Goto(_) | Stmt::Null | Stmt::Break(_) | Stmt::Continue(_) => Ok(()), - Stmt::Labeled(_, s) | Stmt::Default(s, _) => typecheck_stmt(&s.stmt, symbols), - Stmt::Compound(block) => typecheck_block(block, symbols), - Stmt::While(e, s, _) | Stmt::DoWhile(s, e, _) | Stmt::Switch(e, s, ..) | Stmt::Case(e, s, _) => { - typecheck_stmt(&s.stmt, symbols)?; - typecheck_exp(e, symbols) + ParserStmt::Case(e, s, lbl) => { + let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_e = typecheck_exp(e, symbols)?; + Ok(Stmt::Case(typed_e, Box::new(typed_s), lbl)) } - Stmt::For(init, cond, post, body, _) => { - match init { - ForInit::InitExp(Some(e)) => typecheck_exp(e, symbols)?, - ForInit::InitExp(None) => {} - ForInit::InitDecl(decl) => { + ParserStmt::For(init, cond, post, body, lbl) => { + let typed_init = match init { + ParserForInit::InitExp(Some(e)) => { + let typed_e = typecheck_exp(e, symbols)?; + ForInit::InitExp(Some(typed_e)) + } + ParserForInit::InitExp(None) => ForInit::InitExp(None), + ParserForInit::InitDecl(decl) => { if decl.storage_class.is_some() { return Err(SemanticError::with_span( "declaration in for loop initializer cannot have storage class".to_string(), decl.span, )); } - typecheck_local_variable_declaration(decl, symbols)? + let typed_var = typecheck_local_variable_declaration(&decl, symbols)?; + ForInit::InitDecl(typed_var) } - } - if let Some(cond) = cond { - typecheck_exp(cond, symbols)?; - } - if let Some(post) = post { - typecheck_exp(post, symbols)?; - } - typecheck_stmt(&body.stmt, symbols) + }; + let typed_cond = cond.map(|e| typecheck_exp(e, symbols)).transpose()?; + let typed_post = post.map(|e| typecheck_exp(e, symbols)).transpose()?; + let typed_body = typecheck_stmt(body.stmt, symbols, ret_type)?; + Ok(Stmt::For( + Box::new(typed_init), + typed_cond, + typed_post, + Box::new(typed_body), + lbl, + )) } } } +/// Resolves variable names in an expression to their unique renamed identifiers. +/// +/// Mutates the AST in place, replacing each `Var` name with its renamed counterpart +/// from `variable_map`. Tracks used variables in `used_vars` (for `-Wunused-parameter`). +/// Also validates lvalue requirements: assignments and pre/postfix operators must +/// target variables. Function calls are checked for shadowing by local variables. fn resolve_exp( - exp: &mut Expr, - variable_map: &HashMap, - used_vars: &mut HashSet, + exp: &mut ParserExpr, + variable_map: &HashMap, VarInfo>, + used_vars: &mut HashSet>, ) -> Result<(), SemanticError> { match exp { - Expr::Assignment(e1, e2, span) | Expr::CompoundAssignment(_, e1, e2, span) => match &**e1 { - Expr::Var(_, _) => { + ParserExpr::Assignment(e1, e2, span) | ParserExpr::CompoundAssignment(_, e1, e2, span) => match &**e1 { + ParserExpr::Var(_, _) => { resolve_exp(e1, variable_map, used_vars)?; resolve_exp(e2, variable_map, used_vars)?; Ok(()) @@ -488,7 +1391,7 @@ fn resolve_exp( *span, )), }, - Expr::Var(Identifier(name), span) => match variable_map.get(name) { + ParserExpr::Var(Identifier(name), span) => match variable_map.get(name) { Some(var_info) => { *name = var_info.renamed.clone(); used_vars.insert(name.clone()); @@ -499,14 +1402,14 @@ fn resolve_exp( *span, )), }, - Expr::Unary(_, e) => resolve_exp(e, variable_map, used_vars), - Expr::Binary(_, left, right) => { + ParserExpr::Unary(_, e) => resolve_exp(e, variable_map, used_vars), + ParserExpr::Binary(_, left, right, _) => { resolve_exp(left, variable_map, used_vars)?; resolve_exp(right, variable_map, used_vars) } - Expr::Constant(_) => Ok(()), - Expr::PostFixOp(_op, e, span) | Expr::PreFixOp(_op, e, span) => match &**e { - Expr::Var(_, _) => { + ParserExpr::Constant(_) => Ok(()), + ParserExpr::PostFixOp(_op, e, span) | ParserExpr::PreFixOp(_op, e, span) => match &**e { + ParserExpr::Var(_, _) => { resolve_exp(e, variable_map, used_vars)?; Ok(()) } @@ -515,13 +1418,13 @@ fn resolve_exp( *span, )), }, - Expr::Conditional(e, then_exp, else_exp) => { + ParserExpr::Conditional(e, then_exp, else_exp) => { resolve_exp(e, variable_map, used_vars)?; resolve_exp(then_exp, variable_map, used_vars)?; resolve_exp(else_exp, variable_map, used_vars)?; Ok(()) } - Expr::FunctionCall(Identifier(name), args, span) => match variable_map.get(name) { + ParserExpr::FunctionCall(Identifier(name), args, span) => match variable_map.get(name) { Some(var_info) => { // checking if new name matches old tells us if we have a variable shadowing if name == &var_info.renamed { @@ -545,17 +1448,18 @@ fn resolve_exp( *span, )), }, + ParserExpr::Cast(_, e) => resolve_exp(e, variable_map, used_vars), } } fn resolve_fun_decoration( dec: &mut FunDeclaration, - variable_map: &mut HashMap, - block_vars: &mut HashSet, - labels: &mut HashSet, - jumps: &mut HashMap, + variable_map: &mut HashMap, VarInfo>, + block_vars: &mut HashSet>, + labels: &mut HashSet>, + jumps: &mut HashMap, Span>, name_gen: &mut NameGenerator, - used_vars: &mut HashSet, + used_vars: &mut HashSet>, ) -> Result<(), SemanticError> { let Identifier(name) = &dec.name; @@ -585,9 +1489,9 @@ fn resolve_fun_decoration( } block_vars.insert(name.clone()); - let mut inner_map = variable_map.clone(); + let mut inner_map = variable_map.clone(); // TODO: expensive clone of HashMap for nested function - necessary for scoping but consider Arc/Rc approach let mut inner_block_vars = HashSet::new(); - let original_params: Vec = dec.params.iter().map(|Identifier(name)| name.clone()).collect(); + let original_params: Vec> = dec.params.iter().map(|Identifier(name)| name.clone()).collect(); for param in &mut dec.params { resolve_param(param, &mut inner_map, name_gen, &mut inner_block_vars, dec.span)?; @@ -606,15 +1510,7 @@ fn resolve_fun_decoration( } if dec.body.is_some() { for (Identifier(param), org_name) in dec.params.iter().zip(original_params) { - if !used_vars.contains(param) { - eprintln!( - "{}: {}: unused parameter '{}' {}", - dec.span, - "warning".purple(), - org_name.bold(), - "[-Wunused-parameter]".purple() - ); - } + warn_unused_parameter(used_vars.contains(param), &org_name, dec.span); } } Ok(()) @@ -622,9 +1518,9 @@ fn resolve_fun_decoration( fn resolve_param( param: &mut Identifier, - variable_map: &mut HashMap, + variable_map: &mut HashMap, VarInfo>, name_gen: &mut NameGenerator, - block_vars: &mut HashSet, + block_vars: &mut HashSet>, span: Span, ) -> Result<(), SemanticError> { let Identifier(name) = param.clone(); @@ -640,21 +1536,7 @@ fn resolve_param( ext_link: false, }, ); - if let Some(shadow) = shadow { - eprintln!( - "{}: {}: variable {} shadows previous declaration {}", - span, - "warning".purple(), - format!("'{}'", name).bold(), - "[-Wshadow]".purple() - ); - eprintln!( - "{}: {}: previous declaration of {} was here", - shadow.span, - "note".cyan(), - format!("'{}'", name).bold() - ); - } + warn_shadow(&name, span, shadow.map(|s| s.span)); *param = Identifier(unique_name); Ok(()) } else { @@ -678,7 +1560,7 @@ fn resolve_param( /// - Are marked with `ext_link: true` (external linkage by default) /// /// This is the resolve pass counterpart to `typecheck_file_variable_declaration`. -fn resolve_file_var_declaration(dec: &mut VarDeclaration, variable_map: &mut HashMap) { +fn resolve_file_var_declaration(dec: &mut VarDeclaration, variable_map: &mut HashMap, VarInfo>) { let Identifier(name) = &dec.name; variable_map.insert( name.clone(), @@ -705,15 +1587,15 @@ fn resolve_file_var_declaration(dec: &mut VarDeclaration, variable_map: &mut Has /// - Gets a unique renamed identifier (e.g., `x` → `x.1`) /// - Marked with `ext_link: false` /// - Emits `-Wshadow` warning if shadowing an outer scope variable -/// - Initializer expression is resolved if present +/// - Initializer expression is resolved, and checked for `-Wsequence-point`, if present /// /// This is the resolve pass counterpart to `typecheck_local_variable_declaration`. fn resolve_local_var_decoration( dec: &mut VarDeclaration, - variable_map: &mut HashMap, + variable_map: &mut HashMap, VarInfo>, name_gen: &mut NameGenerator, - block_vars: &mut HashSet, - used_vars: &mut HashSet, + block_vars: &mut HashSet>, + used_vars: &mut HashSet>, ) -> Result<(), SemanticError> { let Identifier(name) = &dec.name.clone(); @@ -743,29 +1625,17 @@ fn resolve_local_var_decoration( } else { let unique_name = name_gen.next(name); dec.name = Identifier(unique_name.clone()); - if let Some(shadow) = variable_map.insert( + let shadow = variable_map.insert( name.clone(), VarInfo { renamed: unique_name.clone(), span: dec.span, ext_link: false, }, - ) { - eprintln!( - "{}: {}: variable {} shadows previous declaration {}", - dec.span, - "warning".purple(), - format!("'{}'", name).bold(), - "[-Wshadow]".purple() - ); - eprintln!( - "{}: {}: previous declaration of {} was here", - shadow.span, - "note".cyan(), - format!("'{}'", name).bold() - ); - } + ); + warn_shadow(name, dec.span, shadow.map(|s| s.span)); if let Some(init_expr) = &mut dec.init { + check_sequence_points(init_expr); resolve_exp(init_expr, variable_map, used_vars)?; } } @@ -773,19 +1643,34 @@ fn resolve_local_var_decoration( Ok(()) } +/// Resolution-pass handler for a single statement: renames variables in any contained +/// expressions, recurses into nested statements/blocks, and tracks control-flow labels. +/// +/// - Each contained full expression (conditions, `return`/expression statements, `for` clauses) is +/// renamed via [`resolve_exp`]; emits `-Wsequence-point` for unsequenced double-modifications +/// - `Labeled` registers the label name (a duplicate label is an error); `Goto` records its target +/// in `jumps` for later existence validation +/// - `Compound` and `for` introduce a new scope (a cloned `variable_map`) fn resolve_statement( statement: &mut SpannedStmt, - variable_map: &mut HashMap, - labels: &mut HashSet, - jumps: &mut HashMap, + variable_map: &mut HashMap, VarInfo>, + labels: &mut HashSet>, + jumps: &mut HashMap, Span>, name_gen: &mut NameGenerator, - used_vars: &mut HashSet, + used_vars: &mut HashSet>, ) -> Result<(), SemanticError> { match &mut statement.stmt { - Stmt::Return(e) => resolve_exp(e, variable_map, used_vars), - Stmt::Expression(e) => resolve_exp(e, variable_map, used_vars), - Stmt::Null => Ok(()), - Stmt::If(e, then_stmt, else_stmt) => { + ParserStmt::Return(e) => { + check_sequence_points(e); + resolve_exp(e, variable_map, used_vars) + } + ParserStmt::Expression(e) => { + check_sequence_points(e); + resolve_exp(e, variable_map, used_vars) + } + ParserStmt::Null => Ok(()), + ParserStmt::If(e, then_stmt, else_stmt) => { + check_sequence_points(e); resolve_exp(e, variable_map, used_vars)?; resolve_statement(then_stmt, variable_map, labels, jumps, name_gen, used_vars)?; match else_stmt.as_mut() { @@ -793,21 +1678,23 @@ fn resolve_statement( None => Ok(()), } } - Stmt::Labeled(label_name, stmt) => { + ParserStmt::Labeled(label_name, stmt) => { if !labels.insert(label_name.0.clone()) { - return Err(SemanticError { - message: format!("Label {label_name:} already defined at {}", statement.span), - span: None, - }); + // TODO: add a "previous definition was here" note (like duplicate case values). + // Requires `labels` to store spans (HashSet> -> HashMap, Span>). + return Err(SemanticError::with_span( + format!("duplicate label '{}'", label_name.0.bold()), + statement.span, + )); } resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars) } - Stmt::Goto(label_name) => { + ParserStmt::Goto(label_name) => { jumps.insert(label_name.0.clone(), statement.span); Ok(()) } - Stmt::Compound(block) => { - let mut shadow_map = variable_map.clone(); + ParserStmt::Compound(block) => { + let mut shadow_map = variable_map.clone(); // TODO: expensive clone of HashMap per compound block - happens frequently in nested code Ok(resolve_block( block, &mut HashSet::new(), @@ -818,103 +1705,190 @@ fn resolve_statement( used_vars, )?) } - Stmt::While(exp, stmt, _) | Stmt::Switch(exp, stmt, ..) | Stmt::Case(exp, stmt, ..) => { + ParserStmt::While(exp, stmt, _) | ParserStmt::Switch(exp, stmt, ..) | ParserStmt::Case(exp, stmt, ..) => { + check_sequence_points(exp); resolve_exp(exp, variable_map, used_vars)?; resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars) } - Stmt::DoWhile(stmt, exp, _) => { + ParserStmt::DoWhile(stmt, exp, _) => { resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars)?; + check_sequence_points(exp); resolve_exp(exp, variable_map, used_vars)?; Ok(()) } - Stmt::For(init, e1, e2, stmt, _) => { - let mut shadow_map = variable_map.clone(); + ParserStmt::For(init, e1, e2, stmt, _) => { + let mut shadow_map = variable_map.clone(); // TODO: expensive clone of HashMap per for loop - same issue as compound blocks match init { - ForInit::InitExp(exp) => { + ParserForInit::InitExp(exp) => { if let Some(e) = exp { + check_sequence_points(e); resolve_exp(e, &shadow_map, used_vars)?; } } - ForInit::InitDecl(dec) => { + ParserForInit::InitDecl(dec) => { resolve_local_var_decoration(dec, &mut shadow_map, name_gen, &mut HashSet::new(), used_vars)? } } if let Some(e1) = e1 { + check_sequence_points(e1); resolve_exp(e1, &shadow_map, used_vars)?; } if let Some(e2) = e2 { + check_sequence_points(e2); resolve_exp(e2, &shadow_map, used_vars)?; } resolve_statement(stmt, &mut shadow_map, labels, jumps, name_gen, used_vars)?; Ok(()) } - Stmt::Break(..) | Stmt::Continue(..) => Ok(()), - Stmt::Default(stmt, ..) => resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars), + ParserStmt::Break(..) | ParserStmt::Continue(..) => Ok(()), + ParserStmt::Default(stmt, ..) => resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars), + } +} + +/// Converts a constant to `target_type`. Returns `(value, truncated)` where `truncated` is true +/// only for a narrowing (`long`->`int`) that changed the value — the `-Wconstant-conversion` signal. +/// Widening and same-type conversions never truncate. The caller decides whether to warn +/// (implicit conversions do; explicit casts and internal promotion do not). +fn convert_to_type(val: StaticInt, target_type: &Type) -> (StaticInt, bool) { + match (val, target_type) { + (StaticInt::IntInit(v), Type::Int) => (StaticInt::IntInit(v), false), + (StaticInt::LongInit(v), Type::Long) => (StaticInt::LongInit(v), false), + + (StaticInt::IntInit(v), Type::Long) => (StaticInt::LongInit(v as i64), false), + (StaticInt::LongInit(v), Type::Int) => { + let truncated = v as i32; + (StaticInt::IntInit(truncated), truncated as i64 != v) + } + + (_, Type::FunType { .. }) => unreachable!("Cannot cast to function type in constant expression"), } } -/// Evaluates a constant expression to an i32 value -/// Returns None if the expression is not a compile-time constant -fn eval_constant_expr(expr: &Expr) -> Option { +enum ConstEvalError { + NotConstant, + DivByZero, +} + +/// Evaluate a static / file-scope initializer to its `InitialValue`, mapping the two +/// constant-eval failures to located diagnostics. Shared by the local-`static` and +/// file-scope declaration paths so their error messages stay in sync. +fn eval_static_initializer( + expr: &ParserExpr, + var_type: &Type, + name: &Identifier, + span: Span, +) -> Result { + match eval_constant_expr(expr) { + Ok((c, overflowed)) => { + warn_overflow(overflowed, span); + // Implicit narrowing conversion to the declared type: -Wconstant-conversion. + let (converted, truncated) = convert_to_type(c, var_type); + warn_constant_conversion(truncated, c.as_i64(), converted.as_i64(), span); + Ok(InitialValue::Initial(converted)) + } + Err(ConstEvalError::DivByZero) => Err(SemanticError::with_span( + "division by zero in constant expression".into(), + span, + )), + Err(ConstEvalError::NotConstant) => Err(SemanticError::with_span( + format!( + "initializer for static variable '{}' is not a constant expression", + name.0.bold() + ), + span, + )), + } +} + +/// Evaluates a compile-time constant expression from the parser AST. +/// +/// Handles all arithmetic, bitwise, comparison, and logical operations with proper +/// type promotion (Int + Long = Long). Type conversions follow implementation-defined +/// behavior documented in README (wrapping arithmetic, shift masking, etc.). +/// +/// Used for static initializers, case labels, and other contexts requiring constant +/// expressions. Does NOT call typecheck_exp to avoid mixing with general expression +/// transformations that will be added in later chapters. +/// +/// On success returns `(value, overflowed)`, where `overflowed` is true if any sub-operation +/// wrapped the result type during the fold (`INT_MAX + 1`, `-INT_MIN`, `INT_MIN / -1`, …). The +/// value is still the well-defined wrapped result — callers use the flag to emit `-Woverflow`. +/// +/// Returns `Err(ConstEvalError::NotConstant)` if the expression contains non-constant +/// elements (variables, function calls, assignments, etc.), or +/// `Err(ConstEvalError::DivByZero)` if a `/` or `%` has a zero divisor. +fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInt, bool), ConstEvalError> { match expr { - Expr::Constant(val) => Some(*val), - Expr::Unary(op, inner) => { - let inner_val = eval_constant_expr(inner)?; - match op { - UnaryOp::Negate => Some(-inner_val), - UnaryOp::BitwiseComplement => Some(!inner_val), - UnaryOp::Not => Some(if inner_val == 0 { 1 } else { 0 }), - } + ParserExpr::Constant(Const::ConstInt(val)) => Ok((StaticInt::IntInit(*val), false)), + ParserExpr::Constant(Const::ConstLong(val)) => Ok((StaticInt::LongInit(*val), false)), + ParserExpr::Cast(target, val) => { + let (v, o) = eval_constant_expr(val)?; + // Explicit cast: suppress the conversion-truncation warning (programmer intent), but + // keep `o` so arithmetic overflow inside the cast operand still surfaces. + let (cv, _truncated) = convert_to_type(v, target); + Ok((cv, o)) } - Expr::Binary(op, left, right) => { - let left_val = eval_constant_expr(left)?; - let right_val = eval_constant_expr(right)?; - match op { - BinOp::Add => Some(left_val.wrapping_add(right_val)), - BinOp::Subtract => Some(left_val.wrapping_sub(right_val)), - BinOp::Multiply => Some(left_val.wrapping_mul(right_val)), - BinOp::Divide => { - if right_val == 0 { - None // Division by zero - } else { - Some(left_val / right_val) - } - } - BinOp::Remainder => { - if right_val == 0 { - None // Division by zero - } else { - Some(left_val % right_val) - } - } - BinOp::BitwiseAnd => Some(left_val & right_val), - BinOp::BitwiseOr => Some(left_val | right_val), - BinOp::BitwiseXOr => Some(left_val ^ right_val), - BinOp::BitwiseLeftShift => Some(left_val << (right_val as u32)), - BinOp::BitwiseRightShift => Some(left_val >> (right_val as u32)), - BinOp::Equal => Some(if left_val == right_val { 1 } else { 0 }), - BinOp::NotEqual => Some(if left_val != right_val { 1 } else { 0 }), - BinOp::LessThan => Some(if left_val < right_val { 1 } else { 0 }), - BinOp::LessOrEqual => Some(if left_val <= right_val { 1 } else { 0 }), - BinOp::GreaterThan => Some(if left_val > right_val { 1 } else { 0 }), - BinOp::GreaterOrEqual => Some(if left_val >= right_val { 1 } else { 0 }), - BinOp::And => Some(if left_val != 0 && right_val != 0 { 1 } else { 0 }), - BinOp::Or => Some(if left_val != 0 || right_val != 0 { 1 } else { 0 }), + ParserExpr::Unary(op, inner) => { + let (v, o) = eval_constant_expr(inner)?; + let (r, o2) = match op { + UnaryOp::Negate => v.neg(), + UnaryOp::BitwiseComplement => ( + match v { + StaticInt::IntInit(n) => StaticInt::IntInit(!n), + StaticInt::LongInit(n) => StaticInt::LongInit(!n), + }, + false, + ), + UnaryOp::Not => ( + match v { + StaticInt::IntInit(n) => StaticInt::IntInit(if n == 0 { 1 } else { 0 }), + StaticInt::LongInit(n) => StaticInt::IntInit(if n == 0 { 1 } else { 0 }), + }, + false, + ), + }; + Ok((r, o | o2)) + } + ParserExpr::Binary(op, left, right, _) => { + let (l, lo) = eval_constant_expr(left)?; + let (r, ro) = eval_constant_expr(right)?; + let base = lo | ro; + let (v, op_ovf) = match op { + BinOp::Add => l.add(r), + BinOp::Subtract => l.sub(r), + BinOp::Multiply => l.mul(r), + BinOp::Divide => l.div(r)?, + BinOp::Remainder => l.rem(r)?, + BinOp::BitwiseAnd => (l.bitwise_and(r), false), + BinOp::BitwiseOr => (l.bitwise_or(r), false), + BinOp::BitwiseXOr => (l.bitwise_xor(r), false), + BinOp::BitwiseLeftShift => (l.shl(r), false), + BinOp::BitwiseRightShift => (l.shr(r), false), + BinOp::Equal => (l.eq(r), false), + BinOp::NotEqual => (l.ne(r), false), + BinOp::LessThan => (l.lt(r), false), + BinOp::LessOrEqual => (l.le(r), false), + BinOp::GreaterThan => (l.gt(r), false), + BinOp::GreaterOrEqual => (l.ge(r), false), + BinOp::And => (l.and(r), false), + BinOp::Or => (l.or(r), false), BinOp::Assignment | BinOp::CompoundAssignment | BinOp::Conditional => { unreachable!("only used for parsing") } - } + }; + Ok((v, base | op_ovf)) } - Expr::Conditional(cond, true_expr, false_expr) => { - let cond_val = eval_constant_expr(cond)?; - if cond_val != 0 { - eval_constant_expr(true_expr) + ParserExpr::Conditional(cond, true_expr, false_expr) => { + let (cond_val, co) = eval_constant_expr(cond)?; + let (v, o) = if cond_val.is_zero() { + eval_constant_expr(false_expr)? } else { - eval_constant_expr(false_expr) - } + eval_constant_expr(true_expr)? + }; + Ok((v, co | o)) } // Variables, assignments, function calls etc. are not constant - _ => None, + _ => Err(ConstEvalError::NotConstant), } } @@ -927,7 +1901,7 @@ struct LabelTracker { cur_label: Vec, next_loop_label: u64, next_switch_label: u64, - switch_to_cases: HashMap>, // switch -> case e + switch_to_cases: HashMap>, // switch -> (case, span) for error reporting } impl LabelTracker { @@ -940,69 +1914,57 @@ impl LabelTracker { } } - fn get_break_label(&self) -> Option { + fn get_break_label(&self) -> Option> { if let Some(label) = self.cur_label.last() { let s = match label { LabelTag::Switch(l) => format!("break_switch.{l}"), LabelTag::Loop(l) => format!("break_loop.{l}"), }; - Some(s) + Some(Rc::from(s)) } else { None } } - fn get_continue_label(&self) -> Option { + fn get_continue_label(&self) -> Option> { if let Some(LabelTag::Loop(label)) = self.cur_label.iter().rev().find(|x| match x { LabelTag::Switch(..) => false, LabelTag::Loop(..) => true, }) { - Some(format!("continue_loop.{label}")) + Some(Rc::from(format!("continue_loop.{label}"))) } else { None } } - fn get_switch_case(&mut self, c: i32, span: &Span) -> Result { + fn get_switch_case(&mut self, c: StaticInt, span: &Span) -> Result, SemanticError> { // get the active switch id if let Some(LabelTag::Switch(label)) = self.cur_label.iter().rev().find(|x| match x { LabelTag::Switch(..) => true, LabelTag::Loop(..) => false, }) { - let case_exp = SwitchIntType::Int(c); - if self.switch_to_cases.get_mut(label).unwrap().insert(case_exp.clone()) { - Ok(case_exp.label_str(*label)) - } else { - Err(SemanticError::with_span( - format!("Duplicate Case '{}' found in switch.", format!("{}", c).bold()), - *span, - )) - } + let case_exp = match c { + StaticInt::IntInit(v) => SwitchIntType::Int(v), + StaticInt::LongInit(v) => SwitchIntType::Long(v), + }; + // Just collect cases with spans - duplicate checking happens during typecheck + self.switch_to_cases.get_mut(label).unwrap().push((case_exp, *span)); + Ok(Rc::from(case_exp.label_str(*label))) } else { Err(SemanticError::with_span("Case outside of switch".to_string(), *span)) } } - fn get_switch_default(&mut self, span: &Span) -> Result { + fn get_switch_default(&mut self, span: &Span) -> Result, SemanticError> { // get the active switch id if let Some(LabelTag::Switch(label)) = self.cur_label.iter().rev().find(|x| match x { LabelTag::Switch(..) => true, LabelTag::Loop(..) => false, }) { let default_case = SwitchIntType::Default; - if self - .switch_to_cases - .get_mut(label) - .unwrap() - .insert(default_case.clone()) - { - Ok(default_case.label_str(*label)) - } else { - Err(SemanticError::with_span( - format!("Duplicate '{}' found in switch.", "default".bold()), - *span, - )) - } + // Just collect with span - duplicate checking happens during typecheck + self.switch_to_cases.get_mut(label).unwrap().push((default_case, *span)); + Ok(Rc::from(default_case.label_str(*label))) } else { Err(SemanticError::with_span("Default outside of switch".to_string(), *span)) } @@ -1017,7 +1979,7 @@ impl LabelTracker { fn next_switch_label(&mut self) -> u64 { let res = self.next_switch_label; self.next_switch_label += 1; - self.switch_to_cases.insert(res, HashSet::new()); + self.switch_to_cases.insert(res, Vec::new()); self.cur_label.push(LabelTag::Switch(res)); res } @@ -1026,17 +1988,17 @@ impl LabelTracker { self.cur_label.pop(); } - fn pop_switch(&mut self, switch_id: u64) -> HashSet { + fn pop_switch(&mut self, switch_id: u64) -> Vec<(SwitchIntType, Span)> { self.cur_label.pop(); - self.switch_to_cases.get(&switch_id).unwrap().clone() + self.switch_to_cases.remove(&switch_id).unwrap() } } fn label_statement(stmt: &mut SpannedStmt, label_tracker: &mut LabelTracker) -> Result<(), SemanticError> { match &mut stmt.stmt { // terminating statements - Stmt::Return(_) | Stmt::Expression(_) | Stmt::Goto(..) | Stmt::Null => Ok(()), - Stmt::If(_, then_stmt, else_stmt) => { + ParserStmt::Return(_) | ParserStmt::Expression(_) | ParserStmt::Goto(..) | ParserStmt::Null => Ok(()), + ParserStmt::If(_, then_stmt, else_stmt) => { label_statement(then_stmt, label_tracker)?; if let Some(c) = &mut **else_stmt { label_statement(c, label_tracker) @@ -1044,19 +2006,19 @@ fn label_statement(stmt: &mut SpannedStmt, label_tracker: &mut LabelTracker) -> Ok(()) } } - Stmt::Labeled(_, stmt) => label_statement(stmt, label_tracker), - Stmt::Compound(block) => { + ParserStmt::Labeled(_, stmt) => label_statement(stmt, label_tracker), + ParserStmt::Compound(block) => { for bi in block.iter_mut() { match bi { - BlockItem::Statement(stmt) => { + ParserBlockItem::Statement(stmt) => { label_statement(stmt, label_tracker)?; } - BlockItem::Declaration(_) => {} + ParserBlockItem::Declaration(_) => {} } } Ok(()) } - Stmt::Break(Identifier(s)) => { + ParserStmt::Break(Identifier(s)) => { if let Some(break_label) = label_tracker.get_break_label() { *s = break_label; Ok(()) @@ -1067,7 +2029,7 @@ fn label_statement(stmt: &mut SpannedStmt, label_tracker: &mut LabelTracker) -> )) } } - Stmt::Continue(Identifier(s)) => { + ParserStmt::Continue(Identifier(s)) => { if let Some(label) = label_tracker.get_continue_label() { *s = label; Ok(()) @@ -1078,39 +2040,52 @@ fn label_statement(stmt: &mut SpannedStmt, label_tracker: &mut LabelTracker) -> )) } } - Stmt::While(_, body, loop_num) | Stmt::DoWhile(body, _, loop_num) | Stmt::For(_, _, _, body, loop_num) => { + ParserStmt::While(_, body, loop_num) + | ParserStmt::DoWhile(body, _, loop_num) + | ParserStmt::For(_, _, _, body, loop_num) => { *loop_num = label_tracker.next_loop_label(); let result = label_statement(body, label_tracker); label_tracker.pop(); result } - Stmt::Switch(_, stmt, switch_num, cases) => { + ParserStmt::Switch(_, stmt, switch_num, cases) => { *switch_num = label_tracker.next_switch_label(); let result = label_statement(stmt, label_tracker); *cases = label_tracker.pop_switch(*switch_num); result } - Stmt::Case(exp, s, Identifier(label)) => { - if let Some(exp) = eval_constant_expr(exp) { - *label = label_tracker.get_switch_case(exp, &stmt.span)?; - label_statement(s, label_tracker) - } else { - Err(SemanticError::with_span( - "Expression is not an integer constant expression".to_string(), - stmt.span, - )) - } + ParserStmt::Case(exp, s, Identifier(label)) => { + let value = match eval_constant_expr(exp) { + Ok((v, overflowed)) => { + warn_overflow(overflowed, stmt.span); + v + } + Err(ConstEvalError::DivByZero) => { + return Err(SemanticError::with_span( + "division by zero in constant expression".to_string(), + stmt.span, + )); + } + Err(ConstEvalError::NotConstant) => { + return Err(SemanticError::with_span( + "Expression is not an integer constant expression".to_string(), + stmt.span, + )); + } + }; + *label = label_tracker.get_switch_case(value, &stmt.span)?; + label_statement(s, label_tracker) } - Stmt::Default(s, Identifier(label)) => { + ParserStmt::Default(s, Identifier(label)) => { *label = label_tracker.get_switch_default(&stmt.span)?; label_statement(s, label_tracker) } } } -fn label_block(block: &mut Block, label_tracker: &mut LabelTracker) -> Result<(), SemanticError> { +fn label_block(block: &mut ParserBlock, label_tracker: &mut LabelTracker) -> Result<(), SemanticError> { for bi in block.iter_mut() { - if let BlockItem::Statement(stmt) = bi { + if let ParserBlockItem::Statement(stmt) = bi { label_statement(stmt, label_tracker)?; } } @@ -1118,20 +2093,20 @@ fn label_block(block: &mut Block, label_tracker: &mut LabelTracker) -> Result<() } fn resolve_block( - block: &mut Block, - block_vars: &mut HashSet, - variable_map: &mut HashMap, - labels: &mut HashSet, - jumps: &mut HashMap, + block: &mut ParserBlock, + block_vars: &mut HashSet>, + variable_map: &mut HashMap, VarInfo>, + labels: &mut HashSet>, + jumps: &mut HashMap, Span>, name_gen: &mut NameGenerator, - used_vars: &mut HashSet, + used_vars: &mut HashSet>, ) -> Result<(), SemanticError> { for bi in block.iter_mut() { match bi { - BlockItem::Statement(stmt) => { + ParserBlockItem::Statement(stmt) => { resolve_statement(stmt, variable_map, labels, jumps, name_gen, used_vars)?; } - BlockItem::Declaration(d) => match d { + ParserBlockItem::Declaration(d) => match d { Declaration::VarDeclaration(var) => { resolve_local_var_decoration(var, variable_map, name_gen, block_vars, used_vars)?; } @@ -1156,7 +2131,7 @@ fn resolve_block( Ok(()) } -pub fn resolve_program(program: &mut Program) -> Result<(NameGenerator, SymbolTable), SemanticError> { +pub fn resolve_program(mut program: Program) -> Result<(NameGenerator, TypedProgram, SymbolTable), SemanticError> { let mut variable_map = HashMap::new(); let mut name_gen = NameGenerator::new(); let mut undefined_jumps = Vec::new(); @@ -1168,7 +2143,7 @@ pub fn resolve_program(program: &mut Program) -> Result<(NameGenerator, SymbolTa Declaration::FunDeclaration(function) => { let mut used_vars = HashSet::new(); let mut labels = HashSet::new(); - let mut jumps: HashMap = HashMap::new(); + let mut jumps: HashMap, Span> = HashMap::new(); if let Some(body) = &mut function.body { label_block(body, &mut label_tracker)?; } @@ -1194,8 +2169,8 @@ pub fn resolve_program(program: &mut Program) -> Result<(NameGenerator, SymbolTa } if undefined_jumps.is_empty() { - let symbols = typecheck_program(program)?; - Ok((name_gen, symbols)) + let (typed_program, symbols) = typecheck_program(program)?; + Ok((name_gen, typed_program, symbols)) } else { let (label, span) = &undefined_jumps[0]; Err(SemanticError::with_span( @@ -1205,14 +2180,29 @@ pub fn resolve_program(program: &mut Program) -> Result<(NameGenerator, SymbolTa } } -pub fn typecheck_program(program: &Program) -> Result { +pub fn typecheck_program(program: Program) -> Result<(TypedProgram, SymbolTable), SemanticError> { let mut symbols = SymbolTable::new(); + let mut typed_declarations = Vec::with_capacity(program.declarations.len()); - for decl in &program.declarations { + for decl in program.declarations { match decl { - Declaration::VarDeclaration(dec) => typecheck_file_variable_declaration(dec, &mut symbols)?, - Declaration::FunDeclaration(func) => typecheck_function_declaration(func, &mut symbols)?, + Declaration::VarDeclaration(dec) => { + let typed_dec = typecheck_file_variable_declaration(dec, &mut symbols)?; + typed_declarations.push(TypedDeclaration::Variable(typed_dec)); + } + Declaration::FunDeclaration(func) => { + if let Some(typed_func) = typecheck_function_declaration(func, &mut symbols)? { + // Function has a body (definition) + typed_declarations.push(TypedDeclaration::Function(typed_func)); + } + // If None, it's just a declaration - don't add to typed program + } }; } - Ok(symbols) + Ok(( + TypedProgram { + declarations: typed_declarations, + }, + symbols, + )) } diff --git a/tests/c_programs/declaration/invalid_parse/case_static_decl.c b/tests/c_programs/declaration/invalid_parse/case_static_decl.c new file mode 100644 index 0000000..58dde84 --- /dev/null +++ b/tests/c_programs/declaration/invalid_parse/case_static_decl.c @@ -0,0 +1,9 @@ +// Case label followed by static declaration - should fail to parse +int main(void) { + switch (1) { + case 1: + static int x = 5; + return x; + } + return 0; +} \ No newline at end of file diff --git a/tests/c_programs/declaration/invalid_parse/label_long_decl.c b/tests/c_programs/declaration/invalid_parse/label_long_decl.c new file mode 100644 index 0000000..c9adf9f --- /dev/null +++ b/tests/c_programs/declaration/invalid_parse/label_long_decl.c @@ -0,0 +1,6 @@ +// Label followed by long declaration - should fail to parse +int main(void) { +label: + long x = 5; + return 0; +} \ No newline at end of file diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index 80d30a1..135013f 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -86,5 +86,11 @@ "examples/hello_world.c": { "return_code": 0, "stdout": "Hello, World!\n" + }, + "large_shift_immediate.c": { + "return_code": 0 + }, + "types/compound_assign_mixed_types.c": { + "return_code": 30 } } \ No newline at end of file diff --git a/tests/c_programs/int_wrapping/invalid_parse/above_max.c b/tests/c_programs/int_wrapping/invalid_parse/above_max.c index 127ee00..0d108ca 100644 --- a/tests/c_programs/int_wrapping/invalid_parse/above_max.c +++ b/tests/c_programs/int_wrapping/invalid_parse/above_max.c @@ -1,5 +1,4 @@ - int main(void) { - int int_max = 2147483648; //too large - return int_max; + long long_max = 9223372036854775808; // too large for long + return long_max; } \ No newline at end of file diff --git a/tests/c_programs/int_wrapping/invalid_parse/below_min.c b/tests/c_programs/int_wrapping/invalid_parse/below_min.c index 5b79520..c649440 100644 --- a/tests/c_programs/int_wrapping/invalid_parse/below_min.c +++ b/tests/c_programs/int_wrapping/invalid_parse/below_min.c @@ -1,4 +1,4 @@ int main(void) { - int int_min = -2147483649; // too small - return int_min; + long long_min = -9223372036854775809; // too small for long + return long_min; } \ No newline at end of file diff --git a/tests/c_programs/large_shift_immediate.c b/tests/c_programs/large_shift_immediate.c new file mode 100644 index 0000000..bb55ff3 --- /dev/null +++ b/tests/c_programs/large_shift_immediate.c @@ -0,0 +1,27 @@ +// Test shift with immediate > 255 +// This tests the fix_invalid case where shift count > 255 +// must be loaded into CX register +// +// Note: Shift counts are masked in x86-64: +// - For long: count & 63 +// - For int: count & 31 +// So 256 & 63 = 0, meaning shift by 0 + +int main(void) { + long x = 42L; + + // Shift by 256 - should be masked to 0 for long (256 & 63 = 0) + long result1 = x << 256; + if (result1 != 42L) return 1; + + // Shift by 257 - should be masked to 1 for long (257 & 63 = 1) + long result2 = 10L << 257; + if (result2 != 20L) return 2; + + // Negative shift count (also triggers the fix) + // -1 as unsigned is all 1s, masked to 63 for long + long result3 = 1L << -1; // -1 & 63 = 63 + if (result3 != (1L << 63)) return 3; + + return 0; +} diff --git a/tests/c_programs/switch/invalid_semantics/case_div_by_zero.c b/tests/c_programs/switch/invalid_semantics/case_div_by_zero.c new file mode 100644 index 0000000..c51b0f3 --- /dev/null +++ b/tests/c_programs/switch/invalid_semantics/case_div_by_zero.c @@ -0,0 +1,10 @@ +/* A division-by-zero in a case label is a constant-expression error (exit 30), + reported specifically as "division by zero in constant expression" rather than the + generic "not an integer constant expression". */ +int main(void) { + switch (1) { + case 5 / 0: + return 1; + } + return 0; +} diff --git a/tests/c_programs/types/compound_assign_mixed_types.c b/tests/c_programs/types/compound_assign_mixed_types.c new file mode 100644 index 0000000..793089d --- /dev/null +++ b/tests/c_programs/types/compound_assign_mixed_types.c @@ -0,0 +1,8 @@ +// Tests compound assignment with mixed types (int += long). +// The result should be truncated back to int. +int main(void) { + int x = 10; + long y = 20L; + x += y; // common type is long, but result stored back as int + return x; // expected: 30 +} diff --git a/tests/c_programs/warnings/constant_conversion.c b/tests/c_programs/warnings/constant_conversion.c new file mode 100644 index 0000000..f833a6e --- /dev/null +++ b/tests/c_programs/warnings/constant_conversion.c @@ -0,0 +1,5 @@ +/* -Wconstant-conversion: a constant implicitly narrowed to a type that can't hold it. + `2147483648` is a `long` (too big for `int`); the implicit conversion truncates it to + `-2147483648`. Folds at compile time, so the program runs cleanly to 0. */ +int a = 2147483648; +int main(void) { return 0; } diff --git a/tests/c_programs/warnings/division_by_zero.c b/tests/c_programs/warnings/division_by_zero.c new file mode 100644 index 0000000..8fe1e7a --- /dev/null +++ b/tests/c_programs/warnings/division_by_zero.c @@ -0,0 +1,14 @@ +/* -Wdiv-by-zero: a constant zero divisor warns at compile time. + The divisions sit in a never-taken branch (NCC has no constant propagation, so `n` + is a runtime value) — so the program compiles with warnings but runs cleanly to 0. + The dedicated test asserts the diagnostics via --validate. */ +int main(void) { + int n = 0; + if (n) { + int a = 5 / 0; /* division by zero */ + int b = 7 % 0; /* remainder by zero */ + a /= 0; /* division by zero (compound assignment) */ + return a + b; + } + return 0; +} diff --git a/tests/c_programs/warnings/no_constant_conversion.c b/tests/c_programs/warnings/no_constant_conversion.c new file mode 100644 index 0000000..95b752c --- /dev/null +++ b/tests/c_programs/warnings/no_constant_conversion.c @@ -0,0 +1,5 @@ +/* Explicit casts and in-range / widening conversions must NOT trigger -Wconstant-conversion. */ +int a = (int)2147483648; /* explicit cast — silenced */ +long b = 2147483648; /* fits long (no narrowing) */ +int c = 100; /* fits int */ +int main(void) { return 0; } diff --git a/tests/c_programs/warnings/no_division_by_zero.c b/tests/c_programs/warnings/no_division_by_zero.c new file mode 100644 index 0000000..55a4b79 --- /dev/null +++ b/tests/c_programs/warnings/no_division_by_zero.c @@ -0,0 +1,8 @@ +/* Divisors that are non-constant, or non-zero constants, must NOT trigger + -Wdiv-by-zero. Runs cleanly to 0. */ +int main(void) { + int d = 5; + int x = 10 / d; /* non-constant divisor — no warning */ + int y = 8 / 4; /* non-zero constant divisor — no warning */ + return x - y; /* 2 - 2 = 0 */ +} diff --git a/tests/c_programs/warnings/no_overflow.c b/tests/c_programs/warnings/no_overflow.c new file mode 100644 index 0000000..4a41f9a --- /dev/null +++ b/tests/c_programs/warnings/no_overflow.c @@ -0,0 +1,5 @@ +/* In-range constant folds must NOT trigger -Woverflow. Runs cleanly to 0. */ +int a = 2147483647; /* INT_MAX itself — fits */ +int b = 1000 * 1000; /* 1,000,000 — fits int */ +int c = 5 + 3; +int main(void) { return 0; } diff --git a/tests/c_programs/warnings/no_sequence_point.c b/tests/c_programs/warnings/no_sequence_point.c new file mode 100644 index 0000000..3f6054a --- /dev/null +++ b/tests/c_programs/warnings/no_sequence_point.c @@ -0,0 +1,11 @@ +/* Sequenced or single modifications must NOT trigger -Wsequence-point. Runs cleanly to 0. */ +int main(void) { + int i = 0; + i = i + 1; /* single modification + a read */ + int a = i++; /* single modification */ + int b = i ? i++ : i--; /* ?: is a sequence point */ + int c = (i++) && (i++); /* && is a sequence point */ + i++; + i++; /* separate statements = separate full expressions */ + return 0; +} diff --git a/tests/c_programs/warnings/no_shift_count.c b/tests/c_programs/warnings/no_shift_count.c new file mode 100644 index 0000000..bdf9472 --- /dev/null +++ b/tests/c_programs/warnings/no_shift_count.c @@ -0,0 +1,9 @@ +/* In-range constant shift counts and non-constant counts must NOT trigger a shift-count + warning. Runs cleanly to 0. */ +int main(void) { + int n = 5; + int a = 1 << 5; /* in range for int (< 32) */ + int b = 1 << n; /* non-constant count */ + long c = 1L << 40; /* in range for long (< 64) — width follows the left operand */ + return 0; +} diff --git a/tests/c_programs/warnings/overflow.c b/tests/c_programs/warnings/overflow.c new file mode 100644 index 0000000..066ffda --- /dev/null +++ b/tests/c_programs/warnings/overflow.c @@ -0,0 +1,12 @@ +/* -Woverflow: constant folds that leave the result type, in static initializers (folded at + compile time, so the program runs cleanly to 0). + + Regression: `b`, `c`, and `d` used to PANIC the compiler — `-INT_MIN`, `INT_MIN / -1`, and + `INT_MIN % -1` overflow Rust's checked arithmetic. They now fold with deterministic two's- + complement wrapping and warn instead of crashing. */ +int a = 2147483647 + 1; /* INT_MAX + 1 */ +int b = -(int)2147483648; /* -INT_MIN (previously: negate-overflow panic) */ +int c = (int)2147483648 / -1; /* INT_MIN / -1 (previously: div-overflow panic) */ +int d = (int)2147483648 % -1; /* INT_MIN % -1 (previously: rem-overflow panic) */ + +int main(void) { return 0; } diff --git a/tests/c_programs/warnings/sequence_point.c b/tests/c_programs/warnings/sequence_point.c new file mode 100644 index 0000000..5f579bb --- /dev/null +++ b/tests/c_programs/warnings/sequence_point.c @@ -0,0 +1,12 @@ +/* -Wsequence-point: the same object modified more than once between sequence points + (undefined in standard C). NCC evaluates left-to-right, so these compile with warnings and + run cleanly to 0; the dedicated test asserts the diagnostics via --validate. */ +int two(int a, int b) { return a + b; } + +int main(void) { + int i = 0; + i = i++; /* '=' and '++' both modify i */ + int a = i++ + i++; /* two increments of i in one region */ + two(i++, i++); /* call args are unsequenced w.r.t. each other */ + return 0; +} diff --git a/tests/c_programs/warnings/shift_count.c b/tests/c_programs/warnings/shift_count.c new file mode 100644 index 0000000..1bdc6cf --- /dev/null +++ b/tests/c_programs/warnings/shift_count.c @@ -0,0 +1,13 @@ +/* -Wshift-count-overflow / -Wshift-count-negative: a constant shift count that is negative + or >= the width of the left operand's type. NCC masks shift counts at runtime, so these + compile with warnings and run cleanly to 0; the dedicated test asserts the diagnostics + via --validate. */ +int main(void) { + int a = 1 << 32; /* int width 32: count >= width (overflow) */ + int b = 5 >> 32; /* right shift, same overflow */ + int c = 1 << -1; /* negative count */ + long d = 1L << 64; /* long width 64: count >= width */ + int e = 1; + e <<= 40; /* compound shift: count >= width (32) */ + return 0; +} diff --git a/tests/runner.rs b/tests/runner.rs index 3bbc5a5..1fc8ab1 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -3,8 +3,8 @@ use std::collections::HashMap; use std::fs; use std::path::PathBuf; -static CHAPTER_COMPLETED: i32 = 10; -static EXTRA_COMPLETED: i32 = 10; +static CHAPTER_COMPLETED: i32 = 11; +static EXTRA_COMPLETED: i32 = 11; #[derive(Debug, PartialEq, Clone)] enum ProgramOutput { @@ -23,6 +23,22 @@ struct TestCase { output: ProgramOutput, } +/// Accumulated pass/fail tallies for a single case (a case may run several sub-tests). +#[derive(Debug, Default)] +struct CaseResult { + passed: usize, + failed: usize, + failures: Vec, +} + +impl CaseResult { + fn merge(&mut self, other: CaseResult) { + self.passed += other.passed; + self.failed += other.failed; + self.failures.extend(other.failures); + } +} + /// Load assembly_libs from test_properties.json fn load_assembly_libs() -> HashMap> { let json_content = fs::read_to_string("writing-a-c-compiler-tests/test_properties.json").unwrap_or_default(); @@ -246,14 +262,7 @@ fn load_expected(json_path: &str) -> Result, Box Ok(results) } -fn run_test( - case: &TestCase, - total_passed: &mut usize, - total_failed: &mut usize, - failed_tests: &mut Vec, - extra_args: &[String], - test_label: &str, -) { +fn run_test(case: &TestCase, result: &mut CaseResult, extra_args: &[String], test_label: &str) { let path = std::path::Path::new(&case.c_file); let binary_path = path.with_extension(""); let binary_path_str = binary_path.to_str().unwrap(); @@ -324,15 +333,17 @@ fn run_test( }; if passed { - *total_passed += 1; + result.passed += 1; } else { - *total_failed += 1; + result.failed += 1; let label = if test_label.is_empty() { case.c_file.clone() } else { format!("{} [{}]", case.c_file, test_label) }; - failed_tests.push(format!("{} (expected {:?}, got {:?})", label, case.output, actual)); + result + .failures + .push(format!("{} (expected {:?}, got {:?})", label, case.output, actual)); } } @@ -342,9 +353,7 @@ fn run_library_cross_test( client_file: &str, library_file: &str, expected: &ProgramOutput, - total_passed: &mut usize, - total_failed: &mut usize, - failed_tests: &mut Vec, + result: &mut CaseResult, ncc_compiles_client: bool, ) { let ncc_path = get_ncc_binary_path(); @@ -371,28 +380,28 @@ fn run_library_cross_test( .arg(&client_obj) .status() } else { - std::process::Command::new("gcc") - .arg("-c") - .arg(client_file) - .arg("-o") - .arg(&client_obj) - .status() + let mut cmd = std::process::Command::new("gcc"); + // On arm64 hosts gcc must cross-target x86_64 to match ncc's output. + #[cfg(target_arch = "aarch64")] + cmd.args(["-arch", "x86_64"]); + cmd.arg("-c").arg(client_file).arg("-o").arg(&client_obj).status() }; if client_status.is_err() || !client_status.unwrap().success() { - *total_failed += 1; - failed_tests.push(format!("{} [{}] (client compilation failed)", client_file, test_label)); + result.failed += 1; + result + .failures + .push(format!("{} [{}] (client compilation failed)", client_file, test_label)); return; } // Compile library let library_status = if ncc_compiles_client { - std::process::Command::new("gcc") - .arg("-c") - .arg(library_file) - .arg("-o") - .arg(&library_obj) - .status() + let mut cmd = std::process::Command::new("gcc"); + // On arm64 hosts gcc must cross-target x86_64 to match ncc's output. + #[cfg(target_arch = "aarch64")] + cmd.args(["-arch", "x86_64"]); + cmd.arg("-c").arg(library_file).arg("-o").arg(&library_obj).status() } else { std::process::Command::new(&ncc_path) .arg("-c") @@ -404,13 +413,19 @@ fn run_library_cross_test( if library_status.is_err() || !library_status.unwrap().success() { std::fs::remove_file(&client_obj).ok(); - *total_failed += 1; - failed_tests.push(format!("{} [{}] (library compilation failed)", client_file, test_label)); + result.failed += 1; + result + .failures + .push(format!("{} [{}] (library compilation failed)", client_file, test_label)); return; } // Link with gcc - let link_status = std::process::Command::new("gcc") + let mut link_cmd = std::process::Command::new("gcc"); + // On arm64 hosts gcc must cross-target x86_64 to match ncc's output. + #[cfg(target_arch = "aarch64")] + link_cmd.args(["-arch", "x86_64"]); + let link_status = link_cmd .arg(&client_obj) .arg(&library_obj) .arg("-o") @@ -421,8 +436,10 @@ fn run_library_cross_test( std::fs::remove_file(&library_obj).ok(); if link_status.is_err() || !link_status.unwrap().success() { - *total_failed += 1; - failed_tests.push(format!("{} [{}] (linking failed)", client_file, test_label)); + result.failed += 1; + result + .failures + .push(format!("{} [{}] (linking failed)", client_file, test_label)); return; } @@ -470,94 +487,100 @@ fn run_library_cross_test( }; if passed { - *total_passed += 1; + result.passed += 1; } else { - *total_failed += 1; - failed_tests.push(format!( + result.failed += 1; + result.failures.push(format!( "{} [{}] (expected {:?}, got {:?})", client_file, test_label, expected, actual )); } } -fn run_cases(cases: Vec) { - let mut total_passed = 0; - let mut total_failed = 0; - let mut failed_tests = Vec::new(); - - for case in &cases { - let is_library_test = case.c_file.contains("/libraries/") && case.c_file.ends_with("_client.c"); +/// Runs all sub-tests for a single case and returns its tally. Pure with respect to shared +/// state (output files are derived from the case's own source path, so cases don't collide), +/// which lets `run_cases` evaluate cases concurrently. +fn run_one_case(case: &TestCase) -> CaseResult { + let mut result = CaseResult::default(); + let is_library_test = case.c_file.contains("/libraries/") && case.c_file.ends_with("_client.c"); - match &case.output { - ProgramOutput::Error(_) => { - run_test(case, &mut total_passed, &mut total_failed, &mut failed_tests, &[], ""); - } - ProgramOutput::Result { .. } => { - // For library tests, use cross-compilation to validate ABI compliance - if is_library_test { - if let Some(library_file) = case.extra_files.first() { - // Test 1: ncc compiles client, gcc compiles library (validates ncc as caller) - run_library_cross_test( - &case.c_file, - library_file, - &case.output, - &mut total_passed, - &mut total_failed, - &mut failed_tests, - true, - ); - // Test 2: gcc compiles client, ncc compiles library (validates ncc as callee) - run_library_cross_test( - &case.c_file, - library_file, - &case.output, - &mut total_passed, - &mut total_failed, - &mut failed_tests, - false, - ); - } - } else { - // Standard test: compile everything with ncc - run_test(case, &mut total_passed, &mut total_failed, &mut failed_tests, &[], ""); - run_test( - case, - &mut total_passed, - &mut total_failed, - &mut failed_tests, - &["--no-iced".to_string()], - "no-iced", - ); + match &case.output { + ProgramOutput::Error(_) => { + run_test(case, &mut result, &[], ""); + } + ProgramOutput::Result { .. } => { + // For library tests, use cross-compilation to validate ABI compliance + if is_library_test { + if let Some(library_file) = case.extra_files.first() { + // Test 1: ncc compiles client, gcc compiles library (validates ncc as caller) + run_library_cross_test(&case.c_file, library_file, &case.output, &mut result, true); + // Test 2: gcc compiles client, ncc compiles library (validates ncc as callee) + run_library_cross_test(&case.c_file, library_file, &case.output, &mut result, false); } + } else { + // Standard test: compile everything with ncc + run_test(case, &mut result, &[], ""); + // The --no-iced text emitter forks an extra `as` per test, doubling + // process count. Codecov unions coverage across the CI matrix, so emit.rs + // stays fully covered by the Linux job; only run it there. (A single + // non-linux --no-iced smoke test below keeps the arm64 `as` shim covered.) + #[cfg(target_os = "linux")] + run_test(case, &mut result, &["--no-iced".to_string()], "no-iced"); } } } - // takes too long to do this for all cases + + result +} + +fn run_cases(cases: Vec) { + use rayon::prelude::*; + + // Evaluate cases in parallel. rayon's global pool bounds total concurrency across all + // test functions. `collect` preserves input order, so the sequential merge below lists + // failures deterministically regardless of completion order. + let per_case: Vec = cases.par_iter().map(run_one_case).collect(); + let mut tally = CaseResult::default(); + for r in per_case { + tally.merge(r); + } + + // takes too long to do this for all cases. + // On macOS the default linker is already external `ld` (libwild is linux-only), so this + // case is a redundant no-op there — only exercise it on Linux. + #[cfg(target_os = "linux")] run_test( cases.first().unwrap(), - &mut total_passed, - &mut total_failed, - &mut failed_tests, + &mut tally, &["--external-linker".to_string()], "external-linker", ); - println!("\n=== C Programs Test Results ==="); - println!("Passed: {total_passed}"); - println!("Failed: {total_failed}"); - - if !failed_tests.is_empty() { - println!("\nFailed tests:"); - for test in &failed_tests { - println!(" - {test}"); - } + // On non-Linux hosts the per-test --no-iced runs are skipped above to avoid forking an + // extra `as` per test. Run exactly ONE here so the arm64 `as --arch x86_64` cross-assembly + // shim still gets coverage. Pick the first case whose output is a Result and isn't a + // _client.c library test (those go through the cross-compilation path, not run_test). + #[cfg(not(target_os = "linux"))] + if let Some(case) = cases.iter().find(|c| { + matches!(c.output, ProgramOutput::Result { .. }) + && !(c.c_file.contains("/libraries/") && c.c_file.ends_with("_client.c")) + }) { + run_test(case, &mut tally, &["--no-iced".to_string()], "no-iced-smoke"); } - if total_failed > 0 { - println!("{total_failed} tests failed") - } - assert_eq!(total_failed, 0); - assert!(total_passed > 0) + assert!( + tally.failed == 0, + "{} of {} sub-tests failed:\n{}", + tally.failed, + tally.passed + tally.failed, + tally + .failures + .iter() + .map(|f| format!(" - {f}")) + .collect::>() + .join("\n") + ); + assert!(tally.passed > 0, "no test cases ran"); } #[test] @@ -864,3 +887,290 @@ fn test_no_warning_on_declaration() { println!("✓ No warning on declaration test passed"); } + +#[test] +fn test_division_by_zero_warning() { + let test_file = "tests/c_programs/warnings/division_by_zero.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + + assert!( + stderr_output.contains("-Wdiv-by-zero"), + "Expected -Wdiv-by-zero warning, but stderr was: {}", + stderr_output + ); + + // Both the `/` and `%` cases should be reported with their distinct wording + assert!( + stderr_output.contains("division by zero"), + "Warning should mention division by zero, but stderr was: {}", + stderr_output + ); + assert!( + stderr_output.contains("remainder by zero"), + "Warning should mention remainder by zero, but stderr was: {}", + stderr_output + ); + + println!("✓ Division-by-zero warning test passed"); +} + +#[test] +fn test_no_division_by_zero_on_nonconstant() { + let test_file = "tests/c_programs/warnings/no_division_by_zero.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + + // Non-constant and non-zero constant divisors must not warn + assert!( + !stderr_output.contains("-Wdiv-by-zero"), + "Non-constant / non-zero divisors should not warn, but stderr was: {}", + stderr_output + ); + + println!("✓ No division-by-zero on non-constant divisor test passed"); +} + +#[test] +fn test_shift_count_warning() { + let test_file = "tests/c_programs/warnings/shift_count.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + + // Both the overflow (count >= width) and negative-count cases should be reported + assert!( + stderr_output.contains("-Wshift-count-overflow"), + "Expected -Wshift-count-overflow warning, but stderr was: {}", + stderr_output + ); + assert!( + stderr_output.contains("-Wshift-count-negative"), + "Expected -Wshift-count-negative warning, but stderr was: {}", + stderr_output + ); + + println!("✓ Shift-count warning test passed"); +} + +#[test] +fn test_no_shift_count_on_valid_shifts() { + let test_file = "tests/c_programs/warnings/no_shift_count.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + + // In-range and non-constant shift counts must not warn + assert!( + !stderr_output.contains("-Wshift-count"), + "In-range / non-constant shift counts should not warn, but stderr was: {}", + stderr_output + ); + + println!("✓ No shift-count warning on valid shifts test passed"); +} + +#[test] +fn test_div_by_zero_in_constant_context_error() { + // A constant zero divisor in a context requiring a constant expression is a hard error + // (exit 30) reported specifically as "division by zero in constant expression", not the + // generic "not a constant expression" / "not an integer constant expression". + let test_file = "tests/c_programs/switch/invalid_semantics/case_div_by_zero.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + assert_eq!( + output.status.code(), + Some(30), + "Expected exit code 30 for a div-by-zero case label" + ); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + assert!( + stderr_output.contains("division by zero in constant expression"), + "Expected a specific division-by-zero message, but stderr was: {}", + stderr_output + ); + + println!("✓ Division-by-zero in constant context error test passed"); +} + +#[test] +fn test_overflow_warning() { + // Folds that leave the result type warn with -Woverflow. The `-INT_MIN`, `INT_MIN / -1`, + // and `INT_MIN % -1` cases in this fixture previously *panicked* the compiler, so asserting a + // clean exit (not 101) is also the no-panic regression check. + let test_file = "tests/c_programs/warnings/overflow.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + assert_ne!( + output.status.code(), + Some(101), + "ncc panicked on a constant overflow fold (regression)" + ); + assert_eq!(output.status.code(), Some(0), "expected --validate to succeed"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + assert!( + stderr_output.contains("-Woverflow"), + "Expected -Woverflow warning, but stderr was: {}", + stderr_output + ); + + println!("✓ Overflow warning + no-panic regression test passed"); +} + +#[test] +fn test_no_overflow_on_in_range() { + let test_file = "tests/c_programs/warnings/no_overflow.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + assert!( + !stderr_output.contains("-Woverflow"), + "In-range constant folds should not warn, but stderr was: {}", + stderr_output + ); + + println!("✓ No overflow warning on in-range folds test passed"); +} + +#[test] +fn test_constant_conversion_warning() { + let test_file = "tests/c_programs/warnings/constant_conversion.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + assert!( + stderr_output.contains("-Wconstant-conversion"), + "Expected -Wconstant-conversion warning, but stderr was: {}", + stderr_output + ); + + println!("✓ Constant-conversion warning test passed"); +} + +#[test] +fn test_no_constant_conversion_on_cast_or_fit() { + let test_file = "tests/c_programs/warnings/no_constant_conversion.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + // Explicit casts and conversions that don't lose value must not warn + assert!( + !stderr_output.contains("-Wconstant-conversion"), + "Explicit casts / in-range conversions should not warn, but stderr was: {}", + stderr_output + ); + + println!("✓ No constant-conversion on cast/fit test passed"); +} + +#[test] +fn test_sequence_point_warning() { + let test_file = "tests/c_programs/warnings/sequence_point.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + assert!( + stderr_output.contains("-Wsequence-point"), + "Expected -Wsequence-point warning, but stderr was: {}", + stderr_output + ); + + println!("✓ Sequence-point warning test passed"); +} + +#[test] +fn test_no_sequence_point_on_sequenced() { + let test_file = "tests/c_programs/warnings/no_sequence_point.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + + let stderr_output = String::from_utf8_lossy(&output.stderr); + // Single modifications and sequenced operators (?:, &&, separate statements) must not warn + assert!( + !stderr_output.contains("-Wsequence-point"), + "Sequenced / single modifications should not warn, but stderr was: {}", + stderr_output + ); + + println!("✓ No sequence-point on sequenced expressions test passed"); +}