From 4b90420027255258197b71542d7e722a8266454a Mon Sep 17 00:00:00 2001 From: "Yu En Siao (Dr.Xiao)" Date: Sun, 15 Sep 2024 17:53:48 +0800 Subject: [PATCH 1/2] Check for invalid digits when parsing octal constants Originally, the parser had the ability to parse octal numbers but did not check whether the digits were valid. Therefore, this commit improves the implementation to include the validation check. --- src/parser.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/parser.c b/src/parser.c index fbfb4e1..8ce1c24 100644 --- a/src/parser.c +++ b/src/parser.c @@ -634,7 +634,10 @@ void read_numeric_param(block_t *parent, basic_block_t *bb, int is_neg) } while (is_hex(token[i])); } else { /* octal */ do { - c = token[i++] - '0'; + c = token[i++]; + if (c > '7') + error("Invalid numeric constant"); + c -= '0'; value = (value * 8) + c; } while (is_digit(token[i])); } From 823dde39913ca086c4b498a15269397dceb4e38e Mon Sep 17 00:00:00 2001 From: "Yu En Siao (Dr.Xiao)" Date: Sun, 15 Sep 2024 22:30:41 +0800 Subject: [PATCH 2/2] Add a test case for parsing invalid octal numbers Add a test case with invalid octal numbers to 'tests/driver.sh' to ensure the lexer/parser can detect invalid octal numbers. --- tests/driver.sh | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/driver.sh b/tests/driver.sh index ce66fd3..ec655c9 100755 --- a/tests/driver.sh +++ b/tests/driver.sh @@ -62,6 +62,31 @@ function try_output() { try "$expected" "$expected_output" "$input" } +# try_compile_error - test shecc with invalid C program +# Usage: +# - try_compile_error invalid_input_code +# compile "invalid_input_code" with shecc so that shecc generates a +# compilation error message. +# +# This function uses shecc to compile invalid code and obtains the exit +# code returned by shecc. The exit code must be a non-zero value to +# indicate that shecc has the ability to parse the invalid code and +# output an error message. +function try_compile_error() { + local input=$(cat) + + local tmp_in="$(mktemp --suffix .c)" + local tmp_exe="$(mktemp)" + echo "$input" > "$tmp_in" + "$SHECC" -o "$tmp_exe" "$tmp_in" + local exit_code=$? + + if [ 0 == $exit_code ]; then + echo "Error: compilation is passed." + exit 1 + fi +} + function items() { local expected="$1" local input="$2" @@ -238,6 +263,14 @@ int main() { } EOF +try_compile_error << EOF +int main() { + int a = 03, b = 01118, c = 091; + printf("%d %d %d\n", a, b, c); + return 0; +} +EOF + try_ 1 << EOF int is_odd(int x);