From 40d1e2b96f000801d0e3b983dfbcd792baa7d46f Mon Sep 17 00:00:00 2001 From: Jim Huang Date: Tue, 5 Aug 2025 21:38:20 +0800 Subject: [PATCH] Add support for testing large return values (> 255) Previously, test suite was limited to verifying return values between 0-255 due to Unix exit code constraints. It made testing functions with larger return values awkward, requiring workarounds like "(fib(16) - 987) == 0". This commit introduces a new try_large() function that: - Wraps test code in a test_function() that returns the value to test - Uses printf to output the return value instead of exit codes - Compares the printed output against expected values Close #152 --- tests/driver.sh | 74 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/tests/driver.sh b/tests/driver.sh index f49d7c15..c8880d56 100755 --- a/tests/driver.sh +++ b/tests/driver.sh @@ -114,6 +114,45 @@ function expr() { items "$expected" "exit($input);" } +# try_large - test shecc with large return values (> 255) +# Usage: +# - try_large expected_value input_code +# compile "input_code" with shecc and verify the return value by printing it +# instead of using exit code (which is limited to 0-255). +function try_large() { + local expected="$1" + local input="$(cat)" + + local tmp_in="$(mktemp --suffix .c)" + local tmp_exe="$(mktemp)" + + # Wrap the input to print the return value + cat > "$tmp_in" << EOF +int printf(char *format, ...); +$input +int main() { + int result = test_function(); + printf("%d", result); + return 0; +} +EOF + + $SHECC -o "$tmp_exe" "$tmp_in" + chmod +x $tmp_exe + + local output=$($TARGET_EXEC "$tmp_exe") + + if [ "$output" != "$expected" ]; then + echo "$input => $expected expected, but got $output" + echo "input: $tmp_in" + echo "executable: $tmp_exe" + exit 1 + else + echo "Large value test: $expected" + echo "output => $output" + fi +} + # just a number expr 0 0 expr 42 42 @@ -317,6 +356,41 @@ int main() { } EOF +# Test large fibonacci values using the new try_large function +try_large 987 << EOF +int fib(int n, int a, int b) +{ + if (n == 0) + return a; + if (n == 1) + return b; + return fib(n - 1, b, a + b); +} + +int test_function() { + return fib(16, 0, 1); /* fib(16) = 987 */ +} +EOF + +# Test other large values +try_large 1000 << EOF +int test_function() { + return 1000; +} +EOF + +try_large 65536 << EOF +int test_function() { + return 1 << 16; /* 2^16 = 65536 */ +} +EOF + +try_large 999999 << EOF +int test_function() { + return 999999; +} +EOF + try_compile_error << EOF int main() { int a = 03, b = 01118, c = 091;