Fix array initializer analysis (#2925)

* Fix array initializer analysis: improved semantic checking for arrays with inferred or fixed length,
* Update phrasing

---------

Co-authored-by: Christoffer Lerno <christoffer@aegik.com>
This commit is contained in:
Samuel
2026-02-14 00:38:07 +02:00
committed by GitHub
parent 768d24d580
commit fac9054f1b
5 changed files with 12 additions and 3 deletions

View File

@@ -14,6 +14,7 @@
- Individual warning settings added.
- Change typedef and const enums to not convert from literals by default.
- Add `@constinit` to allow old typedef behaviour.
- Include actual element count in the error message when the array initializer size does not match the expected size.
### Stdlib changes
- Summarize sort macros as generic function wrappers to reduce the amount of generated code. #2831

View File

@@ -350,7 +350,7 @@ static inline bool sema_expr_analyse_array_plain_initializer(SemaContext *contex
}
if (expected_members > 0 && count > 0 && count != expected_members)
{
RETURN_SEMA_ERROR(elements[0], "Too %s elements in initializer, expected %u.", count > expected_members ? "many" : "few", expected_members);
RETURN_SEMA_ERROR(elements[0], "Too %s (%u) elements in initializer, expected %u.", count > expected_members ? "many" : "few", count, expected_members);
}
bool optional = false;
@@ -451,7 +451,7 @@ static inline bool sema_expr_analyse_array_plain_initializer(SemaContext *contex
if (!inferred_len && expected_members > count)
{
if (no_match_ref) goto NO_MATCH;
RETURN_SEMA_ERROR(elements[count - 1], "Too few elements in initializer, %d elements are needed.", expected_members);
RETURN_SEMA_ERROR(elements[count - 1], "Too few elements in initializer, %d elements are needed. Current count: %d.", expected_members, count);
}
initializer->resolve_status = RESOLVE_DONE;

View File

@@ -0,0 +1,4 @@
fn void main()
{
const int[3] ARR = {1, 2}; // #error: Too few (2) elements in initializer, expected 3
}

View File

@@ -0,0 +1,4 @@
fn void main()
{
const int[3] ARR = {1, 2, 3, 4}; // #error: Too many (4) elements in initializer, expected 3
}

View File

@@ -4,5 +4,5 @@ macro void test(int[2][6] a)
}
fn void main()
{
test({ { 1, 2 } }); // #error: Too few elements in initializer
test({ { 1, 2 } }); // #error: Too few (1) elements in initializer, expected 6
}