diff --git a/.gitignore b/.gitignore index c403c34..333895b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target .idea/ +/notes diff --git a/README.md b/README.md index 782379f..0409ffb 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,84 @@ # NCC - Not Completely C + [![Lint](https://github.com/johnhringiv/NCC-Rust/actions/workflows/lint.yml/badge.svg)](https://github.com/johnhringiv/NCC-Rust/actions/workflows/lint.yml) [![codecov](https://codecov.io/gh/johnhringiv/NCC-Rust/graph/badge.svg?token=GJJCD2Z8Y6)](https://codecov.io/gh/johnhringiv/NCC-Rust) A simple C compiler written in Rust, following Sandler's "Writing a C Compiler". Some design decisions are informed by the book but the implementation is my own. -So far chapter 9, including extra credit is implemented, which includes a lexer, parser, semantic analysis, and code generator for C code with functions, local variables, compound statements, loops, and switch statements. -This compiler is a fully standalone executable; it does not rely on any external programs for assembling or linking (on Linux). +So far chapter 10, including extra credit is implemented, which includes a lexer, parser, semantic analysis, and code +generator for C code with functions, local and file-scope variables, storage-class specifiers, compound statements, +loops, and switch statements. +This compiler is a fully standalone executable; it does not rely on any external programs for assembling or linking (on +Linux). All provided tests pass. +## Example + +NCC supports a substantial subset of C, including functions, static variables, all control flow statements, and bitwise +operations. Here's a [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) example showcasing some of +these capabilities: + +```c +// Collatz Conjecture Explorer +// +// For any positive integer n: +// - If n is even: n = n / 2 +// - If n is odd: n = 3n + 1 +// The conjecture states this always reaches 1. +// +// Which number under 100 takes the most steps? + +static int total_steps = 0; + +int collatz(int n) { + int steps = 0; + while (n != 1) { + if (n & 1) { + n = 3 * n + 1; // odd + } else { + n = n >> 1; // even: divide by 2 + } + steps++; + } + total_steps += steps; + return steps; +} + +int main(void) { + int champion = 1; + int max_steps = 0; + + for (int i = 1; i < 100; i++) { + int steps = collatz(i); + if (steps > max_steps) { + max_steps = steps; + champion = i; + } + } + + // Returns 97: takes 118 steps to reach 1! + // 97 -> 292 -> 146 -> 73 -> 220 -> 110 -> 55 -> ... -> 1 + return champion; +} +``` + +```sh +$ ncc collatz.c --run +97 +``` + ## Language Grammar The compiler currently implements a subset of C with the following grammar: ```ebnf - ::= { } + ::= { } ::= | - ::= "int" [ "=" ] ";" - ::= "int" "(" ")" ( | ";" ) + ::= { }+ [ "=" ] ";" + ::= { }+ "(" ")" ( | ";" ) ::= "void" | "int" { "," "int" } + ::= "int" | "static" | "extern" ::= "{" { } "}" ::= | ::= | [ ] ";" @@ -53,9 +113,14 @@ The compiler currently implements a subset of C with the following grammar: ### Supported Features The compiler supports: + - **Multiple functions**: Function definitions and forward declarations -- **Function calls**: Call functions with arguments using the x86-64 System V ABI (first 6 integer arguments in registers RDI, RSI, RDX, RCX, R8, R9; additional arguments on the stack) +- **Function calls**: Call functions with arguments using the x86-64 System V ABI (first 6 integer arguments in + registers RDI, RSI, RDX, RCX, R8, R9; additional arguments on the stack) - **Local variable declarations** with optional initialization +- **File-scope (global) variables**: Defined at file scope with optional initializers (must be constant expressions) +- **Storage-class specifiers**: `static` (internal linkage) and `extern` (external linkage) for both variables and + functions - **Compound statements (blocks)**: `{ ... }` with proper scoping - **Variable scoping**: Block-local variables with shadowing support - **Integer arithmetic**: addition, subtraction, multiplication, division, modulo @@ -66,15 +131,15 @@ The compiler supports: - **Increment/decrement**: prefix (`++x`, `--x`) and postfix (`x++`, `x--`) - **Conditional (ternary) operator**: `condition ? true_expr : false_expr` - **Control flow**: - - `if`/`else` statements - - `switch` statements with `case` and `default` labels - - `while` loops - - `do-while` loops - - `for` loops with all three components (init, condition, update) - - `break` and `continue` statements - - Compound statements/blocks - - `goto` and labeled statements - - `return` statements + - `if`/`else` statements + - `switch` statements with `case` and `default` labels + - `while` loops + - `do-while` loops + - `for` loops with all three components (init, condition, update) + - `break` and `continue` statements + - Compound statements/blocks + - `goto` and labeled statements + - `return` statements - **Expression statements** and **null statements** ### Safer C @@ -82,18 +147,29 @@ The compiler supports: NCC provides several safety features and guarantees to help developers write more reliable code: #### Guaranteed Behaviors -- **Deterministic integer overflow**: Integer arithmetic uses two's complement wrapping (32-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. + +- **Deterministic integer overflow**: Integer arithmetic uses two's complement wrapping (32-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. #### 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 -- **Unused parameters** (`-Wunused-parameter`): Warns when a function parameter is declared but never used in the function body + +- **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 +- **Unused parameters** (`-Wunused-parameter`): Warns when a function parameter is declared but never used in the + function body #### Developer Experience -- **Precise error locations**: All errors and warnings include exact line and column numbers with file:line:column format, making it easy to locate problematic code -- **Contextual error messages**: Semantic errors reference related code locations (e.g., showing both the shadowing variable and the original declaration) -- **Pretty-printed ASTs**: Visual tree representations of parsed code (`--parse`), intermediate representations (`--tacky`), and generated code (`--codegen`) for debugging and understanding compilation stages + +- **Precise error locations**: All errors and warnings include exact line and column numbers with file:line:column + format, making it easy to locate problematic code +- **Contextual error messages**: Semantic errors reference related code locations (e.g., showing both the shadowing + variable and the original declaration) +- **Pretty-printed ASTs**: Visual tree representations of parsed code (`--parse`), intermediate representations ( + `--tacky`), and generated code (`--codegen`) for debugging and understanding compilation stages These features help catch common bugs at compile time while providing predictable runtime behavior. @@ -127,6 +203,7 @@ cargo build --release ``` ### Running Tests + ```sh cargo test ``` @@ -136,25 +213,27 @@ cargo test Usage: ncc [OPTIONS] `...` ### Arguments + `...` Input files (required). Supports multiple C and assembly files. ### Options -| Option | Description | -|---------------------------|----------------------------------------------------| -| `--lex` | Run lexer | -| `--parse` | Run lexer and parser | -| `--validate` | Run lexer, parser, and validator | -| `--codegen` | Run lexer, parser, and code generator | -| `--tacky` | Emit TACKY IR | -| `-S` | Emit assembly | -| `--run` | Run compiled program and print result | -| `-c` | Emit object file only (no linking) | -| `--gcc` | Use GCC for linking (instead of wild) | -| `--static` | Link statically (no runtime dependencies) | + +| Option | Description | +|---------------------------|----------------------------------------------------------| +| `--lex` | Run lexer | +| `--parse` | Run lexer and parser | +| `--validate` | Run lexer, parser, and validator | +| `--codegen` | Run lexer, parser, and code generator | +| `--tacky` | Emit TACKY IR | +| `-S` | Emit assembly | +| `--run` | Run compiled program and print result | +| `-c` | Emit object file only (no linking) | +| `--gcc` | Use GCC for linking (instead of wild) | +| `--static` | Link statically (no runtime dependencies) | | `--no-iced` | Use text-based asm building instead of iced (deprecated) | -| `-o`, `--output ` | Override output file location | -| `-h`, `--help` | Print help | -| `-V`, `--version` | Print version | +| `-o`, `--output ` | Override output file location | +| `-h`, `--help` | Print help | +| `-V`, `--version` | Print version | Note: `--lex`, `--parse`, `--validate`, `--codegen`, `--tacky`, `-S`, `--run`, `-c` are mutually exclusive options. @@ -171,10 +250,12 @@ NCC uses specific exit codes to indicate different types of failures: | 30 | Validation error (semantic error) | ## Contributing + As a reminder to myself. Use the Makefile to check code quality `make quality` and fix formatting `make fix`. ### Requirements for Makefile + ```shell sudo apt-get install pkg-config libssl-dev make ``` diff --git a/src/codegen.rs b/src/codegen.rs index 666a8fc..4764ff3 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -1,8 +1,8 @@ use crate::parser; use crate::parser::Identifier; use crate::tacky; -use crate::tacky::{BinOp, Val}; -use std::collections::HashMap; +use crate::tacky::{BinOp, StaticVariable, Val}; +use std::collections::{HashMap, HashSet}; #[derive(Clone, Debug, PartialEq)] pub enum Reg { @@ -23,6 +23,13 @@ pub enum Operand { Reg(Reg), Pseudo(String), Stack(i32), + Data(String), +} + +impl Operand { + pub fn is_memory(&self) -> bool { + matches!(self, Operand::Data(_) | Operand::Stack(_)) + } } #[derive(Clone, Debug, PartialEq)] @@ -73,27 +80,29 @@ pub enum CondCode { } impl CondCode { - pub fn ins_suffix(&self) -> String { + pub fn ins_suffix(&self) -> &'static str { match self { - CondCode::E => "e".to_string(), - CondCode::NE => "ne".to_string(), - CondCode::G => "g".to_string(), - CondCode::GE => "ge".to_string(), - CondCode::L => "l".to_string(), - CondCode::LE => "le".to_string(), + CondCode::E => "e", + CondCode::NE => "ne", + CondCode::G => "g", + CondCode::GE => "ge", + CondCode::L => "l", + CondCode::LE => "le", } } } -#[derive(Debug, PartialEq)] +#[derive(Debug)] pub struct FunctionDefinition { pub name: String, pub body: Vec, + pub global: bool, } -#[derive(Debug, PartialEq)] +#[derive(Debug)] pub struct Program { pub functions: Vec, + pub static_vars: Vec, } fn convert_function_call(fun_name: &Identifier, args: &[Val], dst: &Val) -> Vec { @@ -117,7 +126,7 @@ fn convert_function_call(fun_name: &Identifier, args: &[Val], dst: &Val) -> Vec< 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::Stack(_) | Operand::Pseudo(_) | Operand::Data(_) => { instructions.push(Instruction::Mov { src: assembly_arg, dst: Operand::Reg(Reg::AX), @@ -209,7 +218,8 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { }, ] } - BinOp::Divide => { + BinOp::Divide | BinOp::Remainder => { + let result_reg = if *op == BinOp::Divide { Reg::AX } else { Reg::DX }; vec![ Instruction::Mov { src: src1, @@ -218,21 +228,7 @@ fn convert_instruction(instruction: &tacky::Instruction) -> Vec { Instruction::Cdq, Instruction::Idiv(src2), Instruction::Mov { - src: Operand::Reg(Reg::AX), - dst, - }, - ] - } - BinOp::Remainder => { - vec![ - Instruction::Mov { - src: src1, - dst: Operand::Reg(Reg::AX), - }, - Instruction::Cdq, - Instruction::Idiv(src2), - Instruction::Mov { - src: Operand::Reg(Reg::DX), + src: Operand::Reg(result_reg), dst, }, ] @@ -316,7 +312,12 @@ impl From<&BinOp> for BinaryOp { BinOp::BitwiseXOr => BinaryOp::BitXOr, BinOp::BitwiseLeftShift => BinaryOp::BitShl, BinOp::BitwiseRightShift => BinaryOp::BitSar, - _ => unimplemented!("Binary operation not implemented: {:?}", op), + BinOp::Equal + | BinOp::NotEqual + | BinOp::LessThan + | BinOp::LessOrEqual + | BinOp::GreaterThan + | BinOp::GreaterOrEqual => unreachable!("Removed in convert_instruction"), } } } @@ -337,7 +338,12 @@ fn convert_val(ast: &tacky::Val) -> Operand { } fn convert_function(ast: &tacky::FunctionDefinition) -> FunctionDefinition { - let tacky::FunctionDefinition { name, params, body } = ast; + let tacky::FunctionDefinition { + name, + params, + body, + global, + } = ast; let arg_registers = [Reg::DI, Reg::SI, Reg::DX, Reg::CX, Reg::R8, Reg::R9]; let mut instructions = vec![]; @@ -361,36 +367,51 @@ fn convert_function(ast: &tacky::FunctionDefinition) -> FunctionDefinition { FunctionDefinition { name: name.to_string(), body: instructions, + global: *global, } } } +/// Converts TACKY IR to x86-64 assembly AST. +/// +/// 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![]; - for function in ast.functions.as_slice() { - functions.push(convert_function(function)) + 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()), + } } - let mut p = Program { functions }; + let mut p = Program { functions, static_vars }; let stack_offsets = replace_pseudo_registers(&mut p); fix_invalid(&mut p, &stack_offsets); coalesce_labels(&mut p); p } -struct StackMapping { - stack_mapping: std::collections::HashMap, +struct StackMapping<'a> { + stack_mapping: HashMap, 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, } -impl StackMapping { - pub fn new() -> Self { +impl<'a> StackMapping<'a> { + fn from_data_vars(data_vars: &'a HashSet) -> Self { StackMapping { - stack_mapping: std::collections::HashMap::new(), + stack_mapping: HashMap::new(), offset: 0, + data_vars, } } - pub fn get_stack_location(&mut self, pseudo: &str) -> Operand { + fn get_stack_location(&mut self, pseudo: &str) -> Operand { let offset_option = self.stack_mapping.get(pseudo); let offset = match offset_option { Some(offset) => offset, @@ -403,18 +424,36 @@ impl StackMapping { Operand::Stack(*offset) } - pub fn replace_pseudo(&mut self, operand: &Operand) -> Operand { + /// Replaces pseudo-register operands with their actual locations. + /// + /// 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 { match operand { - Operand::Pseudo(pseudo) => self.get_stack_location(pseudo), + Operand::Pseudo(pseudo) => { + if self.data_vars.contains(pseudo) { + Operand::Data(pseudo.clone()) + } else { + self.get_stack_location(pseudo) + } + } _ => operand.clone(), } } } +/// Replaces all pseudo-register operands with concrete locations. +/// +/// 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 { + // 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 mut offsets = HashMap::new(); - for FunctionDefinition { name, body } in program.functions.iter_mut() { - let mut stack_mapping = StackMapping::new(); + for FunctionDefinition { name, body, global: _ } in program.functions.iter_mut() { + let mut stack_mapping = StackMapping::from_data_vars(&data_vars); for ins in body.iter_mut() { match ins { @@ -441,8 +480,19 @@ pub fn replace_pseudo_registers(program: &mut Program) -> HashMap { offsets } +/// Fixes invalid x86-64 instruction operand combinations. +/// +/// Rewrites instructions that violate x86-64 encoding rules: +/// - Memory-to-memory moves (uses R10 as intermediate) +/// - Immediate operand to idiv (moves to R10 first) +/// - 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 +/// +/// Also inserts stack allocation at the start of each function. pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) { - for FunctionDefinition { name, body } in program.functions.iter_mut() { + 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 { @@ -451,17 +501,14 @@ pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) let mut new_ins = vec![Instruction::AllocateStack(positive_offset)]; for ins in body.iter() { match ins { - Instruction::Mov { - src: Operand::Stack(src), - dst: Operand::Stack(dst), - } => { + Instruction::Mov { src, dst } if src.is_memory() && dst.is_memory() => { new_ins.push(Instruction::Mov { - src: Operand::Stack(*src), + src: src.clone(), dst: Operand::Reg(Reg::R10), }); new_ins.push(Instruction::Mov { src: Operand::Reg(Reg::R10), - dst: Operand::Stack(*dst), + dst: dst.clone(), }); } Instruction::Idiv(Operand::Imm(c)) => { @@ -474,10 +521,10 @@ pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) Instruction::Binary { op: BinaryOp::Mult, src, - dst: Operand::Stack(dst), - } => { + dst, + } if dst.is_memory() => { new_ins.push(Instruction::Mov { - src: Operand::Stack(*dst), + src: dst.clone(), dst: Operand::Reg(Reg::R11), }); new_ins.push(Instruction::Binary { @@ -487,31 +534,31 @@ pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) }); new_ins.push(Instruction::Mov { src: Operand::Reg(Reg::R11), - dst: Operand::Stack(*dst), + dst: dst.clone(), }); } Instruction::Binary { op: op @ (BinaryOp::Add | BinaryOp::Sub | BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXOr), - src: Operand::Stack(src), - dst: Operand::Stack(dst), - } => { + src, + dst, + } if src.is_memory() && dst.is_memory() => { new_ins.push(Instruction::Mov { - src: Operand::Stack(*src), + src: src.clone(), dst: Operand::Reg(Reg::R10), }); new_ins.push(Instruction::Binary { op: op.clone(), src: Operand::Reg(Reg::R10), - dst: Operand::Stack(*dst), + dst: dst.clone(), }); } Instruction::Binary { op: op @ (BinaryOp::BitShl | BinaryOp::BitSar), - src: Operand::Stack(src), + src, dst, - } => { + } if src.is_memory() => { new_ins.push(Instruction::Mov { - src: Operand::Stack(*src), + src: src.clone(), dst: Operand::Reg(Reg::CX), }); new_ins.push(Instruction::Binary { @@ -520,17 +567,14 @@ pub fn fix_invalid(program: &mut Program, stack_offsets: &HashMap) dst: dst.clone(), }); } - Instruction::Cmp { - v1: Operand::Stack(v1), - v2: Operand::Stack(v2), - } => { + Instruction::Cmp { v1, v2 } if v1.is_memory() && v2.is_memory() => { new_ins.push(Instruction::Mov { - src: Operand::Stack(*v1), + src: v1.clone(), dst: Operand::Reg(Reg::R10), }); new_ins.push(Instruction::Cmp { v1: Operand::Reg(Reg::R10), - v2: Operand::Stack(*v2), + v2: v2.clone(), }); } Instruction::Cmp { @@ -555,7 +599,12 @@ 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) { - for FunctionDefinition { name: _name, body } in program.functions.iter_mut() { + for FunctionDefinition { + name: _name, + body, + global: _, + } in program.functions.iter_mut() + { let mut label_map: std::collections::HashMap = std::collections::HashMap::new(); let mut new_ins = Vec::new(); let mut current_label: Option = None; diff --git a/src/emit.rs b/src/emit.rs index 86ce463..7fc9710 100644 --- a/src/emit.rs +++ b/src/emit.rs @@ -1,4 +1,5 @@ use crate::codegen::{BinaryOp, FunctionDefinition, Instruction, Operand, Program, Reg, UnaryOp}; +use crate::tacky::{StaticVariable, VarInit}; enum RegWidth { Byte, @@ -6,61 +7,61 @@ enum RegWidth { QWord, } -fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> String { +fn emit_reg(reg: &Reg, reg_width: &RegWidth) -> &'static str { match reg_width { RegWidth::Byte => match reg { - Reg::AX => "al".to_string(), - Reg::DX => "dl".to_string(), - Reg::CX => "cl".to_string(), - Reg::DI => "dil".to_string(), - Reg::SI => "sil".to_string(), - Reg::R8 => "r8b".to_string(), - Reg::R9 => "r9b".to_string(), - Reg::R10 => "r10b".to_string(), - Reg::R11 => "r11b".to_string(), + Reg::AX => "al", + Reg::DX => "dl", + Reg::CX => "cl", + Reg::DI => "dil", + Reg::SI => "sil", + Reg::R8 => "r8b", + Reg::R9 => "r9b", + Reg::R10 => "r10b", + Reg::R11 => "r11b", }, RegWidth::DWord => match reg { - Reg::AX => "eax".to_string(), - Reg::DX => "edx".to_string(), - Reg::CX => "ecx".to_string(), - Reg::DI => "edi".to_string(), - Reg::SI => "esi".to_string(), - Reg::R8 => "r8d".to_string(), - Reg::R9 => "r9d".to_string(), - Reg::R10 => "r10d".to_string(), - Reg::R11 => "r11d".to_string(), + Reg::AX => "eax", + Reg::DX => "edx", + Reg::CX => "ecx", + Reg::DI => "edi", + Reg::SI => "esi", + Reg::R8 => "r8d", + Reg::R9 => "r9d", + Reg::R10 => "r10d", + Reg::R11 => "r11d", }, RegWidth::QWord => match reg { - Reg::AX => "rax".to_string(), - Reg::DX => "rdx".to_string(), - Reg::CX => "rcx".to_string(), - Reg::DI => "rdi".to_string(), - Reg::SI => "rsi".to_string(), - Reg::R8 => "r8".to_string(), - Reg::R9 => "r9".to_string(), - Reg::R10 => "r10".to_string(), - Reg::R11 => "r11".to_string(), + Reg::AX => "rax", + Reg::DX => "rdx", + Reg::CX => "rcx", + Reg::DI => "rdi", + Reg::SI => "rsi", + Reg::R8 => "r8", + Reg::R9 => "r9", + Reg::R10 => "r10", + Reg::R11 => "r11", }, } } -fn emit_unaryop(op: &UnaryOp) -> String { +fn emit_unaryop(op: &UnaryOp) -> &'static str { match op { - UnaryOp::Neg => "negl".to_string(), - UnaryOp::Not => "notl".to_string(), + UnaryOp::Neg => "negl", + UnaryOp::Not => "notl", } } -fn emit_binaryop(op: &BinaryOp) -> String { +fn emit_binaryop(op: &BinaryOp) -> &'static str { match op { - BinaryOp::Add => "addl".to_string(), - BinaryOp::Sub => "subl".to_string(), - BinaryOp::Mult => "imull".to_string(), - BinaryOp::BitAnd => "andl".to_string(), - BinaryOp::BitOr => "orl".to_string(), - BinaryOp::BitXOr => "xorl".to_string(), - BinaryOp::BitShl => "shll".to_string(), - BinaryOp::BitSar => "sarl".to_string(), + BinaryOp::Add => "addl", + BinaryOp::Sub => "subl", + BinaryOp::Mult => "imull", + BinaryOp::BitAnd => "andl", + BinaryOp::BitOr => "orl", + BinaryOp::BitXOr => "xorl", + BinaryOp::BitShl => "shll", + BinaryOp::BitSar => "sarl", } } @@ -77,6 +78,14 @@ fn emit_operand(operand: &Operand, reg_width: &RegWidth) -> String { output.push_str(&format!("{offset}(%rbp)")); } &Operand::Pseudo(_) => unreachable!("Must be eliminated before emission"), + Operand::Data(name) => { + // RIP-relative addressing for static/extern variables + if cfg!(target_os = "macos") { + output.push_str(&format!("_{name}(%rip)")); + } else { + output.push_str(&format!("{name}(%rip)")); + } + } } output } @@ -170,13 +179,15 @@ fn emit_instruction(ins: &Instruction, fn_name: &str) -> String { fn emit_function(fun_def: &FunctionDefinition) -> String { let mut output = String::new(); - let FunctionDefinition { name, body } = fun_def; + let FunctionDefinition { name, body, global } = fun_def; let processed_name = if cfg!(target_os = "macos") { format!("_{name}") } else { name.to_string() }; - output.push_str(&format!("\t.global {processed_name}\n")); + if *global { + output.push_str(&format!("\t.globl {processed_name}\n")); + } output.push_str(&format!("{processed_name}:\n")); output.push_str("\tpushq %rbp\n"); output.push_str("\tmovq %rsp, %rbp\n"); @@ -186,11 +197,57 @@ fn emit_function(fun_def: &FunctionDefinition) -> String { output } +fn emit_static_variable(sv: &StaticVariable) -> String { + let mut output = String::new(); + let StaticVariable { name, global, init } = sv; + let processed_name = if cfg!(target_os = "macos") { + format!("_{name}") + } else { + name.to_string() + }; + + // Extern variables don't need any output - they're resolved by the linker + let VarInit::Defined(init_val) = init else { + return output; + }; + + if *global { + 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")); + } + + output +} + pub fn emit_program(program: &Program) -> String { let mut output = String::new(); - for function in &program.functions { - output.push_str(&emit_function(function)); + + // Emit functions in text section + if !program.functions.is_empty() { + output.push_str("\t.text\n"); + for function in &program.functions { + output.push_str(&emit_function(function)); + } } + + // Emit static variables + for sv in &program.static_vars { + output.push_str(&emit_static_variable(sv)); + } + if cfg!(target_os = "linux") { output.push_str("\n.section .note.GNU-stack,\"\",@progbits\n"); } diff --git a/src/emit_iced.rs b/src/emit_iced.rs index 18fb0ec..2a2a50f 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -1,5 +1,6 @@ // 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}; use iced_x86::{BlockEncoderOptions, IcedError, SymbolResolver, SymbolResult, code_asm::*}; use object::write::{ Object, Relocation, RelocationFlags, StandardSection, StandardSegment, Symbol, SymbolFlags, SymbolId, SymbolKind, @@ -11,29 +12,54 @@ use object::{ }; use std::collections::HashMap; -// Symbol resolver for displaying labels in assembly output +/// Creates an undefined symbol (resolved by linker at link time). +fn undefined_symbol(name: &str, kind: SymbolKind) -> Symbol { + Symbol { + name: name.as_bytes().to_vec(), + value: 0, + size: 0, + kind, + scope: SymbolScope::Unknown, + weak: false, + section: SymbolSection::Undefined, + flags: SymbolFlags::None, + } +} + +/// Symbol resolver for displaying labels in assembly output. +/// +/// Handles two types of symbol resolution: +/// - `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, } impl MySymbolResolver { - fn new(symbols: HashMap) -> Self { - Self { symbols } + fn new(symbols: HashMap, reloc_symbols: HashMap) -> Self { + Self { symbols, reloc_symbols } } } impl SymbolResolver for MySymbolResolver { fn symbol( &'_ mut self, - _instruction: &iced_x86::Instruction, + instruction: &iced_x86::Instruction, _operand: u32, _instruction_operand: Option, address: u64, _address_size: u32, ) -> Option> { - self.symbols - .get(&address) - .map(|name| SymbolResult::with_str(address, name.as_str())) + // 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())); + } + // 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())); + } + None } } @@ -41,6 +67,8 @@ impl SymbolResolver for MySymbolResolver { pub fn get_instructions( program: &codegen::Program, ) -> Result<(Vec, MySymbolResolver, HashMap), Box> { + use object::read::RelocationTarget; + let (obj_bytes, internal_labels) = emit_object_with_labels(program)?; // Parse the object file @@ -50,6 +78,14 @@ pub fn get_instructions( let text_section = obj.section_by_name(".text").ok_or("No .text section found")?; let code = text_section.data()?; + // Build symbol index to name map + 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()); + } + } + // Build symbol resolver from object file symbols let mut address_map = HashMap::new(); let mut function_offsets = HashMap::new(); @@ -78,6 +114,14 @@ pub fn get_instructions( decoder.set_ip(0); let instructions: Vec = decoder.into_iter().collect(); + // Build instruction offset ranges: (start, end) for each instruction + let mut ins_ranges: Vec<(usize, usize)> = Vec::new(); + let mut offset = 0; + for ins in &instructions { + ins_ranges.push((offset, offset + ins.len())); + offset += ins.len(); + } + // Map instruction indices from internal_labels to byte offsets let mut current_offset = 0; for (ins_idx, ins) in instructions.iter().enumerate() { @@ -89,13 +133,56 @@ pub fn get_instructions( current_offset += ins.len(); } - Ok((instructions, MySymbolResolver::new(address_map), label_idx)) + // 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(); + 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) + { + // Find which instruction contains this relocation + for (start, end) in ins_ranges.iter() { + if reloc_offset as usize >= *start && (reloc_offset as usize) < *end { + reloc_symbols.insert(*start as u64, symbol_name.clone()); + break; + } + } + } + } + + Ok(( + instructions, + MySymbolResolver::new(address_map, reloc_symbols), + label_idx, + )) } pub fn emit_object(program: &codegen::Program) -> Result, Box> { emit_object_with_labels(program).map(|(bytes, _)| bytes) } +/// Emits an ELF/Mach-O object file from the codegen IR using iced-x86. +/// +/// This is the core emission function that produces relocatable machine code. +/// It performs the following steps: +/// +/// 1. Creates iced-x86 labels for all functions and static variables upfront +/// 2. Emits machine code for each function body, tracking: +/// - External function calls (for PLT relocations) +/// - Data references (for RIP-relative relocations) +/// - Internal jump labels (for disassembly) +/// 3. Assembles the code using iced-x86's block encoder +/// 4. Builds an object file with the `object` crate containing: +/// - `.text` section with the assembled code +/// - `.data`/`.bss` sections for static variables +/// - Symbol table entries for functions and variables +/// - Relocations for external calls and data references +/// +/// # Returns +/// +/// A tuple containing: +/// - The serialized object file bytes +/// - A map from instruction index to label name (for disassembly/debugging) #[allow(clippy::type_complexity)] fn emit_object_with_labels( program: &codegen::Program, @@ -108,8 +195,15 @@ fn emit_object_with_labels( 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(); + 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(); // Track all internal labels across all functions let mut all_label_idx: HashMap = HashMap::new(); @@ -125,7 +219,9 @@ fn emit_object_with_labels( &mut a, fun_def, &fn_labels, + &data_labels, &mut external_calls, + &mut data_relocs, &mut labels, &mut label_idx, )?; @@ -134,13 +230,16 @@ fn emit_object_with_labels( all_label_idx.extend(label_idx); } - let result = a.assemble_options(0, BlockEncoderOptions::RETURN_NEW_INSTRUCTION_OFFSETS)?; + let result = a.assemble_options( + 0, + BlockEncoderOptions::RETURN_NEW_INSTRUCTION_OFFSETS | BlockEncoderOptions::RETURN_CONSTANT_OFFSETS, + )?; // Get function offsets before moving the code buffer - let mut func_offsets: Vec<(String, u64)> = Vec::new(); + let mut func_offsets: Vec<(String, 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)); + func_offsets.push((fun_def.name.clone(), func_off, fun_def.global)); } // Clone instruction offsets before moving the inner @@ -168,34 +267,74 @@ fn emit_object_with_labels( obj.append_section_data(text, &code, 1); // Add all function symbols - for (func_name, func_off) in &func_offsets { + for (func_name, func_off, global) in &func_offsets { let func_size = code.len() as u64 - func_off; obj.add_symbol(Symbol { name: func_name.as_bytes().to_vec(), value: *func_off, size: func_size, kind: SymbolKind::Text, - scope: SymbolScope::Linkage, + // Use Dynamic for global symbols (DEFAULT visibility) to allow linking across object files + // Use Compilation for static symbols (LOCAL binding) + scope: if *global { + SymbolScope::Dynamic + } else { + SymbolScope::Compilation + }, weak: false, section: SymbolSection::Section(text), flags: SymbolFlags::None, }); } + let data = obj.section_id(StandardSection::Data); + 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 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) + }; + + obj.add_symbol(Symbol { + name: name.as_bytes().to_vec(), + value: offset, + size: 4, + kind: SymbolKind::Data, + scope: if *global { + SymbolScope::Dynamic + } else { + SymbolScope::Compilation + }, + weak: false, + section: SymbolSection::Section(*section), + flags: SymbolFlags::None, + }) + } + // Extern variable - undefined symbol resolved by linker + VarInit::Extern => obj.add_symbol(undefined_symbol(name, SymbolKind::Data)), + }; + static_var_symbols.insert(name.clone(), sym_id); + } + // Add external function symbols and relocations let mut external_symbols: HashMap = HashMap::new(); for (_ins_idx, func_name) in &external_calls { if !external_symbols.contains_key(func_name) { - let symbol_id = obj.add_symbol(Symbol { - name: func_name.as_bytes().to_vec(), - value: 0, - size: 0, - kind: SymbolKind::Text, - scope: SymbolScope::Unknown, - weak: false, - section: SymbolSection::Undefined, - flags: SymbolFlags::None, - }); + let symbol_id = obj.add_symbol(undefined_symbol(func_name, SymbolKind::Text)); external_symbols.insert(func_name.clone(), symbol_id); } } @@ -227,21 +366,79 @@ fn emit_object_with_labels( } } + if !static_var_symbols.is_empty() { + for (ins_idx, var_name) in &data_relocs { + if let Some(symbol_id) = static_var_symbols.get(var_name) { + let ins_offset = instruction_offsets[*ins_idx] as u64; + let const_offsets = &result.inner.constant_offsets[*ins_idx]; + let reloc_offset = ins_offset + const_offsets.displacement_offset() as u64; + + // The addend is the negative of the bytes remaining after the displacement field. + // For R_X86_64_PC32: patched_value = S + A - P + // We want: displacement = S - RIP_next = S - (P + bytes_remaining) + // So: A = -bytes_remaining = -(displacement_size + immediate_size) + let bytes_remaining = const_offsets.displacement_size() + const_offsets.immediate_size(); + let addend = -(bytes_remaining as i64); + + obj.add_relocation( + text, + Relocation { + offset: reloc_offset, + flags: RelocationFlags::Generic { + kind: RelocationKind::Relative, + encoding: RelocationEncoding::Generic, + size: 32, + }, + symbol: *symbol_id, + addend, + }, + )?; + } + } + } + Ok((obj.write()?, all_label_idx)) } +/// Emits machine code for a single function body. +/// +/// Generates the standard x86-64 function prologue (`push rbp; mov rbp, rsp`) +/// followed by machine code for each instruction in the function body. +/// +/// # Parameters +/// +/// - `a`: The iced-x86 code assembler to emit instructions into +/// - `fun_def`: The function definition containing the instruction list +/// - `fn_labels`: Pre-created labels for all functions (for internal calls) +/// - `data_labels`: Pre-created labels for static/extern variables (for RIP-relative access) +/// - `external_calls`: Output vec tracking external call sites for relocation +/// - `data_relocs`: Output vec tracking data reference sites for relocation +/// - `labels`: Working map of jump label names to iced-x86 labels (within this function) +/// - `label_idx`: Output map from instruction index to label name (for disassembly) +#[allow(clippy::too_many_arguments)] 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, ) -> Result<(), IcedError> { a.push(gpr64::rbp)?; a.mov(gpr64::rbp, gpr64::rsp)?; for ins in &fun_def.body { - emit_instruction(a, ins, labels, label_idx, fn_labels, external_calls)?; + emit_instruction( + a, + ins, + labels, + label_idx, + fn_labels, + data_labels, + external_calls, + data_relocs, + )?; } Ok(()) } @@ -284,13 +481,22 @@ fn mem_rbp(offset: i32) -> AsmMemoryOperand { } } +// Data operands (static variables) use RIP-relative addressing with relocations. +// +// Note: Many Data destination patterns (e.g., `Add(Reg, Data)`, `Neg(Data)`) are currently +// unreached because the codegen uses load→op→store sequences for static variables. +// These patterns will become reachable after implementing copy propagation and dead store +// elimination, which can optimize `tmp = x; tmp = tmp + 1; x = tmp` into `x = x + 1`. +#[allow(clippy::too_many_arguments)] 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)>, ) -> Result<(), IcedError> { match ins { Instruction::Mov { src, dst } => match (src, dst) { @@ -298,18 +504,43 @@ fn emit_instruction( (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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.mov(gpr32(d), dword_ptr(*lbl))? + } (Operand::Imm(v), Operand::Stack(off)) => a.mov(mem_rbp(*off), *v)?, + (Operand::Imm(v), Operand::Data(name)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.mov(dword_ptr(*lbl), *v)? + } + (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))? + } _ => unreachable!("unsupported mov combination"), }, 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) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.neg(dword_ptr(*lbl))? + } _ => unreachable!(), }, UnaryOp::Not => match dst { Operand::Reg(r) => a.not(gpr32(r))?, Operand::Stack(off) => a.not(mem_rbp(*off))?, + Operand::Data(name) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.not(dword_ptr(*lbl))? + } _ => unreachable!(), }, }, @@ -318,68 +549,155 @@ fn emit_instruction( (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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.add(dword_ptr(*lbl), gpr32(s))? + } (Operand::Imm(v), Operand::Stack(off)) => a.add(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.sub(dword_ptr(*lbl), gpr32(s))? + } (Operand::Imm(v), Operand::Stack(off)) => a.sub(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => 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::Reg(s), Operand::Stack(off)) => a.imul_2(gpr32(s), mem_rbp(*off))?, (Operand::Stack(off), Operand::Reg(d)) => a.imul_2(gpr32(d), mem_rbp(*off))?, - _ => unimplemented!("Mult {:?}, {:?}", src, dst), + (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))? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.and(dword_ptr(*lbl), gpr32(s))? + } (Operand::Imm(v), Operand::Stack(off)) => a.and(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.or(dword_ptr(*lbl), gpr32(s))? + } (Operand::Imm(v), Operand::Stack(off)) => a.or(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.xor(dword_ptr(*lbl), gpr32(s))? + } (Operand::Imm(v), Operand::Stack(off)) => a.xor(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.shl(dword_ptr(*lbl), *v)? + } (Operand::Reg(Reg::CX), Operand::Stack(off)) => a.shl(mem_rbp(*off), gpr8::cl)?, - _ => unimplemented!(), + (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)? + } + _ => 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)) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.sar(dword_ptr(*lbl), *v)? + } (Operand::Reg(Reg::CX), Operand::Stack(off)) => a.sar(mem_rbp(*off), gpr8::cl)?, - _ => unimplemented!(), + (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)? + } + _ => unreachable!(), }, }, Instruction::Cmp { v1, v2 } => match (v1, v2) { (Operand::Reg(r1), Operand::Reg(r2)) => a.cmp(gpr32(r2), gpr32(r1))?, - (Operand::Reg(r1), Operand::Imm(v)) => a.cmp(gpr32(r1), *v)?, (Operand::Reg(r1), Operand::Stack(off)) => a.cmp(mem_rbp(*off), gpr32(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))? + } (Operand::Stack(off), Operand::Reg(r)) => a.cmp(gpr32(r), mem_rbp(*off))?, - (Operand::Stack(o1), Operand::Imm(v)) => a.cmp(mem_rbp(*o1), *v)?, + (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))? + } (Operand::Imm(v), Operand::Reg(r)) => a.cmp(gpr32(r), *v)?, (Operand::Imm(v), Operand::Stack(off)) => a.cmp(mem_rbp(*off), *v)?, - _ => unimplemented!(), + (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)? + } + _ => unreachable!(), }, Instruction::Cdq => { a.cdq()?; @@ -387,7 +705,12 @@ fn emit_instruction( Instruction::Idiv(op) => match op { Operand::Reg(r) => a.idiv(gpr32(r))?, Operand::Stack(off) => a.idiv(mem_rbp(*off))?, - _ => unimplemented!(), + Operand::Data(name) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + a.idiv(dword_ptr(*lbl))? + } + _ => unreachable!(), }, Instruction::Jmp(label) => { let l = *labels.entry(label.0.clone()).or_insert_with(|| a.create_label()); @@ -421,7 +744,19 @@ fn emit_instruction( CondCode::L => a.setl(mem_rbp(*off))?, CondCode::LE => a.setle(mem_rbp(*off))?, }, - _ => unimplemented!(), + Operand::Data(name) => { + let lbl = data_labels.get(name).unwrap(); + data_relocs.push((a.instructions().len(), name.clone())); + match code { + CondCode::E => a.sete(byte_ptr(*lbl))?, + CondCode::NE => a.setne(byte_ptr(*lbl))?, + CondCode::G => a.setg(byte_ptr(*lbl))?, + CondCode::GE => a.setge(byte_ptr(*lbl))?, + CondCode::L => a.setl(byte_ptr(*lbl))?, + CondCode::LE => a.setle(byte_ptr(*lbl))?, + } + } + _ => unreachable!(), }, Instruction::Label(lbl) => { let l = labels.entry(lbl.0.clone()).or_insert_with(|| a.create_label()); @@ -445,7 +780,7 @@ fn emit_instruction( Operand::Imm(c) => a.push(*c)?, Operand::Reg(reg) => a.push(gpr64_reg(reg))?, Operand::Stack(off) => a.push(qword_ptr(gpr64::rbp - (-*off)))?, - Operand::Pseudo(_) => unreachable!(), + Operand::Pseudo(_) | Operand::Data(_) => unreachable!(), }, Instruction::Call(name) => { if let Some(&lbl) = fn_labels.get(&name.0) { diff --git a/src/lexer.rs b/src/lexer.rs index cb9fca5..1437722 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -64,6 +64,8 @@ pub enum Token { DefaultKeyword, // default CaseKeyword, // case Comma, // , + StaticKeyword, // static + ExternKeyword, // extern } const TOKEN_PATTERNS: &[(&str, Token)] = &[ @@ -133,6 +135,8 @@ const TOKEN_PATTERNS: &[(&str, Token)] = &[ (r"^switch\b", Token::SwitchKeyword), (r"^default\b", Token::DefaultKeyword), (r"^case\b", Token::CaseKeyword), + (r"^static\b", Token::StaticKeyword), + (r"^extern\b", Token::ExternKeyword), ]; static TOKEN_DEFS: LazyLock, fn() -> Vec> = LazyLock::new(|| { @@ -184,7 +188,7 @@ impl fmt::Display for Span { } } -#[derive(Clone, PartialEq)] +#[derive(Clone)] pub struct SpannedToken { pub token: Token, pub span: Span, diff --git a/src/main.rs b/src/main.rs index 3f4acdf..bc675d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -160,8 +160,8 @@ fn main() { std::process::exit(0); } - let mut name_gen = validated_result; - let tacky_ast = tacky::tackify_program(&ast, &mut name_gen); + let (mut name_gen, symbols) = validated_result; + let tacky_ast = tacky::tackify_program(&ast, &mut name_gen, &symbols); if args.tacky { println!("{tacky_ast:?}"); @@ -182,6 +182,7 @@ fn main() { let mut formatter = iced_x86::GasFormatter::with_options(Some(Box::new(resolver)), None); let ops = formatter.options_mut(); ops.set_number_base(iced_x86::NumberBase::Decimal); + ops.set_rip_relative_addresses(true); let mut output = MyFormatterOutput::new(); println!("Generated ASM\n"); @@ -208,6 +209,32 @@ fn main() { current_offset += ins.len(); } + // Print static variables (skip extern vars) + let mut defined_vars = code_ast + .static_vars + .iter() + .filter_map(|sv| match sv.init { + tacky::VarInit::Defined(v) => Some((sv, v)), + tacky::VarInit::Extern => None, + }) + .peekable(); + if defined_vars.peek().is_some() { + println!(); + for (sv, init_val) in defined_vars { + let section = if init_val == 0 { ".bss" } else { ".data" }; + println!("{}", section.cyan()); + if sv.global { + println!(" {}", format!(".globl {}", sv.name).dimmed()); + } + println!("{}:", sv.name.green()); + if init_val == 0 { + println!(" {}", ".zero 4".yellow()); + } else { + println!(" {} {}", ".long".yellow(), init_val.to_string().cyan()); + } + } + } + std::process::exit(0); } } @@ -222,12 +249,11 @@ fn main() { std::process::exit(1); }; - let tokens = lexer::tokenizer(&input).unwrap_or_else(|e| { + let mut tokens = lexer::tokenizer(&input).unwrap_or_else(|e| { eprintln!("{e:?}"); std::process::exit(10) }); - let mut tokens = tokens; let ast = parser::parse_program(&mut tokens).unwrap_or_else(|e| { eprintln!("{e:?}"); std::process::exit(20) @@ -239,8 +265,8 @@ fn main() { std::process::exit(30); }); - let mut name_gen = validated_result; - let tacky_ast = tacky::tackify_program(&ast, &mut name_gen); + 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 path = Path::new(c_file); @@ -438,98 +464,3 @@ fn main() { fs::remove_file(&out_file).ok(); } } - -// Available for both unit tests and integration tests -#[cfg(test)] -pub mod test_utils { - use crate::lexer::tokenizer; - use crate::parser::parse_program; - use crate::validate::resolve_program; - use std::fs; - use std::path::Path; - - static CHAPTER_COMPLETED: i32 = 8; - static EXTRA_COMPLETED: i32 = 8; - pub enum Stage { - Lex, - Parse, - Validate, - } - - impl Stage { - pub fn dir(&self) -> &'static str { - match self { - Stage::Lex => "lex", - Stage::Parse => "parse", - Stage::Validate => "semantics", - } - } - } - - pub fn get_sandler_dirs(valid: bool, stage: &Stage) -> Vec { - let mut dirs = vec![]; - for chapter in 1..=CHAPTER_COMPLETED { - if valid { - dirs.push(format!("../writing-a-c-compiler-tests/tests/chapter_{chapter}/valid/")); - } else { - dirs.push(format!( - "../writing-a-c-compiler-tests/tests/chapter_{chapter}/invalid_{:}/", - stage.dir() - )); - } - } - for chapter in 1..=EXTRA_COMPLETED { - if valid { - dirs.push(format!( - "../writing-a-c-compiler-tests/tests/chapter_{chapter}/valid/extra_credit/" - )); - } else { - dirs.push(format!( - "../writing-a-c-compiler-tests/tests/chapter_{chapter}/invalid_{:}/extra_credit/", - stage.dir() - )); - } - } - dirs - } - - pub fn run_tests(dir_paths: &Vec, should_pass: bool, stage: &Stage) -> (usize, Vec) { - let mut passed = 0; - let mut failed = vec![]; - for dir_path in dir_paths { - let test_dir = Path::new(dir_path); - - if test_dir.exists() { - for entry in fs::read_dir(test_dir).unwrap() { - let entry = entry.unwrap(); - let path = entry.path(); - if path.is_file() && path.extension() == Some("c".as_ref()) { - let input = fs::read_to_string(&path).unwrap(); - let test_result = match stage { - Stage::Lex => tokenizer(&input).is_err(), - Stage::Parse => { - let mut tokens = tokenizer(&input).unwrap(); - parse_program(&mut tokens).is_err() - } - Stage::Validate => { - let mut tokens = tokenizer(&input).unwrap(); - let mut program = parse_program(&mut tokens).unwrap(); - resolve_program(&mut program).is_err() - } - }; - - let test_passed = if should_pass { !test_result } else { test_result }; - - if test_passed { - passed += 1; - } else { - failed.push(path.file_name().unwrap().to_str().unwrap().to_string()); - } - } - } - } - } - - (passed, failed) - } -} diff --git a/src/parser.rs b/src/parser.rs index b967e65..c543767 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -187,10 +187,21 @@ pub enum ForInit { InitExp(Option), } +#[derive(PartialEq, Clone, Debug)] +pub enum StorageClass { + Static, + Extern, +} + +enum TypeClass { + Int, +} + #[derive(PartialEq, Clone)] pub struct VarDeclaration { pub name: Identifier, pub init: Option, + pub storage_class: Option, pub span: Span, } @@ -199,6 +210,7 @@ pub struct FunDeclaration { pub name: Identifier, pub params: Vec, pub body: Option, + pub storage_class: Option, pub span: Span, } @@ -225,6 +237,9 @@ fn parse_block(tokens: &mut VecDeque) -> Result, + pub declarations: Vec, } pub struct SyntaxError { @@ -473,6 +488,48 @@ fn parse_exp(tokens: &mut VecDeque, min_prec: u64) -> Result, +) -> Result<(TypeClass, Option), SyntaxError> { + let mut type_specifier = None; + 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::StaticKeyword | Token::ExternKeyword => { + let sc = if token.token == Token::StaticKeyword { + StorageClass::Static + } else { + StorageClass::Extern + }; + if storage_class.is_none() { + storage_class = Some(sc); + } else { + return Err(SyntaxError::with_span( + "Duplicate storage class".to_string(), + Option::from(token.span), + )); + } + } + _ => 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)) + } +} + fn parse_conditional_middle(tokens: &mut VecDeque) -> Result { let e = parse_exp(tokens, 0)?; expect(&Token::Colon, tokens)?; @@ -762,41 +819,49 @@ fn parse_declaration( tokens: &mut VecDeque, err_span: &Option, ) -> Result, SyntaxError> { + let mut specifier_list = Vec::new(); + while let Some(front) = tokens.front() { + match front.token { + Token::IntKeyword | Token::StaticKeyword | Token::ExternKeyword => { + specifier_list.push(tokens.pop_front().unwrap()); + } + _ => break, + } + } + if specifier_list.is_empty() { + return Ok(None); // no declaration + } + 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 front.token == Token::IntKeyword { + if tokens.front().map(|t| &t.token) == Some(&Token::OpenParen) { + // function declaration tokens.pop_front(); - 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 = parse_function_params(tokens, &Some(span))?; - let body = parse_function_body(tokens)?; + let body = parse_function_body(tokens)?; - Ok(Some(Declaration::FunDeclaration(FunDeclaration { - name, - params, - body, - span, - }))) - } else { - let mut init = None; - if front.token == Token::Assignment { - tokens.pop_front(); - init = Some(parse_exp(tokens, 0)?); - } - expect(&Token::Semicolon, tokens)?; - Ok(Some(Declaration::VarDeclaration(VarDeclaration { name, init, span }))) - } - } else { - Err(SyntaxError::with_span( - "EOF when parsing declaration".to_string(), - Some(span), - )) - } + Ok(Some(Declaration::FunDeclaration(FunDeclaration { + name, + params, + body, + storage_class, + span, + }))) } else { - Ok(None) + let mut init = None; + if front.token == Token::Assignment { + tokens.pop_front(); + init = Some(parse_exp(tokens, 0)?); + } + expect(&Token::Semicolon, tokens)?; + Ok(Some(Declaration::VarDeclaration(VarDeclaration { + name, + init, + storage_class, + span, + }))) } } else { Err(SyntaxError::with_span( @@ -883,25 +948,23 @@ fn parse_function_body(tokens: &mut VecDeque) -> Result) -> Result { - expect(&Token::IntKeyword, tokens)?; - let (name, span) = parse_identifier(tokens)?; - expect(&Token::OpenParen, tokens)?; - let params = parse_function_params(tokens, &Some(span))?; - let body = parse_function_body(tokens)?; - - Ok(FunDeclaration { - name, - params, - body, - span, - }) -} - pub fn parse_program(tokens: &mut VecDeque) -> Result { - let mut functions = vec![parse_function_definition(tokens)?]; + let mut declarations = vec![]; while !tokens.is_empty() { - functions.push(parse_function_definition(tokens)?) + // None is ok here as we never hit the err_span case + if let Some(dec) = parse_declaration(tokens, &None)? { + declarations.push(dec); + } else { + let bad_token = tokens.front().unwrap(); + return Err(SyntaxError::with_span( + format!("Unexpected token {:?}", bad_token.token), + Some(bad_token.span), + )); + } + } + if declarations.is_empty() { + Err(SyntaxError::with_span("EOF when parsing program".to_string(), None)) + } else { + Ok(Program { declarations }) } - Ok(Program { functions }) } diff --git a/src/pretty.rs b/src/pretty.rs index 4744bbf..eef63e9 100644 --- a/src/pretty.rs +++ b/src/pretty.rs @@ -11,7 +11,8 @@ use crate::parser::{ Program as ParserProgram, SpannedStmt, Stmt, UnaryOp as ParserUnaryOp, VarDeclaration, }; use crate::tacky::{ - BinOp, FunctionDefinition as TackyFunctionDefinition, Instruction as TackyInstruction, Program as TackyProgram, Val, + BinOp, FunctionDefinition as TackyFunctionDefinition, Instruction as TackyInstruction, Program as TackyProgram, + StaticVariable, TopLevel, Val, VarInit, }; #[derive(Clone)] @@ -112,13 +113,13 @@ macro_rules! impl_function_def { impl_function_def!(TackyFunctionDefinition, CodegenFunctionDefinition); -// Macro for types with `functions` field (Program pattern) +// 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.functions.iter().map(|f| f.itf_node()).collect(); + let children: Vec = self.top_level.iter().map(|t| t.itf_node()).collect(); Node::branch("Program".cyan().to_string(), children) } } @@ -126,7 +127,22 @@ macro_rules! impl_program { }; } -impl_program!(ParserProgram, TackyProgram, CodegenProgram); +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(); + children.extend(self.static_vars.iter().map(|v| v.itf_node())); + Node::branch("Program".cyan().to_string(), children) + } +} + +impl ItfDisplay for ParserProgram { + fn itf_node(&self) -> Node { + let children: Vec = self.declarations.iter().map(|d| d.itf_node()).collect(); + Node::branch("Program".cyan().to_string(), children) + } +} // Macro for enums that just delegate to inner types macro_rules! delegate_variants { @@ -146,6 +162,10 @@ 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 { @@ -407,6 +427,23 @@ impl ItfDisplay for TackyInstruction { } } +impl ItfDisplay for StaticVariable { + fn itf_node(&self) -> Node { + let init_str = match &self.init { + VarInit::Defined(v) => v.to_string(), + VarInit::Extern => "extern".to_string(), + }; + Node::branch( + "StaticVariable".cyan().to_string(), + vec![ + Node::leaf(format!("name: {}", self.name.green())), + Node::leaf(format!("global: {}", self.global)), + Node::leaf(format!("init: {}", init_str.magenta())), + ], + ) + } +} + // ============================================================================= // Codegen types // ============================================================================= @@ -418,6 +455,7 @@ impl ItfDisplay for Operand { Operand::Reg(r) => Node::branch("Reg".cyan().to_string(), vec![r.itf_node()]), Operand::Pseudo(s) => Node::branch("Pseudo".cyan().to_string(), vec![s.itf_node()]), Operand::Stack(o) => Node::branch("Stack".cyan().to_string(), vec![o.itf_node()]), + Operand::Data(s) => Node::branch("Data".cyan().to_string(), vec![s.itf_node()]), } } } diff --git a/src/tacky.rs b/src/tacky.rs index b93130e..5a9ef6d 100644 --- a/src/tacky.rs +++ b/src/tacky.rs @@ -1,7 +1,7 @@ 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::NameGenerator; +use crate::validate::{InitialValue, NameGenerator, SymbolTable, SymbolType}; #[derive(Clone, Debug)] pub enum Val { @@ -121,11 +121,34 @@ pub struct FunctionDefinition { pub name: String, pub params: Vec, pub body: Vec, + pub global: bool, +} + +/// Storage initialization for static variables. +#[derive(Debug, Clone)] +pub enum VarInit { + /// Variable defined here with initial value (0 = .bss, non-zero = .data) + Defined(i32), + /// Extern variable - no storage allocated, resolved by linker + Extern, +} + +#[derive(Debug, Clone)] +pub struct StaticVariable { + pub name: String, + pub global: bool, + pub init: VarInit, +} + +#[derive(Debug)] +pub enum TopLevel { + Function(FunctionDefinition), + StaticVariable(StaticVariable), } #[derive(Debug)] pub struct Program { - pub functions: Vec, + pub top_level: Vec, } /// Converts AST expressions into TACKY IR instructions. @@ -530,6 +553,10 @@ fn tackify_block(block: &Block, instructions: &mut Vec, name_genera } } +/// Emits runtime initialization code for automatic (local) variables only. +/// +/// Static variables are initialized at compile time in the data section. +/// Extern variables have no initialization code emitted. fn tackify_var_declaration( declaration: &VarDeclaration, instructions: &mut Vec, @@ -539,6 +566,7 @@ fn tackify_var_declaration( name, init: Some(e), span, + storage_class: None, } = declaration { let ass = Expr::Assignment(Box::new(Expr::Var(name.clone(), *span)), Box::new(e.clone()), *span); @@ -546,7 +574,11 @@ fn tackify_var_declaration( } } -fn tackify_function(func: &parser::FunDeclaration, name_generator: &mut NameGenerator) -> FunctionDefinition { +fn tackify_function( + func: &parser::FunDeclaration, + name_generator: &mut NameGenerator, + symbols: &SymbolTable, +) -> FunctionDefinition { let mut instructions = Vec::new(); let parser::Identifier(name) = &func.name; if let Some(body) = &func.body { @@ -561,15 +593,70 @@ fn tackify_function(func: &parser::FunDeclaration, name_generator: &mut NameGene name: name.clone(), params: func.params.clone(), body: instructions, + global: symbols.get(name).unwrap().global, } } -pub fn tackify_program(program: &parser::Program, name_generator: &mut NameGenerator) -> Program { - let mut functions = Vec::new(); - for function in &program.functions { - if function.body.is_some() { - functions.push(tackify_function(function, name_generator)); +/// 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) +/// +/// Tentative definitions are initialized to 0. +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 { + name: name.clone(), + global: entry.global, + init: VarInit::Extern, + })); + } + } + } } } - Program { functions } + tacky_defs +} + +/// Converts a parsed C program into TACKY IR. +/// +/// 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(); + for decl in &program.declarations { + if let Declaration::FunDeclaration(func) = decl + && func.body.is_some() + { + top_level.push(TopLevel::Function(tackify_function(func, name_generator, symbols))); + } + } + + let static_var_defs = convert_symbols_to_tacky(symbols); + top_level.extend(static_var_defs); + Program { top_level } } diff --git a/src/validate.rs b/src/validate.rs index aa5e764..294dea5 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -1,13 +1,7 @@ -/* - We allow undefined behavior that is valid c like int foo = foo + 1; - We can add a warning for this in the future. - - We also don't do scope validation another case that deserves a warning -*/ use crate::lexer::Span; use crate::parser::{ BinOp, Block, BlockItem, Declaration, Expr, ForInit, FunDeclaration, Identifier, Program, SpannedStmt, Stmt, - SwitchIntType, UnaryOp, VarDeclaration, + StorageClass, SwitchIntType, UnaryOp, VarDeclaration, }; use colored::*; use std::collections::{HashMap, HashSet}; @@ -36,20 +30,25 @@ impl fmt::Debug for SemanticError { } } -#[derive(Clone, PartialEq, Debug)] +#[derive(Clone)] +pub enum InitialValue { + Tentative, + Initial(i32), + NoInitializer, +} + pub enum SymbolType { - Int, - FunType(u64 /*param count*/), + Int(InitialValue), + FunType { param_cnt: usize, defined: bool }, } -#[derive(Clone)] -struct Symbol { - symbol_type: SymbolType, - initialized: bool, +pub struct Symbol { + pub(crate) symbol_type: SymbolType, + pub(crate) global: bool, span: Span, } -type SymbolTable = HashMap; +pub type SymbolTable = HashMap; #[derive(Clone)] struct VarInfo { @@ -74,18 +73,186 @@ impl NameGenerator { } } -fn typecheck_variable_declaration(decl: &VarDeclaration, symbols: &mut SymbolTable) -> Result<(), SemanticError> { - let sym = Symbol { - symbol_type: SymbolType::Int, - initialized: decl.init.is_some(), - span: decl.span, - }; - symbols.insert(decl.name.0.clone(), sym); - if let Some(init) = &decl.init { - typecheck_exp(init, symbols) +/// Validates a local (block-scope) variable declaration and updates the symbol table. +/// +/// Handles three cases based on storage class: +/// +/// **extern**: References an external variable +/// - Cannot have an initializer +/// - If not already in symbol table, adds with `NoInitializer` and `global: true` +/// - If already exists, must be a variable (not a function) +/// +/// **static**: Local variable with static storage duration +/// - Initializer must be a constant expression (or defaults to 0) +/// - Added to symbol table with `global: false` +/// +/// **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> { + if decl.storage_class == Some(StorageClass::Extern) { + if decl.init.is_some() { + return Err(SemanticError::with_span( + format!("'{}' has both 'extern' and initializer", decl.name.0.bold()), + decl.span, + )); + } + if let Some(old_dec) = symbols.get(&decl.name.0) { + if !matches!(old_dec.symbol_type, SymbolType::Int(_)) { + return Err(SemanticError::with_span( + format!( + "'{}' redeclared as different kind of symbol\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + } else { + symbols.insert( + decl.name.0.clone(), + Symbol { + symbol_type: SymbolType::Int(InitialValue::NoInitializer), + global: true, + 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), + } + } else { + InitialValue::Initial(0) + }; + symbols.insert( + decl.name.0.clone(), + Symbol { + symbol_type: SymbolType::Int(initial_value), + global: false, + span: decl.span, + }, + ); } else { - Ok(()) + // Automatic storage (no storage class specifier) + symbols.insert( + decl.name.0.clone(), + Symbol { + symbol_type: SymbolType::Int(InitialValue::NoInitializer), + global: false, + span: decl.span, + }, + ); + if let Some(init) = &decl.init { + typecheck_exp(init, symbols)?; + } + } + Ok(()) +} + +/// Validates a file-scope variable declaration and updates the symbol table. +/// +/// Enforces the following rules: +/// - Initializers must be constant expressions +/// - A function cannot be redeclared as a variable +/// - Variable linkage (static vs non-static) must be consistent across declarations +/// - Only one definition (with initializer) is allowed per variable +/// +/// Initial value resolution: +/// - Explicit constant initializer → `Initial(value)` +/// - No initializer + `extern` → `NoInitializer` +/// - 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> { + 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), + } + } else if decl.storage_class == Some(StorageClass::Extern) { + InitialValue::NoInitializer + } else { + InitialValue::Tentative + }; + + let mut global = decl.storage_class != Some(StorageClass::Static); + let mut saved_span = decl.span; + + if let Some(old_dec) = symbols.get(&decl.name.0) { + let old_init = match &old_dec.symbol_type { + SymbolType::FunType { .. } => { + return Err(SemanticError::with_span( + format!( + "'{}' redeclared as different kind of symbol\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + SymbolType::Int(old_init) => old_init.clone(), + }; + + if decl.storage_class == Some(StorageClass::Extern) { + global = old_dec.global; + } else if old_dec.global != global { + return Err(SemanticError::with_span( + format!( + "conflicting linkage for '{}'\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + + if matches!(old_init, InitialValue::Initial(_)) { + if matches!(initial_value, InitialValue::Initial(_)) { + return Err(SemanticError::with_span( + format!( + "redefinition of '{}'\n{}: {}: previous definition was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } else { + initial_value = old_init; + saved_span = old_dec.span; + } + } else if !matches!(initial_value, InitialValue::Initial(_)) && matches!(old_init, InitialValue::Tentative) { + initial_value = InitialValue::Tentative; + } } + + symbols.insert( + decl.name.0.clone(), + Symbol { + symbol_type: SymbolType::Int(initial_value), + global, + span: saved_span, + }, + ); + Ok(()) } fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticError> { @@ -94,11 +261,11 @@ fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticEr Expr::Var(Identifier(name), span) => { if let Some(expected) = symbols.get(name) { match expected.symbol_type { - SymbolType::FunType(_) => Err(SemanticError::with_span( + SymbolType::FunType { .. } => Err(SemanticError::with_span( format!("cannot use function '{}' as a variable", name.bold()), *span, )), - SymbolType::Int => Ok(()), + SymbolType::Int(_) => Ok(()), } } else { unreachable!("Undefined variable in typechecking") @@ -117,8 +284,8 @@ fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticEr Expr::FunctionCall(Identifier(name), args, span) => { if let Some(expected) = symbols.get(name) { match expected.symbol_type { - SymbolType::FunType(param_cnt) => { - if param_cnt != args.len() as u64 { + SymbolType::FunType { param_cnt, defined: _ } => { + if param_cnt != args.len() { Err(SemanticError::with_span( format!( "function '{}' expects {} argument{} but {} {} provided", @@ -137,7 +304,7 @@ fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticEr Ok(()) } } - SymbolType::Int => Err(SemanticError::with_span( + SymbolType::Int(_) => Err(SemanticError::with_span( format!("cannot call '{}' as a function: identifier is a variable", name.bold()), *span, )), @@ -149,50 +316,91 @@ fn typecheck_exp(exp: &Expr, symbols: &mut SymbolTable) -> Result<(), SemanticEr } } +/// Validates a function declaration and updates the symbol table. +/// +/// Enforces the following rules: +/// - Parameter count must match any prior declaration +/// - A function can only be defined once (have a body) +/// - A `static` declaration cannot follow a non-static declaration +/// - Global linkage is inherited from the first 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 mut insert = true; - let sym = Symbol { - symbol_type: SymbolType::FunType(decl.params.len() as u64), - initialized: decl.body.is_some(), - span: decl.span, - }; + let param_cnt = decl.params.len(); + let mut global = decl.storage_class != Some(StorageClass::Static); + let mut defined = decl.body.is_some(); + let mut saved_span = decl.span; if let Some(old_dec) = symbols.get(&decl.name.0) { - if old_dec.symbol_type != sym.symbol_type { - return Err(SemanticError::with_span( - format!( - "incompatible declaration of function '{}'\n{}: {}: previous declaration was here", - decl.name.0.bold(), - old_dec.span, - "note".cyan() - ), - decl.span, - )); - } - if old_dec.initialized && decl.body.is_some() { - return Err(SemanticError::with_span( - format!( - "redefinition of function '{}'\n{}: {}: previous definition was here", - decl.name.0.bold(), - old_dec.span, - "note".cyan() - ), - decl.span, - )); + match old_dec.symbol_type { + SymbolType::FunType { + param_cnt: old_param_cnt, + defined: old_defined, + } => { + if old_param_cnt != param_cnt { + return Err(SemanticError::with_span( + format!( + "incompatible declaration of function '{}'\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + if old_defined { + if decl.body.is_some() { + return Err(SemanticError::with_span( + format!( + "redefinition of function '{}'\n{}: {}: previous definition was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + saved_span = old_dec.span; + } + if old_dec.global && decl.storage_class == Some(StorageClass::Static) { + return Err(SemanticError::with_span( + "Static function declaration follows non-static".to_string(), + decl.span, + )); + } + global = old_dec.global; + defined = defined || old_defined; + } + SymbolType::Int(_) => { + return Err(SemanticError::with_span( + format!( + "redeclaration of '{}' as a function\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } } - insert = !old_dec.initialized && sym.initialized; } - if insert { - symbols.insert(decl.name.0.clone(), sym); - } + symbols.insert( + decl.name.0.clone(), + Symbol { + symbol_type: SymbolType::FunType { param_cnt, defined }, + global, + span: saved_span, + }, + ); if let Some(body) = decl.body.as_ref() { for Identifier(name) in &decl.params { symbols.insert( name.clone(), Symbol { - symbol_type: SymbolType::Int, - initialized: true, + symbol_type: SymbolType::Int(InitialValue::NoInitializer), + global: false, span: decl.span, }, ); @@ -207,7 +415,7 @@ fn typecheck_block(block: &Block, symbols: &mut SymbolTable) -> Result<(), Seman for item in block { match item { BlockItem::Declaration(Declaration::VarDeclaration(var)) => { - typecheck_variable_declaration(var, symbols)?; + typecheck_local_variable_declaration(var, symbols)?; } BlockItem::Declaration(Declaration::FunDeclaration(fun)) => { typecheck_function_declaration(fun, symbols)?; @@ -242,7 +450,15 @@ fn typecheck_stmt(stmt: &Stmt, symbols: &mut SymbolTable) -> Result<(), Semantic match init { ForInit::InitExp(Some(e)) => typecheck_exp(e, symbols)?, ForInit::InitExp(None) => {} - ForInit::InitDecl(decl) => typecheck_variable_declaration(decl, symbols)?, + ForInit::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)? + } } if let Some(cond) = cond { typecheck_exp(cond, symbols)?; @@ -455,27 +671,86 @@ fn resolve_param( } } -fn resolve_var_decoration( +/// Registers a file-scope variable declaration in the variable map. +/// +/// File-scope variables: +/// - Keep their original name (no renaming needed - no shadowing at file scope) +/// - 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) { + let Identifier(name) = &dec.name; + variable_map.insert( + name.clone(), + VarInfo { + renamed: name.clone(), + span: dec.span, + ext_link: true, + }, + ); +} + +/// Resolves a local (block-scope) variable declaration. +/// +/// Handles three cases based on storage class: +/// +/// **Conflict detection**: If a variable with the same name exists in the current +/// block scope, it's an error unless both have external linkage (extern). +/// +/// **extern**: References an external variable +/// - Keeps original name (no renaming) +/// - Marked with `ext_link: true` +/// +/// **static or automatic**: Local variable +/// - 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 +/// +/// This is the resolve pass counterpart to `typecheck_local_variable_declaration`. +fn resolve_local_var_decoration( dec: &mut VarDeclaration, variable_map: &mut HashMap, name_gen: &mut NameGenerator, block_vars: &mut HashSet, used_vars: &mut HashSet, ) -> Result<(), SemanticError> { - let Identifier(name) = &dec.name; + let Identifier(name) = &dec.name.clone(); - // if the value doesn't exist in block_vars we want to insert or update - if block_vars.insert(name.clone()) { + if let Some(original_def) = variable_map.get(name) + && block_vars.contains(name) + && !(original_def.ext_link && (dec.storage_class == Some(StorageClass::Extern))) + { + return Err(SemanticError::with_span( + format!( + "Conflicting local declarations for variable {}\n{}: {}: previous decoration was here", + format!("'{}'", name).bold(), + original_def.span, + "note".to_string().cyan(), + ), + dec.span, + )); + } + if dec.storage_class == Some(StorageClass::Extern) { + variable_map.insert( + name.clone(), + VarInfo { + renamed: name.clone(), + span: dec.span, + ext_link: true, + }, + ); + } else { let unique_name = name_gen.next(name); - let shadow = variable_map.insert( + dec.name = Identifier(unique_name.clone()); + if let Some(shadow) = variable_map.insert( name.clone(), VarInfo { renamed: unique_name.clone(), span: dec.span, ext_link: false, }, - ); - if let Some(shadow) = shadow { + ) { eprintln!( "{}: {}: variable {} shadows previous declaration {}", dec.span, @@ -490,25 +765,12 @@ fn resolve_var_decoration( format!("'{}'", name).bold() ); } - dec.name = Identifier(unique_name); - - // Resolve the initializer if present if let Some(init_expr) = &mut dec.init { resolve_exp(init_expr, variable_map, used_vars)?; } - Ok(()) - } else { - let original_def = variable_map.get(name).unwrap(); - Err(SemanticError::with_span( - format!( - "variable {} already declared\n{}: {}: previous decoration was here", - format!("'{}'", name).bold(), - original_def.span, - "note".to_string().cyan(), - ), - dec.span, - )) } + block_vars.insert(name.clone()); + Ok(()) } fn resolve_statement( @@ -574,7 +836,7 @@ fn resolve_statement( } } ForInit::InitDecl(dec) => { - resolve_var_decoration(dec, &mut shadow_map, name_gen, &mut HashSet::new(), used_vars)? + resolve_local_var_decoration(dec, &mut shadow_map, name_gen, &mut HashSet::new(), used_vars)? } } if let Some(e1) = e1 { @@ -871,7 +1133,7 @@ fn resolve_block( } BlockItem::Declaration(d) => match d { Declaration::VarDeclaration(var) => { - resolve_var_decoration(var, variable_map, name_gen, block_vars, used_vars)?; + resolve_local_var_decoration(var, variable_map, name_gen, block_vars, used_vars)?; } Declaration::FunDeclaration(fun) => { if fun.body.is_some() { @@ -880,6 +1142,12 @@ fn resolve_block( fun.span, )); } + if fun.storage_class == Some(StorageClass::Static) { + return Err(SemanticError::with_span( + "static function decloration not allowed in block scope".to_string(), + fun.span, + )); + } resolve_fun_decoration(fun, variable_map, block_vars, labels, jumps, name_gen, used_vars)?; } }, @@ -888,41 +1156,46 @@ fn resolve_block( Ok(()) } -pub fn resolve_program(program: &mut Program) -> Result { +pub fn resolve_program(program: &mut Program) -> Result<(NameGenerator, SymbolTable), SemanticError> { let mut variable_map = HashMap::new(); let mut name_gen = NameGenerator::new(); let mut undefined_jumps = Vec::new(); let mut label_tracker = LabelTracker::new(); - for function in program.functions.iter_mut() { - let mut used_vars = HashSet::new(); - let mut labels = HashSet::new(); - let mut jumps: HashMap = HashMap::new(); - if let Some(body) = &mut function.body { - label_block(body, &mut label_tracker)?; - } - let mut block_vars = HashSet::new(); - resolve_fun_decoration( - function, - &mut variable_map, - &mut block_vars, - &mut labels, - &mut jumps, - &mut name_gen, - &mut used_vars, - )?; + for decl in program.declarations.iter_mut() { + match decl { + Declaration::VarDeclaration(var) => resolve_file_var_declaration(var, &mut variable_map), + Declaration::FunDeclaration(function) => { + let mut used_vars = HashSet::new(); + let mut labels = HashSet::new(); + let mut jumps: HashMap = HashMap::new(); + if let Some(body) = &mut function.body { + label_block(body, &mut label_tracker)?; + } + let mut block_vars = HashSet::new(); + resolve_fun_decoration( + function, + &mut variable_map, + &mut block_vars, + &mut labels, + &mut jumps, + &mut name_gen, + &mut used_vars, + )?; - // Find jumps to non-existent labels and report with spans - for (label, span) in jumps.iter() { - if !labels.contains(label) { - undefined_jumps.push((label.clone(), *span)); + // Find jumps to non-existent labels and report with spans + for (label, span) in jumps.iter() { + if !labels.contains(label) { + undefined_jumps.push((label.clone(), *span)); + } + } } } } if undefined_jumps.is_empty() { - typecheck_program(program)?; - Ok(name_gen) + let symbols = typecheck_program(program)?; + Ok((name_gen, symbols)) } else { let (label, span) = &undefined_jumps[0]; Err(SemanticError::with_span( @@ -932,12 +1205,14 @@ pub fn resolve_program(program: &mut Program) -> Result Result<(), SemanticError> { +pub fn typecheck_program(program: &Program) -> Result { let mut symbols = SymbolTable::new(); - for decl in &program.functions { - typecheck_function_declaration(decl, &mut symbols)?; + 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)?, + }; } - - Ok(()) + Ok(symbols) } diff --git a/tests/c_programs/examples/collatz.c b/tests/c_programs/examples/collatz.c new file mode 100644 index 0000000..d412497 --- /dev/null +++ b/tests/c_programs/examples/collatz.c @@ -0,0 +1,41 @@ +// Collatz Conjecture Explorer +// +// For any positive integer n: +// - If n is even: n = n / 2 +// - If n is odd: n = 3n + 1 +// The conjecture states this always reaches 1. +// +// Which number under 100 takes the most steps? + +static int total_steps = 0; + +int collatz(int n) { + int steps = 0; + while (n != 1) { + if (n & 1) { + n = 3 * n + 1; // odd + } else { + n = n >> 1; // even: divide by 2 + } + steps++; + } + total_steps += steps; + return steps; +} + +int main(void) { + int champion = 1; + int max_steps = 0; + + for (int i = 1; i < 100; i++) { + int steps = collatz(i); + if (steps > max_steps) { + max_steps = steps; + champion = i; + } + } + + // Returns 97: takes 118 steps to reach 1! + // 97 -> 292 -> 146 -> 73 -> 220 -> 110 -> 55 -> ... -> 1 + return champion; +} diff --git a/tests/c_programs/examples/hello_world.c b/tests/c_programs/examples/hello_world.c new file mode 100644 index 0000000..83949e2 --- /dev/null +++ b/tests/c_programs/examples/hello_world.c @@ -0,0 +1,17 @@ +int putchar(int c); +int main(void) { + putchar(72); + putchar(101); + putchar(108); + putchar(108); + putchar(111); + putchar(44); + putchar(32); + putchar(87); + putchar(111); + putchar(114); + putchar(108); + putchar(100); + putchar(33); + putchar(10); +} \ No newline at end of file diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index f11d1f3..80d30a1 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -61,5 +61,30 @@ }, "warnings/unused_parameter.c": { "return_code": 1 + }, + "static_vars/data_operand_coverage.c": { + "return_code": 0 + }, + "static_vars/variable_shift_data.c": { + "return_code": 0 + }, + "static_vars/setcc_data.c": { + "return_code": 0 + }, + "static_vars/cmp_data_patterns.c": { + "return_code": 0 + }, + "static_vars/idiv_data.c": { + "return_code": 0 + }, + "static_vars/mult_data_src.c": { + "return_code": 0 + }, + "examples/collatz.c": { + "return_code": 97 + }, + "examples/hello_world.c": { + "return_code": 0, + "stdout": "Hello, World!\n" } } \ No newline at end of file diff --git a/tests/c_programs/specifiers/invalid_parse/duplicate_type_specifier.c b/tests/c_programs/specifiers/invalid_parse/duplicate_type_specifier.c new file mode 100644 index 0000000..0e52c28 --- /dev/null +++ b/tests/c_programs/specifiers/invalid_parse/duplicate_type_specifier.c @@ -0,0 +1,2 @@ +// Duplicate type specifier should be rejected +int int x; diff --git a/tests/c_programs/static_vars/cmp_data_patterns.c b/tests/c_programs/static_vars/cmp_data_patterns.c new file mode 100644 index 0000000..cfd53ac --- /dev/null +++ b/tests/c_programs/static_vars/cmp_data_patterns.c @@ -0,0 +1,62 @@ +// Test coverage for Cmp instruction with Data operands +// Tests various comparison patterns involving static variables + +int g_val = 50; +int g_other = 30; + +int main(void) { + int local = 40; + + // Cmp(Reg, Data) - compare register with static var + // Generated when we compare local var with static + if (local > g_val) return 1; // 40 > 50 is false, shouldn't return + if (local < g_val) { + // 40 < 50 is true + } else { + return 2; + } + + // Cmp(Data, Reg) - compare static var with register + // Order matters in codegen + if (g_val > local) { + // 50 > 40 is true + } else { + return 3; + } + + // Cmp(Imm, Data) - compare immediate with static var + // This tests the pattern at emit_iced.rs:691-694 + if (g_val == 50) { + // true + } else { + return 4; + } + + if (g_val != 100) { + // true, 50 != 100 + } else { + return 5; + } + + // Cmp two static vars (both memory - gets rewritten but still uses Data) + if (g_val > g_other) { + // 50 > 30 is true + } else { + return 6; + } + + // Edge cases + if (g_val >= 50) { + // true + } else { + return 7; + } + + if (g_val <= 50) { + // true + } else { + return 8; + } + + return 0; +} diff --git a/tests/c_programs/static_vars/data_operand_coverage.c b/tests/c_programs/static_vars/data_operand_coverage.c new file mode 100644 index 0000000..ce33644 --- /dev/null +++ b/tests/c_programs/static_vars/data_operand_coverage.c @@ -0,0 +1,78 @@ +// Test coverage for Data operand patterns in emit_iced.rs +// Exercises direct operations on static/file-scope variables + +int g_add = 10; +int g_sub = 20; +int g_and = 255; +int g_or = 15; +int g_xor = 170; +int g_shl = 1; +int g_sar = -16; +int g_neg = 5; +int g_not = 0; +int g_cmp = 42; +int g_setcc = 99; +int g_idiv_dividend = 100; +int g_idiv_divisor = 7; +int g_mov_imm = 0; + +int main(void) { + int result = 0; + int local_val = 3; + + // Test 1: Mov Imm -> Data (direct constant store to static var) + g_mov_imm = 123; + if (g_mov_imm != 123) return 1; + + // Test 2: Binary Add with Reg -> Data and Imm -> Data + g_add = g_add + local_val; // generates load, add reg, store + g_add = g_add + 5; // Imm -> Data for add + if (g_add != 18) return 2; + + // Test 3: Binary Sub with Reg -> Data and Imm -> Data + g_sub = g_sub - local_val; // Reg -> Data + g_sub = g_sub - 2; // Imm -> Data + if (g_sub != 15) return 3; + + // Test 4: Binary BitAnd with Reg -> Data and Imm -> Data + g_and = g_and & local_val; // local_val = 3, 255 & 3 = 3 + g_and = g_and & 1; // Imm -> Data: 3 & 1 = 1 + if (g_and != 1) return 4; + + // Test 5: Binary BitOr with Reg -> Data and Imm -> Data + g_or = g_or | local_val; // 15 | 3 = 15 + g_or = g_or | 240; // Imm -> Data: 15 | 240 = 255 + if (g_or != 255) return 5; + + // Test 6: Binary BitXor with Reg -> Data and Imm -> Data + g_xor = g_xor ^ local_val; // 170 ^ 3 = 169 + g_xor = g_xor ^ 9; // Imm -> Data: 169 ^ 9 = 160 + if (g_xor != 160) return 6; + + // Test 7: Shift left with Imm -> Data + g_shl = g_shl << 4; // 1 << 4 = 16 + if (g_shl != 16) return 7; + + // Test 8: Arithmetic shift right with Imm -> Data + g_sar = g_sar >> 2; // -16 >> 2 = -4 (arithmetic shift preserves sign) + if (g_sar != -4) return 8; + + // Test 9: Unary Neg on Data + g_neg = -g_neg; // -5 + if (g_neg != -5) return 9; + + // Test 10: Unary Not on Data + g_not = ~g_not; // ~0 = -1 + if (g_not != -1) return 10; + + // Test 11: Cmp with Data operands and various combinations + // Cmp(Imm, Data) - comparing immediate with static var + if (g_cmp != 42) return 11; + + // Test 12: Idiv with Data operand (divisor is static var) + result = g_idiv_dividend / g_idiv_divisor; // 100 / 7 = 14 + if (result != 14) return 12; + + // All tests passed + return 0; +} diff --git a/tests/c_programs/static_vars/idiv_data.c b/tests/c_programs/static_vars/idiv_data.c new file mode 100644 index 0000000..939b7a4 --- /dev/null +++ b/tests/c_programs/static_vars/idiv_data.c @@ -0,0 +1,36 @@ +// Test coverage for Idiv with Data operand +// Division and modulo where divisor is a static variable + +int g_divisor = 7; +int g_neg_divisor = -5; + +int main(void) { + int dividend = 100; + int result; + + // Idiv with positive static divisor + result = dividend / g_divisor; // 100 / 7 = 14 + if (result != 14) return 1; + + // Modulo with positive static divisor + result = dividend % g_divisor; // 100 % 7 = 2 + if (result != 2) return 2; + + // Idiv with negative static divisor + result = dividend / g_neg_divisor; // 100 / -5 = -20 + if (result != -20) return 3; + + // Modulo with negative static divisor + result = dividend % g_neg_divisor; // 100 % -5 = 0 + if (result != 0) return 4; + + // Negative dividend with static divisor + dividend = -100; + result = dividend / g_divisor; // -100 / 7 = -14 (truncated toward zero) + if (result != -14) return 5; + + result = dividend % g_divisor; // -100 % 7 = -2 + if (result != -2) return 6; + + return 0; +} diff --git a/tests/c_programs/static_vars/mult_data_src.c b/tests/c_programs/static_vars/mult_data_src.c new file mode 100644 index 0000000..4593d2f --- /dev/null +++ b/tests/c_programs/static_vars/mult_data_src.c @@ -0,0 +1,29 @@ +// Test coverage for Mult with Data source operand +// Multiplication where one operand is a static variable + +int g_multiplier = 7; +int g_factor = -3; + +int main(void) { + int local = 6; + int result; + + // Mult with static var as source (Data -> Reg) + result = local * g_multiplier; // 6 * 7 = 42 + if (result != 42) return 1; + + // Mult with negative static multiplier + result = local * g_factor; // 6 * -3 = -18 + if (result != -18) return 2; + + // Chain multiplications + result = local * g_multiplier * 2; // 6 * 7 * 2 = 84 + if (result != 84) return 3; + + // Multiply two values where one comes from static + local = 10; + result = g_multiplier * local; // 7 * 10 = 70 + if (result != 70) return 4; + + return 0; +} diff --git a/tests/c_programs/static_vars/setcc_data.c b/tests/c_programs/static_vars/setcc_data.c new file mode 100644 index 0000000..badc0b4 --- /dev/null +++ b/tests/c_programs/static_vars/setcc_data.c @@ -0,0 +1,47 @@ +// Test coverage for SetCC with Data operand +// Stores comparison results directly to static variables + +int g_eq = 99; +int g_ne = 99; +int g_lt = 99; +int g_le = 99; +int g_gt = 99; +int g_ge = 99; + +int main(void) { + int a = 5; + int b = 10; + + // SetCC E (equal) to Data + g_eq = (a == a); + if (g_eq != 1) return 1; + + // SetCC NE (not equal) to Data + g_ne = (a != b); + if (g_ne != 1) return 2; + + // SetCC L (less than) to Data + g_lt = (a < b); + if (g_lt != 1) return 3; + + // SetCC LE (less or equal) to Data + g_le = (a <= b); + if (g_le != 1) return 4; + + // SetCC G (greater than) to Data + g_gt = (b > a); + if (g_gt != 1) return 5; + + // SetCC GE (greater or equal) to Data + g_ge = (b >= a); + if (g_ge != 1) return 6; + + // Test false cases + g_eq = (a == b); + if (g_eq != 0) return 7; + + g_lt = (b < a); + if (g_lt != 0) return 8; + + return 0; +} diff --git a/tests/c_programs/static_vars/variable_shift_data.c b/tests/c_programs/static_vars/variable_shift_data.c new file mode 100644 index 0000000..b33a063 --- /dev/null +++ b/tests/c_programs/static_vars/variable_shift_data.c @@ -0,0 +1,24 @@ +// Test coverage for variable shift amounts on static variables +// This exercises BitShl/BitSar with CX -> Data pattern + +int g_shl_var = 1; +int g_sar_var = -64; + +int main(void) { + int shift_amount = 3; + + // Variable shift left on static var (CX -> Data) + g_shl_var = g_shl_var << shift_amount; // 1 << 3 = 8 + if (g_shl_var != 8) return 1; + + // Variable shift right on static var (CX -> Data) + g_sar_var = g_sar_var >> shift_amount; // -64 >> 3 = -8 + if (g_sar_var != -8) return 2; + + // Chain variable shifts + shift_amount = 2; + g_shl_var = g_shl_var << shift_amount; // 8 << 2 = 32 + if (g_shl_var != 32) return 3; + + return 0; +} diff --git a/tests/runner.rs b/tests/runner.rs index ebe01af..5e5c637 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -3,13 +3,17 @@ use std::collections::HashMap; use std::fs; use std::path::PathBuf; -static CHAPTER_COMPLETED: i32 = 9; -static EXTRA_COMPLETED: i32 = 9; +static CHAPTER_COMPLETED: i32 = 10; +static EXTRA_COMPLETED: i32 = 10; -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Clone)] enum ProgramOutput { Error(i32), - Result(i32), + Result { + code: i32, + stdout: Option, + stderr: Option, + }, } #[derive(Debug)] @@ -101,8 +105,12 @@ fn get_sandler_cases() -> Vec { } else { relative_path.to_string() }; - let expected_value = *expected_results.get(&lookup_path).unwrap_or(&0); - ProgramOutput::Result(expected_value) + let expected = expected_results.get(&lookup_path); + ProgramOutput::Result { + code: expected.map(|e| e.return_code).unwrap_or(0), + stdout: expected.and_then(|e| e.stdout.clone()), + stderr: None, // Expected stderr is always empty + } }; // Determine extra files (library files or assembly files) @@ -153,8 +161,12 @@ fn get_custom_cases() -> Vec { } else { // Valid test - get expected return code from map let relative_path = path_str.strip_prefix("tests/c_programs/").unwrap_or(path_str); - let expected_value = *expected_results.get(relative_path).unwrap_or(&0); - ProgramOutput::Result(expected_value) + let expected = expected_results.get(relative_path); + ProgramOutput::Result { + code: expected.map(|e| e.return_code).unwrap_or(0), + stdout: expected.and_then(|e| e.stdout.clone()), + stderr: None, // Expected stderr is always empty + } }; cases.push(TestCase { @@ -206,7 +218,12 @@ fn get_ncc_binary_path() -> PathBuf { best_path } -fn load_expected(json_path: &str) -> Result, Box> { +struct ExpectedResult { + return_code: i32, + stdout: Option, +} + +fn load_expected(json_path: &str) -> Result, Box> { let json_content = fs::read_to_string(json_path)?; let parsed: serde_json::Value = serde_json::from_str(&json_content)?; @@ -215,7 +232,14 @@ fn load_expected(json_path: &str) -> Result, Box, extra_args: &[String], + test_label: &str, ) { let path = std::path::Path::new(&case.c_file); let binary_path = path.with_extension(""); @@ -255,19 +280,202 @@ fn run_test( let run_output = std::process::Command::new(binary_path_str).output().unwrap(); let return_code = run_output.status.code().unwrap_or(-1); + let stdout = String::from_utf8_lossy(&run_output.stdout).to_string(); + let stderr = String::from_utf8_lossy(&run_output.stderr).to_string(); std::fs::remove_file(&binary_path).ok(); - ProgramOutput::Result(return_code) + ProgramOutput::Result { + code: return_code, + stdout: if stdout.is_empty() { None } else { Some(stdout) }, + stderr: if stderr.is_empty() { None } else { Some(stderr) }, + } } else { ProgramOutput::Error(compile_output.status.code().unwrap_or(-1)) }; - if actual == case.output { + let passed = match (&actual, &case.output) { + (ProgramOutput::Error(a), ProgramOutput::Error(b)) => a == b, + ( + ProgramOutput::Result { + code: a_code, + stdout: a_stdout, + stderr: a_stderr, + }, + ProgramOutput::Result { + code: b_code, + stdout: b_stdout, + stderr: b_stderr, + }, + ) => { + let code_match = a_code == b_code; + let stdout_match = match (a_stdout, b_stdout) { + (_, None) => true, // No expected stdout means we don't check + (Some(a), Some(b)) => a == b, + (None, Some(_)) => false, + }; + // stderr should always be empty (b_stderr is always None) + let stderr_match = match (a_stderr, b_stderr) { + (None, None) => true, + (Some(_), None) => false, // Unexpected stderr output + (_, Some(_)) => unreachable!("Expected stderr should always be None"), + }; + code_match && stdout_match && stderr_match + } + _ => false, + }; + + if passed { + *total_passed += 1; + } else { + *total_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)); + } +} + +/// Runs a cross-compilation test for library files +/// Compiles client with one compiler and library with the other, then links +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, + ncc_compiles_client: bool, +) { + let ncc_path = get_ncc_binary_path(); + let path = std::path::Path::new(client_file); + let binary_path = path.with_extension(""); + let binary_path_str = binary_path.to_str().unwrap(); + + let client_obj = path.with_extension("o"); + let lib_path = std::path::Path::new(library_file); + let library_obj = lib_path.with_extension("o"); + + let test_label = if ncc_compiles_client { + "ncc client + gcc lib" + } else { + "gcc client + ncc lib" + }; + + // Compile client + let client_status = if ncc_compiles_client { + std::process::Command::new(&ncc_path) + .arg("-c") + .arg(client_file) + .arg("-o") + .arg(&client_obj) + .status() + } else { + std::process::Command::new("gcc") + .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)); + 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() + } else { + std::process::Command::new(&ncc_path) + .arg("-c") + .arg(library_file) + .arg("-o") + .arg(&library_obj) + .status() + }; + + 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)); + return; + } + + // Link with gcc + let link_status = std::process::Command::new("gcc") + .arg(&client_obj) + .arg(&library_obj) + .arg("-o") + .arg(binary_path_str) + .status(); + + std::fs::remove_file(&client_obj).ok(); + 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)); + return; + } + + // Run the binary + let run_output = std::process::Command::new(binary_path_str).output().unwrap(); + std::fs::remove_file(&binary_path).ok(); + + let return_code = run_output.status.code().unwrap_or(-1); + let stdout = String::from_utf8_lossy(&run_output.stdout).to_string(); + let stderr = String::from_utf8_lossy(&run_output.stderr).to_string(); + let actual = ProgramOutput::Result { + code: return_code, + stdout: if stdout.is_empty() { None } else { Some(stdout) }, + stderr: if stderr.is_empty() { None } else { Some(stderr) }, + }; + + let passed = match (&actual, expected) { + ( + ProgramOutput::Result { + code: a_code, + stdout: a_stdout, + stderr: a_stderr, + }, + ProgramOutput::Result { + code: b_code, + stdout: b_stdout, + stderr: b_stderr, + }, + ) => { + let code_match = a_code == b_code; + let stdout_match = match (a_stdout, b_stdout) { + (_, None) => true, + (Some(a), Some(b)) => a == b, + (None, Some(_)) => false, + }; + // stderr should always be empty + let stderr_match = match (a_stderr, b_stderr) { + (None, None) => true, + (Some(_), None) => false, + (_, Some(_)) => unreachable!("Expected stderr should always be None"), + }; + code_match && stdout_match && stderr_match + } + _ => false, + }; + + if passed { *total_passed += 1; } else { *total_failed += 1; failed_tests.push(format!( - "{} (expected {:?}, got {:?})", - case.c_file, case.output, actual + "{} [{}] (expected {:?}, got {:?})", + client_file, test_label, expected, actual )); } } @@ -278,17 +486,49 @@ fn run_cases(cases: Vec) { let mut failed_tests = Vec::new(); for case in &cases { - match case.output { - ProgramOutput::Error(_) => run_test(case, &mut total_passed, &mut total_failed, &mut failed_tests, &[]), - ProgramOutput::Result(_) => { - 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()], - ); + 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", + ); + } } } } @@ -299,6 +539,7 @@ fn run_cases(cases: Vec) { &mut total_failed, &mut failed_tests, &["--gcc".to_string()], + "gcc-link", ); println!("\n=== C Programs Test Results ==="); @@ -406,6 +647,65 @@ fn test_label_printing_with_iced() { ); } +#[test] +fn test_data_symbol_resolution_with_iced() { + // Test that -S output shows data symbol names for RIP-relative accesses + let test_file = "writing-a-c-compiler-tests/tests/chapter_10/valid/multiple_static_file_scope_vars.c"; + + let ncc_path = get_ncc_binary_path(); + + let output = std::process::Command::new(&ncc_path) + .arg(test_file) + .arg("-S") + .output() + .expect("Failed to execute ncc"); + + assert!(output.status.success(), "ncc failed to compile {}", test_file); + + let asm_output = String::from_utf8_lossy(&output.stdout); + + // Check that data symbol names appear in RIP-relative addressing (e.g., "foo(%rip)") + let has_data_symbol = asm_output + .lines() + .any(|line| line.contains("(%rip)") && !line.trim().starts_with('.')); + + assert!( + has_data_symbol, + "No data symbol references found in assembly output. Expected symbol(%rip) format.\nOutput:\n{}", + asm_output + ); + + // Verify the symbol name is used, not just a numeric displacement + // Look for pattern like "foo(%rip)" where foo is an identifier + let has_named_symbol = asm_output.lines().any(|line| { + if let Some(idx) = line.find("(%rip)") { + // Get the part before (%rip) + let before = &line[..idx]; + // Check if it ends with an identifier (letters, digits, underscore, dot) + if let Some(last_word) = before.split_whitespace().last() { + // Should contain at least one letter (not just numbers like "-8") + last_word.chars().any(|c| c.is_alphabetic()) + } else { + false + } + } else { + false + } + }); + + assert!( + has_named_symbol, + "Data references use numeric displacements instead of symbol names.\nOutput:\n{}", + asm_output + ); + + // Check that static variables are shown in .data or .bss section + let has_data_section = asm_output.contains(".data") || asm_output.contains(".bss"); + assert!(has_data_section, "No .data or .bss section found in assembly output"); + + println!("✓ Data symbol resolution test passed"); +} + #[test] fn test_parser_printing() { // Test with a file that should generate labels