harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

commit 3f79921d1bfd6992ffa843e4b0be30eefd408098
parent 13688980dfdc1652ae8c008e30533a95447b72bd
Author: Sebastian <sebastian@sebsite.pw>
Date:   Mon,  9 May 2022 21:24:09 -0400

check: ensure constant slice-alloc capacity >= length

For slice allocation, checks at compile time that the capacity is
greater than or equal to the length of the initializer, if both the
capacity and the initializer are part of the translation-compatible
subset. No runtime checks are included in this commit.

References: https://todo.sr.ht/~sircmpwn/hare/477
References: https://todo.sr.ht/~sircmpwn/hare/581
Signed-off-by: Sebastian <sebastian@sebsite.pw>

Diffstat:
Msrc/check.c | 16++++++++++++++++
1 file changed, 16 insertions(+), 0 deletions(-)

diff --git a/src/check.c b/src/check.c @@ -1,5 +1,6 @@ #include <assert.h> #include <stdarg.h> +#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -360,6 +361,21 @@ check_expr_alloc_slice(struct context *ctx, } expr->alloc.cap = lower_implicit_cast(&builtin_type_size, expr->alloc.cap); + struct expression cap = {0}; + if (expr->alloc.init->type == EXPR_CONSTANT + && eval_expr(ctx, expr->alloc.cap, &cap) == EVAL_OK) { + uintmax_t len = 0; + for (struct array_constant *c = expr->alloc.init->constant.array; + c != NULL; c = c->next) { + len++; + } + if (cap.constant.uval < len) { + error(ctx, aexpr->alloc.cap->loc, expr, + "Slice capacity cannot be smaller than length of initializer"); + return; + } + } + const struct type *membtype = type_dealias(objtype)->array.members; expr->result = type_store_lookup_slice(ctx->store, membtype);