From 43d26e45181e7e86cec43a643adbe877f6dec5b7 Mon Sep 17 00:00:00 2001 From: John Ring Date: Sat, 24 Oct 2026 22:09:14 -0400 Subject: [PATCH 1/6] Fix latent backend bugs B1-B7 from the bug review - B1: load memory shift counts at 4 bytes, not the shifted value's width - B2: SetCC on a register now encodes the matched register, not always AL - B3: double -> unsigned int keys on dst type; out-of-range/NaN -> 0 (codegen and const-eval agree) - B4/F3: INT_MIN / -1 and % -1 wrap instead of trapping with SIGFPE - B5: function symbol sizes end at the next function, not end of .text - B6: unreachable xorps-from-stack arm is now unreachable!() - B7: zero comparison results at int width, not the operands' width Each fix has a regression test in tests/c_programs/ or tests/runner.rs. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- src/codegen.rs | 81 ++++++++- src/emit_iced.rs | 40 ++++- src/validate.rs | 14 +- tests/c_programs/compare_result_width.c | 26 +++ .../conversions/double_to_uint_edges.c | 43 +++++ tests/c_programs/expected_results.json | 12 ++ .../int_wrapping/div_overflow_wrap.c | 55 +++++++ tests/c_programs/shift_count_static_int.c | 12 ++ tests/runner.rs | 155 ++++++++++++++++++ 10 files changed, 425 insertions(+), 19 deletions(-) create mode 100644 tests/c_programs/compare_result_width.c create mode 100644 tests/c_programs/conversions/double_to_uint_edges.c create mode 100644 tests/c_programs/int_wrapping/div_overflow_wrap.c create mode 100644 tests/c_programs/shift_count_static_int.c diff --git a/README.md b/README.md index 4c7767c..9945726 100644 --- a/README.md +++ b/README.md @@ -306,8 +306,10 @@ NCC provides several safety features and guarantees to help developers write mor #### Guaranteed Behaviors - **Deterministic integer overflow**: Signed integer arithmetic uses two's complement wrapping (`int`: 32-bit, - `long`: 64-bit) instead of being undefined — e.g. `INT_MAX + 1` reliably wraps to `INT_MIN`. Unsigned arithmetic - (`unsigned int`, `unsigned long`) already wraps modulo 2^N per the C standard. + `long`: 64-bit) instead of being undefined — e.g. `INT_MAX + 1` reliably wraps to `INT_MIN`. This includes + division overflow: `INT_MIN / -1` wraps to `INT_MIN` (and `INT_MIN % -1` is `0`) rather than trapping with + SIGFPE as x86 `idiv` natively would. Unsigned arithmetic (`unsigned int`, `unsigned long`) already wraps + modulo 2^N per the C standard. - **Left-to-right evaluation**: Binary operations are evaluated left to right, eliminating undefined behavior from evaluation order. - **Type conversions**: Narrowing (e.g. `long` to `int`) truncates to the lower 32 bits using two's complement diff --git a/src/codegen.rs b/src/codegen.rs index 80f4a1f..3f5adcc 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -556,10 +556,12 @@ fn convert_instruction( v2: val_operand(src, constants, 8), size, }, + // Zero dst at its own width (always int), not the operand's: the first + // instruction to touch a pseudo sets its stack-slot size. Instruction::Mov { src: Operand::Imm(0), dst: val_operand(dst, constants, 8), - size, + size: symbols.get_assembly_type(dst), }, Instruction::SetCC { code: CondCode::E, @@ -662,8 +664,53 @@ fn convert_instruction( size, }]; if signed { - ins.push(Instruction::Cdq(size)); - ins.push(Instruction::Idiv(val_operand(src2, constants, 8), size)); + // `idiv` is the one integer instruction that refuses to wrap: MIN / -1 + // overflows the quotient and raises #DE (SIGFPE) instead. The README + // guarantees signed overflow wraps, so divisor -1 is special-cased: + // quotient = neg(dividend) (neg wraps MIN -> MIN natively), remainder = 0. + // A constant divisor is decided here; a runtime divisor gets a cmp/branch. + let wrap_ins = |ins: &mut Vec| { + if *op == BinOp::Divide { + ins.push(Instruction::Unary { + op: UnaryOp::Neg, + dst: Operand::Reg(Reg::AX), + size, + }); + } else { + ins.push(Instruction::Mov { + src: Operand::Imm(0), + dst: Operand::Reg(Reg::DX), + size, + }); + } + }; + let divisor = val_operand(src2, constants, 8); + match divisor { + Operand::Imm(-1) => wrap_ins(&mut ins), + Operand::Imm(_) => { + ins.push(Instruction::Cdq(size)); + ins.push(Instruction::Idiv(divisor, size)); + } + _ => { + let do_div = Identifier(name_gen.next("sdiv")); + let end = Identifier(name_gen.next("sdiv_end")); + ins.push(Instruction::Cmp { + v1: Operand::Imm(-1), + v2: divisor.clone(), + size, + }); + ins.push(Instruction::JmpCC { + code: CondCode::NE, + label: do_div.clone(), + }); + wrap_ins(&mut ins); + ins.push(Instruction::Jmp(end.clone())); + ins.push(Instruction::Label(do_div)); + ins.push(Instruction::Cdq(size)); + ins.push(Instruction::Idiv(divisor, size)); + ins.push(Instruction::Label(end)); + } + } } else { ins.push(Instruction::Mov { src: Operand::Imm(0), @@ -715,10 +762,11 @@ fn convert_instruction( }; let mut ins = vec![ Instruction::Cmp { v1, v2, size }, + // dst is int regardless of operand width; see the `Not` arm above Instruction::Mov { src: Operand::Imm(0), dst: val_operand(dst, constants, 8), - size, + size: symbols.get_assembly_type(dst), }, Instruction::SetCC { code, @@ -868,11 +916,22 @@ fn convert_instruction( tacky::Instruction::DoubleToUInt { src: src_raw, dst: dst_raw } => { let src = val_operand(src_raw, constants, 8); let dst = val_operand(dst_raw, constants, 8); - if matches!(symbols.get_assembly_type(src_raw), AssemblyType::Longword) { - // u32: every value in range fits the positive i64 range, so convert to a full - // 64-bit signed int and keep the low 32 bits. + // Dispatch on the *destination* width — the source is always a double. + if matches!(symbols.get_assembly_type(dst_raw), AssemblyType::Longword) { + // u32: every in-range value fits the positive i64 range, so convert with the + // 64-bit signed `cvttsd2si`, then range-check the result. Every invalid source + // (NaN, >= 2^32, <= -1, +/-inf) lands outside [0, 2^32) as an unsigned 64-bit + // value — including the i64::MIN indefinite — so one unsigned compare catches + // them all and yields the documented result for unsigned targets: the type + // minimum, 0. + let in_range = Identifier(name_gen.next("d2u_ok")); vec![ Instruction::Cvttsd2si { src, dst: Operand::Reg(Reg::AX), size: AssemblyType::Quadword }, + Instruction::Mov { src: Operand::Imm(4294967296), dst: Operand::Reg(Reg::R10), size: AssemblyType::Quadword }, // 2^32 + Instruction::Cmp { v1: Operand::Reg(Reg::R10), v2: Operand::Reg(Reg::AX), size: AssemblyType::Quadword }, // rax vs 2^32 + Instruction::JmpCC { code: CondCode::B, label: in_range.clone() }, // rax < 2^32 unsigned -> valid + Instruction::Mov { src: Operand::Imm(0), dst: Operand::Reg(Reg::AX), size: AssemblyType::Quadword }, // invalid -> 0 + Instruction::Label(in_range), Instruction::Mov { src: Operand::Reg(Reg::AX), dst, size: AssemblyType::Longword } ] } else { @@ -1559,10 +1618,16 @@ fn fix_invalid(program: &mut Program, stack_offsets: &HashMap, i32>) { dst, size, } if src.is_memory() || matches!(src, Operand::Imm(val) if !(0..=255).contains(&val)) => { + // Shift operands are not converted to a common type, so a memory-resident + // count may be a 4-byte object while `size` (the shifted value's width) is + // Quadword — loading at `size` would read past the count. Only CL is + // consumed, so a Longword load is always sufficient and stays in bounds. + // Immediates keep `size` so 64-bit counts still encode. + let count_size = if src.is_memory() { AssemblyType::Longword } else { size }; new_ins.push(Instruction::Mov { src, dst: Operand::Reg(Reg::CX), - size, + size: count_size, }); new_ins.push(Instruction::Binary { op, diff --git a/src/emit_iced.rs b/src/emit_iced.rs index 505ad1b..e918931 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -351,9 +351,15 @@ fn emit_object_with_labels( let text = obj.section_id(StandardSection::Text); obj.append_section_data(text, &code, 1); - // Add all function symbols - for (func_name, func_off, global) in &func_offsets { - let func_size = code.len() as u64 - func_off; + // Add all function symbols. Functions are appended to .text in order, so each one ends + // where the next begins (the last ends at end-of-text) — sizing to end-of-text instead + // would make every st_size overlap all following functions, corrupting profilers, + // debuggers, and size-based tooling like `nm -S`. + for (i, (func_name, func_off, global)) in func_offsets.iter().enumerate() { + let func_end = func_offsets + .get(i + 1) + .map_or(code.len() as u64, |(_, next_off, _)| *next_off); + let func_size = func_end - func_off; obj.add_symbol(Symbol { name: func_name.as_bytes().to_vec(), value: *func_off, @@ -586,6 +592,23 @@ fn gpr32(reg: &Reg) -> AsmRegister32 { } } +fn gpr8_reg(reg: &Reg) -> AsmRegister8 { + use codegen::Reg::*; + match reg { + AX => gpr8::al, + DX => gpr8::dl, + R10 => gpr8::r10b, + R11 => gpr8::r11b, + CX => gpr8::cl, + DI => gpr8::dil, + SI => gpr8::sil, + R8 => gpr8::r8b, + R9 => gpr8::r9b, + SP => gpr8::spl, + _ => unreachable!("Only for GP reg"), + } +} + fn gpr64_reg(reg: &Reg) -> AsmRegister64 { use codegen::Reg::*; match reg { @@ -975,8 +998,13 @@ fn emit_instruction( }, BinaryOp::BitXOr => match (src, dst, size) { (Operand::Reg(s), Operand::Reg(d), AssemblyType::Double) => a.xorps(xmm_reg(d), xmm_reg(s))?, - (Operand::Stack(off), Operand::Reg(d), AssemblyType::Double) => { - a.xorps(xmm_reg(d), mem_rbp(*off, *size))? + (Operand::Stack(_), Operand::Reg(_), AssemblyType::Double) => { + // A working-looking encode here would be a trap: `xorps xmm, m128` reads 16 + // bytes and requires 16-byte alignment, but an rbp-relative double slot is 8 + // bytes and 8-aligned (#GP + out-of-bounds read if ever executed). Double xor + // only exists for negation, whose sign-bit mask is always a 16-aligned + // `.rodata` Data operand; the validator rejects bitwise ops on doubles. + unreachable!("double xor src is never a stack slot (negation mask lives in .rodata)") } (Operand::Data(name), Operand::Reg(d), AssemblyType::Double) => { let lbl = data_labels.get(name).unwrap(); @@ -1169,7 +1197,7 @@ fn emit_instruction( }; } Instruction::SetCC { code, op } => match op { - Operand::Reg(_r) => emit_setcc!(a, code, gpr8::al), + Operand::Reg(r) => emit_setcc!(a, code, gpr8_reg(r)), Operand::Stack(off) => emit_setcc!(a, code, byte_ptr(gpr64::rbp - (-*off))), Operand::Data(name) => { let lbl = data_labels.get(name).unwrap(); diff --git a/src/validate.rs b/src/validate.rs index c31eef2..aa9e928 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -1834,7 +1834,8 @@ enum Wide { // truncated value is already in range. So: explicit range/NaN check returning the indefinite value // on failure, and plain `as` (which truncates toward zero, matching cvttsd2si) on success. // -// `double_to_u32`/`u64` build on the signed path because `cvttsd2si` is signed-only (see each fn). +// `double_to_u64` builds on the signed path because `cvttsd2si` is signed-only; `double_to_u32` +// range-checks directly, mirroring the runtime lowering (invalid -> 0, the unsigned "indefinite"). fn double_to_i32(d: f64) -> i32 { // cvttsd2si: valid iff trunc(d) fits in i32; NaN/inf/overflow -> indefinite (INT_MIN) if d.is_nan() || d < i32::MIN as f64 || d >= 2147483648.0 @@ -1868,8 +1869,15 @@ fn double_to_u64(d: f64) -> u64 { } fn double_to_u32(d: f64) -> u32 { - // u32's full range fits in i64, so convert via the signed 64-bit path and truncate. - double_to_i64(d) as u32 + // valid iff trunc(d) fits in u32; NaN/inf/overflow -> unsigned "indefinite" = 0 (u32 MIN), + // mirroring the runtime lowering's range check. Note (-1.0, 0.0) truncates to 0 and is valid. + if d.is_nan() || d <= -1.0 || d >= 4294967296.0 + /* 2^32 */ + { + 0 + } else { + d as u32 // in range: truncates toward zero, matches cvttsd2si + } } /// Casts a normalized value (`i64`/`u64`) to each target type, yielding `(result, out_of_range)` diff --git a/tests/c_programs/compare_result_width.c b/tests/c_programs/compare_result_width.c new file mode 100644 index 0000000..89e56eb --- /dev/null +++ b/tests/c_programs/compare_result_width.c @@ -0,0 +1,26 @@ +/* A comparison's result is always int, even when its operands are 8 bytes wide. + * Codegen zeroes the result before `setCC`; that zeroing must use the result's + * width (movl), not the operands' (movq). A stack slot's size is set by the first + * instruction that touches it, so the wide zeroing gave every such result an + * 8-byte slot. That slot was self-consistent (nothing clobbered), so exit codes + * can't catch it — test_compare_result_width in tests/runner.rs checks the asm. + * Covers every operand shape that reaches the zeroing: long, unsigned long, + * double (ordered and ==/!= with the NaN fixup), and `!` on long. */ +int main(void) { + long a = 5; + long b = 7; + unsigned long ua = 1ul; + unsigned long ub = 2ul; + double d = 1.5; + double e = 2.5; + + int r1 = a < b; /* 1 */ + int r2 = ua >= ub; /* 0 */ + int r3 = d < e; /* 1 */ + int r4 = d == d; /* 1 */ + int r5 = d != e; /* 1 */ + int r6 = !a; /* 0 */ + int r7 = !(a - 5); /* 1 */ + + return r1 + 2 * r2 + 4 * r3 + 8 * r4 + 16 * r5 + 32 * r6 + 64 * r7; /* 93 */ +} diff --git a/tests/c_programs/conversions/double_to_uint_edges.c b/tests/c_programs/conversions/double_to_uint_edges.c new file mode 100644 index 0000000..a3ed7a5 --- /dev/null +++ b/tests/c_programs/conversions/double_to_uint_edges.c @@ -0,0 +1,43 @@ +/* NCC-specific deterministic edge: converting an out-of-range or NaN `double` to `unsigned int` + is undefined behavior in standard C. NCC defines it as the unsigned "integer indefinite" = + the target type's minimum, i.e. 0 — matching the README's float-cast contract. Companion to + double_to_int_edges.c (signed targets); this locks in the u32 path, both the runtime lowering + and const-eval (static initializers), which must agree. + + Checks use discriminating comparisons rather than bare casts so a wrong nonzero result (e.g. + the old low-32-bits behavior: (unsigned int)1e12 -> 3567587328) can't alias the expected 0 in + the 8-bit exit code. Returns the number of checks that held; expected result is 11. */ + +static unsigned int s_big = (unsigned int) 1e12; /* out of range -> 0 */ +static unsigned int s_neg = (unsigned int) -1e30; /* out of range -> 0 */ +static unsigned int s_max = (unsigned int) 4294967295.0; /* UINT_MAX, exactly representable */ + +int main(void) { + int passed = 0; + + double big = 1e12; /* above u32 range, within i64 range (old code kept low 32 bits) */ + double huge = 1e30; /* above i64 range too (indefinite path) */ + double neg = -1e30; /* far below */ + double inf = 2e308; /* rounds to +infinity (also fires -Woverflow at compile time) */ + double nan = 0.0 / 0.0; /* NaN */ + double two32 = 4294967296.0; /* 2^32: first value out of range */ + + /* invalid conversions: all must yield 0 */ + if ((unsigned int) big == 0u) passed = passed + 1; + if ((unsigned int) huge == 0u) passed = passed + 1; + if ((unsigned int) neg == 0u) passed = passed + 1; + if ((unsigned int) inf == 0u) passed = passed + 1; + if ((unsigned int) nan == 0u) passed = passed + 1; + if ((unsigned int) two32 == 0u) passed = passed + 1; + + /* valid conversions: truncate toward zero */ + if ((unsigned int) 4294967295.0 == 4294967295u) passed = passed + 1; /* last in-range value */ + if ((unsigned int) -0.75 == 0u) passed = passed + 1; /* truncates to 0: valid */ + + /* static (const-eval) results must match the runtime rules above */ + if (s_big == 0u) passed = passed + 1; + if (s_neg == 0u) passed = passed + 1; + if (s_max == 4294967295u) passed = passed + 1; + + return passed; /* expect 11 */ +} \ No newline at end of file diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index 9329b9a..30db358 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -65,6 +65,9 @@ "switch/complex_const_int.c": { "return_code": 16 }, + "int_wrapping/div_overflow_wrap.c": { + "return_code": 13 + }, "int_wrapping/int_wrapping.c": { "return_code": 0 }, @@ -111,10 +114,19 @@ "large_shift_immediate.c": { "return_code": 0 }, + "shift_count_static_int.c": { + "return_code": 16 + }, "types/compound_assign_mixed_types.c": { "return_code": 30 }, "conversions/double_to_int_edges.c": { "return_code": 7 + }, + "conversions/double_to_uint_edges.c": { + "return_code": 11 + }, + "compare_result_width.c": { + "return_code": 93 } } \ No newline at end of file diff --git a/tests/c_programs/int_wrapping/div_overflow_wrap.c b/tests/c_programs/int_wrapping/div_overflow_wrap.c new file mode 100644 index 0000000..cf5185d --- /dev/null +++ b/tests/c_programs/int_wrapping/div_overflow_wrap.c @@ -0,0 +1,55 @@ +/* NCC-specific deterministic edge: INT_MIN / -1 (and % -1) overflows the quotient, and x86 + `idiv` raises #DE (SIGFPE) instead of wrapping — the only integer instruction that refuses + to. NCC's README guarantees signed overflow wraps, so codegen special-cases divisor -1: + quotient = neg(dividend) (wraps MIN -> MIN), remainder = 0. Const-eval already wrapped via + `overflowing_div`/`rem`; these checks lock runtime and const-eval to the same values. + + Covers both codegen paths: a runtime-variable divisor (cmp/branch) and a constant -1 divisor + (decided at compile time, no branch). Non-overflowing divisions guard against the wrap path + or branch polarity being wrong for ordinary values. Returns checks passed; expect 13. */ + +int int_min(void) { + return -2147483647 - 1; // INT_MIN, built without an out-of-range literal +} + +long long_min(void) { + return -9223372036854775807L - 1L; // LONG_MIN +} + +static int s_div = (-2147483647 - 1) / -1; /* const-eval wraps to INT_MIN (-Woverflow) */ +static int s_rem = (-2147483647 - 1) % -1; /* 0 */ +static long s_ldiv = (-9223372036854775807L - 1L) / -1; /* LONG_MIN */ + +int main(void) { + int passed = 0; + + int m = int_min(); + long lm = long_min(); + int neg1 = -1; /* runtime-variable divisors: force the cmp/branch path */ + long lneg1 = -1; + + /* overflow, runtime divisor: must wrap, not SIGFPE */ + if (m / neg1 == int_min()) passed = passed + 1; + if (m % neg1 == 0) passed = passed + 1; + if (lm / lneg1 == long_min()) passed = passed + 1; + if (lm % lneg1 == 0) passed = passed + 1; + + /* overflow, constant divisor: compile-time-decided path */ + if (m / -1 == int_min()) passed = passed + 1; + if (m % -1 == 0) passed = passed + 1; + if (lm / -1 == long_min()) passed = passed + 1; + + /* no overflow, divisor -1: wrap path must still compute correct values */ + if (7 / neg1 == -7) passed = passed + 1; + if (7 % neg1 == 0) passed = passed + 1; + + /* no overflow, divisor != -1: branch must fall through to plain idiv */ + if (10 / -3 == -3) passed = passed + 1; + if (10 % -3 == 1) passed = passed + 1; + + /* const-eval results must match the runtime rules above */ + if (s_div == int_min()) passed = passed + 1; + if (s_rem == 0 && s_ldiv == long_min()) passed = passed + 1; + + return passed; /* expect 13 */ +} diff --git a/tests/c_programs/shift_count_static_int.c b/tests/c_programs/shift_count_static_int.c new file mode 100644 index 0000000..ecc45bd --- /dev/null +++ b/tests/c_programs/shift_count_static_int.c @@ -0,0 +1,12 @@ +/* Shift count is a memory-resident int while the shifted value is a long. + * Shift operands are deliberately not converted to a common type, so the + * fixup that moves the count into CX must load it at the count's own width + * (4 bytes). Loading at the shifted value's width reads past the 4-byte + * static; the runtime result is still correct (only CL is consumed), so the + * width is asserted by test_shift_count_load_width in tests/runner.rs. */ +static int scount = 3; + +int main(void) { + long lv = 2l << scount; + return (int)lv; +} \ No newline at end of file diff --git a/tests/runner.rs b/tests/runner.rs index 1cfc15c..6d3289a 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -871,6 +871,161 @@ fn test_data_symbol_resolution_with_iced() { println!("✓ Data symbol resolution test passed"); } +#[test] +fn test_shift_count_load_width() { + // Regression test for the shift-count fixup width bug: `long << int_count` with a + // memory-resident count must load the count into CX at the count's own width (%ecx), + // not the shifted value's (%rcx). An 8-byte load of the 4-byte static reads past the + // object, but the computed value is still correct (only CL is consumed) — so the bug + // is only observable in the generated assembly, never via exit code. + let test_file = "tests/c_programs/shift_count_static_int.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); + + // Sanity: the quadword shift-by-CL this test targets must actually be present, + // otherwise codegen changed shape and the assertion below would pass vacuously. + assert!( + asm_output + .lines() + .any(|line| line.trim().starts_with("shlq") && line.contains("%cl")), + "expected a quadword shift by %cl in assembly output:\n{asm_output}" + ); + + let count_load = asm_output + .lines() + .find(|line| line.contains("scount(%rip)") && (line.contains("%rcx") || line.contains("%ecx"))) + .unwrap_or_else(|| panic!("no load of scount into CX found in assembly output:\n{asm_output}")); + + assert!( + count_load.contains("%ecx"), + "shift count loaded at the shifted value's width (8-byte read of a 4-byte static): `{}`", + count_load.trim() + ); + + println!("✓ Shift count load width test passed"); +} + +#[test] +fn test_compare_result_width() { + // Regression test: a comparison's int result must be zeroed at its own width (movl) + // before `setCC`, not at the operands' width (movq). The first instruction touching a + // pseudo sets its stack-slot size, so the wide zeroing silently gave every result an + // 8-byte slot — self-consistent, so only visible in the generated assembly. + let test_file = "tests/c_programs/compare_result_width.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); + let lines: Vec<&str> = asm_output.lines().map(str::trim).collect(); + + // setCC into memory (not the %al NaN fixup) — the line before it zeroes the result. + let mut checked = 0; + for pair in lines.windows(2) { + let (prev, cur) = (pair[0], pair[1]); + if cur.starts_with("set") && cur.contains("(%rbp)") { + assert!( + prev.starts_with("movl $0,"), + "comparison result zeroed at the wrong width: `{prev}` before `{cur}`" + ); + checked += 1; + } + } + + // 7 comparisons in the test file; guards against the scan passing vacuously. + assert_eq!(checked, 7, "expected 7 setCC-to-stack sites:\n{asm_output}"); + + println!("✓ Compare result width test passed"); +} + +// nm -S on Mach-O doesn't report symbol sizes (they aren't part of the format), so this +// ELF symbol-size check is Linux-only. +#[cfg(target_os = "linux")] +#[test] +fn test_function_symbol_sizes() { + // Regression test for function st_size: every function's size must end where the next + // function begins, not extend to end-of-text. Overlapping sizes don't affect execution + // but corrupt profilers, debuggers, and size-based tooling. + let test_file = "tests/c_programs/conversions/double_to_int_edges.c"; // 3 functions + + let ncc_path = get_ncc_binary_path(); + + // `-c` writes `.o` next to the input (ignoring -o), so compile a copy in the + // temp dir to keep the repo tree clean. + let src_path = std::env::temp_dir().join("ncc_symbol_size_test.c"); + let obj_path = std::env::temp_dir().join("ncc_symbol_size_test.o"); + std::fs::copy(test_file, &src_path).expect("failed to copy test source to temp dir"); + + let output = std::process::Command::new(&ncc_path) + .arg(&src_path) + .arg("-c") + .output() + .expect("Failed to execute ncc"); + + assert!(output.status.success(), "ncc failed to compile {}", test_file); + + let nm = std::process::Command::new("nm") + .arg("-S") + .arg(&obj_path) + .output() + .expect("Failed to execute nm"); + assert!(nm.status.success(), "nm failed on {}", obj_path.display()); + + // nm -S text symbol lines: " T|t " + let nm_output = String::from_utf8_lossy(&nm.stdout); + let mut funcs: Vec<(u64, u64, String)> = nm_output + .lines() + .filter_map(|line| { + let mut parts = line.split_whitespace(); + let value = u64::from_str_radix(parts.next()?, 16).ok()?; + let size = u64::from_str_radix(parts.next()?, 16).ok()?; + let kind = parts.next()?; + let name = parts.next()?; + (kind == "T" || kind == "t").then(|| (value, size, name.to_string())) + }) + .collect(); + funcs.sort_unstable(); + + assert!( + funcs.len() >= 2, + "expected multiple function symbols with sizes, got:\n{nm_output}" + ); + + for pair in funcs.windows(2) { + let (off, size, name) = &pair[0]; + let (next_off, _, next_name) = &pair[1]; + assert!(size > &0, "function '{name}' has zero size"); + assert!( + off + size <= *next_off, + "function '{name}' (offset {off:#x}, size {size:#x}) overlaps '{next_name}' at {next_off:#x}" + ); + } + + let _ = std::fs::remove_file(&obj_path); + let _ = std::fs::remove_file(&src_path); + println!( + "✓ Function symbol size test passed: {} functions, no overlap", + funcs.len() + ); +} + #[test] fn test_parser_printing() { // Test with a file that should generate labels From 91dbeb2ae1ba01c569c1387dcb20443aa4b740b3 Mon Sep 17 00:00:00 2001 From: John Ring Date: Sun, 25 Oct 2026 09:28:37 -0400 Subject: [PATCH 2/6] Fix bugs from the second review pass (B8, B9, P1-P5, P7, W1) Backend: - B8: size stack slots from the symbol table, not the first instruction that touches them. Truncate and long shift counts gave longs 4-byte slots, so later 8-byte writes clobbered neighbours (miscompile). - B9: pad the 16-aligned xorps negation mask to 16 bytes in .rodata Lexer/parser: - P1: `/*/` no longer closes the comment it opens - P2: malformed for-header clauses are errors, not empty clauses - P3: parameter/argument lists require `,` or `)` between items - P4: `f(void)` is no longer accepted as a call - P5: `-2147483648` is a long, not an int - P7: form feed and vertical tab are whitespace Warnings: - W1: -Wshift-count-overflow uses width 64 for unsigned long Every fix has a regression test that fails on the previous commit. Co-Authored-By: Claude Opus 5.5 --- src/codegen.rs | 87 ++++++++----------- src/emit_iced.rs | 9 +- src/lexer.rs | 6 +- src/parser.rs | 84 ++++++++++++------ src/validate.rs | 2 +- .../invalid_parse/call_with_void.c | 8 ++ .../invalid_parse/missing_arg_comma.c | 8 ++ .../invalid_parse/missing_param_comma.c | 8 ++ tests/c_programs/double_negation_mask.c | 12 +++ tests/c_programs/expected_results.json | 15 ++++ .../lexer/comment_slash_star_slash.c | 6 ++ .../lexer/formfeed_vtab_whitespace.c | 6 ++ .../loops/invalid_parse/for_bad_condition.c | 8 ++ .../loops/invalid_parse/for_bad_init.c | 7 ++ .../loops/invalid_parse/for_bad_post.c | 8 ++ tests/c_programs/stack_slot_width.c | 42 +++++++++ .../types/int_min_literal_is_long.c | 20 +++++ tests/c_programs/warnings/no_shift_count.c | 2 + tests/runner.rs | 54 ++++++++++++ 19 files changed, 311 insertions(+), 81 deletions(-) create mode 100644 tests/c_programs/declaration/invalid_parse/call_with_void.c create mode 100644 tests/c_programs/declaration/invalid_parse/missing_arg_comma.c create mode 100644 tests/c_programs/declaration/invalid_parse/missing_param_comma.c create mode 100644 tests/c_programs/double_negation_mask.c create mode 100644 tests/c_programs/lexer/comment_slash_star_slash.c create mode 100644 tests/c_programs/lexer/formfeed_vtab_whitespace.c create mode 100644 tests/c_programs/loops/invalid_parse/for_bad_condition.c create mode 100644 tests/c_programs/loops/invalid_parse/for_bad_init.c create mode 100644 tests/c_programs/loops/invalid_parse/for_bad_post.c create mode 100644 tests/c_programs/stack_slot_width.c create mode 100644 tests/c_programs/types/int_min_literal_is_long.c diff --git a/src/codegen.rs b/src/codegen.rs index 3f5adcc..44dd9b0 100644 --- a/src/codegen.rs +++ b/src/codegen.rs @@ -1308,47 +1308,50 @@ struct StackMapping<'a> { /// 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>, + /// Source of each pseudo's type, which decides its slot size. + symbols: &'a BackendSymbolTable, } impl<'a> StackMapping<'a> { - fn from_data_vars(data_vars: &'a HashSet>) -> Self { + fn new(data_vars: &'a HashSet>, symbols: &'a BackendSymbolTable) -> Self { StackMapping { stack_mapping: HashMap::new(), offset: 0, data_vars, + symbols, } } /// Returns the stack operand for a pseudo-register, allocating a new slot if needed. /// - /// Stack grows downward: each new allocation decrements the offset by the type's size. - fn get_stack_location(&mut self, pseudo: &str, asm_type: AssemblyType) -> Operand { - let offset_option = self.stack_mapping.get(pseudo); - let offset = match offset_option { - Some(offset) => offset, + /// Stack grows downward: each new allocation decrements the offset by the size of the + /// pseudo's *declared type*. Sizing from the type (not from the width of whichever + /// instruction touches the pseudo first) matters: narrowing reads (`Truncate`) and shift + /// counts touch an operand at a different width than its type, and a slot sized from + /// them would be too small, so later full-width writes would clobber the neighbouring slot. + fn get_stack_location(&mut self, pseudo: &str) -> Operand { + let offset = match self.stack_mapping.get(pseudo) { + Some(offset) => *offset, None => { - self.offset -= asm_type.size() as i32; + self.offset -= self.symbols.get_obj_type(pseudo).size() as i32; self.stack_mapping.insert(Rc::from(pseudo), self.offset); - &self.offset + self.offset } }; - Operand::Stack(*offset) + Operand::Stack(offset) } /// 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, asm_type: AssemblyType) -> Operand { - match operand { - Operand::Pseudo(pseudo) => { - if self.data_vars.contains(pseudo) { - Operand::Data(pseudo.clone()) - } else { - self.get_stack_location(pseudo, asm_type) - } - } - _ => operand.clone(), + fn replace_pseudo(&mut self, operand: &mut Operand) { + if let Operand::Pseudo(pseudo) = operand { + *operand = if self.data_vars.contains(pseudo) { + Operand::Data(pseudo.clone()) + } else { + self.get_stack_location(pseudo) + }; } } } @@ -1364,41 +1367,25 @@ fn replace_pseudo_registers(program: &mut Program, symbols: &BackendSymbolTable) let mut offsets = HashMap::new(); for FunctionDefinition { name, body, global: _ } in program.functions.iter_mut() { - let mut stack_mapping = StackMapping::from_data_vars(&data_vars); + let mut stack_mapping = StackMapping::new(&data_vars, symbols); for ins in body.iter_mut() { match ins { - Instruction::Mov { src, dst, size } | Instruction::Binary { op: _, src, dst, size } => { - *src = stack_mapping.replace_pseudo(src, *size); - *dst = stack_mapping.replace_pseudo(dst, *size); - } - Instruction::Cvttsd2si { src, dst, size } => { - *src = stack_mapping.replace_pseudo(src, AssemblyType::Double); // src is double - *dst = stack_mapping.replace_pseudo(dst, *size); // dst is integer - } - Instruction::Cvtsi2sd { src, dst, size } => { - *src = stack_mapping.replace_pseudo(src, *size); // src is integer - *dst = stack_mapping.replace_pseudo(dst, AssemblyType::Double); // dst is double - } - Instruction::Unary { op: _, dst, size } => *dst = stack_mapping.replace_pseudo(dst, *size), - Instruction::Movsx { src, dst } | Instruction::MovZeroExtend { src, dst } => { - *src = stack_mapping.replace_pseudo(src, AssemblyType::Longword); - *dst = stack_mapping.replace_pseudo(dst, AssemblyType::Quadword); - } - Instruction::Idiv(src, size) | Instruction::Div(src, size) => { - *src = stack_mapping.replace_pseudo(src, *size); - } - Instruction::Cmp { v1, v2, size } => { - *v1 = stack_mapping.replace_pseudo(v1, *size); - *v2 = stack_mapping.replace_pseudo(v2, *size); - } - Instruction::SetCC { op, .. } => { - if let Operand::Pseudo(name) = op { - let size = symbols.get_obj_type(name); - *op = stack_mapping.replace_pseudo(op, size); - } + Instruction::Mov { src, dst, .. } + | Instruction::Binary { src, dst, .. } + | Instruction::Cvttsd2si { src, dst, .. } + | Instruction::Cvtsi2sd { src, dst, .. } + | Instruction::Movsx { src, dst } + | Instruction::MovZeroExtend { src, dst } + | Instruction::Cmp { v1: src, v2: dst, .. } => { + stack_mapping.replace_pseudo(src); + stack_mapping.replace_pseudo(dst); } - Instruction::Push(op) => *op = stack_mapping.replace_pseudo(op, AssemblyType::Quadword), + Instruction::Unary { dst: op, .. } + | Instruction::Idiv(op, _) + | Instruction::Div(op, _) + | Instruction::SetCC { op, .. } + | Instruction::Push(op) => stack_mapping.replace_pseudo(op), Instruction::Ret | Instruction::Call(_) | Instruction::Label(_) diff --git a/src/emit_iced.rs b/src/emit_iced.rs index e918931..0d0ad41 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -447,12 +447,17 @@ fn emit_object_with_labels( // compiled objects, which a whole-program compiler essentially never produces. let rodata = obj.section_id(StandardSection::ReadOnlyData); for codegen::StaticConstant { name, init, alignment } in &program.static_constants { - let bytes = init.to_le_bytes(); + let mut bytes = init.to_le_bytes(); + // A 16-aligned constant is the `xorps` sign-flip mask, and `xorps m128` reads 16 bytes. + // Pad it with a zero upper lane (as gcc does) so the read never runs past the entry, + // which matters when it is the last thing in `.rodata` (the pool sorts by bit pattern, + // so `-0.0` = 0x8000... usually is). + bytes.resize(*alignment.max(&8) as usize, 0); let offset = obj.append_section_data(rodata, &bytes, *alignment); let sym_id = obj.add_symbol(Symbol { name: name.as_bytes().to_vec(), value: offset, - size: 8, + size: bytes.len() as u64, kind: SymbolKind::Data, scope: SymbolScope::Compilation, weak: false, diff --git a/src/lexer.rs b/src/lexer.rs index 6101582..c53091e 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -320,7 +320,8 @@ pub(crate) fn tokenizer(mut input: &str) -> Result, Lexer let mut line = 1; let mut col = 1; while !input.is_empty() { - let trimmed = input.trim_start_matches([' ', '\t', '\r']); + // C whitespace also includes form feed and vertical tab + let trimmed = input.trim_start_matches([' ', '\t', '\r', '\x0C', '\x0B']); col += input.len() - trimmed.len(); input = trimmed; @@ -338,7 +339,8 @@ pub(crate) fn tokenizer(mut input: &str) -> Result, Lexer } continue; } else if input.starts_with("/*") { - if let Some(end_comment_index) = input.find("*/") { + // Search past the opening `/*` so `/*/` doesn't pair its own `*` with the `/` + if let Some(end_comment_index) = input[2..].find("*/").map(|i| i + 2) { let comment = &input[..end_comment_index + 2]; let newline_count = comment.matches('\n').count(); if newline_count > 0 { diff --git a/src/parser.rs b/src/parser.rs index 9fd421a..edda247 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -594,13 +594,21 @@ fn parse_factor(tokens: &mut VecDeque) -> Result { - // Fold a leading `-` into the literal so INT_MIN / LONG_MIN keep the right type: - // their magnitude (2^31 / 2^63) isn't representable in the positive range, so - // parsing the magnitude then negating would overflow-promote and mistype them. + // Fold a leading `-` into the literal. Needed for LONG_MIN: its magnitude 2^63 has + // no 64-bit type, so parsing it then negating would be a parse error. Folding is + // harmless whenever it keeps C's type for `-literal` (the type of the magnitude). + // The exception is 2147483648: C types it `long`, so `-2147483648` is a `long`, + // but folded it would fit `int`. Leave that one as a negation. + let is_int_min_magnitude = matches!( + tokens.get(1), + Some(SpannedToken { token: Token::ConstantInt(v), .. }) + if v.parse::().is_err() && format!("-{v}").parse::().is_ok() + ); if let Some(SpannedToken { token: Token::ConstantInt(value_str) | Token::ConstantLong(value_str), span: _, }) = tokens.get_mut(1) + && !is_int_min_magnitude { *value_str = format!("-{value_str}"); tokens.pop_front(); @@ -1005,13 +1013,13 @@ fn parse_statement(tokens: &mut VecDeque) -> Result, terminator: &Token) -> Result, SyntaxError> { + if tokens.front().map(|t| &t.token) == Some(terminator) { + Ok(None) + } else { + parse_exp(tokens, 0).map(Some) + } +} + +/// Consumes the separator after a parameter or argument: a `,` (not followed by `)`), or nothing +/// if the list ends here. Anything else is an error. Without this, `f(int a int b)` and `f(1 2)` +/// would parse as if the commas were there. fn parse_arg_comma(tokens: &mut VecDeque) -> Result<(), SyntaxError> { - if let Some(next_token) = tokens.front().cloned() - && next_token.token == Token::Comma - { - tokens.pop_front(); - if tokens.front().map(|t| &t.token) == Some(&Token::CloseParen) { - return Err(SyntaxError::with_span( - "Trailing comma not allowed.".to_string(), - Some(next_token.span), - )); + match tokens.front().cloned() { + Some(SpannedToken { + token: Token::Comma, + span, + }) => { + tokens.pop_front(); + if tokens.front().map(|t| &t.token) == Some(&Token::CloseParen) { + return Err(SyntaxError::with_span( + "Trailing comma not allowed.".to_string(), + Some(span), + )); + } + Ok(()) } + Some(SpannedToken { + token: Token::CloseParen, + .. + }) => Ok(()), + Some(SpannedToken { token, span }) => Err(SyntaxError::with_span( + format!("Expected ',' or ')' but found {token:?}"), + Some(span), + )), + // EOF is reported by the caller's `expect(CloseParen)` + None => Ok(()), } - Ok(()) } /// Parses a function's parameter list (after the opening parenthesis). @@ -1267,17 +1302,14 @@ fn parse_function_params( fn parse_function_args(tokens: &mut VecDeque, err_span: &Option) -> Result, SyntaxError> { let mut params = vec![]; - if let Some(front) = tokens.front().cloned() { - if front.token == Token::VoidKeyword { - tokens.pop_front(); - } else { - loop { - if tokens.front().map(|t| &t.token) == Some(&Token::CloseParen) { - break; - } - params.push(parse_exp(tokens, 0)?); - parse_arg_comma(tokens)?; + // Unlike parameter lists, `void` has no special meaning here: `f(void)` is not a call. + if tokens.front().is_some() { + loop { + if tokens.front().map(|t| &t.token) == Some(&Token::CloseParen) { + break; } + params.push(parse_exp(tokens, 0)?); + parse_arg_comma(tokens)?; } expect(&Token::CloseParen, tokens)?; Ok(params) diff --git a/src/validate.rs b/src/validate.rs index aa9e928..1982b38 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -823,7 +823,7 @@ fn warn_shift_count(left_type: &Type, rhs: &ParserExpr, span: Span) { && !matches!(v, StaticInit::DoubleInit(_)) { let width: i64 = match left_type { - Type::Long => 64, + Type::Long | Type::ULong => 64, _ => 32, }; let count = v.as_i64(); diff --git a/tests/c_programs/declaration/invalid_parse/call_with_void.c b/tests/c_programs/declaration/invalid_parse/call_with_void.c new file mode 100644 index 0000000..4be43c4 --- /dev/null +++ b/tests/c_programs/declaration/invalid_parse/call_with_void.c @@ -0,0 +1,8 @@ +/* `void` only means "no parameters" in a declaration. In a call, `f(void)` is an error. */ +int f(void) { + return 3; +} + +int main(void) { + return f(void); +} diff --git a/tests/c_programs/declaration/invalid_parse/missing_arg_comma.c b/tests/c_programs/declaration/invalid_parse/missing_arg_comma.c new file mode 100644 index 0000000..b5e4e42 --- /dev/null +++ b/tests/c_programs/declaration/invalid_parse/missing_arg_comma.c @@ -0,0 +1,8 @@ +/* Call arguments must be separated by commas. */ +int f(int a, int b) { + return a - b; +} + +int main(void) { + return f(5 2); +} diff --git a/tests/c_programs/declaration/invalid_parse/missing_param_comma.c b/tests/c_programs/declaration/invalid_parse/missing_param_comma.c new file mode 100644 index 0000000..138612a --- /dev/null +++ b/tests/c_programs/declaration/invalid_parse/missing_param_comma.c @@ -0,0 +1,8 @@ +/* Parameters must be separated by commas. */ +int f(int a int b) { + return a - b; +} + +int main(void) { + return f(5, 2); +} diff --git a/tests/c_programs/double_negation_mask.c b/tests/c_programs/double_negation_mask.c new file mode 100644 index 0000000..5ed8fc2 --- /dev/null +++ b/tests/c_programs/double_negation_mask.c @@ -0,0 +1,12 @@ +/* Negating a double uses `xorps` with a sign-bit mask from .rodata, and `xorps` reads 16 bytes. + The mask must be stored as a full 16-byte entry so the read never runs past .rodata. + test_double_negation_mask_size in tests/runner.rs checks the entry size; this file also runs. + Returns 5. */ +double neg(double x) { + return -x; +} + +int main(void) { + double d = neg(2.5) + -2.5; /* -5.0 */ + return (int) -d; +} diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index 30db358..c3542ce 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -128,5 +128,20 @@ }, "compare_result_width.c": { "return_code": 93 + }, + "stack_slot_width.c": { + "return_code": 2 + }, + "types/int_min_literal_is_long.c": { + "return_code": 3 + }, + "lexer/comment_slash_star_slash.c": { + "return_code": 1 + }, + "lexer/formfeed_vtab_whitespace.c": { + "return_code": 7 + }, + "double_negation_mask.c": { + "return_code": 5 } } \ No newline at end of file diff --git a/tests/c_programs/lexer/comment_slash_star_slash.c b/tests/c_programs/lexer/comment_slash_star_slash.c new file mode 100644 index 0000000..762f5f2 --- /dev/null +++ b/tests/c_programs/lexer/comment_slash_star_slash.c @@ -0,0 +1,6 @@ +// The sequence slash-star-slash opens a block comment but does not close it: the star belongs +// to the opener. The comment below runs until the second slash-star-slash, hiding `+ 1`, so +// this returns 1. (The header uses line comments since the sequence would end a block comment.) +int main(void) { + return 1 /*/ + 1 /*/ ; +} diff --git a/tests/c_programs/lexer/formfeed_vtab_whitespace.c b/tests/c_programs/lexer/formfeed_vtab_whitespace.c new file mode 100644 index 0000000..1b7cf9b --- /dev/null +++ b/tests/c_programs/lexer/formfeed_vtab_whitespace.c @@ -0,0 +1,6 @@ +/* Form feed (\f) and vertical tab (\v) are whitespace in C. This file has both between + tokens. Returns 7. */ +int main(void) { + int x = 7; + return x; +} diff --git a/tests/c_programs/loops/invalid_parse/for_bad_condition.c b/tests/c_programs/loops/invalid_parse/for_bad_condition.c new file mode 100644 index 0000000..65026fe --- /dev/null +++ b/tests/c_programs/loops/invalid_parse/for_bad_condition.c @@ -0,0 +1,8 @@ +/* A malformed for-loop condition must be a parse error. Treating it as empty would make the + loop run forever. */ +int main(void) { + int x; + for (x = 0; x < ; x = x + 1) + ; + return 0; +} diff --git a/tests/c_programs/loops/invalid_parse/for_bad_init.c b/tests/c_programs/loops/invalid_parse/for_bad_init.c new file mode 100644 index 0000000..d564f27 --- /dev/null +++ b/tests/c_programs/loops/invalid_parse/for_bad_init.c @@ -0,0 +1,7 @@ +/* A malformed for-loop init must be a parse error, not silently treated as an empty clause. */ +int main(void) { + int x; + for (x = ; x < 3; x = x + 1) + ; + return 0; +} diff --git a/tests/c_programs/loops/invalid_parse/for_bad_post.c b/tests/c_programs/loops/invalid_parse/for_bad_post.c new file mode 100644 index 0000000..67de166 --- /dev/null +++ b/tests/c_programs/loops/invalid_parse/for_bad_post.c @@ -0,0 +1,8 @@ +/* A malformed for-loop post expression must be a parse error. Dropping it would also drop the + valid `i++`, so the loop would never end. */ +int main(void) { + int i; + for (i = 0; i < 10; i++ +) + ; + return 0; +} diff --git a/tests/c_programs/stack_slot_width.c b/tests/c_programs/stack_slot_width.c new file mode 100644 index 0000000..49538be --- /dev/null +++ b/tests/c_programs/stack_slot_width.c @@ -0,0 +1,42 @@ +/* A stack slot must be sized by its variable's type, not by the width of the first instruction + that touches it. In both cases below, a loop puts a narrower read of a `long` earlier in the + code than its first write: + - `(int)x` reads only the low 4 bytes of `x`; + - `1 << c` with `long c` reads the count at the shifted value's (int) width. + With 4-byte slots, the later 8-byte writes clobbered the neighbouring slot. + Returns the number of checks that held; expected result is 2. */ +int truncate_first(void) { + long x; + int keep; + int r; + for (int i = 0; i < 2; i = i + 1) { + if (i == 1) { + keep = 7; + r = (int) x; + x = 1311768464867721217l; /* high half nonzero: clobbers `keep` if x's slot is 4 bytes */ + return keep + r; /* 7 + 3 */ + } + x = 3; + } + return 0; +} + +int shift_count_first(void) { + long c; + int r; + for (int i = 0; i < 2; i = i + 1) { + if (i == 1) { + r = 1 << c; /* writes r's temp, which sat in c's upper half */ + return (int) (c >> 32); /* 5 */ + } + c = 21474836483l; /* 5 * 2^32 + 3 */ + } + return 0; +} + +int main(void) { + int passed = 0; + if (truncate_first() == 10) passed = passed + 1; + if (shift_count_first() == 5) passed = passed + 1; + return passed; /* expect 2 */ +} diff --git a/tests/c_programs/types/int_min_literal_is_long.c b/tests/c_programs/types/int_min_literal_is_long.c new file mode 100644 index 0000000..e24fef4 --- /dev/null +++ b/tests/c_programs/types/int_min_literal_is_long.c @@ -0,0 +1,20 @@ +/* `2147483648` doesn't fit int, so C types it `long`, and `-2147483648` is a `long` too (the + minus is an operator, not part of the literal). Arithmetic on it is done in 64 bits. + Returns the number of checks that held; expected result is 3. */ +int main(void) { + int passed = 0; + int c = 1; + + /* long arithmetic: no 32-bit wrap */ + long x = -2147483648 - 1; + if (x < 0) passed = passed + 1; + + /* common type of long and unsigned int is long, so the result stays negative */ + long v = c ? -2147483648 : 4294967295u; + if (v < 0) passed = passed + 1; + + /* as a long, negating it again gives +2^31; as an int it would wrap back to INT_MIN */ + if (-2147483648 / -1 > 0) passed = passed + 1; + + return passed; /* expect 3 */ +} diff --git a/tests/c_programs/warnings/no_shift_count.c b/tests/c_programs/warnings/no_shift_count.c index bdf9472..2cadfd1 100644 --- a/tests/c_programs/warnings/no_shift_count.c +++ b/tests/c_programs/warnings/no_shift_count.c @@ -5,5 +5,7 @@ int main(void) { int a = 1 << 5; /* in range for int (< 32) */ int b = 1 << n; /* non-constant count */ long c = 1L << 40; /* in range for long (< 64) — width follows the left operand */ + unsigned long d = 1ul << 40; /* unsigned long is 64 bits too */ + d >>= 63; return 0; } diff --git a/tests/runner.rs b/tests/runner.rs index 6d3289a..55f663d 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -1026,6 +1026,60 @@ fn test_function_symbol_sizes() { ); } +// Same as above: nm -S needs ELF symbol sizes, so Linux-only. +#[cfg(target_os = "linux")] +#[test] +fn test_double_negation_mask_size() { + // Regression test: the `xorps` sign-flip mask must be a 16-byte .rodata entry, because + // `xorps m128` reads 16 bytes. An 8-byte entry let the read run past the end of .rodata + // (harmless unless the section ends at a page boundary, so only visible in the object). + let test_file = "tests/c_programs/double_negation_mask.c"; + + let ncc_path = get_ncc_binary_path(); + + // `-c` writes `.o` next to the input, so compile a copy in the temp dir. + let src_path = std::env::temp_dir().join("ncc_negation_mask_test.c"); + let obj_path = std::env::temp_dir().join("ncc_negation_mask_test.o"); + std::fs::copy(test_file, &src_path).expect("failed to copy test source to temp dir"); + + let output = std::process::Command::new(&ncc_path) + .arg(&src_path) + .arg("-c") + .output() + .expect("Failed to execute ncc"); + assert!(output.status.success(), "ncc failed to compile {}", test_file); + + let nm = std::process::Command::new("nm") + .arg("-S") + .arg(&obj_path) + .output() + .expect("Failed to execute nm"); + assert!(nm.status.success(), "nm failed on {}", obj_path.display()); + + // nm -S read-only data lines: " r " + let nm_output = String::from_utf8_lossy(&nm.stdout); + let rodata_sizes: Vec = nm_output + .lines() + .filter_map(|line| { + let parts: Vec<&str> = line.split_whitespace().collect(); + match parts.as_slice() { + [_, size, "r", _] => u64::from_str_radix(size, 16).ok(), + _ => None, + } + }) + .collect(); + + let _ = std::fs::remove_file(&obj_path); + let _ = std::fs::remove_file(&src_path); + + assert!( + rodata_sizes.contains(&16), + "expected a 16-byte .rodata entry for the negation mask, got sizes {rodata_sizes:?}:\n{nm_output}" + ); + + println!("✓ Double negation mask size test passed"); +} + #[test] fn test_parser_printing() { // Test with a file that should generate labels From 298ec6735179f6bb1d336ad2afa40587167fd01b Mon Sep 17 00:00:00 2001 From: John Ring Date: Sun, 25 Oct 2026 09:48:23 -0400 Subject: [PATCH 3/6] Octal literals, line splicing, and the remaining review fixes Language: - Octal integer literals (leading 0), with C11 type ladders: unsuffixed octal can become unsigned (int -> unsigned int -> long -> unsigned long). 8 and 9 are rejected in octal; 08.5 stays a valid double. - Backslash-newline splicing before tokenizing (translation phase 2), with a byte -> source position table so spans stay accurate. `#` only starts a skipped line as the first non-blank character of a line. Semantics: - A block-scope extern that hides a local can't bind to a file-scope static (it would need both linkages); now an error. Diagnostics (all checked against gcc): - -Wswitch-unreachable follows gcc's reachability model - -Wsequence-point catches conflicts across &&/||/?: and call arguments - -Wshadow: silent for prototype params and function names; warns for an extern hiding a local - shift-count warnings in file-scope initializers - -Wconstant-conversion for automatic locals with constant initializers - parameter warnings point at the parameter; switch-on-double error has a location; correct messages for %/shift/bitwise on doubles in constant expressions; source names (not b.1) and "conflicting types" wording Every fix has a test that fails on the previous commit. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 32 ++- src/lexer.rs | 142 +++++++----- src/parser.rs | 214 ++++++++++++----- src/validate.rs | 216 ++++++++++++------ .../extern_conflicting_types.c | 8 + .../invalid_semantics/extern_hides_static.c | 12 + tests/c_programs/expected_results.json | 6 + .../lexer/invalid_lex/octal_bad_digit.c | 4 + .../c_programs/lexer/invalid_lex/stray_hash.c | 6 + tests/c_programs/lexer/line_splice.c | 14 ++ tests/c_programs/lexer/octal_literals.c | 30 +++ .../static_init_not_constant.c | 7 + .../const_remainder_double.c | 7 + .../warnings/constant_conversion_local.c | 6 + .../warnings/no_constant_conversion.c | 7 +- tests/c_programs/warnings/no_sequence_point.c | 1 + tests/c_programs/warnings/no_shadow.c | 20 ++ .../warnings/no_switch_unreachable.c | 13 ++ tests/c_programs/warnings/sequence_point.c | 10 +- tests/c_programs/warnings/shadow_extern.c | 11 + .../warnings/shift_count_file_scope.c | 6 + .../c_programs/warnings/switch_unreachable.c | 12 + tests/runner.rs | 123 +++++++++- 24 files changed, 708 insertions(+), 201 deletions(-) create mode 100644 tests/c_programs/declaration/invalid_semantics/extern_conflicting_types.c create mode 100644 tests/c_programs/declaration/invalid_semantics/extern_hides_static.c create mode 100644 tests/c_programs/lexer/invalid_lex/octal_bad_digit.c create mode 100644 tests/c_programs/lexer/invalid_lex/stray_hash.c create mode 100644 tests/c_programs/lexer/line_splice.c create mode 100644 tests/c_programs/lexer/octal_literals.c create mode 100644 tests/c_programs/static_vars/invalid_semantics/static_init_not_constant.c create mode 100644 tests/c_programs/types/invalid_semantics/const_remainder_double.c create mode 100644 tests/c_programs/warnings/constant_conversion_local.c create mode 100644 tests/c_programs/warnings/no_shadow.c create mode 100644 tests/c_programs/warnings/no_switch_unreachable.c create mode 100644 tests/c_programs/warnings/shadow_extern.c create mode 100644 tests/c_programs/warnings/shift_count_file_scope.c create mode 100644 tests/c_programs/warnings/switch_unreachable.c diff --git a/CLAUDE.md b/CLAUDE.md index 4aa6145..5404b6a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -93,7 +93,7 @@ Source .c → Lexer → Parser → Validator → Tackifier → Codegen → Emitt ### Core Passes (src/) -**Lexer** (`lexer.rs`): Tokenizes source using regex patterns with maximal munch. Each token carries a `Span` (file, line, column) for error reporting. Exit code 10 on error. +**Lexer** (`lexer.rs`): Joins backslash-newline line splices first, then tokenizes using regex patterns with maximal munch. Each token carries a `Span` (file, line, column) for error reporting. Exit code 10 on error. **Parser** (`parser.rs`): Recursive descent parser with precedence climbing. Builds an abstract AST representing C syntax. No semantic analysis yet—identifiers are just strings, types are not checked. Exit code 20 on error. diff --git a/README.md b/README.md index 9945726..eaae626 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ The compiler currently implements a subset of C with the following grammar: | "==" | "!=" | "<" | "<=" | ">" | ">=" ::= "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ::= ? An identifier token ? - ::= ? An integer constant token ? + ::= ? An integer constant token: decimal, or octal with a leading 0 (e.g. 017) ? ::= ? A long integer constant token (suffix 'l' or 'L') ? ::= ? An unsigned int constant token (suffix 'u' or 'U') ? ::= ? An unsigned long constant token (suffix combining 'u'/'U' and 'l'/'L') ? @@ -298,6 +298,13 @@ The compiler supports: - `goto` and labeled statements - `return` statements - **Expression statements** and **null statements** +- **Integer literals**: decimal and octal (a leading `0`, e.g. `0755`), with `u`/`l` suffixes. Each literal takes the + first type that holds its value, per C11 6.4.4.1: decimal goes `int` → `long`, while octal can also become + unsigned (`int` → `unsigned int` → `long` → `unsigned long`), so `037777777777` is an `unsigned int`. Hexadecimal + is not supported yet +- **Line splicing**: a backslash at the end of a line joins it with the next before tokenizing, anywhere in the source + (inside tokens and `//` comments too). There is no preprocessor: a line whose first non-blank character is `#` is + skipped, along with any lines spliced onto it ### Safer C @@ -334,10 +341,14 @@ NCC provides several safety features and guarantees to help developers write mor #### Compile-Time Warnings -- **Variable shadowing** (`-Wshadow`): Warns when a variable declaration shadows a previous declaration in an outer - scope -- **Unreachable switch code** (`-Wswitch-unreachable`): Warns about statements before the first `case` label in a - switch, which can never be executed +- **Variable shadowing** (`-Wshadow`): Warns when a variable or parameter declaration shadows a variable in an outer + scope, including a block-scope `extern` that hides a local. Like gcc, it stays silent for prototype parameter + names and for variables that shadow a function +- **Unreachable switch code** (`-Wswitch-unreachable`): Warns about code before the first label in a switch body, + which can never be executed: a statement, an initialized declaration, or the first part of a construct that runs + before any label inside it (an `if` condition, a `for` initializer, a nested switch's controlling expression). + Empty statements, uninitialized declarations, labeled statements, and loops entered through a `case` inside them + are reachable or harmless, and don't warn (matching gcc) - **Unused parameters** (`-Wunused-parameter`): Warns when a function parameter is declared but never used in the function body - **Division by zero** (`-Wdiv-by-zero`): Warns when `/` or `%`, including the compound forms `/=` and `%=`, has @@ -350,12 +361,13 @@ NCC provides several safety features and guarantees to help developers write mor static initializer or case label overflows the result type (e.g. `int x = 2147483647 + 1;`). NCC wraps deterministically (two's complement) rather than treating it as undefined, so this flags non-portable code instead of erroring. Unsigned wraparound is well-defined and is *not* warned (matching gcc/clang) -- **Constant changed by an implicit conversion** (`-Wconstant-conversion`): Warns when a constant initializer is - implicitly narrowed to a type that can't hold it (e.g. `int x = 2147483648;`, which truncates to `-2147483648`). - An explicit cast (`int x = (int)2147483648;`) silences it +- **Constant changed by an implicit conversion** (`-Wconstant-conversion`): Warns when a constant initializer (of a + static, file-scope, or automatic variable) is implicitly narrowed to a type that can't hold it (e.g. + `int x = 2147483648;`, which truncates to `-2147483648`). An explicit cast (`int x = (int)2147483648;`) silences it - **Unsequenced modification** (`-Wsequence-point`): Warns when the same object is modified more than once between - sequence points (e.g. `i = i++`, `i++ + i++`, `f(i++, i++)`) — undefined in standard C. NCC evaluates left-to-right - so the result is well-defined, but the code is non-portable + sequence points (e.g. `i = i++`, `i++ + i++`, `f(i++, i++)`, `i++ + f(i++)`) — undefined in standard C. `&&`, `||` + and `?:` sequence their own operands, but not against the rest of the expression, so `(j && i++) + i++` also warns. + NCC evaluates left-to-right so the result is well-defined, but the code is non-portable #### Developer Experience diff --git a/src/lexer.rs b/src/lexer.rs index c53091e..cbb5224 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -13,16 +13,22 @@ //! //! ## What This Pass Accomplishes //! -//! - Strips comments (`//`, `/* */`, `#` line directives) +//! - Joins backslash-newline line splices first (C translation phase 2), keeping each byte's +//! original position for spans +//! - Strips comments (`//`, `/* */`) and `#` lines (only when `#` starts the line; a stray `#` +//! elsewhere is an error) //! - Produces a [`VecDeque`] carrying line/column [`Span`]s for error reporting //! - Detects lexer errors (unexpected characters, unterminated comments) and exits with code 10 //! - Promotes integer literals with an `L`/`l` suffix to [`Token::ConstantLong`] +//! - Keeps integer lexemes as written (a leading `0` marks octal, which the parser reads in base 8) +//! and rejects the digits 8 and 9 in octal literals //! - Recognizes floating-point literals (fraction and/or exponent) as [`Token::ConstantDouble`] //! //! ## Call Order //! //! ```text //! tokenizer() — public entry point, drives the scan loop +//! ├─ splice_lines() — joins backslash-newlines, maps bytes back to source positions //! └─ next_token() — tries all TOKEN_DEFS, returns longest match //! ``` @@ -278,6 +284,20 @@ fn next_token(input: &str, span: Span) -> Result { } } if let Some(best_match) = matches.iter().max_by_key(|m| m.length) { + // A leading `0` makes an integer literal octal, so 8 and 9 are invalid in it. Checked on + // the winning match only: `08.5` and `09e1` are decimal floating literals, which is fine. + if let Token::ConstantInt(digits) + | Token::ConstantLong(digits) + | Token::ConstantUnsignedInt(digits) + | Token::ConstantUnsignedLong(digits) = &best_match.token + && digits.starts_with('0') + && digits.contains(['8', '9']) + { + return Err(LexerError::with_span( + format!("invalid digit in octal constant: {}", digits.bold()), + span, + )); + } Ok(best_match.clone()) } else { let preview = if input.len() > 20 { @@ -315,69 +335,77 @@ impl fmt::Debug for LexerError { } } -pub(crate) fn tokenizer(mut input: &str) -> Result, LexerError> { +/// Joins lines ending in a backslash (C translation phase 2), before any tokenizing. +/// +/// Returns the spliced text and, for every byte of it, the original 1-based (line, column) it +/// came from, so spans still point at the source the user wrote. A splice can fall anywhere, +/// even inside a token (`ret\` + newline + `urn` is `return`) or a `//` comment, which then +/// continues onto the next line. +fn splice_lines(source: &str) -> (String, Vec) { + let mut text = String::with_capacity(source.len()); + let mut positions = Vec::with_capacity(source.len() + 1); + let (mut line, mut column) = (1, 1); + let mut rest = source; + while let Some(c) = rest.chars().next() { + let splice_len = if rest.starts_with("\\\n") { + 2 + } else if rest.starts_with("\\\r\n") { + 3 + } else { + 0 + }; + if splice_len > 0 { + line += 1; + column = 1; + rest = &rest[splice_len..]; + continue; + } + text.push(c); + // one entry per byte, so any byte offset into `text` can be looked up + positions.extend(std::iter::repeat_n(Span { line, column }, c.len_utf8())); + if c == '\n' { + line += 1; + column = 1; + } else { + column += c.len_utf8(); + } + rest = &rest[c.len_utf8()..]; + } + positions.push(Span { line, column }); // end of input + (text, positions) +} + +pub(crate) fn tokenizer(source: &str) -> Result, LexerError> { + let (text, positions) = splice_lines(source); let mut tokens = VecDeque::new(); - let mut line = 1; - let mut col = 1; + let mut input = text.as_str(); + // Original source position of the current scan point. + let pos = |input: &str| positions[text.len() - input.len()]; + // `#` starts a (skipped) preprocessing directive only as the first non-blank character of a + // line. Anywhere else it's a stray character, which `next_token` rejects. + let mut at_line_start = true; while !input.is_empty() { // C whitespace also includes form feed and vertical tab - let trimmed = input.trim_start_matches([' ', '\t', '\r', '\x0C', '\x0B']); - col += input.len() - trimmed.len(); - input = trimmed; + input = input.trim_start_matches([' ', '\t', '\r', '\x0C', '\x0B']); - // check for comments and skip them need to support both // and /* */ - // also skipping # for now - if ["//", "\n", "#"].iter().any(|s| input.starts_with(s)) { - // same line, col logic - if let Some(newline_index) = input.find('\n') { - line += 1; - col = 1; - input = &input[newline_index + 1..]; - } else { - // End of file reached with // or # comment - skip rest of input - break; - } - continue; + if input.starts_with('\n') { + input = &input[1..]; + at_line_start = true; + } else if input.starts_with("//") || (at_line_start && input.starts_with('#')) { + // Skip to the end of the line; the newline itself is handled next iteration. + input = &input[input.find('\n').unwrap_or(input.len())..]; } else if input.starts_with("/*") { // Search past the opening `/*` so `/*/` doesn't pair its own `*` with the `/` - if let Some(end_comment_index) = input[2..].find("*/").map(|i| i + 2) { - let comment = &input[..end_comment_index + 2]; - let newline_count = comment.matches('\n').count(); - if newline_count > 0 { - line += newline_count; - // Set col to the position after the last newline in the comment - if let Some(last_newline) = comment.rfind('\n') { - col = comment.len() - last_newline; - } else { - col += comment.len(); - } - } else { - col += comment.len(); - } - input = &input[end_comment_index + 2..]; - } else { - return Err(LexerError::with_span( - "unterminated comment".to_string(), - Span { line, column: col }, - )); - } - continue; - } - - if input.is_empty() { - break; - } - - match next_token(input, Span { line, column: col }) { - Ok(TokenMatch { token, length }) => { - tokens.push_back(SpannedToken { - token, - span: Span { line, column: col }, - }); - col += length; // no newline in tokens - input = &input[length..]; + match input[2..].find("*/") { + Some(i) => input = &input[i + 4..], + None => return Err(LexerError::with_span("unterminated comment".to_string(), pos(input))), } - Err(e) => return Err(e), + } else if !input.is_empty() { + let span = pos(input); + let TokenMatch { token, length } = next_token(input, span)?; + tokens.push_back(SpannedToken { token, span }); + input = &input[length..]; + at_line_start = false; } } Ok(tokens) diff --git a/src/parser.rs b/src/parser.rs index edda247..9fe6b72 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -359,12 +359,18 @@ pub struct VarDeclaration { pub var_type: Type, pub storage_class: Option, pub span: Span, + /// Set by the resolve pass on a block-scope `extern` declared while a local variable hides + /// every earlier declaration of the name. Such an `extern` can't inherit internal linkage + /// from a file-scope `static` (C11 6.2.2p4), so the type checker must reject that pairing. + pub prior_linkage_hidden: bool, } #[derive(Debug, Clone)] pub struct FunDeclaration { pub name: Identifier, pub params: Vec, + /// Source location of each parameter's name, parallel to `params` (for diagnostics). + pub param_spans: Vec, pub body: Option, pub fun_type: Type, pub storage_class: Option, @@ -486,12 +492,18 @@ fn expect(expected: &Token, tokens: &mut VecDeque) -> Result) -> Result Result { - match &token.token { - Token::ConstantInt(value_str) => match value_str.parse::() { - Ok(val) => Ok(Expr::Constant(Const::ConstInt(val))), - Err(_) => parse_constant(&SpannedToken { - token: Token::ConstantLong(value_str.clone()), - span: token.span, - }), - }, - Token::ConstantUnsignedInt(value_str) => match value_str.parse::() { - Ok(val) => Ok(Expr::Constant(Const::ConstUInt(val))), - Err(_) => parse_constant(&SpannedToken { - token: Token::ConstantUnsignedLong(value_str.clone()), - span: token.span, - }), - }, - Token::ConstantLong(value_str) => match value_str.parse::() { - Ok(val) => Ok(Expr::Constant(Const::ConstLong(val))), - Err(_) => Err(SyntaxError::with_span( - format!( - "Integer constant '{}' does not fit in 64-bit signed int", - value_str.bold() - ), - Some(token.span), - )), - }, - Token::ConstantUnsignedLong(value_str) => match value_str.parse::() { - Ok(val) => Ok(Expr::Constant(Const::ConstULong(val))), - Err(_) => Err(SyntaxError::with_span( - format!( - "Integer constant '{}' does not fit in 64-bit unsigned int", - value_str.bold() - ), - Some(token.span), - )), - }, + use Const::*; + // Each candidate converts the value if it fits that type. + type Candidate = fn(i128) -> Option; + let int: Candidate = |v| i32::try_from(v).ok().map(ConstInt); + let uint: Candidate = |v| u32::try_from(v).ok().map(ConstUInt); + let long: Candidate = |v| i64::try_from(v).ok().map(ConstLong); + let ulong: Candidate = |v| u64::try_from(v).ok().map(ConstULong); + + let (value_str, ladder): (&String, &[Candidate]) = match &token.token { + Token::ConstantInt(v) if is_octal_literal(v) => (v, &[int, uint, long, ulong]), + Token::ConstantInt(v) => (v, &[int, long]), + Token::ConstantUnsignedInt(v) => (v, &[uint, ulong]), + Token::ConstantLong(v) if is_octal_literal(v) => (v, &[long, ulong]), + Token::ConstantLong(v) => (v, &[long]), + Token::ConstantUnsignedLong(v) => (v, &[ulong]), Token::ConstantDouble(value_str) => { let val = value_str .parse::() .expect("lexer regex guarantees a valid float literal"); warn_overflow(val, value_str, token.span); - Ok(Expr::Constant(Const::ConstDouble(val))) + return Ok(Expr::Constant(Const::ConstDouble(val))); } _ => unreachable!(), + }; + + let (negative, digits) = match value_str.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, value_str.as_str()), + }; + let radix = if is_octal_literal(digits) { 8 } else { 10 }; + // i128 holds every 64-bit magnitude; anything that doesn't parse is too big for any type. + let value = i128::from_str_radix(digits, radix) + .ok() + .map(|v| if negative { -v } else { v }); + match value.and_then(|v| ladder.iter().find_map(|fits| fits(v))) { + Some(c) => Ok(Expr::Constant(c)), + None => Err(SyntaxError::with_span( + format!("Integer constant '{}' is too large for its type", value_str.bold()), + Some(token.span), + )), } } +/// True for an octal integer lexeme: a leading `0` followed by more digits (`0` alone is decimal, +/// though the two readings agree). The lexer has already rejected the digits 8 and 9 in these. +fn is_octal_literal(digits: &str) -> bool { + digits.len() > 1 && digits.starts_with('0') +} + /// True if `t` is a type-specifier keyword (`int`, `long`, `signed`, `unsigned`, `double`). fn is_type_specifier(t: &Token) -> bool { matches!( @@ -599,16 +614,24 @@ fn parse_factor(tokens: &mut VecDeque) -> Result().is_err() && format!("-{v}").parse::().is_ok() ); + let is_octal = matches!( + tokens.get(1), + Some(SpannedToken { token: Token::ConstantInt(v) | Token::ConstantLong(v), .. }) + if is_octal_literal(v) + ); if let Some(SpannedToken { token: Token::ConstantInt(value_str) | Token::ConstantLong(value_str), span: _, }) = tokens.get_mut(1) && !is_int_min_magnitude + && !is_octal { *value_str = format!("-{value_str}"); tokens.pop_front(); @@ -1055,7 +1078,7 @@ fn parse_statement(tokens: &mut VecDeque) -> Result) -> Result bool { + let has_for_init = |init: &ForInit| match init { + ForInit::InitDecl(decl) => decl.init.is_some(), + ForInit::InitExp(exp) => exp.is_some(), + }; match &stmt.stmt { - Stmt::Case(..) | Stmt::Default(..) | Stmt::Null => {} - Stmt::Compound(block) => { - if let Some(BlockItem::Statement(s)) = block.first() { - warn_switch_unreachable(s) + Stmt::Null => false, + Stmt::Compound(block) => block.iter().any(|item| match item { + BlockItem::Statement(s) => first_unreachable(s), + BlockItem::Declaration(Declaration::VarDeclaration(VarDeclaration { + init: Some(_), span, .. + })) => { + warn_switch_unreachable(*span); + true } + BlockItem::Declaration(_) => false, + }), + Stmt::Labeled(..) | Stmt::Case(..) | Stmt::Default(..) => true, + Stmt::While(..) | Stmt::DoWhile(..) if contains_label(stmt, false) => true, + Stmt::For(init, ..) if !has_for_init(init) && contains_label(stmt, false) => true, + _ => { + warn_switch_unreachable(stmt.span); + true } - _ => eprintln!( - "{}: {}: statement will never be executed {}", - stmt.span, - "warning".purple(), - "[-Wswitch-unreachable]".purple() - ), } } +/// True if `stmt` contains a label that control can jump to from outside it: any `goto` label, or +/// a `case`/`default` that belongs to the enclosing switch (`in_nested_switch` excludes the ones +/// owned by a switch nested inside `stmt`). +fn contains_label(stmt: &SpannedStmt, in_nested_switch: bool) -> bool { + match &stmt.stmt { + Stmt::Labeled(..) => true, + Stmt::Case(..) | Stmt::Default(..) if !in_nested_switch => true, + Stmt::Case(_, s, _) | Stmt::Default(s, _) => contains_label(s, in_nested_switch), + Stmt::Switch(_, s, _, _) => contains_label(s, true), + Stmt::If(_, then_s, else_s) => { + contains_label(then_s, in_nested_switch) + || else_s + .as_ref() + .as_ref() + .is_some_and(|e| contains_label(e, in_nested_switch)) + } + Stmt::While(_, s, _) | Stmt::DoWhile(s, _, _) | Stmt::For(_, _, _, s, _) => contains_label(s, in_nested_switch), + Stmt::Compound(block) => block.iter().any(|item| match item { + BlockItem::Statement(s) => contains_label(s, in_nested_switch), + BlockItem::Declaration(_) => false, + }), + Stmt::Return(_) | Stmt::Expression(_) | Stmt::Goto(_) | Stmt::Break(_) | Stmt::Continue(_) | Stmt::Null => { + false + } + } +} + +/// `-Wswitch-unreachable`: the code at `span` comes before every label in a switch body. +fn warn_switch_unreachable(span: Span) { + eprintln!( + "{}: {}: statement will never be executed {}", + span, + "warning".purple(), + "[-Wswitch-unreachable]".purple() + ); +} + /// `-Woverflow`: a floating-point literal that can't be represented in `double`. C makes an /// out-of-range floating constant undefined behavior; like every real implementation, NCC rounds it /// (too large -> infinity, too small -> zero) rather than rejecting it, so this flags the silent @@ -1173,7 +1258,7 @@ fn parse_declaration( if tokens.front().map(|t| &t.token) == Some(&Token::OpenParen) { // function declaration tokens.pop_front(); - let (params, types) = parse_function_params(tokens, &Some(span))?; + let (params, param_spans, types) = parse_function_params(tokens, &Some(span))?; let body = parse_function_body(tokens)?; let defined = body.is_some(); @@ -1181,6 +1266,7 @@ fn parse_declaration( Ok(Some(Declaration::FunDeclaration(FunDeclaration { name, params, + param_spans, body, fun_type: Type::FunType { params: types, @@ -1203,6 +1289,7 @@ fn parse_declaration( var_type: type_class, storage_class, span, + prior_linkage_hidden: false, }))) } } else { @@ -1255,15 +1342,19 @@ fn parse_arg_comma(tokens: &mut VecDeque) -> Result<(), SyntaxErro } } +/// Parameter names, their spans, and their types, as parallel vecs. +type ParamList = (Vec, Vec, Vec); + /// Parses a function's parameter list (after the opening parenthesis). /// /// Handles `void` for no parameters, or a comma-separated list of typed parameters. -/// Consumes the closing `)`. Returns parallel vecs of parameter names and their types. +/// Consumes the closing `)`. Returns parallel vecs of parameter names, their spans, and their types. fn parse_function_params( tokens: &mut VecDeque, err_span: &Option, -) -> Result<(Vec, Vec), SyntaxError> { +) -> Result { let mut params = vec![]; + let mut spans = vec![]; let mut types = vec![]; if let Some(front) = tokens.front().cloned() { if front.token == Token::VoidKeyword { @@ -1285,13 +1376,14 @@ fn parse_function_params( )); } types.push(parse_type(&type_tokens, &err_span)?); - let (name, _span) = parse_identifier(tokens)?; + let (name, span) = parse_identifier(tokens)?; params.push(name.clone()); + spans.push(span); parse_arg_comma(tokens)?; } } expect(&Token::CloseParen, tokens)?; - Ok((params, types)) + Ok((params, spans, types)) } else { Err(SyntaxError::with_span( "EOF when parsing function parameters".to_string(), diff --git a/src/validate.rs b/src/validate.rs index 1982b38..be4c79e 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -469,6 +469,9 @@ struct VarInfo { renamed: Rc, span: Span, ext_link: bool, + /// Functions and variables share the identifier namespace. Like gcc, `-Wshadow` doesn't + /// fire when a variable shadows a function. + is_function: bool, } pub struct NameGenerator { @@ -505,6 +508,7 @@ impl NameGenerator { /// /// **none (automatic)**: Regular local variable with automatic storage /// - Initializer is typechecked and converted to variable's type +/// - A constant initializer whose value the conversion changes emits `-Wconstant-conversion` /// - Added to symbol table with `global: false` /// - `defined: true` (allocates stack storage) /// @@ -522,9 +526,26 @@ fn typecheck_local_variable_declaration( } if let Some(old_dec) = symbols.get(&decl.name.0) { if old_dec.symbol_type != decl.var_type { + let what = if matches!(old_dec.symbol_type, Type::FunType { .. }) { + "redeclared as different kind of symbol" + } else { + "has conflicting types" + }; return Err(SemanticError::with_span( format!( - "'{}' redeclared as different kind of symbol\n{}: {}: previous declaration was here", + "'{}' {what}\n{}: {}: previous declaration was here", + decl.name.0.bold(), + old_dec.span, + "note".cyan() + ), + decl.span, + )); + } + if decl.prior_linkage_hidden && !old_dec.global { + return Err(SemanticError::with_span( + format!( + "'{}' declared 'extern' while a local hides its 'static' declaration, so it \ + would need both external and internal linkage\n{}: {}: 'static' declaration was here", decl.name.0.bold(), old_dec.span, "note".cyan() @@ -567,7 +588,13 @@ fn typecheck_local_variable_declaration( }, ); } else { - // Automatic storage (no storage class specifier) + // Automatic storage (no storage class specifier). A constant initializer is converted at + // run time, but its value is known now, so a lossy conversion still gets + // -Wconstant-conversion, as for statics. Non-constant initializers are skipped. + if let Some(Ok((value, _))) = decl.init.as_ref().map(eval_constant_expr) { + let (converted, changed) = convert_to_type(value, &decl.var_type); + warn_constant_conversion(changed, &value, &converted, decl.span); + } symbols.insert( decl.name.0.clone(), Symbol { @@ -613,7 +640,11 @@ fn typecheck_file_variable_declaration( symbols: &mut SymbolTable, ) -> Result { let mut initial_value = if let Some(expr) = &decl.init { - eval_static_initializer(expr, &decl.var_type, &decl.name, decl.span)? + let value = eval_static_initializer(expr, &decl.var_type, &decl.name, decl.span)?; + // The value comes from constant evaluation; type-checking the expression too (result + // discarded) emits its expression-level warnings, e.g. -Wshift-count-*, as for locals. + typecheck_exp(expr.clone(), symbols)?; + value } else if decl.storage_class == Some(StorageClass::Extern) { InitialValue::NoInitializer } else { @@ -736,8 +767,13 @@ fn check_sequence_points(expr: &ParserExpr) { } /// Walks `expr` within the current unsequenced region, recording modifications into `region`. -/// Sequence-point operators (`&&`, `||`, `?:`, and function-call arguments) start fresh regions -/// via [`check_sequence_points`]; everything else shares the region with its operands. +/// +/// `&&`, `||` and `?:` have a sequence point after their first operand, so each operand is walked +/// in its own region (catching double modifications inside it). The operator as a whole is still +/// unsequenced relative to its siblings, though: `(j && i++) + i++` modifies `i` twice. So the +/// operands' modifications are then merged into `region`, as a union first, since `i++ && i++` +/// itself is fine. Call arguments are unsequenced among themselves *and* relative to the rest of +/// the enclosing expression (`i++ + f(i++)`), so they share `region` directly. fn walk_region(expr: &ParserExpr, region: &mut HashMap, Span>) { match expr { ParserExpr::Assignment(lhs, rhs, span) | ParserExpr::CompoundAssignment(_, lhs, rhs, span) => { @@ -749,25 +785,17 @@ fn walk_region(expr: &ParserExpr, region: &mut HashMap, Span>) { } ParserExpr::Binary(op, lhs, rhs, _) => { if matches!(op, BinOp::And | BinOp::Or) { - // sequence points - check_sequence_points(lhs); - check_sequence_points(rhs); + walk_sequenced(&[lhs, rhs], region); } else { walk_region(lhs, region); walk_region(rhs, region); } } ParserExpr::Unary(_, e, _) | ParserExpr::Cast(_, e) => walk_region(e, region), - ParserExpr::Conditional(c, t, f) => { - check_sequence_points(c); - check_sequence_points(t); - check_sequence_points(f); - } + ParserExpr::Conditional(c, t, f) => walk_sequenced(&[c, t, f], region), ParserExpr::FunctionCall(_, args, _) => { - // args have no sequence points between them - let mut arg_region = HashMap::new(); for a in args { - walk_region(a, &mut arg_region); + walk_region(a, region); } } ParserExpr::Var(..) | ParserExpr::Constant(..) => {} @@ -778,9 +806,29 @@ fn walk_region(expr: &ParserExpr, region: &mut HashMap, Span>) { /// subset). A second modification of the same object in the current region is an unsequenced /// double-modification — emit `-Wsequence-point`. fn warn_sequence_point(target: &ParserExpr, span: Span, region: &mut HashMap, Span>) { - if let ParserExpr::Var(Identifier(name), _) = target - && region.insert(name.clone(), span).is_some() - { + if let ParserExpr::Var(Identifier(name), _) = target { + record_modification(name, span, region); + } +} + +/// Walks operands that are separated by sequence points (see [`walk_region`]): each in its own +/// region, then the union of their modifications is recorded in the enclosing `region`. +fn walk_sequenced(operands: &[&ParserExpr], region: &mut HashMap, Span>) { + let mut modified: HashMap, Span> = HashMap::new(); + for operand in operands { + let mut own = HashMap::new(); + walk_region(operand, &mut own); + modified.extend(own); + } + for (name, span) in modified { + record_modification(&name, span, region); + } +} + +/// `-Wsequence-point`: records that `name` is modified at `span`, and emits the warning if +/// `region` already has a modification of it. +fn record_modification(name: &Rc, span: Span, region: &mut HashMap, Span>) { + if region.insert(name.clone(), span).is_some() { eprintln!( "{}: {}: '{}' modified more than once between sequence points (undefined in standard C; NCC evaluates left-to-right) {}", span, @@ -881,6 +929,12 @@ fn warn_constant_conversion(changed: bool, from: &StaticInit, to: &StaticInit, s } } +/// The span to report for `-Wshadow` when a declaration replaced `shadow` in the scope map: +/// `None` if nothing was shadowed or the shadowed name is a function (gcc doesn't warn then). +fn shadowed_variable_span(shadow: Option<&VarInfo>) -> Option { + shadow.filter(|s| !s.is_function).map(|s| s.span) +} + /// `-Wshadow`: a declaration shadows one in an outer scope. `prev` is the shadowed entry's span /// (the value returned when inserting into the scope map), or `None` if nothing was shadowed. /// Emits the warning plus a note pointing at the previous declaration. @@ -977,10 +1031,9 @@ fn typecheck_exp(exp: ParserExpr, symbols: &mut SymbolTable) -> Result Ok(unary_exp.with_type(Type::Int)), - UnaryOp::BitwiseComplement if !inner_type.is_integer() => Err(SemanticError::with_span( - "bitwise complement '~' requires an integer operand".to_string(), - span, - )), + UnaryOp::BitwiseComplement if !inner_type.is_integer() => { + Err(SemanticError::with_span(COMPLEMENT_DOUBLE_MSG.to_string(), span)) + } _ => Ok(unary_exp.with_type(inner_type)), } } @@ -1017,10 +1070,7 @@ fn typecheck_exp(exp: ParserExpr, symbols: &mut SymbolTable) -> Result Result { - let typed_stmt = typecheck_stmt(stmt.stmt, symbols, ret_type)?; + let typed_stmt = typecheck_stmt(stmt.stmt, stmt.span, symbols, ret_type)?; typed_items.push(BlockItem::Statement(typed_stmt)); } } @@ -1308,7 +1355,13 @@ fn typecheck_block(block: ParserBlock, symbols: &mut SymbolTable, ret_type: &Typ /// `ret_type` is the enclosing function's return type, used to insert implicit casts /// on `return` expressions. Switch statements normalize case values to the controlling /// expression's type and check for duplicates. -fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) -> Result { +/// `span` is the statement's location, for diagnostics about the statement as a whole. +fn typecheck_stmt( + stmt: ParserStmt, + span: Span, + symbols: &mut SymbolTable, + ret_type: &Type, +) -> Result { match stmt { ParserStmt::Return(e1) => { let typed_e1 = typecheck_exp(e1, symbols)?; @@ -1321,9 +1374,9 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) } ParserStmt::If(cond, then_s, else_s) => { let typed_cond = typecheck_exp(cond, symbols)?; - let converted_then = typecheck_stmt(then_s.stmt, symbols, ret_type)?; + let converted_then = typecheck_stmt(then_s.stmt, then_s.span, symbols, ret_type)?; let typed_else = (*else_s) - .map(|e| typecheck_stmt(e.stmt, symbols, ret_type)) + .map(|e| typecheck_stmt(e.stmt, e.span, symbols, ret_type)) .transpose()? .map(Box::new); Ok(Stmt::If(typed_cond, Box::new(converted_then), typed_else)) @@ -1333,11 +1386,11 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) ParserStmt::Break(lbl) => Ok(Stmt::Break(lbl)), ParserStmt::Continue(lbl) => Ok(Stmt::Continue(lbl)), ParserStmt::Labeled(lbl, s) => { - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; Ok(Stmt::Labeled(lbl, Box::new(typed_s))) } ParserStmt::Default(s, lbl) => { - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; Ok(Stmt::Default(Box::new(typed_s), lbl)) } ParserStmt::Compound(block) => { @@ -1346,12 +1399,12 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) } ParserStmt::While(e, s, lbl) => { let typed_e = typecheck_exp(e, symbols)?; - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; Ok(Stmt::While(typed_e, Box::new(typed_s), lbl)) } ParserStmt::DoWhile(s, e, lbl) => { let typed_e = typecheck_exp(e, symbols)?; - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; Ok(Stmt::DoWhile(Box::new(typed_s), typed_e, lbl)) } ParserStmt::Switch(e, s, lbl, cases) => { @@ -1361,10 +1414,10 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) // The controlling expression must have integer type (C §6.8.4.2). Reject `double` here, // before `as_i64` normalizes case values against it (that would otherwise panic). if !switch_type.is_integer() { - return Err(SemanticError { - message: "switch controlling expression must have integer type".to_string(), - span: None, - }); + return Err(SemanticError::with_span( + "switch controlling expression must have integer type".to_string(), + span, + )); } // Normalize cases and check for duplicates @@ -1389,13 +1442,13 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) } } - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; // Convert Vec to HashSet for output (tacky doesn't need spans) let cases_set = cases.iter().map(|(c, _span)| *c).collect(); Ok(Stmt::Switch(typed_e, Box::new(typed_s), lbl, cases_set)) } ParserStmt::Case(e, s, lbl) => { - let typed_s = typecheck_stmt(s.stmt, symbols, ret_type)?; + let typed_s = typecheck_stmt(s.stmt, s.span, symbols, ret_type)?; let typed_e = typecheck_exp(e, symbols)?; Ok(Stmt::Case(typed_e, Box::new(typed_s), lbl)) } @@ -1419,7 +1472,7 @@ fn typecheck_stmt(stmt: ParserStmt, symbols: &mut SymbolTable, ret_type: &Type) }; let typed_cond = cond.map(|e| typecheck_exp(e, symbols)).transpose()?; let typed_post = post.map(|e| typecheck_exp(e, symbols)).transpose()?; - let typed_body = typecheck_stmt(body.stmt, symbols, ret_type)?; + let typed_body = typecheck_stmt(body.stmt, body.span, symbols, ret_type)?; Ok(Stmt::For( Box::new(typed_init), typed_cond, @@ -1533,6 +1586,7 @@ fn resolve_fun_decoration( renamed: name.clone(), span: dec.span, ext_link: true, + is_function: true, }, ); if let Some(shadow) = shadow @@ -1556,8 +1610,10 @@ fn resolve_fun_decoration( let mut inner_block_vars = HashSet::new(); let original_params: Vec> = dec.params.iter().map(|Identifier(name)| name.clone()).collect(); - for param in &mut dec.params { - resolve_param(param, &mut inner_map, name_gen, &mut inner_block_vars, dec.span)?; + // A prototype's parameter names are only documentation, so they don't shadow anything. + let has_body = dec.body.is_some(); + for (param, &span) in dec.params.iter_mut().zip(&dec.param_spans) { + resolve_param(param, &mut inner_map, name_gen, &mut inner_block_vars, span, has_body)?; } if let Some(block) = &mut dec.body { @@ -1571,20 +1627,24 @@ fn resolve_fun_decoration( used_vars, )?; } - if dec.body.is_some() { - for (Identifier(param), org_name) in dec.params.iter().zip(original_params) { - warn_unused_parameter(used_vars.contains(param), &org_name, dec.span); + if has_body { + for ((Identifier(param), org_name), &span) in dec.params.iter().zip(original_params).zip(&dec.param_spans) { + warn_unused_parameter(used_vars.contains(param), &org_name, span); } } Ok(()) } +/// Resolves one function parameter: gives it a unique name in the function's scope (a duplicate +/// parameter name is an error). In a definition (`has_body`), emits `-Wshadow` if it shadows a +/// variable; a prototype's parameter names are only documentation, so they never warn. fn resolve_param( param: &mut Identifier, variable_map: &mut HashMap, VarInfo>, name_gen: &mut NameGenerator, block_vars: &mut HashSet>, span: Span, + has_body: bool, ) -> Result<(), SemanticError> { let Identifier(name) = param.clone(); @@ -1597,9 +1657,12 @@ fn resolve_param( renamed: unique_name.clone(), span, ext_link: false, + is_function: false, }, ); - warn_shadow(&name, span, shadow.map(|s| s.span)); + if has_body { + warn_shadow(&name, span, shadowed_variable_span(shadow.as_ref())); + } *param = Identifier(unique_name); Ok(()) } else { @@ -1631,6 +1694,7 @@ fn resolve_file_var_declaration(dec: &mut VarDeclaration, variable_map: &mut Has renamed: name.clone(), span: dec.span, ext_link: true, + is_function: false, }, ); } @@ -1645,6 +1709,7 @@ fn resolve_file_var_declaration(dec: &mut VarDeclaration, variable_map: &mut Has /// **extern**: References an external variable /// - Keeps original name (no renaming) /// - Marked with `ext_link: true` +/// - If it hides a local, emits `-Wshadow` and sets `prior_linkage_hidden` (see that field) /// /// **static or automatic**: Local variable /// - Gets a unique renamed identifier (e.g., `x` → `x.1`) @@ -1677,14 +1742,24 @@ fn resolve_local_var_decoration( )); } if dec.storage_class == Some(StorageClass::Extern) { - variable_map.insert( + let shadow = variable_map.insert( name.clone(), VarInfo { renamed: name.clone(), span: dec.span, ext_link: true, + is_function: false, }, ); + // Shadowing a local (no linkage) hides every earlier declaration, so this `extern` can't + // inherit a file-scope `static`'s internal linkage. It names a *different* object than + // the local, so it also warrants -Wshadow; redeclaring a linked name does not. + if let Some(shadow) = shadow + && !shadow.ext_link + { + dec.prior_linkage_hidden = true; + warn_shadow(name, dec.span, Some(shadow.span)); + } } else { let unique_name = name_gen.next(name); dec.name = Identifier(unique_name.clone()); @@ -1694,9 +1769,10 @@ fn resolve_local_var_decoration( renamed: unique_name.clone(), span: dec.span, ext_link: false, + is_function: false, }, ); - warn_shadow(name, dec.span, shadow.map(|s| s.span)); + warn_shadow(name, dec.span, shadowed_variable_span(shadow.as_ref())); if let Some(init_expr) = &mut dec.init { check_sequence_points(init_expr); resolve_exp(init_expr, variable_map, used_vars)?; @@ -1926,7 +2002,19 @@ fn convert_to_type(val: StaticInit, target_type: &Type) -> (StaticInit, bool) { enum ConstEvalError { NotConstant, DivByZero, - InvalidType, + /// An operator applied to a `double` that requires integers; carries the diagnostic. + InvalidType(&'static str), +} + +/// Diagnostic for `~` on a `double` (shared by runtime type checking and constant evaluation). +const COMPLEMENT_DOUBLE_MSG: &str = "bitwise complement '~' requires an integer operand"; +/// Diagnostic for `%`, `&`, `|`, `^`, `<<`, `>>` with a `double` operand (shared likewise). +const INTEGER_OPERANDS_MSG: &str = "bitwise, shift, and remainder operators require integer operands"; + +/// The name as written in the source: the resolve pass renames locals to `name.N`, and `.` +/// can't appear in a C identifier, so everything from the first `.` on is the suffix. +fn source_name(name: &str) -> &str { + name.split('.').next().unwrap_or(name) } /// Evaluate a static / file-scope initializer to its `InitialValue`, mapping the @@ -1954,14 +2042,11 @@ fn eval_static_initializer( Err(ConstEvalError::NotConstant) => Err(SemanticError::with_span( format!( "initializer for static variable '{}' is not a constant expression", - name.0.bold() + source_name(&name.0).bold() ), span, )), - Err(ConstEvalError::InvalidType) => Err(SemanticError::with_span( - format!("cannot take bitwise complement of a {} value", "'double'".bold()), - span, - )), + Err(ConstEvalError::InvalidType(msg)) => Err(SemanticError::with_span(msg.to_string(), span)), } } @@ -2006,7 +2091,7 @@ fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEval StaticInit::LongInit(n) => StaticInit::LongInit(!n), StaticInit::ULongInit(n) => StaticInit::ULongInit(!n), StaticInit::UIntInit(n) => StaticInit::UIntInit(!n), - StaticInit::DoubleInit(_) => return Err(ConstEvalError::InvalidType), + StaticInit::DoubleInit(_) => return Err(ConstEvalError::InvalidType(COMPLEMENT_DOUBLE_MSG)), }, false, ), @@ -2030,7 +2115,7 @@ fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEval | BinOp::BitwiseRightShift ) { - return Err(ConstEvalError::InvalidType); + return Err(ConstEvalError::InvalidType(INTEGER_OPERANDS_MSG)); } let base = lo | ro; let (v, op_ovf) = match op { @@ -2264,11 +2349,8 @@ fn label_statement(stmt: &mut SpannedStmt, label_tracker: &mut LabelTracker) -> stmt.span, )); } - Err(ConstEvalError::InvalidType) => { - return Err(SemanticError::with_span( - format!("cannot take bitwise complement of a {} value", "'double'".bold()), - stmt.span, - )); + Err(ConstEvalError::InvalidType(msg)) => { + return Err(SemanticError::with_span(msg.to_string(), stmt.span)); } }; *label = label_tracker.get_switch_case(value, &stmt.span)?; diff --git a/tests/c_programs/declaration/invalid_semantics/extern_conflicting_types.c b/tests/c_programs/declaration/invalid_semantics/extern_conflicting_types.c new file mode 100644 index 0000000..f99416b --- /dev/null +++ b/tests/c_programs/declaration/invalid_semantics/extern_conflicting_types.c @@ -0,0 +1,8 @@ +/* Two block-scope `extern` declarations of the same object with different types. */ +int main(void) { + extern long x; + { + extern int x; + } + return 0; +} diff --git a/tests/c_programs/declaration/invalid_semantics/extern_hides_static.c b/tests/c_programs/declaration/invalid_semantics/extern_hides_static.c new file mode 100644 index 0000000..b937a21 --- /dev/null +++ b/tests/c_programs/declaration/invalid_semantics/extern_hides_static.c @@ -0,0 +1,12 @@ +/* The local `s` hides the file-scope `static int s`, so the block-scope `extern int s` can't see + it and gets external linkage. The same name then has both internal and external linkage, + which is an error (C11 6.2.2p4, p7). */ +static int s = 4; + +int main(void) { + int s = 1; + { + extern int s; + return s; + } +} diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index c3542ce..fa6f5c7 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -143,5 +143,11 @@ }, "double_negation_mask.c": { "return_code": 5 + }, + "lexer/octal_literals.c": { + "return_code": 10 + }, + "lexer/line_splice.c": { + "return_code": 21 } } \ No newline at end of file diff --git a/tests/c_programs/lexer/invalid_lex/octal_bad_digit.c b/tests/c_programs/lexer/invalid_lex/octal_bad_digit.c new file mode 100644 index 0000000..644bf0b --- /dev/null +++ b/tests/c_programs/lexer/invalid_lex/octal_bad_digit.c @@ -0,0 +1,4 @@ +/* A leading 0 makes an integer literal octal, so the digit 8 is invalid. */ +int main(void) { + return 08; +} diff --git a/tests/c_programs/lexer/invalid_lex/stray_hash.c b/tests/c_programs/lexer/invalid_lex/stray_hash.c new file mode 100644 index 0000000..6d77a77 --- /dev/null +++ b/tests/c_programs/lexer/invalid_lex/stray_hash.c @@ -0,0 +1,6 @@ +/* `#` only starts a (skipped) directive as the first character on a line. Anywhere else it is a + stray character, not a comment that swallows the rest of the line. */ +int main(void) { + return 2 # junk + ; +} diff --git a/tests/c_programs/lexer/line_splice.c b/tests/c_programs/lexer/line_splice.c new file mode 100644 index 0000000..0818713 --- /dev/null +++ b/tests/c_programs/lexer/line_splice.c @@ -0,0 +1,14 @@ +// Backslash-newline joins two lines before tokenizing (C translation phase 2). The splice +// can fall between tokens, inside a token, or at the end of a // comment or # line, which then +// continues onto the next line. Returns 21. +#define IGNORED this directive \ + continues here +int main(void) { + int x = 1; // this comment ends in a splice, so the next line is comment too \ + x = 100; + int y = 2\ +0; + re\ +turn x \ ++ y; +} diff --git a/tests/c_programs/lexer/octal_literals.c b/tests/c_programs/lexer/octal_literals.c new file mode 100644 index 0000000..34cd85f --- /dev/null +++ b/tests/c_programs/lexer/octal_literals.c @@ -0,0 +1,30 @@ +/* Integer literals with a leading 0 are octal. Unsuffixed octal literals also take unsigned + types when the value only fits there (int, unsigned int, long, unsigned long), unlike decimal + literals (int, long). Floating literals are always decimal, even with leading zeros. + Returns the number of checks that held; expected result is 10. */ +int main(void) { + int passed = 0; + + if (010 == 8) passed = passed + 1; + if (0777 == 511) passed = passed + 1; + if (00 == 0) passed = passed + 1; + if (017l == 15l && 017u == 15u && 017ul == 15ul) passed = passed + 1; + + /* 037777777777 = 2^32 - 1 fits unsigned int but not int: it is unsigned, so > 0 ... */ + if (037777777777 > 0) passed = passed + 1; + /* ... and negating it wraps as unsigned int: -(2^32 - 1) = 1 */ + if (-037777777777 == 1) passed = passed + 1; + /* the decimal spelling is a long instead, so it stays negative */ + if (-4294967295 < 0) passed = passed + 1; + + /* 2^63 fits unsigned long only (as an octal literal it has a type; in decimal it wouldn't) */ + if (01000000000000000000000 == 9223372036854775808ul) passed = passed + 1; + + /* octal-suffixed long that doesn't fit long becomes unsigned long */ + if (0777777777777777777777l > 0) passed = passed + 1; + + /* floating literals with leading zeros are decimal; 8 and 9 are fine there */ + if (08.5 == 8.5 && 09e1 == 90.0) passed = passed + 1; + + return passed; /* expect 10 */ +} diff --git a/tests/c_programs/static_vars/invalid_semantics/static_init_not_constant.c b/tests/c_programs/static_vars/invalid_semantics/static_init_not_constant.c new file mode 100644 index 0000000..38e0475 --- /dev/null +++ b/tests/c_programs/static_vars/invalid_semantics/static_init_not_constant.c @@ -0,0 +1,7 @@ +/* A static local's initializer must be a constant expression. The error must name `b` as + written, not the resolver's internal `b.N`. */ +int main(void) { + int a = 1; + static int b = a; + return b; +} diff --git a/tests/c_programs/types/invalid_semantics/const_remainder_double.c b/tests/c_programs/types/invalid_semantics/const_remainder_double.c new file mode 100644 index 0000000..d8a6bfd --- /dev/null +++ b/tests/c_programs/types/invalid_semantics/const_remainder_double.c @@ -0,0 +1,7 @@ +/* `%` needs integer operands, in a static initializer as anywhere else. The error must describe + `%`, not `~`. */ +static int x = 5.0 % 2; + +int main(void) { + return x; +} diff --git a/tests/c_programs/warnings/constant_conversion_local.c b/tests/c_programs/warnings/constant_conversion_local.c new file mode 100644 index 0000000..7e05e0c --- /dev/null +++ b/tests/c_programs/warnings/constant_conversion_local.c @@ -0,0 +1,6 @@ +/* -Wconstant-conversion also covers automatic locals: the conversion happens at run time, but a + constant initializer's value is known at compile time. Runs cleanly to 0. */ +int main(void) { + int x = 2147483648; /* long constant truncated to int */ + return x - x; +} diff --git a/tests/c_programs/warnings/no_constant_conversion.c b/tests/c_programs/warnings/no_constant_conversion.c index 95b752c..1741963 100644 --- a/tests/c_programs/warnings/no_constant_conversion.c +++ b/tests/c_programs/warnings/no_constant_conversion.c @@ -2,4 +2,9 @@ int a = (int)2147483648; /* explicit cast — silenced */ long b = 2147483648; /* fits long (no narrowing) */ int c = 100; /* fits int */ -int main(void) { return 0; } +int main(void) { + int d = (int)2147483648; /* explicit cast in an automatic local — silenced */ + long e = 2147483648; /* fits long */ + int f = d; /* not a constant */ + return 0; +} diff --git a/tests/c_programs/warnings/no_sequence_point.c b/tests/c_programs/warnings/no_sequence_point.c index 3f6054a..8c90e00 100644 --- a/tests/c_programs/warnings/no_sequence_point.c +++ b/tests/c_programs/warnings/no_sequence_point.c @@ -5,6 +5,7 @@ int main(void) { int a = i++; /* single modification */ int b = i ? i++ : i--; /* ?: is a sequence point */ int c = (i++) && (i++); /* && is a sequence point */ + int d = (i++ || 0) ? i++ : i--; /* every modification is separated by a sequence point */ i++; i++; /* separate statements = separate full expressions */ return 0; diff --git a/tests/c_programs/warnings/no_shadow.c b/tests/c_programs/warnings/no_shadow.c new file mode 100644 index 0000000..ae81434 --- /dev/null +++ b/tests/c_programs/warnings/no_shadow.c @@ -0,0 +1,20 @@ +/* Cases that must NOT trigger -Wshadow (matching gcc). Runs cleanly to 0. */ +int a; +int proto(int a); /* prototype parameter names don't shadow anything */ + +int g(void) { + int g = 3; /* a variable shadowing a function */ + return g - 3; +} + +int h(int h) { /* a parameter shadowing a function */ + return h; +} + +int proto(int b) { + return b; +} + +int main(void) { + return g() + h(0) + proto(0); +} diff --git a/tests/c_programs/warnings/no_switch_unreachable.c b/tests/c_programs/warnings/no_switch_unreachable.c new file mode 100644 index 0000000..03ec078 --- /dev/null +++ b/tests/c_programs/warnings/no_switch_unreachable.c @@ -0,0 +1,13 @@ +/* Switch bodies whose first code is reachable must NOT get -Wswitch-unreachable (matching gcc). + Runs cleanly to 0. */ +int main(void) { + int x = 1; + int y = 0; + switch (x) { int z; case 1: y = 0; } /* declaration without initializer */ + switch (x) { lbl: case 1: y = 0; } /* labeled statement */ + switch (x) { while (y) { case 1: y = 0; } } /* loop condition runs after the jump */ + switch (x) { do { case 1: y = 0; } while (y); } + switch (x) { for (; y; ) { case 1: y = 0; } } /* `for` with no initializer */ + switch (x) ; /* empty body */ + return y; +} diff --git a/tests/c_programs/warnings/sequence_point.c b/tests/c_programs/warnings/sequence_point.c index 5f579bb..a87beaa 100644 --- a/tests/c_programs/warnings/sequence_point.c +++ b/tests/c_programs/warnings/sequence_point.c @@ -1,6 +1,6 @@ /* -Wsequence-point: the same object modified more than once between sequence points (undefined in standard C). NCC evaluates left-to-right, so these compile with warnings and - run cleanly to 0; the dedicated test asserts the diagnostics via --validate. */ + run cleanly to 0; the dedicated test asserts there are exactly 7 diagnostics. */ int two(int a, int b) { return a + b; } int main(void) { @@ -8,5 +8,13 @@ int main(void) { i = i++; /* '=' and '++' both modify i */ int a = i++ + i++; /* two increments of i in one region */ two(i++, i++); /* call args are unsequenced w.r.t. each other */ + + /* &&, || and ?: sequence their own operands, but not against the rest of the expression, + and call arguments are unsequenced against it too */ + int j = 0; + j = i++ + two(i++, 0); /* argument vs. the enclosing expression */ + j = (i ? i++ : 0) + i++; /* ?: operand vs. sibling */ + j = (j && i++) + i++; /* && operand vs. sibling */ + j = two(i++, two(i++, 0)); /* nested call arguments */ return 0; } diff --git a/tests/c_programs/warnings/shadow_extern.c b/tests/c_programs/warnings/shadow_extern.c new file mode 100644 index 0000000..1484bc2 --- /dev/null +++ b/tests/c_programs/warnings/shadow_extern.c @@ -0,0 +1,11 @@ +/* A block-scope `extern` hiding a local: the inner `x` is a different object (the file-scope + one below), so the declaration shadows the local, and -Wshadow fires once. Returns 0. */ +int main(void) { + int x = 1; + { + extern int x; + return x - 5; + } +} + +int x = 5; diff --git a/tests/c_programs/warnings/shift_count_file_scope.c b/tests/c_programs/warnings/shift_count_file_scope.c new file mode 100644 index 0000000..570917a --- /dev/null +++ b/tests/c_programs/warnings/shift_count_file_scope.c @@ -0,0 +1,6 @@ +/* -Wshift-count-overflow in a file-scope initializer (folded at compile time, but still a + shift whose count is >= the width of int). Runs cleanly to 0. */ +int a = 1 << 32; +int main(void) { + return 0; +} diff --git a/tests/c_programs/warnings/switch_unreachable.c b/tests/c_programs/warnings/switch_unreachable.c new file mode 100644 index 0000000..dcb4a2f --- /dev/null +++ b/tests/c_programs/warnings/switch_unreachable.c @@ -0,0 +1,12 @@ +/* Each switch below has code before its first label that can never run, so each must get + exactly one -Wswitch-unreachable warning (5 total, matching gcc). Runs cleanly to 0. */ +int main(void) { + int x = 1; + int y = 0; + switch (x) { ; y = 2; case 1: y = 0; } /* empty statement skipped */ + switch (x) { int z = 3; case 1: y = 0; } /* initialized declaration */ + switch (x) { if (y) { case 1: y = 0; } } /* `if` condition runs first */ + switch (x) { for (y = 0; y < 1; y = y + 1) { case 1: ; } } /* `for` initializer runs first */ + switch (x) { switch (y) { default: ; } case 1: ; } /* nested switch's expression */ + return 0; +} diff --git a/tests/runner.rs b/tests/runner.rs index 55f663d..7ef56b1 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -1177,6 +1177,113 @@ fn test_switch_unreachable() { for file in files { test_warning(file, "-Wswitch-unreachable") } + + // One warning per switch with dead code before its first label, none when it's reachable + for (file, expected) in [ + ("tests/c_programs/warnings/switch_unreachable.c", 5), + ("tests/c_programs/warnings/no_switch_unreachable.c", 0), + ] { + let stderr = validate_stderr(file); + assert_eq!( + stderr.matches("-Wswitch-unreachable").count(), + expected, + "{file}: expected {expected} -Wswitch-unreachable warnings, stderr was: {stderr}" + ); + } +} + +/// Runs `ncc --validate` and returns stderr with ANSI color codes removed. +fn validate_stderr(file: &str) -> String { + let output = std::process::Command::new(get_ncc_binary_path()) + .arg(file) + .arg("--validate") + .output() + .expect("Failed to execute ncc"); + strip_ansi(&String::from_utf8_lossy(&output.stderr)) +} + +/// Removes ANSI escape sequences (`ESC [ ... m`) so diagnostics can be matched as plain text. +fn strip_ansi(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c == '\x1b' { + chars.by_ref().find(|&c| c == 'm'); + } else { + out.push(c); + } + } + out +} + +#[test] +fn test_wshadow_cases() { + // gcc-compatible -Wshadow: silent for prototype parameters and for names shadowing a function + let stderr = validate_stderr("tests/c_programs/warnings/no_shadow.c"); + assert!( + !stderr.contains("-Wshadow"), + "expected no -Wshadow, stderr was: {stderr}" + ); + + // a block-scope extern hiding a local is a different object: exactly one warning, at the extern + let stderr = validate_stderr("tests/c_programs/warnings/shadow_extern.c"); + assert_eq!(stderr.matches("-Wshadow").count(), 1, "stderr was: {stderr}"); + assert!( + stderr.contains("shadow_extern.c:6:"), + "expected the warning at the extern on line 6, stderr was: {stderr}" + ); +} + +#[test] +fn test_warnings_outside_function_bodies() { + // -Wshift-count-overflow in a file-scope initializer (only constant-folded, never run) + let stderr = validate_stderr("tests/c_programs/warnings/shift_count_file_scope.c"); + assert!(stderr.contains("-Wshift-count-overflow"), "stderr was: {stderr}"); + + // -Wconstant-conversion on an automatic local with a constant initializer + let stderr = validate_stderr("tests/c_programs/warnings/constant_conversion_local.c"); + assert!(stderr.contains("-Wconstant-conversion"), "stderr was: {stderr}"); +} + +#[test] +fn test_semantic_error_messages() { + // (file, text the error must contain, text it must not contain) + let cases = [ + ( + "tests/c_programs/types/invalid_semantics/const_remainder_double.c", + "remainder operators require integer operands", + "complement", + ), + ( + "tests/c_programs/static_vars/invalid_semantics/static_init_not_constant.c", + "static variable 'b' is not a constant expression", + "b.", + ), + ( + "tests/c_programs/declaration/invalid_semantics/extern_conflicting_types.c", + "conflicting types", + "different kind of symbol", + ), + ( + "tests/c_programs/declaration/invalid_semantics/extern_hides_static.c", + "both external and internal linkage", + "\0", + ), + ( + // the error carries a location (it used to have none) + "writing-a-c-compiler-tests/tests/chapter_13/invalid_types/extra_credit/switch_on_double.c", + "switch_on_double.c:", + "\0", + ), + ]; + for (file, must, must_not) in cases { + let stderr = validate_stderr(file); + assert!(stderr.contains(must), "{file}: expected `{must}`, stderr was: {stderr}"); + assert!( + !stderr.contains(must_not), + "{file}: unexpected `{must_not}`, stderr was: {stderr}" + ); + } } #[test] @@ -1212,6 +1319,13 @@ fn test_unused_parameter_warning() { stderr_output ); + // The warning points at the parameter itself (`y` is at 1:20), not at the function + assert!( + strip_ansi(&stderr_output).contains("unused_parameter.c:1:20: warning: unused parameter 'y'"), + "Warning should point at parameter 'y' (1:20), but stderr was: {}", + stderr_output + ); + println!("✓ Unused parameter warning test passed"); } @@ -1519,9 +1633,12 @@ fn test_sequence_point_warning() { .expect("Failed to execute ncc"); let stderr_output = String::from_utf8_lossy(&output.stderr); - assert!( - stderr_output.contains("-Wsequence-point"), - "Expected -Wsequence-point warning, but stderr was: {}", + // 3 basic cases plus 4 where a sequenced operator or a call argument conflicts with a + // modification elsewhere in the same expression: each must warn exactly once. + assert_eq!( + stderr_output.matches("-Wsequence-point").count(), + 7, + "Expected 7 -Wsequence-point warnings, but stderr was: {}", stderr_output ); From 2b45825a457e94d686e55987b040a83a00440062 Mon Sep 17 00:00:00 2001 From: John Ring Date: Sun, 25 Oct 2026 22:16:54 -0400 Subject: [PATCH 4/6] Constant folding converts operands like typecheck_exp (F1, F4, F5) Factor the binary-operator type rules into binary_types, shared by typecheck_exp and eval_constant_expr, so compile-time folding converts operands the same way runtime code does. - F1: ?: converts the taken branch to the common type of both branches. - F4: operands are converted before the zero-divisor check, so 1.0 / 0 folds to infinity instead of being rejected. - F5: && / || and the untaken ?: branch are folded as unevaluated operands: a zero divisor there is not an error and overflow there does not warn. They must still be constant expressions. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- src/validate.rs | 166 +++++++++++------- tests/c_programs/expected_results.json | 5 +- .../static_vars/const_eval_conversions.c | 41 +++++ tests/c_programs/warnings/no_overflow.c | 4 + 5 files changed, 152 insertions(+), 67 deletions(-) create mode 100644 tests/c_programs/static_vars/const_eval_conversions.c diff --git a/README.md b/README.md index eaae626..09d98e5 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,8 @@ NCC provides several safety features and guarantees to help developers write mor function body - **Division by zero** (`-Wdiv-by-zero`): Warns when `/` or `%`, including the compound forms `/=` and `%=`, has a constant zero divisor (e.g. `x / 0`, `x % 0`, `x /= 0`, `x %= 0`). A constant zero divisor in a context that - requires a constant expression (such as a static initializer) is a hard error instead + requires a constant expression (such as a static initializer) is a hard error instead, unless the division is a + `double` one (`1.0 / 0` folds to infinity) or sits in an operand that is never evaluated (`1 || 1 / 0`) - **Out-of-range shift count** (`-Wshift-count-overflow`, `-Wshift-count-negative`): Warns when a `<<` or `>>` (including `<<=` / `>>=`) has a constant shift count that is negative or `>=` the width of the left operand's type (32 for 32-bit types, 64 for 64-bit types), e.g. `1 << 32` or `1 << -1` diff --git a/src/validate.rs b/src/validate.rs index be4c79e..199b382 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -970,6 +970,39 @@ fn warn_unused_parameter(used: bool, name: &str, span: Span) { } } +/// The type rules for a binary operator, shared by `typecheck_exp` and `eval_constant_expr` so +/// runtime code and compile-time folding convert operands the same way. +/// +/// Returns `(operand_type, result_type)`. `operand_type` is the common type both operands convert +/// to (the usual arithmetic conversions), or `None` when each keeps its own type: `&&`/`||` test +/// each operand for truthiness, and shifts use the left operand's type and leave the count alone. +fn binary_types(op: BinOp, left: &Type, right: &Type) -> (Option, Type) { + match op { + BinOp::And | BinOp::Or => (None, Type::Int), + BinOp::BitwiseLeftShift | BinOp::BitwiseRightShift => (None, left.clone()), + BinOp::Equal + | BinOp::NotEqual + | BinOp::LessThan + | BinOp::LessOrEqual + | BinOp::GreaterThan + | BinOp::GreaterOrEqual => (Some(left.common_with(right)), Type::Int), + BinOp::Add + | BinOp::Subtract + | BinOp::Multiply + | BinOp::Divide + | BinOp::Remainder + | BinOp::BitwiseAnd + | BinOp::BitwiseOr + | BinOp::BitwiseXOr => { + let common = left.common_with(right); + (Some(common.clone()), common) + } + BinOp::Assignment | BinOp::CompoundAssignment | BinOp::Conditional => { + unreachable!("only used for parsing") + } + } +} + /// Type-checks an expression, returning a `TypedExpression` with a resolved type. /// /// Inserts implicit casts where operand types differ (using the common-type rule), @@ -1072,40 +1105,12 @@ fn typecheck_exp(exp: ParserExpr, symbols: &mut SymbolTable) -> Result (convert_to(typed_lhs, t), convert_to(typed_rhs, t)), + None => (typed_lhs, typed_rhs), }; - - // Bitshift: result type is the type of left operand (not common type) - if matches!(op, BinOp::BitwiseLeftShift | BinOp::BitwiseRightShift) { - let result_type = typed_lhs.exp_type.clone(); - let binary_exp = Expr::Binary(op, Box::new(typed_lhs), Box::new(typed_rhs)); - return Ok(binary_exp.with_type(result_type)); - } - - let common_type = typed_lhs.exp_type.common_with(&typed_rhs.exp_type); - let converted_lhs = convert_to(typed_lhs, &common_type); - let converted_rhs = convert_to(typed_rhs, &common_type); - let binary_exp = Expr::Binary(op, Box::new(converted_lhs), Box::new(converted_rhs)); - let result_type = match op { - BinOp::Add - | BinOp::Subtract - | BinOp::Multiply - | BinOp::Divide - | BinOp::Remainder - | BinOp::BitwiseAnd - | BinOp::BitwiseOr - | BinOp::BitwiseXOr => common_type, - BinOp::Equal - | BinOp::NotEqual - | BinOp::LessThan - | BinOp::LessOrEqual - | BinOp::GreaterThan - | BinOp::GreaterOrEqual => Type::Int, - _ => unreachable!(), - }; - Ok(binary_exp.with_type(result_type)) + Ok(Expr::Binary(op, Box::new(lhs), Box::new(rhs)).with_type(result_type)) } ParserExpr::Assignment(lhs, rhs, _) => { let typed_lhs = typecheck_exp(*lhs, symbols)?; @@ -2052,37 +2057,48 @@ fn eval_static_initializer( /// Evaluates a compile-time constant expression from the parser AST. /// -/// Handles all arithmetic, bitwise, comparison, and logical operations with proper -/// type promotion (Int + Long = Long). Type conversions follow implementation-defined -/// behavior documented in README (wrapping arithmetic, shift masking, etc.). +/// Handles all arithmetic, bitwise, comparison, and logical operations. Operands are converted +/// with the same rules `typecheck_exp` uses (see [`binary_types`] and the `?:` common type), so a +/// constant folds to the value the runtime code would compute. Type conversions follow +/// implementation-defined behavior documented in README (wrapping arithmetic, shift masking, etc.). /// /// Used for static initializers, case labels, and other contexts requiring constant /// expressions. Does NOT call typecheck_exp to avoid mixing with general expression /// transformations that will be added in later chapters. /// -/// On success returns `(value, overflowed)`, where `overflowed` is true if any sub-operation -/// wrapped the result type during the fold (`INT_MAX + 1`, `-INT_MIN`, `INT_MIN / -1`, …). The -/// value is still the well-defined wrapped result — callers use the flag to emit `-Woverflow`. +/// On success returns `(value, overflowed)`, where `overflowed` is true if any evaluated +/// sub-operation wrapped the result type during the fold (`INT_MAX + 1`, `-INT_MIN`, +/// `INT_MIN / -1`, …). The value is still the well-defined wrapped result — callers use the +/// flag to emit `-Woverflow`. /// /// Returns `Err(ConstEvalError::NotConstant)` if the expression contains non-constant /// elements (variables, function calls, assignments, etc.), or -/// `Err(ConstEvalError::DivByZero)` if a `/` or `%` has a zero divisor. +/// `Err(ConstEvalError::DivByZero)` if an evaluated `/` or `%` has a zero divisor. fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEvalError> { - match expr { - ParserExpr::Constant(Const::ConstInt(val)) => Ok((StaticInit::IntInit(*val), false)), - ParserExpr::Constant(Const::ConstLong(val)) => Ok((StaticInit::LongInit(*val), false)), - ParserExpr::Constant(Const::ConstUInt(val)) => Ok((StaticInit::UIntInit(*val), false)), - ParserExpr::Constant(Const::ConstULong(val)) => Ok((StaticInit::ULongInit(*val), false)), - ParserExpr::Constant(Const::ConstDouble(val)) => Ok((StaticInit::DoubleInit(*val), false)), + fold_constant(expr, true) +} + +/// The worker for [`eval_constant_expr`]. `live` is false inside an operand C doesn't evaluate: +/// the right side of a short-circuited `&&`/`||`, or the untaken branch of `?:`. That operand +/// must still be a constant expression, and its type still matters (the untaken branch decides +/// the `?:` result type), so it is folded anyway, but a zero divisor there isn't an error and +/// overflow there doesn't warn. +fn fold_constant(expr: &ParserExpr, live: bool) -> Result<(StaticInit, bool), ConstEvalError> { + let (value, overflowed) = match expr { + ParserExpr::Constant(Const::ConstInt(val)) => (StaticInit::IntInit(*val), false), + ParserExpr::Constant(Const::ConstLong(val)) => (StaticInit::LongInit(*val), false), + ParserExpr::Constant(Const::ConstUInt(val)) => (StaticInit::UIntInit(*val), false), + ParserExpr::Constant(Const::ConstULong(val)) => (StaticInit::ULongInit(*val), false), + ParserExpr::Constant(Const::ConstDouble(val)) => (StaticInit::DoubleInit(*val), false), ParserExpr::Cast(target, val) => { - let (v, o) = eval_constant_expr(val)?; + let (v, o) = fold_constant(val, live)?; // Explicit cast: suppress the conversion-truncation warning (programmer intent), but // keep `o` so arithmetic overflow inside the cast operand still surfaces. let (cv, _truncated) = convert_to_type(v, target); - Ok((cv, o)) + (cv, o) } ParserExpr::Unary(op, inner, _) => { - let (v, o) = eval_constant_expr(inner)?; + let (v, o) = fold_constant(inner, live)?; let (r, o2) = match op { UnaryOp::Negate => v.neg(), UnaryOp::BitwiseComplement => ( @@ -2099,11 +2115,17 @@ fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEval }; // Unsigned wraparound is well-defined, not overflow — only signed ops warn (-Woverflow). let o2 = o2 && r.get_type().is_signed(); - Ok((r, o | o2)) + (r, o | o2) } ParserExpr::Binary(op, left, right, _) => { - let (l, lo) = eval_constant_expr(left)?; - let (r, ro) = eval_constant_expr(right)?; + let (l, lo) = fold_constant(left, live)?; + // `&&`/`||` don't evaluate the right side once the left side decides the result. + let short_circuits = match op { + BinOp::And => l.is_zero(), + BinOp::Or => !l.is_zero(), + _ => false, + }; + let (r, ro) = fold_constant(right, live && !short_circuits)?; if (matches!(l, StaticInit::DoubleInit(_)) || matches!(r, StaticInit::DoubleInit(_))) && matches!( op, @@ -2117,13 +2139,23 @@ fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEval { return Err(ConstEvalError::InvalidType(INTEGER_OPERANDS_MSG)); } - let base = lo | ro; + // Usual arithmetic conversions, before the operation: `1.0 / 0` divides by `0.0`. + let (l, r) = match binary_types(*op, &l.get_type(), &r.get_type()).0 { + // Converting to the common type only widens or reinterprets, so it never truncates. + Some(t) => (convert_to_type(l, &t).0, convert_to_type(r, &t).0), + None => (l, r), + }; + // A zero divisor in an unevaluated operand is fine; any value of the right type will do. + let div = |result: Result<(StaticInit, bool), ConstEvalError>| match result { + Err(ConstEvalError::DivByZero) if !live => Ok((l, false)), + other => other, + }; let (v, op_ovf) = match op { BinOp::Add => l.add(r), BinOp::Subtract => l.sub(r), BinOp::Multiply => l.mul(r), - BinOp::Divide => l.div(r)?, - BinOp::Remainder => l.rem(r)?, + BinOp::Divide => div(l.div(r))?, + BinOp::Remainder => div(l.rem(r))?, BinOp::BitwiseAnd => (l.bitwise_and(r), false), BinOp::BitwiseOr => (l.bitwise_or(r), false), BinOp::BitwiseXOr => (l.bitwise_xor(r), false), @@ -2143,20 +2175,24 @@ fn eval_constant_expr(expr: &ParserExpr) -> Result<(StaticInit, bool), ConstEval }; // Unsigned wraparound is well-defined, not overflow — only signed ops warn (-Woverflow). let op_ovf = op_ovf && v.get_type().is_signed(); - Ok((v, base | op_ovf)) + (v, lo | ro | op_ovf) } ParserExpr::Conditional(cond, true_expr, false_expr) => { - let (cond_val, co) = eval_constant_expr(cond)?; - let (v, o) = if cond_val.is_zero() { - eval_constant_expr(false_expr)? - } else { - eval_constant_expr(true_expr)? - }; - Ok((v, co | o)) + let (cond_val, co) = fold_constant(cond, live)?; + let take_true = !cond_val.is_zero(); + // Both branches are folded: the untaken one still sets the result type. + let (t, to) = fold_constant(true_expr, live && take_true)?; + let (f, fo) = fold_constant(false_expr, live && !take_true)?; + let common_type = t.get_type().common_with(&f.get_type()); + let (v, o) = if take_true { (t, to) } else { (f, fo) }; + // Converting to the common type only widens or reinterprets, so it never truncates. + (convert_to_type(v, &common_type).0, co | o) } // Variables, assignments, function calls etc. are not constant - _ => Err(ConstEvalError::NotConstant), - } + _ => return Err(ConstEvalError::NotConstant), + }; + // Overflow in an unevaluated operand never happens at runtime, so it doesn't warn. + Ok((value, overflowed && live)) } enum LabelTag { diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index fa6f5c7..945a571 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -149,5 +149,8 @@ }, "lexer/line_splice.c": { "return_code": 21 + }, + "static_vars/const_eval_conversions.c": { + "return_code": 8 } -} \ No newline at end of file +} diff --git a/tests/c_programs/static_vars/const_eval_conversions.c b/tests/c_programs/static_vars/const_eval_conversions.c new file mode 100644 index 0000000..6897404 --- /dev/null +++ b/tests/c_programs/static_vars/const_eval_conversions.c @@ -0,0 +1,41 @@ +/* Constant folding must convert operands the same way runtime code does. + * Each static is checked against the same expression computed at runtime. */ + +/* ?: converts the taken branch to the common type of both branches (unsigned int here). */ +static int ternary_cmp = (1 ? -1 : 0u) < 0; /* -1 becomes 4294967295u: 0 */ +static long ternary_div = (1 ? -6 : 0u) / 2; /* 4294967290u / 2 = 2147483645 */ +static double ternary_double = 1 ? 3 : 0.5; /* 3.0 */ + +/* The divisor is converted to double before the zero check: 1.0 / 0.0 is +inf. */ +static double inf = 1.0 / 0; + +/* && and || don't evaluate the right side once the left side decides the result, + * and neither does the untaken branch of ?:. */ +static int or_skips = 1 || 1 / 0; +static int and_skips = 0 && 1 / 0; +static int ternary_skips = 1 ? 5 : 1 / 0; + +int main(void) { + int one = 1; + unsigned int zero_u = 0u; + int zero = 0; + int checks = 0; + + if (ternary_cmp == ((one ? -1 : zero_u) < 0)) checks = checks + 1; + if (ternary_div == (one ? -6 : zero_u) / 2) checks = checks + 1; + if (ternary_div == 2147483645) checks = checks + 1; + if (ternary_double == (one ? 3 : 0.5)) checks = checks + 1; + if (inf == 1.0 / zero) checks = checks + 1; + if (inf > 1e308) checks = checks + 1; + if (or_skips == 1 && and_skips == 0 && ternary_skips == 5) checks = checks + 1; + + /* Case labels use the same folding: this one is 2147483645, not -3. */ + switch (2147483645) { + case (1 ? -6 : 0u) / 2: + checks = checks + 1; + break; + default: + break; + } + return checks; +} diff --git a/tests/c_programs/warnings/no_overflow.c b/tests/c_programs/warnings/no_overflow.c index 4a41f9a..12ca116 100644 --- a/tests/c_programs/warnings/no_overflow.c +++ b/tests/c_programs/warnings/no_overflow.c @@ -3,3 +3,7 @@ int a = 2147483647; /* INT_MAX itself — fits */ int b = 1000 * 1000; /* 1,000,000 — fits int */ int c = 5 + 3; int main(void) { return 0; } +/* Overflow in an operand that is never evaluated doesn't warn (matches gcc). */ +int d = 1 || 2147483647 + 1; +int e = 0 && 2147483647 + 1; +int f = 1 ? 0 : 2147483647 + 1; From 555cc92b6f313e5a13f4311ab10de6fe774bbfe6 Mon Sep 17 00:00:00 2001 From: John Ring Date: Sun, 25 Oct 2026 22:18:40 -0400 Subject: [PATCH 5/6] Fold NaN to unsigned long like the runtime (F2) double_to_u64 took the subtract-2^63 path for NaN and folded to 0, while the runtime lowering fails the range check and yields 2^63. Docs now spell out the unsigned long conversion results. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 4 +++- src/validate.rs | 6 ++++-- .../conversions/double_to_ulong_nan.c | 18 ++++++++++++++++++ tests/c_programs/expected_results.json | 3 +++ 5 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 tests/c_programs/conversions/double_to_ulong_nan.c diff --git a/CLAUDE.md b/CLAUDE.md index 5404b6a..fb74e4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,7 +152,7 @@ Tests validate both successful compilation and error handling: **Integer Arithmetic**: Signed overflow wraps deterministically (non-standard C extension; standard C makes it UB); unsigned wraps mod 2^N (standard). Shift amounts are masked to prevent undefined behavior. The `-Woverflow` warning fires only for signed overflow. -**Floating Point**: `double` arithmetic/comparisons use SSE2 (`addsd`/`comisd`/etc.); constants live in a `.rodata` pool. Comparisons follow IEEE-754 ordering — a `NaN` operand is unordered (relationals and `==` are false, `!=` true, `NaN` is truthy in conditions), implemented via the parity flag. `double`→integer truncates toward zero; out-of-range or `NaN` yields the x86 `cvttsd2si` "integer indefinite" value (target MIN). Unsigned↔`double` conversions use SSE2 workarounds (no native unsigned convert pre-AVX-512). An out-of-range floating constant rounds to ±infinity or zero (`-Woverflow`). +**Floating Point**: `double` arithmetic/comparisons use SSE2 (`addsd`/`comisd`/etc.); constants live in a `.rodata` pool. Comparisons follow IEEE-754 ordering — a `NaN` operand is unordered (relationals and `==` are false, `!=` true, `NaN` is truthy in conditions), implemented via the parity flag. `double`→integer truncates toward zero; out-of-range or `NaN` yields the x86 `cvttsd2si` "integer indefinite" value (target MIN), except `unsigned long`, which converts values below 2^63 and NaN as `long` (`-1.0` → `ULONG_MAX`, NaN → 2^63). Unsigned↔`double` conversions use SSE2 workarounds (no native unsigned convert pre-AVX-512). An out-of-range floating constant rounds to ±infinity or zero (`-Woverflow`). **Evaluation Order**: Left-to-right (non-standard, eliminates UB). diff --git a/README.md b/README.md index 09d98e5..79f9650 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,9 @@ NCC provides several safety features and guarantees to help developers write mor constant too large for `double` rounds to ±infinity and one too small rounds to zero (both flagged by `-Woverflow`), where C §6.4.4.2 leaves an out-of-range floating constant undefined. Converting a `double` to an integer truncates toward zero; out-of-range or NaN values produce the x86 `cvttsd2si` "integer indefinite" result - (the target type's minimum, e.g. `INT_MIN`), where C §6.3.1.4 leaves the conversion undefined. + (the target type's minimum, e.g. `INT_MIN`), where C §6.3.1.4 leaves the conversion undefined. `unsigned long` + follows its two-step lowering instead: values below 2^63 (including negatives) and NaN convert as `long` and + are reinterpreted (`-1.0` → `ULONG_MAX`, NaN → 2^63), and values at or above 2^64 give 0. - **Consistent compile-time and runtime behavior**: Constant expressions (static initializers, case labels) are folded with the *same* arithmetic and type-conversion rules as runtime expressions — including all of the deterministic resolutions above. Where standard C would make an overflowing or out-of-range constant expression a diff --git a/src/validate.rs b/src/validate.rs index 199b382..b9fc561 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -1941,8 +1941,10 @@ fn double_to_i64(d: f64) -> i64 { fn double_to_u64(d: f64) -> u64 { const TWO_POW_63: f64 = 9223372036854775808.0; // 2^63 - if d < TWO_POW_63 { - double_to_i64(d) as u64 // fits signed range + // NaN fails the `comisd` range check too, so like the runtime it takes the direct conversion + // (indefinite = 2^63) rather than the subtract-2^63 path. + if d.is_nan() || d < TWO_POW_63 { + double_to_i64(d) as u64 // fits signed range, or NaN } else { // subtract 2^63, convert the (now in-range) remainder, restore the top bit (double_to_i64(d - TWO_POW_63) as u64).wrapping_add(1u64 << 63) diff --git a/tests/c_programs/conversions/double_to_ulong_nan.c b/tests/c_programs/conversions/double_to_ulong_nan.c new file mode 100644 index 0000000..23184c7 --- /dev/null +++ b/tests/c_programs/conversions/double_to_ulong_nan.c @@ -0,0 +1,18 @@ +/* NCC-specific: NaN -> unsigned long is undefined in standard C. At runtime NCC's lowering fails + the 2^63 range check (NaN is unordered), takes the direct cvttsd2si path, and yields the + "integer indefinite" bit pattern 0x8000000000000000. Constant folding must give the same value. + Returns the number of checks that held; expected result is 3. */ + +static unsigned long s_nan = (unsigned long) (0.0 / 0.0); + +int main(void) { + int passed = 0; + double zero = 0.0; + double nan = zero / zero; + + if ((unsigned long) nan == 9223372036854775808ul) passed = passed + 1; + if (s_nan == 9223372036854775808ul) passed = passed + 1; + if (s_nan == (unsigned long) nan) passed = passed + 1; + + return passed; /* expect 3 */ +} diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index 945a571..eb98aff 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -152,5 +152,8 @@ }, "static_vars/const_eval_conversions.c": { "return_code": 8 + }, + "conversions/double_to_ulong_nan.c": { + "return_code": 3 } } From 624312bc542838f86c93bcd57573b3863a1058a8 Mon Sep 17 00:00:00 2001 From: John Ring Date: Sun, 25 Oct 2026 22:28:40 -0400 Subject: [PATCH 6/6] Hex literals, case-label conversion warning, unsigned shift count - Hex integer literals (0x/0X) with the same type ladders as octal; the lexer and parser share literal_radix. Hex floating literals are not supported. - -Wconstant-conversion for a case value narrowed to the switch type (gcc reports these as -Woverflow). Sign-only changes don't warn. - A huge unsigned shift count is reported as too wide, not negative. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 +++++---- src/lexer.rs | 35 +++++++++++++++---- src/parser.rs | 32 ++++++++--------- src/validate.rs | 29 ++++++++++++--- tests/c_programs/expected_results.json | 3 ++ tests/c_programs/lexer/hex_literals.c | 31 ++++++++++++++++ .../lexer/invalid_lex/hex_bad_digit.c | 4 +++ .../lexer/invalid_lex/hex_no_digits.c | 3 ++ .../lexer/invalid_parse/hex_too_large.c | 4 +++ tests/c_programs/warnings/case_conversion.c | 33 +++++++++++++++++ .../warnings/shift_count_huge_unsigned.c | 7 ++++ tests/runner.rs | 23 ++++++++++++ 12 files changed, 184 insertions(+), 36 deletions(-) create mode 100644 tests/c_programs/lexer/hex_literals.c create mode 100644 tests/c_programs/lexer/invalid_lex/hex_bad_digit.c create mode 100644 tests/c_programs/lexer/invalid_lex/hex_no_digits.c create mode 100644 tests/c_programs/lexer/invalid_parse/hex_too_large.c create mode 100644 tests/c_programs/warnings/case_conversion.c create mode 100644 tests/c_programs/warnings/shift_count_huge_unsigned.c diff --git a/README.md b/README.md index 79f9650..f5211e4 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ The compiler currently implements a subset of C with the following grammar: | "==" | "!=" | "<" | "<=" | ">" | ">=" ::= "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" ::= ? An identifier token ? - ::= ? An integer constant token: decimal, or octal with a leading 0 (e.g. 017) ? + ::= ? An integer constant token: decimal, octal with a leading 0 (e.g. 017), or hex with 0x (e.g. 0x1F) ? ::= ? A long integer constant token (suffix 'l' or 'L') ? ::= ? An unsigned int constant token (suffix 'u' or 'U') ? ::= ? An unsigned long constant token (suffix combining 'u'/'U' and 'l'/'L') ? @@ -298,10 +298,10 @@ The compiler supports: - `goto` and labeled statements - `return` statements - **Expression statements** and **null statements** -- **Integer literals**: decimal and octal (a leading `0`, e.g. `0755`), with `u`/`l` suffixes. Each literal takes the - first type that holds its value, per C11 6.4.4.1: decimal goes `int` → `long`, while octal can also become - unsigned (`int` → `unsigned int` → `long` → `unsigned long`), so `037777777777` is an `unsigned int`. Hexadecimal - is not supported yet +- **Integer literals**: decimal, octal (a leading `0`, e.g. `0755`), and hexadecimal (`0x`/`0X`, e.g. `0xFF`), with + `u`/`l` suffixes. Each literal takes the first type that holds its value, per C11 6.4.4.1: decimal goes `int` → + `long`, while octal and hex can also become unsigned (`int` → `unsigned int` → `long` → `unsigned long`), so + `0xFFFFFFFF` is an `unsigned int`. Hexadecimal floating literals (`0x1p3`) are not supported - **Line splicing**: a backslash at the end of a line joins it with the next before tokenizing, anywhere in the source (inside tokens and `//` comments too). There is no preprocessor: a line whose first non-blank character is `#` is skipped, along with any lines spliced onto it @@ -359,14 +359,16 @@ NCC provides several safety features and guarantees to help developers write mor `double` one (`1.0 / 0` folds to infinity) or sits in an operand that is never evaluated (`1 || 1 / 0`) - **Out-of-range shift count** (`-Wshift-count-overflow`, `-Wshift-count-negative`): Warns when a `<<` or `>>` (including `<<=` / `>>=`) has a constant shift count that is negative or `>=` the width of the left operand's type - (32 for 32-bit types, 64 for 64-bit types), e.g. `1 << 32` or `1 << -1` + (32 for 32-bit types, 64 for 64-bit types), e.g. `1 << 32` or `1 << -1`. An unsigned count is never negative, so + `1 << 18446744073709551615ul` is reported as too wide - **Integer overflow in a constant expression** (`-Woverflow`): Warns when folding a *signed* constant expression in a static initializer or case label overflows the result type (e.g. `int x = 2147483647 + 1;`). NCC wraps deterministically (two's complement) rather than treating it as undefined, so this flags non-portable code instead of erroring. Unsigned wraparound is well-defined and is *not* warned (matching gcc/clang) - **Constant changed by an implicit conversion** (`-Wconstant-conversion`): Warns when a constant initializer (of a static, file-scope, or automatic variable) is implicitly narrowed to a type that can't hold it (e.g. - `int x = 2147483648;`, which truncates to `-2147483648`). An explicit cast (`int x = (int)2147483648;`) silences it + `int x = 2147483648;`, which truncates to `-2147483648`), and when a `case` value is narrowed to the switch's type + (`case 4294967296L:` in an `int` switch is `case 0:`). An explicit cast (`int x = (int)2147483648;`) silences it - **Unsequenced modification** (`-Wsequence-point`): Warns when the same object is modified more than once between sequence points (e.g. `i = i++`, `i++ + i++`, `f(i++, i++)`, `i++ + f(i++)`) — undefined in standard C. `&&`, `||` and `?:` sequence their own operands, but not against the rest of the expression, so `(j && i++) + i++` also warns. diff --git a/src/lexer.rs b/src/lexer.rs index cbb5224..05582f6 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -20,8 +20,9 @@ //! - Produces a [`VecDeque`] carrying line/column [`Span`]s for error reporting //! - Detects lexer errors (unexpected characters, unterminated comments) and exits with code 10 //! - Promotes integer literals with an `L`/`l` suffix to [`Token::ConstantLong`] -//! - Keeps integer lexemes as written (a leading `0` marks octal, which the parser reads in base 8) -//! and rejects the digits 8 and 9 in octal literals +//! - Keeps integer lexemes as written (a `0x` prefix marks hex and a leading `0` marks octal; the +//! parser reads them in that base, see [`literal_radix`]) and rejects the digits 8 and 9 in octal +//! literals //! - Recognizes floating-point literals (fraction and/or exponent) as [`Token::ConstantDouble`] //! //! ## Call Order @@ -113,11 +114,18 @@ pub enum Token { const TOKEN_PATTERNS: &[(&str, Token)] = &[ // Special handling tokens (handled differently in next_token) (r"^[a-zA-Z_]\w*\b", Token::Identifier(String::new())), - (r"^[0-9]+\b", Token::ConstantInt(String::new())), - (r"^[0-9]+[lL]\b", Token::ConstantLong(String::new())), - (r"^[0-9]+[uU]\b", Token::ConstantUnsignedInt(String::new())), + // Integer literals: hex (`0x1F`) or decimal/octal digits, then an optional suffix. + (r"^(?:0[xX][0-9a-fA-F]+|[0-9]+)\b", Token::ConstantInt(String::new())), ( - r"^[0-9]++([lL][uU]|[uU][lL])\b", + r"^(?:0[xX][0-9a-fA-F]+|[0-9]+)[lL]\b", + Token::ConstantLong(String::new()), + ), + ( + r"^(?:0[xX][0-9a-fA-F]+|[0-9]+)[uU]\b", + Token::ConstantUnsignedInt(String::new()), + ), + ( + r"^(?:0[xX][0-9a-fA-F]++|[0-9]++)([lL][uU]|[uU][lL])\b", Token::ConstantUnsignedLong(String::new()), ), ( @@ -250,6 +258,19 @@ pub struct SpannedToken { pub span: Span, } +/// The base of an integer lexeme as written (suffix already removed): 16 for a `0x`/`0X` prefix, +/// 8 for a leading `0` followed by more digits, otherwise 10. A lone `0` counts as decimal; both +/// readings give the same value. +pub(crate) fn literal_radix(lexeme: &str) -> u32 { + if lexeme.starts_with("0x") || lexeme.starts_with("0X") { + 16 + } else if lexeme.len() > 1 && lexeme.starts_with('0') { + 8 + } else { + 10 + } +} + fn next_token(input: &str, span: Span) -> Result { let mut matches = vec![]; for TokenDef { regex, variant } in TOKEN_DEFS.iter() { @@ -290,7 +311,7 @@ fn next_token(input: &str, span: Span) -> Result { | Token::ConstantLong(digits) | Token::ConstantUnsignedInt(digits) | Token::ConstantUnsignedLong(digits) = &best_match.token - && digits.starts_with('0') + && literal_radix(digits) == 8 && digits.contains(['8', '9']) { return Err(LexerError::with_span( diff --git a/src/parser.rs b/src/parser.rs index 9fe6b72..a5361ae 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -35,7 +35,7 @@ //! └─ parse_block_item() — compound statements (recursive) //! ``` //! -use crate::lexer::{Span, SpannedToken, Token}; +use crate::lexer::{Span, SpannedToken, Token, literal_radix}; use colored::*; use std::collections::VecDeque; use std::fmt; @@ -493,10 +493,11 @@ fn expect(expected: &Token, tokens: &mut VecDeque) -> Result Result { let ulong: Candidate = |v| u64::try_from(v).ok().map(ConstULong); let (value_str, ladder): (&String, &[Candidate]) = match &token.token { - Token::ConstantInt(v) if is_octal_literal(v) => (v, &[int, uint, long, ulong]), + Token::ConstantInt(v) if literal_radix(v) != 10 => (v, &[int, uint, long, ulong]), Token::ConstantInt(v) => (v, &[int, long]), Token::ConstantUnsignedInt(v) => (v, &[uint, ulong]), - Token::ConstantLong(v) if is_octal_literal(v) => (v, &[long, ulong]), + Token::ConstantLong(v) if literal_radix(v) != 10 => (v, &[long, ulong]), Token::ConstantLong(v) => (v, &[long]), Token::ConstantUnsignedLong(v) => (v, &[ulong]), Token::ConstantDouble(value_str) => { @@ -540,7 +541,8 @@ fn parse_constant(token: &SpannedToken) -> Result { Some(rest) => (true, rest), None => (false, value_str.as_str()), }; - let radix = if is_octal_literal(digits) { 8 } else { 10 }; + let radix = literal_radix(digits); + let digits = if radix == 16 { &digits[2..] } else { digits }; // i128 holds every 64-bit magnitude; anything that doesn't parse is too big for any type. let value = i128::from_str_radix(digits, radix) .ok() @@ -554,12 +556,6 @@ fn parse_constant(token: &SpannedToken) -> Result { } } -/// True for an octal integer lexeme: a leading `0` followed by more digits (`0` alone is decimal, -/// though the two readings agree). The lexer has already rejected the digits 8 and 9 in these. -fn is_octal_literal(digits: &str) -> bool { - digits.len() > 1 && digits.starts_with('0') -} - /// True if `t` is a type-specifier keyword (`int`, `long`, `signed`, `unsigned`, `double`). fn is_type_specifier(t: &Token) -> bool { matches!( @@ -614,24 +610,24 @@ fn parse_factor(tokens: &mut VecDeque) -> Result().is_err() && format!("-{v}").parse::().is_ok() ); - let is_octal = matches!( + let is_octal_or_hex = matches!( tokens.get(1), Some(SpannedToken { token: Token::ConstantInt(v) | Token::ConstantLong(v), .. }) - if is_octal_literal(v) + if literal_radix(v) != 10 ); if let Some(SpannedToken { token: Token::ConstantInt(value_str) | Token::ConstantLong(value_str), span: _, }) = tokens.get_mut(1) && !is_int_min_magnitude - && !is_octal + && !is_octal_or_hex { *value_str = format!("-{value_str}"); tokens.pop_front(); diff --git a/src/validate.rs b/src/validate.rs index b9fc561..d1eef52 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -874,15 +874,19 @@ fn warn_shift_count(left_type: &Type, rhs: &ParserExpr, span: Span) { Type::Long | Type::ULong => 64, _ => 32, }; - let count = v.as_i64(); - if count < 0 { + // An unsigned count is never negative, however large (`1 << 18446744073709551615ul`). + let (negative, too_wide) = match v.wide() { + Wide::Signed(n) => (n < 0, n >= width), + Wide::Unsigned(n) => (false, n >= width as u64), + }; + if negative { eprintln!( "{}: {}: shift count is negative {}", span, "warning".purple(), "[-Wshift-count-negative]".purple() ); - } else if count >= width { + } else if too_wide { eprintln!( "{}: {}: shift count >= width of type ({}) {}", span, @@ -894,6 +898,17 @@ fn warn_shift_count(left_type: &Type, rhs: &ParserExpr, span: Span) { } } +/// A `case` value as a constant, or `None` for `default`. +fn case_constant(case: &SwitchIntType) -> Option { + match *case { + SwitchIntType::Int(v) => Some(StaticInit::IntInit(v)), + SwitchIntType::Long(v) => Some(StaticInit::LongInit(v)), + SwitchIntType::UInt(v) => Some(StaticInit::UIntInit(v)), + SwitchIntType::ULong(v) => Some(StaticInit::ULongInit(v)), + SwitchIntType::Default => None, + } +} + /// `-Woverflow`: a constant fold whose result left the result type. NCC wraps deterministically /// (two's complement), so this flags non-portable code rather than reporting UB. Only emitted in /// constant contexts (static initializers, case labels), where `eval_constant_expr` folds. @@ -1359,7 +1374,8 @@ fn typecheck_block(block: ParserBlock, symbols: &mut SymbolTable, ret_type: &Typ /// /// `ret_type` is the enclosing function's return type, used to insert implicit casts /// on `return` expressions. Switch statements normalize case values to the controlling -/// expression's type and check for duplicates. +/// expression's type and check for duplicates; emits `-Wconstant-conversion` for a case value the +/// conversion changes. /// `span` is the statement's location, for diagnostics about the statement as a whole. fn typecheck_stmt( stmt: ParserStmt, @@ -1428,6 +1444,11 @@ fn typecheck_stmt( // Normalize cases and check for duplicates let mut normalized: HashMap, Span> = HashMap::new(); for (case, case_span) in cases.iter() { + // Each case value converts to the switch type; warn if that narrowing changes it. + if let Some(c) = case_constant(case) { + let (converted, truncated) = convert_to_type(c, switch_type); + warn_constant_conversion(truncated, &c, &converted, *case_span); + } let norm_value = case.as_i64(switch_type); if let Some(previous_span) = normalized.insert(norm_value, *case_span) { let (message, prev_note) = match norm_value { diff --git a/tests/c_programs/expected_results.json b/tests/c_programs/expected_results.json index eb98aff..e6a9298 100644 --- a/tests/c_programs/expected_results.json +++ b/tests/c_programs/expected_results.json @@ -155,5 +155,8 @@ }, "conversions/double_to_ulong_nan.c": { "return_code": 3 + }, + "lexer/hex_literals.c": { + "return_code": 10 } } diff --git a/tests/c_programs/lexer/hex_literals.c b/tests/c_programs/lexer/hex_literals.c new file mode 100644 index 0000000..cfe4e57 --- /dev/null +++ b/tests/c_programs/lexer/hex_literals.c @@ -0,0 +1,31 @@ +/* Hex integer literals (0x/0X prefix, either letter case). Like octal, unsuffixed hex literals + take unsigned types when the value only fits there (int, unsigned int, long, unsigned long). + Returns the number of checks that held; expected result is 10. */ +int main(void) { + int passed = 0; + + if (0x10 == 16 && 0XfF == 255 && 0xABCDEF == 11259375) passed = passed + 1; + if (0x10u == 16u && 0x10L == 16l && 0x10ul == 16ul && 0X10LU == 16ul) passed = passed + 1; + + /* digits that look like an exponent or octal-invalid digits are plain hex digits */ + if (0x1e5 == 485 && 0x89 == 137) passed = passed + 1; + /* a hex digit run ends the literal: 1 - 0x1 is a subtraction */ + if (1 - 0x1 == 0) passed = passed + 1; + + /* 0x80000000 fits unsigned int but not int: it is unsigned, so negating it stays positive */ + if (-0x80000000 > 0) passed = passed + 1; + /* -(2^32 - 1) wraps as unsigned int to 1 */ + if (-0xFFFFFFFF == 1) passed = passed + 1; + /* the decimal spelling of 2^31 is a long instead, so it stays negative */ + if (-2147483648 < 0) passed = passed + 1; + + /* 0x100000000 needs 64 bits: long, so it doesn't truncate */ + if (0x100000000 / 2 == 2147483648l) passed = passed + 1; + + /* 2^64 - 1 fits unsigned long only */ + if (0xFFFFFFFFFFFFFFFF == 18446744073709551615ul) passed = passed + 1; + /* hex-suffixed long that doesn't fit long becomes unsigned long */ + if (0x8000000000000000l > 0) passed = passed + 1; + + return passed; /* expect 10 */ +} diff --git a/tests/c_programs/lexer/invalid_lex/hex_bad_digit.c b/tests/c_programs/lexer/invalid_lex/hex_bad_digit.c new file mode 100644 index 0000000..4f13f1f --- /dev/null +++ b/tests/c_programs/lexer/invalid_lex/hex_bad_digit.c @@ -0,0 +1,4 @@ +/* Hex has no exponent form for integers, and hex floating literals are not supported. */ +int main(void) { + return 0x1g; +} diff --git a/tests/c_programs/lexer/invalid_lex/hex_no_digits.c b/tests/c_programs/lexer/invalid_lex/hex_no_digits.c new file mode 100644 index 0000000..696ae6f --- /dev/null +++ b/tests/c_programs/lexer/invalid_lex/hex_no_digits.c @@ -0,0 +1,3 @@ +int main(void) { + return 0x; +} diff --git a/tests/c_programs/lexer/invalid_parse/hex_too_large.c b/tests/c_programs/lexer/invalid_parse/hex_too_large.c new file mode 100644 index 0000000..e1d30ef --- /dev/null +++ b/tests/c_programs/lexer/invalid_parse/hex_too_large.c @@ -0,0 +1,4 @@ +int main(void) { + /* 2^64: too large for unsigned long */ + return 0x10000000000000000 == 0; +} diff --git a/tests/c_programs/warnings/case_conversion.c b/tests/c_programs/warnings/case_conversion.c new file mode 100644 index 0000000..5dd0703 --- /dev/null +++ b/tests/c_programs/warnings/case_conversion.c @@ -0,0 +1,33 @@ +/* -Wconstant-conversion on case labels: each case value converts to the switch's type, and a + narrowing that changes the value warns (gcc reports these as -Woverflow). Sign-only changes + and widenings don't warn. Expect exactly 3 warnings, on lines 9, 11, and 17. Runs to 0. */ +int pick(int i, unsigned int u, long l) { + int r = 0; + switch (i) { + case 1: + r = 1; + case 4294967298l: /* long -> int: 4294967298 becomes 2 (warns) */ + r = 2; + case 4294967299ul: /* unsigned long -> int: becomes 3 (warns) */ + r = 3; + case 4294967295u: /* unsigned int -> int: sign change only, -1 (no warning) */ + r = 4; + } + switch (u) { + case 8589934590l: /* long -> unsigned int: becomes 4294967294 (warns) */ + r = 5; + case -3: /* int -> unsigned int: sign change only (no warning) */ + r = 6; + } + switch (l) { + case -1: /* int -> long: widening (no warning) */ + r = 7; + case 4294967295u: /* unsigned int -> long: widening (no warning) */ + r = 8; + } + return r; +} + +int main(void) { + return pick(0, 0u, 0l); +} diff --git a/tests/c_programs/warnings/shift_count_huge_unsigned.c b/tests/c_programs/warnings/shift_count_huge_unsigned.c new file mode 100644 index 0000000..0f840c5 --- /dev/null +++ b/tests/c_programs/warnings/shift_count_huge_unsigned.c @@ -0,0 +1,7 @@ +/* A huge unsigned shift count is too wide, not negative: expect -Wshift-count-overflow only. + NCC masks shift counts, so this runs; the result isn't checked. */ +int main(void) { + int x = 1 << 18446744073709551615ul; + long y = 1l << 4294967295u; + return 0; +} diff --git a/tests/runner.rs b/tests/runner.rs index 7ef56b1..7cd9526 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -1245,6 +1245,29 @@ fn test_warnings_outside_function_bodies() { assert!(stderr.contains("-Wconstant-conversion"), "stderr was: {stderr}"); } +#[test] +fn test_case_label_constant_conversion() { + // A case value narrowed to the switch type warns; sign-only changes and widenings don't + let stderr = validate_stderr("tests/c_programs/warnings/case_conversion.c"); + let lines: Vec<&str> = stderr.lines().filter(|l| l.contains("-Wconstant-conversion")).collect(); + assert_eq!(lines.len(), 3, "stderr was: {stderr}"); + for (line, pos) in lines.iter().zip([":9:5:", ":11:5:", ":17:5:"]) { + assert!(line.contains(pos), "expected a warning at {pos}, stderr was: {stderr}"); + } +} + +#[test] +fn test_shift_count_huge_unsigned() { + // A huge unsigned count is too wide, not negative + let stderr = validate_stderr("tests/c_programs/warnings/shift_count_huge_unsigned.c"); + assert_eq!( + stderr.matches("-Wshift-count-overflow").count(), + 2, + "stderr was: {stderr}" + ); + assert!(!stderr.contains("-Wshift-count-negative"), "stderr was: {stderr}"); +} + #[test] fn test_semantic_error_messages() { // (file, text the error must contain, text it must not contain)