From d04aea3c5875cd2859d6ab961256b11189c49839 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Thu, 28 Oct 2021 10:40:22 +0200 Subject: Prepare for closure capture --- src/bytecode/objects.c | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) (limited to 'src/bytecode/objects.c') diff --git a/src/bytecode/objects.c b/src/bytecode/objects.c index 3b4a2eb..c2fb989 100644 --- a/src/bytecode/objects.c +++ b/src/bytecode/objects.c @@ -23,11 +23,13 @@ make_symbol(StringView sv) { } Object -make_lambda(StringView name) { +make_lambda(Chunk *chunk) { Object obj = { .type = OBJ_TYPE_LAMBDA, - .chunk = chunk_init(name), }; + obj.closure = malloc(sizeof(Closure)); + obj.closure->chunk = chunk; + array_init(obj.closure->values, 0); return obj; } @@ -58,8 +60,9 @@ object_display(Object obj) { // printf(")"); } break; case OBJ_TYPE_LAMBDA: { + Chunk *chunk = obj.closure->chunk; printf("#{procedure:%.*s}", - (int)array_size(obj.chunk->name), obj.chunk->name); + (int)array_size(chunk->name), chunk->name); } break; case OBJ_TYPE_ERR: { printf("#{error}"); @@ -69,13 +72,21 @@ object_display(Object obj) { } void -object_free(Object obj) { - if (IS_STRING(obj) || IS_SYMBOL(obj)) { - array_free(obj.text); +object_free(Object *obj) { + if (IS_STRING(*obj) || IS_SYMBOL(*obj)) { + array_free(obj->text); return; } - if (IS_LAMBDA(obj)) { - chunk_free(obj.chunk); + if (IS_LAMBDA(*obj)) { + Closure *closure = obj->closure; + for (size_t i = 0; i < array_size(closure->values); i++) { + object_free(&closure->values[i]); + } + array_free(closure->values); + // NOTE: we are leaking memory without this, we'll need a GC + // soon... + // chunk_free(closure->chunk); + free(closure); } } @@ -104,7 +115,7 @@ object_equal(Object a, Object b) { } } break; case OBJ_TYPE_LAMBDA: { - return a.chunk == b.chunk; + return a.closure == b.closure; } break; default: { return false; -- cgit v1.2.1