diff --git a/releasenotes.md b/releasenotes.md index 1f62b0d98..51efb089e 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -40,6 +40,7 @@ - Cast removing arbitrary array indices and converting them to pointers should always be fine #1664 - Incorrect "no-libc" definition of `cos`, making it unavailable for wasm. - Fix issue with the adjoint and inverse calculations for `Matrix2x2`. +- It was possible to create 0 length arrays using byte literals. #1678 ### Stdlib changes - Add `io::MultiReader`, `io::MultiWriter`, and `io::TeeReader` structs. diff --git a/src/compiler/parse_expr.c b/src/compiler/parse_expr.c index b78a4b126..a00890add 100644 --- a/src/compiler/parse_expr.c +++ b/src/compiler/parse_expr.c @@ -1751,6 +1751,11 @@ static Expr *parse_bytes_expr(ParseContext *c, Expr *left) len = new_len; advance(c); } + if (len == 0) + { + PRINT_ERROR_LAST("A byte array must be at least 1 byte long. While an array cannot be zero length, you can initialize a zero length slice using '{}'."); + return poisoned_expr; + } Expr *expr_bytes = EXPR_NEW_TOKEN(EXPR_CONST); expr_bytes->const_expr.bytes.ptr = data; expr_bytes->const_expr.bytes.len = len; diff --git a/src/compiler/types.c b/src/compiler/types.c index 5a13c55a9..cb1a697dd 100644 --- a/src/compiler/types.c +++ b/src/compiler/types.c @@ -1154,6 +1154,7 @@ static Type *type_create_array(Type *element_type, ArraySize len, bool vector, b Type *type_get_array(Type *arr_type, ArraySize len) { + ASSERT(len > 0, "Created a zero length array"); ASSERT0(type_is_valid_for_array(arr_type)); return type_create_array(arr_type, len, false, false); } diff --git a/test/test_suite/constants/empty_byte_literal.c3 b/test/test_suite/constants/empty_byte_literal.c3 new file mode 100644 index 000000000..f2de965cf --- /dev/null +++ b/test/test_suite/constants/empty_byte_literal.c3 @@ -0,0 +1,8 @@ +import std; + +fn void main() +{ + char[] cd = {}; + char[*] b = x""; // #error: must be at least 1 byte + io::printfn("%d", b.len); +} \ No newline at end of file