From bdb57bd16a313e8674d4292a9a5882adfd365629 Mon Sep 17 00:00:00 2001 From: Akuli Date: Tue, 31 Jan 2023 01:40:23 +0200 Subject: [PATCH] Add an error for trying to pass an array as vararg (#161) --- src/typecheck.c | 7 +++++++ tests/should_succeed/file.jou | 1 - tests/wrong_type/array_vararg.jou | 10 ++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tests/wrong_type/array_vararg.jou diff --git a/src/typecheck.c b/src/typecheck.c index ac3709e4..4d36da03 100644 --- a/src/typecheck.c +++ b/src/typecheck.c @@ -478,6 +478,13 @@ static const Type *typecheck_function_call(TypeContext *ctx, const AstCall *call for (int i = sig->nargs; i < call->nargs; i++) { // This code runs for varargs, e.g. the things to format in printf(). ExpressionTypes *types = typecheck_expression_not_void(ctx, &call->args[i]); + + if (types->type->kind == TYPE_ARRAY) { + fail_with_error( + call->args[i].location, + "arrays cannot be passed as varargs (try &array[0] instead of array)"); + } + if ((is_integer_type(types->type) && types->type->data.width_in_bits < 32) || types->type == boolType) { diff --git a/tests/should_succeed/file.jou b/tests/should_succeed/file.jou index 44edba16..3bfccdd4 100644 --- a/tests/should_succeed/file.jou +++ b/tests/should_succeed/file.jou @@ -37,7 +37,6 @@ def read_hello_123() -> void: rewind(f) text: byte[100] fgets(&text[0], 100, f) - # FIXME: crashes at runtime if you pass the array without & printf("got %s", &text[0]) # Output: got hello 123 fclose(f) diff --git a/tests/wrong_type/array_vararg.jou b/tests/wrong_type/array_vararg.jou new file mode 100644 index 00000000..80d70bb0 --- /dev/null +++ b/tests/wrong_type/array_vararg.jou @@ -0,0 +1,10 @@ +from "stdlib/io.jou" import printf + +def main() -> int: + s: byte[3] + s[0] = 'h' + s[1] = 'i' + s[2] = '\0' + printf("%s\n", &s[0]) # This works. No error + printf("%s\n", s) # Error: arrays cannot be passed as varargs (try &array[0] instead of array) + return 0