refcount: own constants, closure attrs and generators

- bytecode constant pool: cat_bytecode_add_const retains, and
  cat_bytecode_function_free releases each constant, so a chunk owns its
  constants even when built from borrowed values (bc_run).  The compiler
  drops its own reference via add_const_owned.
- closures: function_destroy releases upvalues (if any) and the attrs
  table.
- generators: add a destroy that frees the operand stack and releases
  the captured closure and arguments; generator_new retains them.

Verified with AddressSanitizer (detect_leaks=0): suite 130 green, no
ASan reports.
This commit is contained in:
Minus committed 2026-11-17 22:15:10 +00:00
1 parent fddfa5dea2
commit ee5861a25c
4 files changed
+52 -12

No files matched your search

+18 -6
View File
@@ -112,7 +112,19 @@ static FuncCtx *ctx(Compiler *c)
static int add_string(Compiler *c, const char *s)
{
return cat_bytecode_add_const(cur_fn(c), cat_types_ascii_text_new(s));
CAT_VALUE_Value *v = cat_types_ascii_text_new(s);
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v); /* pool owns it now */
return k;
}
/* Add a freshly-created constant: the pool takes a reference, we drop
* ours, so the constant lives exactly as long as the chunk. */
static int add_const_owned(Compiler *c, CAT_VALUE_Value *v)
{
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v);
return k;
}
static CAT_BYTECODE_Function *cur_fn(Compiler *c)
@@ -284,13 +296,13 @@ static void primary(Compiler *c)
switch (t.kind) {
case CAT_LEXER_TOK_INT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_int_new(t.ival));
int k = add_const_owned(c, cat_types_int_new(t.ival));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
}
case CAT_LEXER_TOK_FLOAT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_float_new(t.fval));
int k = add_const_owned(c, cat_types_float_new(t.fval));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
@@ -353,7 +365,7 @@ static void primary(Compiler *c)
c->lx.line = sl;
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
add_const_owned(c,
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
@@ -363,7 +375,7 @@ static void primary(Compiler *c)
} else {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
add_const_owned(c,
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
@@ -735,7 +747,7 @@ static void stat(Compiler *c)
expr(c); /* step */
else
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c), cat_types_int_new(1)),
add_const_owned(c, cat_types_int_new(1)),
0, line);
expect(c, CAT_LEXER_TOK_DO, "'do'");
slot = add_local(c, var);