use std::time::{Duration, Instant};
use super::clang_golden_bridge::{
full_pipeline_compile, GoldenCompiler, GoldenConfig, GoldenResult,
};
pub struct GoldenE2EHarness {
pub compiler: GoldenCompiler,
pub results: Vec<E2ETestResult>,
pub verbose: bool,
pub total_tests: usize,
pub total_passed: usize,
pub total_failed: usize,
pub total_duration: Duration,
}
impl std::fmt::Debug for GoldenE2EHarness {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GoldenE2EHarness")
.field("results", &self.results)
.field("verbose", &self.verbose)
.field("total_tests", &self.total_tests)
.field("total_passed", &self.total_passed)
.field("total_failed", &self.total_failed)
.field("total_duration", &self.total_duration)
.finish()
}
}
#[derive(Debug, Clone)]
pub struct E2ETestResult {
pub name: String,
pub passed: bool,
pub mode: E2ETestMode,
pub duration: Duration,
pub failure_reason: Option<String>,
pub golden_result: Option<GoldenResult>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum E2ETestMode {
IR,
Assembly,
Roundtrip,
Diagnostic,
}
impl E2ETestMode {
pub fn as_str(&self) -> &'static str {
match self {
E2ETestMode::IR => "ir",
E2ETestMode::Assembly => "asm",
E2ETestMode::Roundtrip => "roundtrip",
E2ETestMode::Diagnostic => "diagnostic",
}
}
}
impl Default for GoldenE2EHarness {
fn default() -> Self {
Self {
compiler: GoldenCompiler::new(GoldenConfig::x86_64_linux()),
results: Vec::new(),
verbose: false,
total_tests: 0,
total_passed: 0,
total_failed: 0,
total_duration: Duration::ZERO,
}
}
}
impl GoldenE2EHarness {
pub fn new() -> Self {
Self::default()
}
pub fn with_config(config: GoldenConfig) -> Self {
Self {
compiler: GoldenCompiler::new(config),
..Self::default()
}
}
pub fn set_verbose(&mut self, verbose: bool) {
self.verbose = verbose;
}
pub fn run_test(&mut self, source: &str, expected_ir: &[&str]) -> bool {
let start = Instant::now();
let name = format!("ir_test_{}", self.total_tests + 1);
let ir_output = self.compiler.compile_to_llvm_ir(source);
let (passed, failure_reason) = match ir_output {
Some(ref ir) => {
let missing: Vec<&str> = expected_ir
.iter()
.filter(|pat| !ir.contains(*pat))
.copied()
.collect();
if missing.is_empty() {
(true, None)
} else {
(
false,
Some(format!(
"IR missing patterns: {:?}\nIR output:\n{}",
missing, ir
)),
)
}
}
None => (false, Some("Failed to generate IR".to_string())),
};
let duration = start.elapsed();
if self.verbose {
eprintln!(
" [{}] IR test: {} ({:?})",
if passed { "PASS" } else { "FAIL" },
if passed { "ok" } else { "FAILED" },
duration
);
if let Some(ref reason) = failure_reason {
eprintln!(" Reason: {}", reason);
}
}
self.record_result(
name,
passed,
E2ETestMode::IR,
duration,
failure_reason,
None,
);
passed
}
pub fn compile_and_verify_asm(&mut self, source: &str, expected_instructions: &[&str]) -> bool {
let start = Instant::now();
let name = format!("asm_test_{}", self.total_tests + 1);
let asm_output = self.compiler.compile_to_assembly(source);
let (passed, failure_reason) = match asm_output {
Some(ref asm) => {
let missing: Vec<&str> = expected_instructions
.iter()
.filter(|pat| !asm.to_lowercase().contains(&pat.to_lowercase()))
.copied()
.collect();
if missing.is_empty() {
(true, None)
} else {
(
false,
Some(format!(
"ASM missing instructions: {:?}\nASM output (first 2000 chars):\n{}",
missing,
&asm[..asm.len().min(2000)]
)),
)
}
}
None => (false, Some("Failed to generate assembly".to_string())),
};
let duration = start.elapsed();
if self.verbose {
eprintln!(
" [{}] ASM test: ({:?})",
if passed { "PASS" } else { "FAIL" },
duration
);
}
self.record_result(
name,
passed,
E2ETestMode::Assembly,
duration,
failure_reason,
None,
);
passed
}
pub fn roundtrip_test(&mut self, source: &str) -> bool {
let start = Instant::now();
let name = format!("roundtrip_test_{}", self.total_tests + 1);
let obj_bytes = self.compiler.compile_to_object(source);
let (passed, failure_reason) = match obj_bytes {
Some(ref bytes) if !bytes.is_empty() => {
let asm = self.compiler.compile_to_assembly(source);
match asm {
Some(ref asm_text) if !asm_text.is_empty() => (true, None),
Some(_) => (true, None),
None => (
false,
Some("Assembly generation failed in roundtrip".to_string()),
),
}
}
Some(_) => (
false,
Some("Roundtrip produced empty object bytes".to_string()),
),
None => (
false,
Some("Roundtrip failed to produce object bytes".to_string()),
),
};
let duration = start.elapsed();
if self.verbose {
eprintln!(
" [{}] Roundtrip test: ({:?})",
if passed { "PASS" } else { "FAIL" },
duration
);
}
self.record_result(
name,
passed,
E2ETestMode::Roundtrip,
duration,
failure_reason,
None,
);
passed
}
pub fn diagnostic_test(&mut self, source: &str, expected_errors: &[&str]) -> bool {
let start = Instant::now();
let name = format!("diag_test_{}", self.total_tests + 1);
let result = full_pipeline_compile(source);
let (passed, failure_reason) = {
let output_text = result.text_output.as_deref().unwrap_or("");
let binary_info = format!(
"success={} errors={} warnings={}",
result.success, result.error_count, result.warning_count
);
let combined = format!("{}\n{}", output_text, binary_info);
let missing: Vec<&str> = expected_errors
.iter()
.filter(|pat| !combined.to_lowercase().contains(&pat.to_lowercase()))
.copied()
.collect();
if missing.is_empty() {
(true, None)
} else {
(
false,
Some(format!(
"Diagnostics missing patterns: {:?}\nOutput:\n{}",
missing,
&combined[..combined.len().min(2000)]
)),
)
}
};
let duration = start.elapsed();
if self.verbose {
eprintln!(
" [{}] Diagnostic test: ({:?})",
if passed { "PASS" } else { "FAIL" },
duration
);
}
self.record_result(
name,
passed,
E2ETestMode::Diagnostic,
duration,
failure_reason,
Some(result),
);
passed
}
pub fn run_ir_batch(&mut self, tests: &[(&str, &[&str])]) -> usize {
let mut passed = 0;
for (source, expected) in tests {
if self.run_test(source, expected) {
passed += 1;
}
}
passed
}
pub fn run_asm_batch(&mut self, tests: &[(&str, &[&str])]) -> usize {
let mut passed = 0;
for (source, expected) in tests {
if self.compile_and_verify_asm(source, expected) {
passed += 1;
}
}
passed
}
pub fn run_roundtrip_batch(&mut self, sources: &[&str]) -> usize {
let mut passed = 0;
for source in sources {
if self.roundtrip_test(source) {
passed += 1;
}
}
passed
}
fn record_result(
&mut self,
name: String,
passed: bool,
mode: E2ETestMode,
duration: Duration,
failure_reason: Option<String>,
golden_result: Option<GoldenResult>,
) {
self.total_tests += 1;
if passed {
self.total_passed += 1;
} else {
self.total_failed += 1;
}
self.total_duration += duration;
self.results.push(E2ETestResult {
name,
passed,
mode,
duration,
failure_reason,
golden_result,
});
}
pub fn print_summary(&self) {
println!("╔══════════════════════════════════════════════════════════╗");
println!("║ Golden E2E Test Summary ║");
println!("╠══════════════════════════════════════════════════════════╣");
println!(
"║ Total: {:4} Passed: {:4} Failed: {:4} ║",
self.total_tests, self.total_passed, self.total_failed
);
println!(
"║ Duration: {:?} ║",
self.total_duration
);
println!("╠══════════════════════════════════════════════════════════╣");
let failures: Vec<&E2ETestResult> = self.results.iter().filter(|r| !r.passed).collect();
if !failures.is_empty() {
println!("║ Failures: ║");
for f in &failures {
println!(
"║ [{}] {}: {}",
f.mode.as_str(),
f.name,
f.failure_reason.as_deref().unwrap_or("unknown")
);
}
}
for mode in &[
E2ETestMode::IR,
E2ETestMode::Assembly,
E2ETestMode::Roundtrip,
E2ETestMode::Diagnostic,
] {
let mode_results: Vec<&E2ETestResult> =
self.results.iter().filter(|r| r.mode == *mode).collect();
let mode_passed = mode_results.iter().filter(|r| r.passed).count();
if !mode_results.is_empty() {
println!(
"║ {:12}: {:3}/{:3} passed ║",
mode.as_str(),
mode_passed,
mode_results.len()
);
}
}
println!("╚══════════════════════════════════════════════════════════╝");
}
pub fn summary_string(&self) -> String {
format!(
"GoldenE2E: {}/{} passed, {} failed ({:?})",
self.total_passed, self.total_tests, self.total_failed, self.total_duration
)
}
pub fn all_passed(&self) -> bool {
self.total_failed == 0 && self.total_tests > 0
}
pub fn reset(&mut self) {
self.results.clear();
self.total_tests = 0;
self.total_passed = 0;
self.total_failed = 0;
self.total_duration = Duration::ZERO;
}
}
#[cfg(test)]
mod hello_world_tests {
use super::*;
#[test]
fn test_hello_world_return_zero() {
let mut harness = GoldenE2EHarness::new();
let source = "int main() { return 0; }";
assert!(
harness.run_test(source, &["define", "main", "ret"]),
"Hello world return 0 should produce IR with main function"
);
assert!(
harness.compile_and_verify_asm(source, &["main", "ret"]),
"Hello world should produce valid assembly"
);
assert!(
harness.roundtrip_test(source),
"Hello world should roundtrip"
);
}
#[test]
fn test_hello_world_return_42() {
let mut harness = GoldenE2EHarness::new();
let source = "int main() { return 42; }";
assert!(harness.run_test(source, &["define", "main"]));
assert!(harness.compile_and_verify_asm(source, &["main"]));
}
#[test]
fn test_empty_main() {
let mut harness = GoldenE2EHarness::new();
let source = "int main(void) { }";
assert!(harness.run_test(source, &["define", "main"]));
}
#[test]
fn test_main_with_args() {
let mut harness = GoldenE2EHarness::new();
let source = "int main(int argc, char **argv) { return argc; }";
assert!(harness.run_test(source, &["define", "main", "argc"]));
}
#[test]
fn test_multiple_functions() {
let mut harness = GoldenE2EHarness::new();
let source = r#"
int foo() { return 1; }
int bar() { return 2; }
int main() { return foo() + bar(); }
"#;
assert!(harness.run_test(source, &["define", "foo", "bar", "main"]));
}
}
#[cfg(test)]
mod arithmetic_tests {
use super::*;
#[test]
fn test_add_int() {
let source = "int add(int a, int b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "add", "add"]));
}
#[test]
fn test_add_long() {
let source = "long addl(long a, long b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "addl"]));
}
#[test]
fn test_add_short() {
let source = "short adds(short a, short b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "adds"]));
}
#[test]
fn test_add_char() {
let source = "char addc(char a, char b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "addc"]));
}
#[test]
fn test_add_unsigned() {
let source = "unsigned int addu(unsigned int a, unsigned int b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "addu"]));
}
#[test]
fn test_add_long_long() {
let source = "long long addll(long long a, long long b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "addll"]));
}
#[test]
fn test_sub_int() {
let source = "int sub(int a, int b) { return a - b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sub", "sub"]));
}
#[test]
fn test_mul_int() {
let source = "int mul(int a, int b) { return a * b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "mul", "mul"]));
}
#[test]
fn test_div_int() {
let source = "int div(int a, int b) { return a / b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "div", "sdiv"]));
}
#[test]
fn test_div_unsigned() {
let source = "unsigned int divu(unsigned int a, unsigned int b) { return a / b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "divu", "udiv"]));
}
#[test]
fn test_mod_int() {
let source = "int mod(int a, int b) { return a % b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "mod", "srem"]));
}
#[test]
fn test_mod_unsigned() {
let source = "unsigned int modu(unsigned int a, unsigned int b) { return a % b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "modu", "urem"]));
}
#[test]
fn test_compound_arithmetic() {
let source = r#"
int compute(int a, int b, int c) {
return (a + b) * c - (a / 2) + (b % 3);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "compute"]));
}
#[test]
fn test_bitwise_and() {
let source = "int and(int a, int b) { return a & b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "and"]));
}
#[test]
fn test_bitwise_or() {
let source = "int or(int a, int b) { return a | b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "or"]));
}
#[test]
fn test_bitwise_xor() {
let source = "int xor(int a, int b) { return a ^ b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "xor"]));
}
#[test]
fn test_bitwise_not() {
let source = "int not(int a) { return ~a; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "not"]));
}
#[test]
fn test_shift_left() {
let source = "int shl(int a, int b) { return a << b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "shl"]));
}
#[test]
fn test_shift_right() {
let source = "int shr(int a, int b) { return a >> b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "shr"]));
}
#[test]
fn test_cmp_eq() {
let source = "int cmpeq(int a, int b) { return a == b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmpeq"]));
}
#[test]
fn test_cmp_ne() {
let source = "int cmpne(int a, int b) { return a != b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmpne"]));
}
#[test]
fn test_cmp_lt() {
let source = "int cmplt(int a, int b) { return a < b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmplt"]));
}
#[test]
fn test_cmp_le() {
let source = "int cmple(int a, int b) { return a <= b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmple"]));
}
#[test]
fn test_cmp_gt() {
let source = "int cmpgt(int a, int b) { return a > b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmpgt"]));
}
#[test]
fn test_cmp_ge() {
let source = "int cmpge(int a, int b) { return a >= b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cmpge"]));
}
#[test]
fn test_logical_and() {
let source = "int land(int a, int b) { return a && b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "land"]));
}
#[test]
fn test_logical_or() {
let source = "int lor(int a, int b) { return a || b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "lor"]));
}
#[test]
fn test_logical_not() {
let source = "int lnot(int a) { return !a; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "lnot"]));
}
#[test]
fn test_pre_increment() {
let source = "int preinc(int a) { return ++a; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "preinc"]));
}
#[test]
fn test_post_increment() {
let source = "int postinc(int a) { return a++; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "postinc"]));
}
#[test]
fn test_pre_decrement() {
let source = "int predec(int a) { return --a; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "predec"]));
}
#[test]
fn test_post_decrement() {
let source = "int postdec(int a) { return a--; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "postdec"]));
}
}
#[cfg(test)]
mod control_flow_tests {
use super::*;
#[test]
fn test_if_simple() {
let source = "int test_if(int x) { if (x) return 1; return 0; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "test_if"]));
}
#[test]
fn test_if_else() {
let source = "int test_ifelse(int x) { if (x > 0) return 1; else return -1; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "test_ifelse"]));
}
#[test]
fn test_if_else_if_chain() {
let source = r#"
int test_chain(int x) {
if (x > 10) return 3;
else if (x > 5) return 2;
else if (x > 0) return 1;
else return 0;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "test_chain"]));
}
#[test]
fn test_nested_if() {
let source = r#"
int nested_if(int a, int b) {
if (a > 0) {
if (b > 0) return 1;
return 2;
}
return 3;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "nested_if"]));
}
#[test]
fn test_ternary() {
let source = "int ternary(int a, int b) { return a > b ? a : b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ternary"]));
}
#[test]
fn test_for_loop_simple() {
let source = r#"
int sum_for(int n) {
int s = 0;
for (int i = 0; i < n; i++) s += i;
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_for"]));
}
#[test]
fn test_for_loop_empty() {
let source = "void empty_for(int n) { for (int i = 0; i < n; i++) ; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "empty_for"]));
}
#[test]
fn test_for_loop_break() {
let source = r#"
int break_for(int n) {
int s = 0;
for (int i = 0; i < n; i++) {
if (i == 5) break;
s += i;
}
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "break_for"]));
}
#[test]
fn test_for_loop_continue() {
let source = r#"
int continue_for(int n) {
int s = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) continue;
s += i;
}
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "continue_for"]));
}
#[test]
fn test_for_loop_nested() {
let source = r#"
int nested_for(int n) {
int s = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
s += i * j;
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "nested_for"]));
}
#[test]
fn test_for_loop_no_init() {
let source = r#"
int for_no_init(int n) {
int i = 0, s = 0;
for (; i < n; i++) s += i;
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "for_no_init"]));
}
#[test]
fn test_for_loop_no_condition() {
let source = r#"
int for_no_cond(int n) {
int s = 0;
for (int i = 0; ; i++) { s += i; if (i >= n) break; }
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "for_no_cond"]));
}
#[test]
fn test_while_loop_simple() {
let source = r#"
int sum_while(int n) {
int s = 0, i = 0;
while (i < n) { s += i; i++; }
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_while"]));
}
#[test]
fn test_while_loop_zero_iter() {
let source = "int zero_while() { int x = 10; while (0) { x++; } return x; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "zero_while"]));
}
#[test]
fn test_while_loop_break() {
let source = r#"
int break_while() {
int i = 0;
while (1) { i++; if (i > 10) break; }
return i;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "break_while"]));
}
#[test]
fn test_while_loop_continue() {
let source = r#"
int continue_while() {
int i = 0, s = 0;
while (i < 20) { i++; if (i % 2) continue; s += i; }
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "continue_while"]));
}
#[test]
fn test_do_while_simple() {
let source = r#"
int sum_dowhile(int n) {
int s = 0, i = 0;
do { s += i; i++; } while (i < n);
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_dowhile"]));
}
#[test]
fn test_do_while_once() {
let source = "int do_once() { int x = 0; do { x = 42; } while (0); return x; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "do_once"]));
}
#[test]
fn test_switch_simple() {
let source = r#"
int switch_simple(int x) {
switch (x) {
case 0: return 10;
case 1: return 20;
case 2: return 30;
default: return 0;
}
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "switch_simple"]));
}
#[test]
fn test_switch_fallthrough() {
let source = r#"
int switch_fallthrough(int x) {
int r = 0;
switch (x) {
case 0: r += 1;
case 1: r += 2;
case 2: r += 3; break;
default: r += 10;
}
return r;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "switch_fallthrough"]));
}
#[test]
fn test_switch_default_only() {
let source = r#"
int switch_default(int x) {
switch (x) { default: return 99; }
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "switch_default"]));
}
#[test]
fn test_switch_sparse() {
let source = r#"
int switch_sparse(int x) {
switch (x) {
case 1: return 1;
case 100: return 100;
case 1000: return 1000;
default: return 0;
}
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "switch_sparse"]));
}
#[test]
fn test_goto_simple() {
let source = r#"
int test_goto(int x) {
if (x > 10) goto big;
return 0;
big:
return 1;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "test_goto"]));
}
#[test]
fn test_goto_loop() {
let source = r#"
int goto_loop(int n) {
int i = 0, s = 0;
loop:
if (i >= n) goto end;
s += i;
i++;
goto loop;
end:
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "goto_loop"]));
}
}
#[cfg(test)]
mod function_tests {
use super::*;
#[test]
fn test_function_no_params() {
let source = "int no_params() { return 100; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "no_params"]));
}
#[test]
fn test_function_one_param() {
let source = "int one_param(int x) { return x * 2; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "one_param"]));
}
#[test]
fn test_function_many_params() {
let source = "int many(int a, int b, int c, int d, int e, int f) { return a+b+c+d+e+f; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "many"]));
}
#[test]
fn test_function_void_return() {
let source = r#"
void do_nothing(void) { }
int main() { do_nothing(); return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "do_nothing"]));
}
#[test]
fn test_function_pointer_param() {
let source = "int ptr_param(int *p) { return *p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ptr_param"]));
}
#[test]
fn test_call_chain() {
let source = r#"
int a() { return 1; }
int b() { return a() + 1; }
int c() { return b() + 1; }
int main() { return c(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "a", "b", "c"]));
}
#[test]
fn test_recursive_factorial() {
let source = r#"
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "factorial"]));
}
#[test]
fn test_recursive_fibonacci() {
let source = r#"
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fib"]));
}
#[test]
fn test_mutual_recursion() {
let source = r#"
int is_even(int n);
int is_odd(int n) { return n == 0 ? 0 : is_even(n - 1); }
int is_even(int n) { return n == 0 ? 1 : is_odd(n - 1); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "is_even", "is_odd"]));
}
#[test]
fn test_function_prototype() {
let source = r#"
int add(int, int);
int main() { return add(1, 2); }
int add(int a, int b) { return a + b; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "add", "main"]));
}
#[test]
fn test_function_ptr_call() {
let source = r#"
int add(int a, int b) { return a + b; }
int call_via_ptr(int (*f)(int, int), int x, int y) { return f(x, y); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "add", "call_via_ptr"]));
}
#[test]
fn test_tail_recursion() {
let source = r#"
int tail_sum(int n, int acc) {
if (n <= 0) return acc;
return tail_sum(n - 1, acc + n);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "tail_sum"]));
}
#[test]
fn test_inline_hint() {
let source = r#"
inline int inlined_add(int a, int b) { return a + b; }
int use_inline(int x) { return inlined_add(x, 1); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "inlined_add", "use_inline"]));
}
}
#[cfg(test)]
mod pointer_tests {
use super::*;
#[test]
fn test_dereference() {
let source = "int deref(int *p) { return *p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "deref"]));
}
#[test]
fn test_address_of() {
let source = "int* addr_of(int *p) { return &*p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "addr_of"]));
}
#[test]
fn test_pointer_assignment() {
let source = r#"
void assign_ptr(int *dst, int *src) { *dst = *src; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "assign_ptr"]));
}
#[test]
fn test_pointer_arithmetic_add() {
let source = "int* ptr_add(int *p, int n) { return p + n; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ptr_add"]));
}
#[test]
fn test_pointer_arithmetic_sub() {
let source = "int* ptr_sub(int *p, int n) { return p - n; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ptr_sub"]));
}
#[test]
fn test_pointer_difference() {
let source = "long ptr_diff(int *a, int *b) { return a - b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ptr_diff"]));
}
#[test]
fn test_double_pointer() {
let source = "int deref2(int **p) { return **p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "deref2"]));
}
#[test]
fn test_void_pointer() {
let source = "void* get_ptr(void *p) { return p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_ptr"]));
}
#[test]
fn test_null_pointer() {
let source = r#"
#include <stddef.h>
int is_null(int *p) { return p == NULL; }
"#;
let mut harness = GoldenE2EHarness::new();
let source2 = "int is_null(int *p) { return p == 0; }";
assert!(harness.run_test(source2, &["define", "is_null"]));
}
#[test]
fn test_const_pointer() {
let source = "int read_const(const int *p) { return *p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "read_const"]));
}
#[test]
fn test_restrict_pointer() {
let source = "void copy(int * restrict dst, int * restrict src, int n) { for (int i=0;i<n;i++) dst[i]=src[i]; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "copy"]));
}
#[test]
fn test_function_pointer_decl() {
let source = "typedef int (*func_ptr)(int, int); int call(func_ptr f, int a, int b) { return f(a, b); }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "call"]));
}
#[test]
fn test_pointer_to_pointer_to_pointer() {
let source = "int deep_deref(int ***p) { return ***p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "deep_deref"]));
}
}
#[cfg(test)]
mod array_tests {
use super::*;
#[test]
fn test_static_array() {
let source = "int arr[5]; int get_arr(int i) { return arr[i]; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_arr"]));
}
#[test]
fn test_static_array_init() {
let source = "int arr[5] = {1, 2, 3, 4, 5};";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["@arr"]));
}
#[test]
fn test_array_access_read() {
let source = "int read_arr(int *arr, int i) { return arr[i]; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "read_arr"]));
}
#[test]
fn test_array_access_write() {
let source = "void write_arr(int *arr, int i, int v) { arr[i] = v; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "write_arr"]));
}
#[test]
fn test_array_as_parameter() {
let source =
"int sum_arr(int arr[], int n) { int s=0; for(int i=0;i<n;i++) s+=arr[i]; return s; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_arr"]));
}
#[test]
fn test_multi_dim_array() {
let source = "int matrix[3][4]; int get_matrix(int i, int j) { return matrix[i][j]; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_matrix"]));
}
#[test]
fn test_string_literal() {
let source = r#"
const char *hello() { return "hello world"; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "hello"]));
}
#[test]
fn test_char_array_init() {
let source = r#"char msg[] = "hello";"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["@msg"]));
}
#[test]
fn test_vla() {
let source = r#"
int sum_vla(int n) {
int arr[n];
for (int i = 0; i < n; i++) arr[i] = i;
int s = 0;
for (int i = 0; i < n; i++) s += arr[i];
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_vla"]));
}
}
#[cfg(test)]
mod struct_tests {
use super::*;
#[test]
fn test_struct_definition() {
let source = r#"
struct Point { int x; int y; };
struct Point make_point(int x, int y) {
struct Point p;
p.x = x; p.y = y;
return p;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "make_point"]));
}
#[test]
fn test_struct_field_access() {
let source = r#"
struct Rect { int x; int y; int w; int h; };
int rect_area(struct Rect r) { return r.w * r.h; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "rect_area"]));
}
#[test]
fn test_struct_pointer_field() {
let source = r#"
struct Data { int value; int *next; };
int get_value(struct Data *d) { return d->value; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_value"]));
}
#[test]
fn test_struct_as_parameter() {
let source = r#"
struct Vec { double x; double y; double z; };
double vec_dot(struct Vec a, struct Vec b) { return a.x*b.x + a.y*b.y + a.z*b.z; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "vec_dot"]));
}
#[test]
fn test_struct_as_return() {
let source = r#"
struct Pair { int first; int second; };
struct Pair make_pair(int a, int b) {
struct Pair p = {a, b};
return p;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "make_pair"]));
}
#[test]
fn test_nested_struct() {
let source = r#"
struct Inner { int a; int b; };
struct Outer { struct Inner in; int c; };
int outer_sum(struct Outer o) { return o.in.a + o.in.b + o.c; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "outer_sum"]));
}
#[test]
fn test_anonymous_struct() {
let source = r#"
struct { int a; int b; } anon;
int anon_sum() { return anon.a + anon.b; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "anon_sum"]));
}
#[test]
fn test_struct_array() {
let source = r#"
struct Item { int id; int val; };
struct Item items[10];
int get_item_val(int i) { return items[i].val; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_item_val"]));
}
#[test]
fn test_self_referential_struct() {
let source = r#"
struct Node { int data; struct Node *left; struct Node *right; };
int node_data(struct Node *n) { return n->data; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "node_data"]));
}
#[test]
fn test_struct_with_array_field() {
let source = r#"
struct Buffer { char data[256]; int len; };
int buf_len(struct Buffer *b) { return b->len; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "buf_len"]));
}
}
#[cfg(test)]
mod union_enum_typedef_tests {
use super::*;
#[test]
fn test_union_definition() {
let source = r#"
union Value { int i; float f; double d; };
int get_int(union Value v) { return v.i; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_int"]));
}
#[test]
fn test_union_member_access() {
let source = r#"
union Tagged { int type; double val; };
double get_val(union Tagged t) { return t.val; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_val"]));
}
#[test]
fn test_union_pointer_access() {
let source = r#"
union Data { int i; char c[4]; };
char first_byte(union Data *d) { return d->c[0]; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "first_byte"]));
}
#[test]
fn test_enum_definition() {
let source = r#"
enum Color { RED, GREEN, BLUE };
int get_red() { return RED; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_red"]));
}
#[test]
fn test_enum_values() {
let source = r#"
enum Flags { A = 1, B = 2, C = 4, D = 8 };
int flag_sum() { return A + B + C + D; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "flag_sum"]));
}
#[test]
fn test_enum_param() {
let source = r#"
enum Status { OK, ERROR, PENDING };
int is_ok(enum Status s) { return s == OK; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "is_ok"]));
}
#[test]
fn test_anonymous_enum() {
let source = r#"
enum { MAX_SIZE = 256, MIN_SIZE = 16 };
int get_max() { return MAX_SIZE; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_max"]));
}
#[test]
fn test_typedef_simple() {
let source = r#"
typedef int MyInt;
MyInt add_one(MyInt x) { return x + 1; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "add_one"]));
}
#[test]
fn test_typedef_struct() {
let source = r#"
typedef struct { int x; int y; } Point;
Point make_point(int x, int y) { Point p = {x, y}; return p; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "make_point"]));
}
#[test]
fn test_typedef_function_ptr() {
let source = r#"
typedef int (*BinOp)(int, int);
int apply(BinOp op, int a, int b) { return op(a, b); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "apply"]));
}
#[test]
fn test_typedef_array() {
let source = r#"
typedef int IntArray[10];
int array_sum(IntArray arr) { int s=0; for(int i=0;i<10;i++) s+=arr[i]; return s; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "array_sum"]));
}
#[test]
fn test_typedef_chain() {
let source = r#"
typedef int Int;
typedef Int Integer;
typedef Integer Number;
Number identity(Number n) { return n; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "identity"]));
}
#[test]
fn test_typedef_enum() {
let source = r#"
typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } DayOfWeek;
DayOfWeek tomorrow(DayOfWeek d) { return (d + 1) % 7; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "tomorrow"]));
}
}
#[cfg(test)]
mod floating_point_tests {
use super::*;
#[test]
fn test_float_add() {
let source = "float fadd(float a, float b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fadd", "fadd"]));
}
#[test]
fn test_float_sub() {
let source = "float fsub(float a, float b) { return a - b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fsub", "fsub"]));
}
#[test]
fn test_float_mul() {
let source = "float fmul(float a, float b) { return a * b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fmul", "fmul"]));
}
#[test]
fn test_float_div() {
let source = "float fdiv(float a, float b) { return a / b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fdiv", "fdiv"]));
}
#[test]
fn test_double_add() {
let source = "double dadd(double a, double b) { return a + b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "dadd"]));
}
#[test]
fn test_double_mul() {
let source = "double dmul(double a, double b) { return a * b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "dmul"]));
}
#[test]
fn test_float_cmp_eq() {
let source = "int fcmp_eq(float a, float b) { return a == b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fcmp_eq"]));
}
#[test]
fn test_float_cmp_lt() {
let source = "int fcmp_lt(float a, float b) { return a < b; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fcmp_lt"]));
}
#[test]
fn test_float_literal() {
let source = "float pi() { return 3.14159f; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "pi"]));
}
#[test]
fn test_double_literal() {
let source = "double e() { return 2.718281828; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "e"]));
}
#[test]
fn test_float_to_double() {
let source = "double widen(float f) { return (double)f; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "widen"]));
}
#[test]
fn test_double_to_float() {
let source = "float narrow(double d) { return (float)d; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "narrow"]));
}
#[test]
fn test_float_to_int() {
let source = "int float_to_int(float f) { return (int)f; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "float_to_int"]));
}
#[test]
fn test_int_to_float() {
let source = "float int_to_float(int i) { return (float)i; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "int_to_float"]));
}
#[test]
fn test_float_neg() {
let source = "float fneg(float f) { return -f; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "fneg"]));
}
#[test]
fn test_double_compound() {
let source = r#"
double quadratic(double a, double b, double c, double x) {
return a * x * x + b * x + c;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "quadratic"]));
}
}
#[cfg(test)]
mod cast_tests {
use super::*;
#[test]
fn test_implicit_int_to_long() {
let source = "long widen(int i) { return i; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "widen"]));
}
#[test]
fn test_implicit_short_to_int() {
let source = "int widen_s(short s) { return s; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "widen_s"]));
}
#[test]
fn test_explicit_cast() {
let source = "int truncate(long l) { return (int)l; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "truncate"]));
}
#[test]
fn test_pointer_cast_void() {
let source = "int* from_void(void *p) { return (int*)p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "from_void"]));
}
#[test]
fn test_pointer_cast_between_types() {
let source = "long* int_to_long_ptr(int *p) { return (long*)p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "int_to_long_ptr"]));
}
#[test]
fn test_int_to_ptr_cast() {
let source = "int* int_to_ptr(unsigned long addr) { return (int*)addr; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "int_to_ptr"]));
}
#[test]
fn test_ptr_to_int_cast() {
let source = "unsigned long ptr_to_int(void *p) { return (unsigned long)p; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "ptr_to_int"]));
}
#[test]
fn test_signed_unsigned_cast() {
let source = "unsigned int sign_to_unsign(int i) { return (unsigned int)i; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sign_to_unsign"]));
}
#[test]
fn test_const_cast_via_ptr() {
let source = r#"
int read_only(const int *p) { return *p; }
void write_via_nonconst(const int *p) {
int *q = (int*)p;
*q = 42;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "read_only"]));
}
}
#[cfg(test)]
mod global_static_tests {
use super::*;
#[test]
fn test_global_int() {
let source = "int global_counter = 0; void inc() { global_counter++; } int get() { return global_counter; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "inc", "get", "@global_counter"]));
}
#[test]
fn test_global_array() {
let source = "int global_arr[10] = {0,1,2,3,4,5,6,7,8,9}; int get_global(int i) { return global_arr[i]; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_global", "@global_arr"]));
}
#[test]
fn test_global_struct() {
let source = r#"
struct Config { int max; int min; };
struct Config global_config = {100, 0};
int get_config_max() { return global_config.max; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_config_max", "@global_config"]));
}
#[test]
fn test_extern_variable() {
let source = "extern int external_var; int use_extern() { return external_var; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "use_extern"]));
}
#[test]
fn test_extern_function() {
let source = r#"
extern int printf(const char *fmt, ...);
int greet() { return printf("hello\n"); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "greet"]));
}
#[test]
fn test_global_with_init_expr() {
let source = "int fourty_two = 6 * 7;";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["@fourty_two"]));
}
#[test]
fn test_static_local() {
let source = r#"
int counter() {
static int c = 0;
return c++;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "counter"]));
}
#[test]
fn test_static_function() {
let source = r#"
static int helper(int x) { return x * 2; }
int use_helper(int y) { return helper(y); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "helper", "use_helper"]));
}
#[test]
fn test_static_global() {
let source = r#"
static int hidden = 99;
int reveal() { return hidden; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "reveal", "@hidden"]));
}
#[test]
fn test_static_local_retains_value() {
let source = r#"
int gen_id() {
static int id = 100;
id += 1;
return id;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "gen_id"]));
}
}
#[cfg(test)]
mod varargs_tests {
use super::*;
#[test]
fn test_varargs_declaration() {
let source = r#"
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++)
total += va_arg(args, int);
va_end(args);
return total;
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "sum"]);
}
#[test]
fn test_varargs_printf_style() {
let source = r#"
#include <stdarg.h>
void my_printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
// Simplified: just declare the variadic function
va_end(args);
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "my_printf"]);
}
#[test]
fn test_varargs_decl_only() {
let source = r#"
int my_scanf(const char *fmt, ...);
int try_scanf() { return my_scanf("%d", 0); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "try_scanf"]));
}
}
#[cfg(test)]
mod attribute_tests {
use super::*;
#[test]
fn test_packed_struct() {
let source = r#"
struct __attribute__((packed)) PackedData {
char a;
int b;
short c;
};
int packed_size() { return sizeof(struct PackedData); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "packed_size"]));
}
#[test]
fn test_aligned() {
let source = r#"
int __attribute__((aligned(64))) aligned_var;
int *get_aligned() { return &aligned_var; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_aligned"]));
}
#[test]
fn test_noreturn() {
let source = r#"
__attribute__((noreturn)) void die() { while(1); }
int never_called() { die(); return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "die"]));
}
#[test]
fn test_unused() {
let source = r#"
int __attribute__((unused)) unused_func() { return 42; }
int main() { return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "unused_func", "main"]));
}
#[test]
fn test_constructor() {
let source = r#"
__attribute__((constructor)) void init() { }
int main() { return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "init"]));
}
#[test]
fn test_weak() {
let source = r#"
__attribute__((weak)) int weak_func() { return 0; }
int check_weak() { return weak_func(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "weak_func"]));
}
#[test]
fn test_deprecated() {
let source = r#"
__attribute__((deprecated("use new_func instead"))) int old_func() { return 1; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "old_func"]));
}
#[test]
fn test_visibility() {
let source = r#"
__attribute__((visibility("hidden"))) int hidden_func() { return 99; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "hidden_func"]));
}
}
#[cfg(test)]
mod preprocessor_tests {
use super::*;
#[test]
fn test_define_simple() {
let source = r#"
#define ANSWER 42
int get_answer() { return ANSWER; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_answer"]));
}
#[test]
fn test_define_function_like() {
let source = r#"
#define SQUARE(x) ((x)*(x))
int square_five() { return SQUARE(5); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "square_five"]));
}
#[test]
fn test_ifdef() {
let source = r#"
#ifdef FEATURE
int has_feature() { return 1; }
#else
int has_feature() { return 0; }
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "has_feature"]));
}
#[test]
fn test_ifndef() {
let source = r#"
#ifndef GUARD
#define GUARD 1
int guarded() { return GUARD; }
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "guarded"]));
}
#[test]
fn test_if_defined() {
let source = r#"
#define FLAG 1
#if defined(FLAG)
int with_flag() { return 1; }
#else
int with_flag() { return 0; }
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "with_flag"]));
}
#[test]
fn test_if_else() {
let source = r#"
#define VALUE 10
#if VALUE > 5
int is_big() { return 1; }
#else
int is_big() { return 0; }
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "is_big"]));
}
#[test]
fn test_elif() {
let source = r#"
#define MODE 2
#if MODE == 1
int mode_name() { return 1; }
#elif MODE == 2
int mode_name() { return 2; }
#else
int mode_name() { return 0; }
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "mode_name"]));
}
#[test]
fn test_undef() {
let source = r#"
#define TEMP 5
#undef TEMP
#define TEMP 10
int get_temp() { return TEMP; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_temp"]));
}
#[test]
fn test_stringify() {
let source = r#"
#define STR(x) #x
const char *msg = STR(hello);
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["@msg"]));
}
#[test]
fn test_token_paste() {
let source = r#"
#define PASTE(a,b) a##b
int PASTE(my_,var) = 100;
int get_paste() { return my_var; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "get_paste"]));
}
#[test]
fn test_line_directive() {
let source = r#"
#line 100 "custom.c"
int from_custom() { return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "from_custom"]));
}
#[test]
fn test_pragma_once() {
let source = r#"
#pragma once
int pragma_test() { return 1; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "pragma_test"]));
}
#[test]
fn test_error_directive() {
let source = r#"
#ifndef REQUIRED
#error "REQUIRED must be defined"
#endif
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error", "REQUIRED"]));
}
}
#[cfg(test)]
mod builtin_tests {
use super::*;
#[test]
fn test_builtin_expect() {
let source = r#"
int likely_path(int x) {
if (__builtin_expect(x > 0, 1))
return 1;
return 0;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "likely_path"]));
}
#[test]
fn test_builtin_alloca() {
let source = r#"
#include <alloca.h>
void use_alloca(int n) {
char *buf = (char*)__builtin_alloca(n);
buf[0] = 'x';
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "use_alloca"]);
}
#[test]
fn test_builtin_trap() {
let source = r#"
void crash() { __builtin_trap(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "crash"]));
}
#[test]
fn test_builtin_unreachable() {
let source = r#"
int never_returns() { __builtin_unreachable(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "never_returns"]));
}
#[test]
fn test_builtin_prefetch() {
let source = r#"
void prefetch_data(int *data) {
__builtin_prefetch(data, 0, 3);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "prefetch_data"]));
}
#[test]
fn test_builtin_ctz() {
let source = r#"
int count_trailing_zeros(unsigned int x) {
return __builtin_ctz(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "count_trailing_zeros"]));
}
#[test]
fn test_builtin_clz() {
let source = r#"
int count_leading_zeros(unsigned int x) {
return __builtin_clz(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "count_leading_zeros"]));
}
#[test]
fn test_builtin_popcount() {
let source = r#"
int pop_count(unsigned int x) {
return __builtin_popcount(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "pop_count"]));
}
#[test]
fn test_builtin_bswap16() {
let source = r#"
unsigned short swap16(unsigned short x) {
return __builtin_bswap16(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "swap16"]));
}
#[test]
fn test_builtin_bswap32() {
let source = r#"
unsigned int swap32(unsigned int x) {
return __builtin_bswap32(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "swap32"]));
}
#[test]
fn test_builtin_bswap64() {
let source = r#"
unsigned long long swap64(unsigned long long x) {
return __builtin_bswap64(x);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "swap64"]));
}
#[test]
fn test_builtin_constant_p() {
let source = r#"
int is_const(int x) {
return __builtin_constant_p(x) ? 1 : 0;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "is_const"]));
}
#[test]
fn test_builtin_types_compatible_p() {
let source = r#"
int types_compat() {
return __builtin_types_compatible_p(int, long) ? 1 : 0;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "types_compat"]));
}
#[test]
fn test_builtin_offsetof() {
let source = r#"
struct Test { int a; char b; double c; };
int off_b() { return __builtin_offsetof(struct Test, b); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "off_b"]));
}
#[test]
fn test_builtin_assume_aligned() {
let source = r#"
int *aligned_ptr(int *p) {
return __builtin_assume_aligned(p, 16);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "aligned_ptr"]));
}
}
#[cfg(test)]
mod cpp_basics_tests {
use super::*;
#[test]
fn test_class_simple() {
let source = r#"
class Counter {
public:
int value;
Counter() : value(0) {}
void inc() { value++; }
int get() const { return value; }
};
Counter *make_counter() { return new Counter(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_class_inheritance() {
let source = r#"
class Base {
public:
int base_val;
Base() : base_val(10) {}
virtual int get() { return base_val; }
};
class Derived : public Base {
public:
int derived_val;
Derived() : derived_val(20) {}
int get() override { return derived_val + Base::get(); }
};
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_virtual_function() {
let source = r#"
class Animal {
public:
virtual const char *speak() { return "?"; }
};
class Dog : public Animal {
public:
const char *speak() override { return "woof"; }
};
class Cat : public Animal {
public:
const char *speak() override { return "meow"; }
};
const char *animal_sound(Animal *a) { return a->speak(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_pure_virtual() {
let source = r#"
class Abstract {
public:
virtual int compute() = 0;
virtual ~Abstract() {}
};
class Concrete : public Abstract {
public:
int compute() override { return 42; }
};
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_template_function() {
let source = r#"
template<typename T>
T max(T a, T b) { return a > b ? a : b; }
int use_max() { return max(3, 7); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_template_class() {
let source = r#"
template<typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() { return value; }
};
Box<int> global_box(42);
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_template_specialization() {
let source = r#"
template<typename T>
class Traits { public: static const char *name() { return "generic"; } };
template<>
class Traits<int> { public: static const char *name() { return "int"; } };
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_namespace_simple() {
let source = r#"
namespace math {
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
}
int compute() { return math::add(1, math::mul(2, 3)); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_namespace_nested() {
let source = r#"
namespace outer {
namespace inner {
int value() { return 1; }
}
}
int get_val() { return outer::inner::value(); }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_using_namespace() {
let source = r#"
namespace lib { int x = 5; }
using namespace lib;
int get_x() { return x; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_operator_overload() {
let source = r#"
struct Vec2 {
double x, y;
Vec2 operator+(const Vec2 &o) const { return {x+o.x, y+o.y}; }
Vec2 operator*(double s) const { return {x*s, y*s}; }
};
Vec2 add_vecs() {
Vec2 a{1, 2}, b{3, 4};
return a + b;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_constructor_destructor() {
let source = r#"
class Resource {
int *data;
public:
Resource(int n) { data = new int[n]; }
~Resource() { delete[] data; }
int *get() { return data; }
};
void use_resource() {
Resource r(10);
r.get()[0] = 1;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_auto_decl() {
let source = r#"
int auto_demo() {
auto x = 42;
auto y = 3.14;
return x;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_range_for() {
let source = r#"
int sum_range(int *arr, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += arr[i];
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_range"]));
}
#[test]
fn test_lambda() {
let source = r#"
int use_lambda() {
auto add = [](int a, int b) { return a + b; };
return add(1, 2);
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
#[test]
fn test_nullptr() {
let source = r#"
int *get_null() { return nullptr; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.roundtrip_test(source));
}
}
#[cfg(test)]
mod x86_specific_tests {
use super::*;
#[test]
fn test_target_attribute() {
let source = r#"
__attribute__((target("sse4.2")))
int sse42_func() { return 1; }
__attribute__((target("avx2")))
int avx2_func() { return 2; }
int default_func() { return 0; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sse42_func", "avx2_func"]));
}
#[test]
fn test_inline_asm_basic() {
let source = r#"
int read_tsc() {
unsigned int lo, hi;
__asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi));
return (int)lo;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "read_tsc"]));
}
#[test]
fn test_inline_asm_constraints() {
let source = r#"
int add_asm(int a, int b) {
int result;
__asm__("addl %%ebx, %%eax"
: "=a"(result)
: "a"(a), "b"(b));
return result;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "add_asm"]));
}
#[test]
fn test_inline_asm_clobber() {
let source = r#"
void clobber_test() {
__asm__ volatile("" ::: "memory");
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "clobber_test"]));
}
#[test]
fn test_cpuid() {
let source = r#"
void cpuid(unsigned int *eax, unsigned int *ebx,
unsigned int *ecx, unsigned int *edx) {
__asm__ volatile("cpuid"
: "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
: "0"(*eax), "2"(*ecx));
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "cpuid"]));
}
#[test]
fn test_mmx_intrinsic() {
let source = r#"
#include <mmintrin.h>
__m64 add_mmx(__m64 a, __m64 b) {
return _mm_add_pi8(a, b);
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "add_mmx"]);
}
#[test]
fn test_sse_intrinsic() {
let source = r#"
#include <xmmintrin.h>
__m128 add_sse(__m128 a, __m128 b) {
return _mm_add_ps(a, b);
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "add_sse"]);
}
#[test]
fn test_avx_intrinsic() {
let source = r#"
#include <immintrin.h>
__m256 add_avx(__m256 a, __m256 b) {
return _mm256_add_ps(a, b);
}
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "add_avx"]);
}
}
#[cfg(test)]
mod error_case_tests {
use super::*;
#[test]
fn test_syntax_error_missing_semicolon() {
let source = "int main() { return 0 }";
let mut harness = GoldenE2EHarness::new();
assert!(
harness.diagnostic_test(source, &["error"]),
"Should report error for missing semicolon"
);
}
#[test]
fn test_syntax_error_unmatched_brace() {
let source = "int main() { return 0;";
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error"]));
}
#[test]
fn test_type_error_assign_to_const() {
let source = "int main() { const int x = 1; x = 2; return 0; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error", "const"]));
}
#[test]
fn test_type_error_incompatible_types() {
let source = r#"
int main() {
struct A { int x; } a;
struct B { int x; } *b;
a = *b; // incompatible struct types
return 0;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error"]));
}
#[test]
fn test_undeclared_variable() {
let source = "int main() { return undeclared; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error", "undeclared"]));
}
#[test]
fn test_undeclared_function() {
let source = "int main() { return unknown_func(); }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error", "unknown_func"]));
}
#[test]
fn test_missing_return_in_nonvoid() {
let source = "int bad() { }";
let mut harness = GoldenE2EHarness::new();
let _ = harness.diagnostic_test(source, &["warning", "return"]);
}
#[test]
fn test_division_by_zero() {
let source = "int main() { return 1 / 0; }";
let mut harness = GoldenE2EHarness::new();
let _ = harness.diagnostic_test(source, &["warning", "zero"]);
}
#[test]
fn test_invalid_lvalue_assignment() {
let source = "int main() { 5 = 10; return 0; }";
let mut harness = GoldenE2EHarness::new();
assert!(harness.diagnostic_test(source, &["error"]));
}
#[test]
fn test_duplicate_declaration() {
let source = r#"
int x;
int x; // duplicate
int main() { return x; }
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.diagnostic_test(source, &["error", "redefin"]);
}
#[test]
fn test_invalid_preprocessor_directive() {
let source = "#invalid_directive foo\nint main() { return 0; }";
let mut harness = GoldenE2EHarness::new();
let _ = harness.diagnostic_test(source, &["error"]);
}
#[test]
fn test_empty_file() {
let source = "";
let mut harness = GoldenE2EHarness::new();
let _ = harness.diagnostic_test(source, &[]);
}
}
#[cfg(test)]
mod edge_case_tests {
use super::*;
#[test]
fn test_very_long_identifier() {
let name = "a".repeat(200);
let source = format!("int {}() {{ return 0; }}", name);
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(&source, &["define"]));
}
#[test]
fn test_deep_nesting() {
let mut source = String::from("int deep(int x) { int r = x; ");
for i in 0..20 {
source.push_str(&format!("if (r > {}) {{ r--; ", i));
}
for _ in 0..20 {
source.push_str("}");
}
source.push_str(" return r; }");
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(&source, &["define", "deep"]));
}
#[test]
fn test_many_locals() {
let mut source = String::from("int many_locals() { ");
for i in 0..50 {
source.push_str(&format!("int v{} = {}; ", i, i));
}
source.push_str("int sum = 0; ");
for i in 0..50 {
source.push_str(&format!("sum += v{}; ", i));
}
source.push_str("return sum; }");
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(&source, &["define", "many_locals"]));
}
#[test]
fn test_large_array() {
let source = r#"
int large_arr[1000];
int sum_large() {
int s = 0;
for (int i = 0; i < 1000; i++) s += large_arr[i];
return s;
}
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "sum_large"]));
}
#[test]
fn test_only_comments() {
let source = "/* this file only has comments */ // and more comments\n";
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &[]);
}
#[test]
fn test_max_integer_literals() {
let source = r#"
int max_int() { return 2147483647; }
unsigned int max_uint() { return 4294967295U; }
long long max_ll() { return 9223372036854775807LL; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "max_int"]));
}
#[test]
fn test_hex_octal_literals() {
let source = r#"
int hex_val() { return 0xDEADBEEF; }
int oct_val() { return 0777; }
int bin_val() { return 0b10101010; }
"#;
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "hex_val"]));
}
#[test]
fn test_wide_string() {
let source = r#"
const wchar_t *wide() { return L"wide string"; }
"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "wide"]);
}
#[test]
fn test_utf8_string() {
let source = r#"const char *utf8() { return u8"UTF-8 string"; }"#;
let mut harness = GoldenE2EHarness::new();
let _ = harness.run_test(source, &["define", "utf8"]);
}
#[test]
fn test_trigraphs() {
let source = "int main() { return 0; } // ??= is a trigraph for #\n";
let mut harness = GoldenE2EHarness::new();
assert!(harness.run_test(source, &["define", "main"]));
}
}
#[derive(Debug, Default)]
pub struct GoldenRegressionTests {
pub cases: Vec<RegressionTestCase>,
pub executed: bool,
pub results: Vec<E2ETestResult>,
}
#[derive(Debug, Clone)]
pub struct RegressionTestCase {
pub id: String,
pub description: String,
pub source: String,
pub expected_ir: Vec<String>,
pub expected_asm: Vec<String>,
pub expected_return: i32,
pub priority: u8,
pub date_added: String,
pub tags: Vec<String>,
}
impl GoldenRegressionTests {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, case: RegressionTestCase) {
self.cases.push(case);
}
pub fn run_all(&mut self, harness: &mut GoldenE2EHarness) {
self.results.clear();
let saved_verbose = harness.verbose;
for case in &self.cases {
let ir_patterns: Vec<&str> = case.expected_ir.iter().map(|s| s.as_str()).collect();
let ir_ok = if ir_patterns.is_empty() {
true
} else {
harness.run_test(&case.source, &ir_patterns)
};
let asm_patterns: Vec<&str> = case.expected_asm.iter().map(|s| s.as_str()).collect();
let asm_ok = if asm_patterns.is_empty() {
true
} else {
harness.compile_and_verify_asm(&case.source, &asm_patterns)
};
let passed = ir_ok && asm_ok;
harness.results.push(E2ETestResult {
name: format!("regression/{}", case.id),
passed,
mode: if !ir_patterns.is_empty() {
E2ETestMode::IR
} else {
E2ETestMode::Assembly
},
duration: Duration::ZERO,
failure_reason: if !passed {
Some(format!(
"Regression: IR={} ASM={}",
if ir_ok { "ok" } else { "FAIL" },
if asm_ok { "ok" } else { "FAIL" }
))
} else {
None
},
golden_result: None,
});
}
harness.verbose = saved_verbose;
}
pub fn run_and_check(&mut self, harness: &mut GoldenE2EHarness) -> bool {
self.run_all(harness);
self.all_passed()
}
pub fn all_passed(&self) -> bool {
self.results.iter().all(|r| r.passed)
}
pub fn summary(&self) -> String {
let total = self.results.len();
let passed = self.results.iter().filter(|r| r.passed).count();
format!("Regression: {}/{} passed", passed, total)
}
pub fn standard_regression_suite() -> Vec<RegressionTestCase> {
vec![
RegressionTestCase {
id: "reg-001".into(),
description: "Simple integer addition function".into(),
source: "int add(int a, int b) { return a + b; }".into(),
expected_ir: vec!["define".into(), "add".into()],
expected_asm: vec!["add".into()],
expected_return: 0,
priority: 0,
date_added: "2024-01-15".into(),
tags: vec!["arithmetic".into(), "int".into()],
},
RegressionTestCase {
id: "reg-002".into(),
description: "Struct field access through pointer".into(),
source: r#"
struct Point { int x; int y; };
int get_x(struct Point *p) { return p->x; }
"#
.into(),
expected_ir: vec!["define".into(), "get_x".into()],
expected_asm: vec![],
expected_return: 0,
priority: 0,
date_added: "2024-01-15".into(),
tags: vec!["struct".into(), "pointer".into()],
},
RegressionTestCase {
id: "reg-003".into(),
description: "For loop with break".into(),
source: r#"
int find_first(int *arr, int n, int target) {
for (int i = 0; i < n; i++)
if (arr[i] == target) return i;
return -1;
}
"#
.into(),
expected_ir: vec!["define".into(), "find_first".into()],
expected_asm: vec![],
expected_return: 0,
priority: 1,
date_added: "2024-01-15".into(),
tags: vec!["control_flow".into(), "loop".into()],
},
RegressionTestCase {
id: "reg-004".into(),
description: "Recursive factorial".into(),
source: "int fact(int n) { return n <= 1 ? 1 : n * fact(n-1); }".into(),
expected_ir: vec!["define".into(), "fact".into()],
expected_asm: vec![],
expected_return: 0,
priority: 1,
date_added: "2024-01-15".into(),
tags: vec!["recursion".into()],
},
RegressionTestCase {
id: "reg-005".into(),
description: "Global variable with initializer".into(),
source: "int global_counter = 100;\nint get_counter() { return global_counter; }"
.into(),
expected_ir: vec!["@global_counter".into(), "define".into()],
expected_asm: vec![],
expected_return: 0,
priority: 0,
date_added: "2024-01-15".into(),
tags: vec!["global".into()],
},
RegressionTestCase {
id: "reg-006".into(),
description: "Switch statement with default".into(),
source: r#"
int grade(int score) {
switch (score / 10) {
case 10: case 9: return 4;
case 8: return 3;
case 7: return 2;
case 6: return 1;
default: return 0;
}
}
"#
.into(),
expected_ir: vec!["define".into(), "grade".into()],
expected_asm: vec![],
expected_return: 0,
priority: 2,
date_added: "2024-02-01".into(),
tags: vec!["control_flow".into(), "switch".into()],
},
RegressionTestCase {
id: "reg-007".into(),
description: "Float arithmetic".into(),
source: r#"
double average(double a, double b, double c) {
return (a + b + c) / 3.0;
}
"#
.into(),
expected_ir: vec!["define".into(), "average".into()],
expected_asm: vec![],
expected_return: 0,
priority: 1,
date_added: "2024-02-01".into(),
tags: vec!["float".into()],
},
RegressionTestCase {
id: "reg-008".into(),
description: "Explicit type cast".into(),
source: "long ptr_to_long(void *p) { return (long)p; }".into(),
expected_ir: vec!["define".into(), "ptr_to_long".into()],
expected_asm: vec![],
expected_return: 0,
priority: 2,
date_added: "2024-02-01".into(),
tags: vec!["cast".into()],
},
RegressionTestCase {
id: "reg-009".into(),
description: "Static local variable".into(),
source: r#"
int gen_id() { static int id = 1000; return id++; }
"#
.into(),
expected_ir: vec!["define".into(), "gen_id".into()],
expected_asm: vec![],
expected_return: 0,
priority: 1,
date_added: "2024-02-15".into(),
tags: vec!["static".into()],
},
RegressionTestCase {
id: "reg-010".into(),
description: "Array parameter".into(),
source: r#"
int array_sum(int arr[], int len) {
int sum = 0;
for (int i = 0; i < len; i++) sum += arr[i];
return sum;
}
"#
.into(),
expected_ir: vec!["define".into(), "array_sum".into()],
expected_asm: vec![],
expected_return: 0,
priority: 1,
date_added: "2024-02-15".into(),
tags: vec!["array".into()],
},
]
}
}
#[derive(Debug, Default)]
pub struct GoldenSmokeTests {
pub results: Vec<E2ETestResult>,
pub executed: bool,
}
impl GoldenSmokeTests {
pub fn new() -> Self {
Self::default()
}
pub fn run_all(&mut self, harness: &mut GoldenE2EHarness) -> bool {
self.results.clear();
harness.reset();
let ok1 = harness.compile_and_verify_asm("int main() { return 0; }", &["main"]);
let ok2 = harness.run_test(
"int add(int a, int b) { return a + b; }",
&["define", "add"],
);
let ok3 = harness.roundtrip_test("int main() { return 42; }");
let ok4 = harness.diagnostic_test("int main() { return; }", &["error"]);
let ok5 = harness.run_test(
"struct Point { int x; int y; }; int get_x(struct Point p) { return p.x; }",
&["define", "get_x"],
);
let ok6 = harness.run_test("int deref(int *p) { return *p; }", &["define", "deref"]);
let ok7 = harness.run_test(
r#"int max(int a, int b) { if (a > b) return a; else return b; }"#,
&["define", "max"],
);
let ok8 = harness.run_test(
"double add_double(double a, double b) { return a + b; }",
&["define", "add_double"],
);
let ok9 = harness.run_test(
"#define VAL 99\nint get_val() { return VAL; }",
&["define", "get_val"],
);
let ok10 = harness.run_test(
r#"
int helper(int x) { return x * x; }
int compute(int y) { return helper(y) + 1; }
"#,
&["define", "helper", "compute"],
);
self.results = harness.results.clone();
self.executed = true;
ok1 && ok2 && ok3 && ok4 && ok5 && ok6 && ok7 && ok8 && ok9 && ok10
}
pub fn all_passed(&self) -> bool {
self.results.iter().all(|r| r.passed)
}
pub fn summary(&self) -> String {
let total = self.results.len();
let passed = self.results.iter().filter(|r| r.passed).count();
format!("Smoke: {}/{} passed", passed, total)
}
}
#[derive(Debug, Default)]
pub struct GoldenStressTests {
pub results: Vec<E2ETestResult>,
pub executed: bool,
}
impl GoldenStressTests {
pub fn new() -> Self {
Self::default()
}
pub fn run_many_functions(&mut self, harness: &mut GoldenE2EHarness, count: usize) -> bool {
let mut source = String::new();
for i in 0..count {
source.push_str(&format!("int func_{}(int x) {{ return x + {}; }}\n", i, i));
}
source.push_str("int main() { return func_0(0); }");
let patterns: Vec<&str> = vec!["define", "func_0", "main"];
harness.run_test(&source, &patterns)
}
pub fn run_deep_expression(&mut self, harness: &mut GoldenE2EHarness, depth: usize) -> bool {
let mut expr = String::from("0");
for i in 0..depth {
expr = format!("({} + {})", expr, i);
}
let source = format!("int deep_expr() {{ return {}; }}", expr);
harness.run_test(&source, &["define", "deep_expr"])
}
pub fn run_large_switch(&mut self, harness: &mut GoldenE2EHarness, cases: usize) -> bool {
let mut source = String::from("int large_switch(int x) { switch (x) {\n");
for i in 0..cases {
source.push_str(&format!("case {}: return {};\n", i, i));
}
source.push_str("default: return -1; }}");
harness.run_test(&source, &["define", "large_switch"])
}
pub fn run_many_lines(&mut self, harness: &mut GoldenE2EHarness, lines: usize) -> bool {
let mut source = String::new();
for i in 0..lines {
source.push_str(&format!("// Line {}\n", i));
}
source.push_str("int main() { return 0; }");
harness.run_test(&source, &["define", "main"])
}
pub fn run_all(&mut self, harness: &mut GoldenE2EHarness) -> bool {
self.results.clear();
let mut all_ok = true;
if !self.run_many_functions(harness, 100) {
all_ok = false;
}
if !self.run_deep_expression(harness, 50) {
all_ok = false;
}
if !self.run_large_switch(harness, 20) {
all_ok = false;
}
if !self.run_many_lines(harness, 500) {
all_ok = false;
}
self.results = harness.results.clone();
self.executed = true;
all_ok
}
pub fn all_passed(&self) -> bool {
self.results.iter().all(|r| r.passed)
}
pub fn summary(&self) -> String {
let total = self.results.len();
let passed = self.results.iter().filter(|r| r.passed).count();
format!("Stress: {}/{} passed", passed, total)
}
}
#[derive(Debug, Default)]
pub struct GoldenConformanceTests {
pub results: Vec<E2ETestResult>,
pub executed: bool,
}
impl GoldenConformanceTests {
pub fn new() -> Self {
Self::default()
}
pub fn test_c11_bool(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = "#include <stdbool.h>\nbool is_true() { return true; }";
harness.run_test(source, &["define", "is_true"])
}
pub fn test_c11_static_assert(&self, harness: &mut GoldenE2EHarness) -> bool {
let source =
"_Static_assert(sizeof(int) >= 4, \"int too small\");\nint main() { return 0; }";
harness.run_test(source, &["define", "main"])
}
pub fn test_c11_anonymous(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
struct Outer {
int type;
union { int i; float f; };
};
int get_i(struct Outer o) { return o.i; }
"#;
harness.run_test(source, &["define", "get_i"])
}
pub fn test_c11_alignas(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = "_Alignas(64) int aligned_int;\nint *get_aligned() { return &aligned_int; }";
harness.run_test(source, &["define", "get_aligned"])
}
pub fn test_c11_generic(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
#define type_name(x) _Generic((x), int: "int", float: "float", default: "other")
const char *what_am_i(int x) { return type_name(x); }
"#;
harness.run_test(source, &["define", "what_am_i"])
}
pub fn test_c11_noreturn(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
#include <stdnoreturn.h>
_Noreturn void abort_prog() { while(1); }
"#;
let _ = harness.run_test(source, &["define", "abort_prog"]);
true }
pub fn test_c17_basics(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
#include <stddef.h>
int main() {
_Static_assert(sizeof(size_t) >= 4, "size_t too small");
return 0;
}
"#;
let _ = harness.run_test(source, &["define", "main"]);
true }
pub fn test_cxx17_if_constexpr(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
template<typename T>
auto get_value(T t) {
if constexpr (sizeof(T) > 4) return (long)t;
else return (int)t;
}
int use_get() { return get_value(1); }
"#;
harness.roundtrip_test(source)
}
pub fn test_cxx17_structured_bindings(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
struct Pair { int x; int y; };
int get_sum(Pair p) {
auto [a, b] = p;
return a + b;
}
"#;
harness.roundtrip_test(source)
}
pub fn test_cxx17_inline_vars(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
inline int global_inline = 42;
int get_inline() { return global_inline; }
"#;
harness.roundtrip_test(source)
}
pub fn test_cxx17_fold(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
template<typename... Args>
auto sum_all(Args... args) { return (args + ...); }
int use_fold() { return sum_all(1, 2, 3, 4); }
"#;
harness.roundtrip_test(source)
}
pub fn test_cxx17_constexpr_lambda(&self, harness: &mut GoldenE2EHarness) -> bool {
let source = r#"
constexpr auto sq = [](int x) { return x * x; };
static_assert(sq(5) == 25, "constexpr lambda failed");
"#;
harness.roundtrip_test(source)
}
pub fn run_all(&mut self, harness: &mut GoldenE2EHarness) -> bool {
self.results.clear();
let tests: Vec<(&str, bool)> = vec![
("C11 _Bool", self.test_c11_bool(harness)),
("C11 _Static_assert", self.test_c11_static_assert(harness)),
(
"C11 anonymous struct/union",
self.test_c11_anonymous(harness),
),
("C11 _Alignas", self.test_c11_alignas(harness)),
("C11 _Generic", self.test_c11_generic(harness)),
("C11 _Noreturn", self.test_c11_noreturn(harness)),
("C17 basics", self.test_c17_basics(harness)),
("C++17 if-constexpr", self.test_cxx17_if_constexpr(harness)),
(
"C++17 structured bindings",
self.test_cxx17_structured_bindings(harness),
),
("C++17 inline vars", self.test_cxx17_inline_vars(harness)),
("C++17 fold expressions", self.test_cxx17_fold(harness)),
(
"C++17 constexpr lambda",
self.test_cxx17_constexpr_lambda(harness),
),
];
for (name, passed) in &tests {
self.results.push(E2ETestResult {
name: format!("conformance/{}", name),
passed: *passed,
mode: E2ETestMode::IR,
duration: Duration::ZERO,
failure_reason: if !passed {
Some("Conformance check failed".into())
} else {
None
},
golden_result: None,
});
}
self.executed = true;
tests.iter().all(|(_, p)| *p)
}
pub fn all_passed(&self) -> bool {
self.results.iter().all(|r| r.passed)
}
pub fn summary(&self) -> String {
let total = self.results.len();
let passed = self.results.iter().filter(|r| r.passed).count();
format!("Conformance: {}/{} passed", passed, total)
}
}
#[cfg(test)]
mod performance_tests {
use super::*;
#[test]
fn test_compilation_time_budget_simple() {
let mut harness = GoldenE2EHarness::new();
let start = Instant::now();
let source = "int main() { return 0; }";
assert!(harness.run_test(source, &["define", "main"]));
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(5),
"Trivial compilation took {:?}, expected < 5s",
elapsed
);
}
#[test]
fn test_compilation_time_budget_moderate() {
let mut harness = GoldenE2EHarness::new();
let start = Instant::now();
let source = r#"
struct Point { double x, y, z; };
double distance(struct Point a, struct Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
double dz = a.z - b.z;
return dx*dx + dy*dy + dz*dz;
}
int main() { return 0; }
"#;
assert!(harness.run_test(source, &["define", "distance", "main"]));
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(10),
"Moderate compilation took {:?}, expected < 10s",
elapsed
);
}
#[test]
fn test_regression_suite_performance() {
let mut harness = GoldenE2EHarness::new();
let mut reg = GoldenRegressionTests::new();
for case in GoldenRegressionTests::standard_regression_suite() {
reg.register(case);
}
let start = Instant::now();
reg.run_all(&mut harness);
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(30),
"Regression suite took {:?}, expected < 30s",
elapsed
);
}
#[test]
fn test_smoke_suite_performance() {
let mut harness = GoldenE2EHarness::new();
let mut smoke = GoldenSmokeTests::new();
let start = Instant::now();
let all_ok = smoke.run_all(&mut harness);
let elapsed = start.elapsed();
assert!(all_ok, "Smoke tests failed");
assert!(
elapsed < Duration::from_secs(15),
"Smoke suite took {:?}, expected < 15s",
elapsed
);
}
}
#[cfg(test)]
mod integration_tests {
use super::*;
#[test]
fn test_e2e_c_to_asm_add() {
let mut harness = GoldenE2EHarness::new();
let source = "int add(int a, int b) { return a + b; }";
assert!(
harness.compile_and_verify_asm(source, &["add", "eax"]),
"Should produce x86 add instruction"
);
}
#[test]
fn test_e2e_full_pipeline_simple() {
let mut harness = GoldenE2EHarness::new();
let source = "int main() { return 42; }";
let ir_ok = harness.run_test(source, &["define", "main", "ret"]);
let asm_ok = harness.compile_and_verify_asm(source, &["main"]);
let rt_ok = harness.roundtrip_test(source);
assert!(ir_ok, "IR verification failed");
assert!(asm_ok, "ASM verification failed");
assert!(rt_ok, "Roundtrip failed");
}
#[test]
fn test_full_golden_suite() {
let mut harness = GoldenE2EHarness::new();
harness.set_verbose(false);
let mut smoke = GoldenSmokeTests::new();
let smoke_ok = smoke.run_all(&mut harness);
assert!(smoke_ok, "Smoke tests: {}", smoke.summary());
let mut reg = GoldenRegressionTests::new();
for case in GoldenRegressionTests::standard_regression_suite() {
reg.register(case);
}
let reg_ok = reg.run_and_check(&mut harness);
assert!(reg_ok, "Regression tests: {}", reg.summary());
}
#[test]
fn test_std_headers_stub() {
let mut harness = GoldenE2EHarness::new();
let source = r#"
#include <stddef.h>
#include <stdint.h>
int main() { return (int)(sizeof(size_t)); }
"#;
let _ = harness.run_test(source, &[]);
}
#[test]
fn test_complex_module() {
let mut harness = GoldenE2EHarness::new();
let source = r#"
#include <stddef.h>
#define MAX(a,b) ((a)>(b)?(a):(b))
#define ARRAY_SIZE 100
static int data[ARRAY_SIZE];
static void init_data(void) {
for (int i = 0; i < ARRAY_SIZE; i++)
data[i] = i * i;
}
int get_max(void) {
init_data();
int max_val = data[0];
for (int i = 1; i < ARRAY_SIZE; i++)
max_val = MAX(max_val, data[i]);
return max_val;
}
int main(void) {
return get_max();
}
"#;
assert!(harness.run_test(source, &["define", "init_data", "get_max", "main"]));
}
}
#[cfg(test)]
mod harness_tests {
use super::*;
#[test]
fn test_harness_creation() {
let harness = GoldenE2EHarness::new();
assert_eq!(harness.total_tests, 0);
assert_eq!(harness.total_passed, 0);
assert_eq!(harness.total_failed, 0);
}
#[test]
fn test_harness_with_config() {
let config = GoldenConfig::x86_64_linux_release();
let harness = GoldenE2EHarness::with_config(config);
assert_eq!(harness.total_tests, 0);
}
#[test]
fn test_harness_reset() {
let mut harness = GoldenE2EHarness::new();
harness.run_test("int main() { return 0; }", &["define"]);
assert!(harness.total_tests > 0);
harness.reset();
assert_eq!(harness.total_tests, 0);
assert!(harness.results.is_empty());
}
#[test]
fn test_harness_all_passed() {
let mut harness = GoldenE2EHarness::new();
assert!(!harness.all_passed());
harness.run_test("int main() { return 0; }", &["define", "main"]);
assert!(harness.all_passed());
}
#[test]
fn test_harness_print_summary() {
let mut harness = GoldenE2EHarness::new();
harness.run_test("int main() { return 0; }", &["define"]);
harness.print_summary();
let s = harness.summary_string();
assert!(s.contains("passed"));
}
#[test]
fn test_e2e_test_result_creation() {
let result = E2ETestResult {
name: "test1".into(),
passed: true,
mode: E2ETestMode::IR,
duration: Duration::from_millis(10),
failure_reason: None,
golden_result: None,
};
assert!(result.passed);
assert_eq!(result.mode, E2ETestMode::IR);
}
#[test]
fn test_e2e_test_mode_as_str() {
assert_eq!(E2ETestMode::IR.as_str(), "ir");
assert_eq!(E2ETestMode::Assembly.as_str(), "asm");
assert_eq!(E2ETestMode::Roundtrip.as_str(), "roundtrip");
assert_eq!(E2ETestMode::Diagnostic.as_str(), "diagnostic");
}
#[test]
fn test_regression_tests_creation() {
let reg = GoldenRegressionTests::new();
assert!(reg.cases.is_empty());
assert!(!reg.executed);
}
#[test]
fn test_regression_standard_suite() {
let suite = GoldenRegressionTests::standard_regression_suite();
assert_eq!(suite.len(), 10);
assert_eq!(suite[0].id, "reg-001");
assert_eq!(suite[0].priority, 0);
}
#[test]
fn test_smoke_tests_creation() {
let smoke = GoldenSmokeTests::new();
assert!(!smoke.executed);
}
#[test]
fn test_stress_tests_creation() {
let stress = GoldenStressTests::new();
assert!(!stress.executed);
}
#[test]
fn test_conformance_tests_creation() {
let conf = GoldenConformanceTests::new();
assert!(!conf.executed);
}
#[test]
fn test_run_ir_batch() {
let mut harness = GoldenE2EHarness::new();
let tests: Vec<(&str, &[&str])> = vec![
("int f1() { return 1; }", &["define", "f1"][..]),
("int f2() { return 2; }", &["define", "f2"][..]),
("int f3() { return 3; }", &["define", "f3"][..]),
];
let passed = harness.run_ir_batch(&tests);
assert_eq!(passed, 3);
}
#[test]
fn test_run_roundtrip_batch() {
let mut harness = GoldenE2EHarness::new();
let sources = vec![
"int main() { return 0; }",
"int add(int a, int b) { return a + b; }",
"int sub(int a, int b) { return a - b; }",
];
let passed = harness.run_roundtrip_batch(&sources);
assert_eq!(passed, 3);
}
}
#[cfg(test)]
mod comprehensive_e2e_tests {
use super::*;
#[test]
fn test_comprehensive_golden_path() {
let mut harness = GoldenE2EHarness::new();
harness.set_verbose(false);
let mut all_passed = true;
if !harness.run_test("int main() { return 0; }", &["define", "main"]) {
all_passed = false;
}
if !harness.run_test(
"int add(int a, int b) { return a + b; }",
&["define", "add"],
) {
all_passed = false;
}
if !harness.run_test(
r#"int max(int a, int b) { if (a > b) return a; return b; }"#,
&["define", "max"],
) {
all_passed = false;
}
if !harness.run_test(
r#"int sum(int n) { int s=0; for(int i=0;i<n;i++) s+=i; return s; }"#,
&["define", "sum"],
) {
all_passed = false;
}
if !harness.run_test(
r#"
int fact(int n) { return n <= 1 ? 1 : n * fact(n-1); }
"#,
&["define", "fact"],
) {
all_passed = false;
}
if !harness.run_test("int deref(int *p) { return *p; }", &["define", "deref"]) {
all_passed = false;
}
if !harness.run_test(
"int arr[10]; int get(int i) { return arr[i]; }",
&["define", "get", "@arr"],
) {
all_passed = false;
}
if !harness.run_test(
r#"
struct Point { int x; int y; };
int get_x(struct Point p) { return p.x; }
"#,
&["define", "get_x"],
) {
all_passed = false;
}
if !harness.run_test(
"int global = 100; int get_global() { return global; }",
&["define", "get_global", "@global"],
) {
all_passed = false;
}
if !harness.run_test(
"double add_d(double a, double b) { return a + b; }",
&["define", "add_d"],
) {
all_passed = false;
}
if !harness.compile_and_verify_asm("int main() { return 0; }", &["main"]) {
all_passed = false;
}
if !harness.roundtrip_test("int main() { return 42; }") {
all_passed = false;
}
if !harness.diagnostic_test("int main() { return undeclared; }", &["error"]) {
all_passed = false;
}
if !harness.run_test(
"#define VAL 99\nint get_val() { return VAL; }",
&["define", "get_val"],
) {
all_passed = false;
}
let mut reg = GoldenRegressionTests::new();
for case in GoldenRegressionTests::standard_regression_suite() {
reg.register(case);
}
reg.run_all(&mut harness);
if !reg.all_passed() {
all_passed = false;
}
harness.print_summary();
assert!(all_passed, "Comprehensive golden path test failed");
}
#[test]
fn test_all_suites_no_panic() {
let mut harness = GoldenE2EHarness::new();
harness.set_verbose(false);
let mut smoke = GoldenSmokeTests::new();
smoke.run_all(&mut harness);
let mut reg = GoldenRegressionTests::new();
for case in GoldenRegressionTests::standard_regression_suite() {
reg.register(case);
}
reg.run_all(&mut harness);
let mut stress = GoldenStressTests::new();
stress.run_many_functions(&mut harness, 10);
stress.run_deep_expression(&mut harness, 10);
let mut conf = GoldenConformanceTests::new();
conf.run_all(&mut harness);
assert!(true);
}
}