Compare commits

...
5 Commits
Author SHA1 Message Date
Minus 7cdf388bf4 object, not table: fix user-facing terminology
The language is OOP with a single compound value, the object (an
anonymous `{...}` or a class instance); it is not Lua and has no
"tables".  The visible type name was already `object`; this fixes the
remaining user-facing wording:

- error messages: "object has no member 'x'", "object is not callable".
- README: drop the "Lua-like" phrasing; describe member objects, not
  tables.
- self-hosted front-end AST node `t="object"` (was "table"), updated
  across parser/compiler/checker.
- test comments/expected output aligned ("object:").

The internal C symbols keep the cat_types_table_* naming convention.
Suite stays 130 green.
2026-11-17 23:14:17 +00:00
Minus a73600e221 refcount: globals, modules and stdlib own their values
Extend the ownership discipline to the VM's global table and the
non-container value producers:

- cat_vm_set_global_owned: takes ownership of a freshly-created value
  (used for the native-registered globals and the `module` table).
- cat_vm_free releases the saved `module` stack entries and the globals
  table (which cascades: each stored value drops its reference).
- module enter/leave retains the saved `module` while it is off-global.
- stdlib/ffi/file build their tables with owned values and drop the
  transient reference after a store.

Suite stays 130 green.
2026-11-17 22:43:29 +00:00
Minus ee5861a25c 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.
2026-11-17 22:15:10 +00:00
Minus fddfa5dea2 refcount: containers own their values (table, list)
Wiring the reference count into the two value containers:

- cat_types_table_set retains the new value and releases the old one;
  table_destroy releases every stored value before freeing its own keys.
- cat_types_list_push / list_set_attribute retain; list_destroy releases.
- ffi library/function constructors set refcnt = 1 (they are heap-owned);
  selector singletons are immortal like empty/true/false.
- file / in-memory stream constructors set refcnt = 1.
- the stack-allocated closure in cat_vm_run is marked immortal so a
  stray release can never free stack storage.

Globals are a table, so they inherit the ownership rule for free.
Suite still 130 green.
2026-11-17 22:14:03 +00:00
Minus 22b8de3040 value: thread-safe reference counting foundation
Add an atomic reference count to the common value header and the
retain/release API, without changing any existing ownership behaviour
(containers still do not free their children, so nothing new is freed
and the suite stays green).

- CAT_VALUE_Value gains `_Atomic long refcnt`.
- cat_value_retain / cat_value_release use atomic RMW with acq_rel
  ordering; the last release calls vtable->destroy after an acquire
  fence.  cat_value_refcount and cat_value_make_immortal complete the
  API.
- every heap constructor sets refcnt = 1 (its creator's reference).
- singletons are immortal (refcnt = -1): the empty object and
  true/false, so they are never freed and need no locking.

This makes the COUNT safe to share across threads.  It does not make a
mutable object safe under concurrent writes.
2026-11-17 22:12:31 +00:00
34 changed files with 273 additions and 68 deletions

No files matched your search

+4 -4
View File
@@ -1,7 +1,7 @@
# catscript
Uma linguagem de scripting pequena, escrita em C, **100% orientada a
objetos**, com sintaxe parecida com Lua e **tipagem estrutural**.
objetos**, com sintaxe enxuta e **tipagem estrutural**.
Este repositório contém:
@@ -64,7 +64,7 @@ parser, o checker e o compiler são programas catscript**:
- `src/catscript/compiler.cat` — gera bytecode a partir da AST.
O runtime C expõe primitivas (`bc_run`, `bc_dump`) que transformam uma
"chunk" (uma tabela catscript: `{name, nparams, nlocals, consts, protos,
"chunk" (um objeto catscript: `{name, nparams, nlocals, consts, protos,
code}`) em bytecode executável. Assim, código catscript compila e executa
código catscript.
@@ -339,8 +339,8 @@ Vulkan roda **headless** (lavapipe/llvmpipe); GLFW precisa de um display
## Funções também são objetos
Uma closure tem sua própria tabela de membros, então carrega `_doc_` (e
qualquer outro atributo) como uma tabela:
Uma closure tem seu próprio objeto de membros, então carrega `_doc_` (e
qualquer outro atributo) como um objeto:
```lua
function add(a, b) return a + b end
+31 -1
View File
@@ -18,6 +18,7 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdatomic.h>
struct CAT_ERROR_Error;
struct CAT_VALUE_Value;
@@ -151,11 +152,40 @@ struct CAT_VALUE_Vtable {
void (*destroy)(CAT_VALUE_Value *self);
};
/* The common header shared by every concrete value. */
/* The common header shared by every concrete value.
*
* `refcnt` is a thread-safe reference count:
* - a live, heap-owned value starts at 1 (its creator's reference);
* - `cat_value_retain`/`cat_value_release` add/drop references with
* atomic operations, and the last release calls vtable->destroy;
* - a value with a negative count is IMMORTAL (singletons such as the
* empty object and true/false, or stack-allocated wrappers): retain
* and release are no-ops for it, so it is never freed.
*
* Note: atomic refcounts make the COUNT safe across threads; they do NOT
* make a mutable object (a table being written from two threads) safe. */
struct CAT_VALUE_Value {
CAT_VALUE_Vtable *vtable;
_Atomic long refcnt;
};
/* ---- reference counting (thread-safe) ---- */
/* Add a reference. No-op for NULL and immortal values. */
void cat_value_retain(CAT_VALUE_Value *v);
/* Drop a reference. When the last reference goes, calls vtable->destroy.
* No-op for NULL and immortal values. */
void cat_value_release(CAT_VALUE_Value *v);
/* The current reference count (for tests/diagnostics); negative means
* immortal, 0 means unowned/NULL. */
long cat_value_refcount(CAT_VALUE_Value *v);
/* Mark a value immortal (never freed). Used for singletons and for
* wrappers whose storage lives on the C stack. */
void cat_value_make_immortal(CAT_VALUE_Value *v);
/* ---- dispatch helpers used by compiler/VM and embedders ---- */
int cat_value_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
+6
View File
@@ -88,6 +88,12 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out);
CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name);
int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v);
/* Like cat_vm_set_global, but the caller hands over its reference: the
* globals table takes ownership and the caller's ref is dropped. Use
* with an inline-created value. */
int cat_vm_set_global_owned(CAT_VM_State *vm, const char *name,
CAT_VALUE_Value *v);
void cat_vm_free(CAT_VM_State *vm);
#endif /* CAT_VM_H */
+8 -6
View File
@@ -55,6 +55,10 @@ int cat_bytecode_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v)
fn->consts = ncp;
fn->capconsts = nc;
}
/* The pool owns a reference: this keeps constants alive as long as
* the chunk does, even when the caller built it from borrowed
* values (e.g. `bc_run` reading a table). */
cat_value_retain(v);
fn->consts[fn->nconsts].value = v;
return fn->nconsts++;
}
@@ -115,12 +119,10 @@ void cat_bytecode_function_free(CAT_BYTECODE_Function *fn)
if (fn == NULL)
return;
/* Constant VALUES are intentionally not destroyed here. A chunk's
* constants may be shared (e.g. a chunk built from a catscript table
* via bc_run borrows the table's values), and destroying them would
* double-free. The pool itself is freed; leaked values are bounded
* by the number of compilations in a single run. */
(void)i;
/* Release the constant values this chunk owned (it took a reference
* in cat_bytecode_add_const). The last holder frees them. */
for (i = 0; i < fn->nconsts; i++)
cat_value_release(fn->consts[i].value);
for (i = 0; i < fn->nprotos; i++)
cat_bytecode_function_free(fn->protos[i]);
free(fn->code);
+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);
+20 -11
View File
@@ -86,22 +86,25 @@ static void module_dir(const char *path, char *buf, size_t cap)
CAT_VALUE_Value *cat_module_table(const char *name, const char *path)
{
CAT_VALUE_Value *t = cat_types_table_new();
CAT_VALUE_Value *nv;
CAT_ERROR_Error e;
char dir[512];
cat_error_clear(&e);
cat_types_table_set(t, "name",
cat_types_ascii_text_new(name ? name : "main"),
&e);
nv = cat_types_ascii_text_new(name ? name : "main");
cat_types_table_set(t, "name", nv, &e);
cat_value_release(nv);
/* `path`/`dir` reflect where this unit came from, when known. */
if (path != NULL && path[0] != '\0') {
cat_error_clear(&e);
cat_types_table_set(t, "path",
cat_types_ascii_text_new(path), &e);
nv = cat_types_ascii_text_new(path);
cat_types_table_set(t, "path", nv, &e);
cat_value_release(nv);
module_dir(path, dir, sizeof(dir));
cat_error_clear(&e);
cat_types_table_set(t, "dir",
cat_types_ascii_text_new(dir), &e);
nv = cat_types_ascii_text_new(dir);
cat_types_table_set(t, "dir", nv, &e);
cat_value_release(nv);
}
return t;
}
@@ -114,15 +117,21 @@ void cat_module_enter(CAT_VM_State *vm, const char *name, const char *path)
return;
prev = cat_vm_get_global(vm, "module");
if (vm->nmodule < (int)(sizeof(vm->module_stack) /
sizeof(vm->module_stack[0])))
sizeof(vm->module_stack[0]))) {
/* Keep the saved module alive while it is off the global. */
cat_value_retain(prev);
vm->module_stack[vm->nmodule++] = prev;
cat_vm_set_global(vm, "module", cat_module_table(name, path));
}
cat_vm_set_global_owned(vm, "module", cat_module_table(name, path));
}
void cat_module_leave(CAT_VM_State *vm)
{
CAT_VALUE_Value *prev;
if (vm == NULL || vm->nmodule <= 0)
return;
cat_vm_set_global(vm, "module",
vm->module_stack[--vm->nmodule]);
prev = vm->module_stack[--vm->nmodule];
cat_vm_set_global(vm, "module", prev);
cat_value_release(prev); /* drop the stack's reference */
}
+8 -8
View File
@@ -665,27 +665,27 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
int i;
for (i = 0; std[i].name != NULL; i++)
cat_vm_set_global(vm, std[i].name,
cat_vm_set_global_owned(vm, std[i].name,
cat_types_native_new_doc(std[i].name, std[i].cb,
std[i].doc));
cat_vm_register_native(vm, "__class_new", lf_class_new);
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
cat_vm_set_global(vm, "AbstractFile",
cat_vm_set_global_owned(vm, "AbstractFile",
cat_types_native_new("AbstractFile", lf_abstractfile));
cat_vm_set_global(vm, "File", cat_types_file_class_table());
cat_vm_set_global(vm, "StringIO",
cat_vm_set_global_owned(vm, "File", cat_types_file_class_table());
cat_vm_set_global_owned(vm, "StringIO",
cat_types_native_new("StringIO", lf_stringio));
cat_vm_set_global(vm, "BytesIO",
cat_vm_set_global_owned(vm, "BytesIO",
cat_types_native_new("BytesIO", lf_bytesio));
/* the `ffi` library: call native code (ctypes/CDLL-like) */
cat_vm_set_global(vm, "ffi", cat_types_ffi_module());
cat_vm_set_global_owned(vm, "ffi", cat_types_ffi_module());
/* the empty object: the value for "no value" (catscript has no nil) */
cat_vm_set_global(vm, "empty", cat_types_empty());
/* `memory(n)` -- an owned, bounds-checked byte buffer */
cat_vm_set_global(vm, "memory",
cat_vm_set_global_owned(vm, "memory",
cat_types_native_new_doc("memory", lf_memory,
"memory(n) -- buffer de n bytes com limites verificados."));
/* `module` reflects the unit currently executing (name/path/dir) */
cat_vm_set_global(vm, "module", cat_module_table("main", NULL));
cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL));
return 0;
}
+1
View File
@@ -46,6 +46,7 @@ CAT_VALUE_Value *cat_types_ascii_text_new(const char *s)
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_ascii_vtable;
t->text.base.refcnt = 1;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
+2 -2
View File
@@ -24,12 +24,12 @@ CAT_VALUE_Vtable *cat_types_bool_vtable(void)
CAT_VALUE_Value *cat_types_bool_true(void)
{
static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable }, 1 };
static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable, -1 }, 1 };
return &t.base;
}
CAT_VALUE_Value *cat_types_bool_false(void)
{
static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable }, 0 };
static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable, -1 }, 0 };
return &f.base;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_byte_new(unsigned int v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_byte_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 0;
n->number.i = (long long)(v & 0xFFu);
n->number.f = (double)(v & 0xFFu);
+1
View File
@@ -59,6 +59,7 @@ CAT_VALUE_Value *cat_types_char_new(int width, const char *s)
}
c->buf[width] = '\0';
c->text.base.vtable = cat_types_char_vtable(width);
c->text.base.refcnt = 1;
c->text.bytes = c->buf;
c->text.len = width;
return &c->text.base;
+7
View File
@@ -44,7 +44,14 @@ CAT_VALUE_Vtable *cat_types_empty_vtable(void)
CAT_VALUE_Value *cat_types_empty(void)
{
static CAT_VALUE_Value g_empty;
static int inited = 0;
if (!inited) {
g_empty.vtable = &g_empty_vtable;
/* immortal: the empty object is shared and never freed */
atomic_store_explicit(&g_empty.refcnt, -1, memory_order_relaxed);
inited = 1;
}
return &g_empty;
}
+10 -5
View File
@@ -331,6 +331,7 @@ CAT_VALUE_Value *cat_types_ffi_load(const char *path)
return cat_types_empty();
}
l->base.vtable = &g_library_vtable;
l->base.refcnt = 1;
l->handle = h;
l->path = strdup(path);
return &l->base;
@@ -353,6 +354,7 @@ CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name,
if (f == NULL)
return cat_types_empty();
f->base.vtable = &g_function_vtable;
f->base.refcnt = 1;
f->sym = sym;
f->name = strdup(name);
f->sig = sig ? strdup(sig) : NULL;
@@ -374,6 +376,7 @@ CAT_VALUE_Value *cat_types_ffi_bind_addr(unsigned long long addr,
if (f == NULL)
return cat_types_empty();
f->base.vtable = &g_function_vtable;
f->base.refcnt = 1;
f->sym = (void *)(size_t)addr;
f->name = strdup(name ? name : "?");
f->sig = sig ? strdup(sig) : NULL;
@@ -441,13 +444,15 @@ static int ffi_pointer_native(CAT_VM_State *vm, CAT_VALUE_Value **args,
CAT_VALUE_Value *cat_types_ffi_module(void)
{
CAT_VALUE_Value *m = cat_types_table_new();
CAT_VALUE_Value *nv;
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(m, "load",
cat_types_native_new("load", ffi_load_native), &e);
cat_types_table_set(m, "pointer",
cat_types_native_new("pointer", ffi_pointer_native),
&e);
nv = cat_types_native_new("load", ffi_load_native);
cat_types_table_set(m, "load", nv, &e);
cat_value_release(nv);
nv = cat_types_native_new("pointer", ffi_pointer_native);
cat_types_table_set(m, "pointer", nv, &e);
cat_value_release(nv);
return m;
}
+6 -1
View File
@@ -297,6 +297,7 @@ CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode)
return cat_types_empty();
}
f->af.base.vtable = &g_file_vtable;
f->af.base.refcnt = 1;
f->af.mode = m;
f->af.closed = 0;
f->af.is_bytes = 0;
@@ -312,6 +313,7 @@ CAT_VALUE_Value *cat_types_file_stringio(const char *initial)
if (m == NULL)
return cat_types_empty();
m->af.base.vtable = &g_memfile_vtable;
m->af.base.refcnt = 1;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->af.is_bytes = 1; /* in-memory */
m->cap = 128;
@@ -342,6 +344,7 @@ CAT_VALUE_Value *cat_types_file_bytesio(void)
if (m == NULL)
return cat_types_empty();
m->af.base.vtable = &g_memfile_vtable;
m->af.base.refcnt = 1;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->cap = 128;
m->buf = malloc((size_t)m->cap);
@@ -380,9 +383,11 @@ static int cm_open(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value *cat_types_file_class_table(void)
{
CAT_VALUE_Value *t = cat_types_table_new();
CAT_VALUE_Value *nv = cat_types_native_new("open", cm_open);
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(t, "open", cat_types_native_new("open", cm_open), &e);
cat_types_table_set(t, "open", nv, &e);
cat_value_release(nv);
return t;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_float_new(double v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_float_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 1;
n->number.f = v;
n->number.i = (long long)v;
+7
View File
@@ -67,7 +67,13 @@ static int function_set_attribute(CAT_VALUE_Value *self, const char *name,
static void function_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self;
int i;
for (i = 0; i < cl->nupvals; i++)
cat_value_release(cl->upvals[i]);
free(cl->upvals);
if (cl->attrs != NULL)
cat_value_release(cl->attrs);
/* proto is owned by its enclosing module/bytecode tree, unless this
* closure built it at runtime (injected bytecode) */
if (cl->owns_proto && cl->proto != NULL)
@@ -105,6 +111,7 @@ CAT_VALUE_Value *cat_types_function_new(CAT_BYTECODE_Function *proto)
if (cl == NULL)
return NULL;
cl->base.vtable = &g_function_vtable;
cl->base.refcnt = 1;
cl->proto = proto;
cl->nupvals = 0;
cl->upvals = NULL;
+21
View File
@@ -31,11 +31,25 @@ static int generator_get_attribute(CAT_VALUE_Value *self, const char *name,
return (cat_error_raise(err, "generator has no method '%s'", name), -1);
}
static void generator_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_GENERATOR_Generator *g = (CAT_TYPES_GENERATOR_Generator *)self;
int i;
free(g->stack);
for (i = 0; i < g->nargs; i++)
cat_value_release(g->args[i]);
if (g->cl != NULL)
cat_value_release(&g->cl->base);
free(g);
}
static CAT_VALUE_Vtable g_generator_vtable = {
.type_name = "generator",
.kind = CAT_VALUE_KIND_GENERATOR,
.next = { generator_next },
.get_attribute = { generator_get_attribute },
.destroy = generator_destroy,
};
CAT_VALUE_Vtable *cat_types_generator_vtable(void)
@@ -58,6 +72,7 @@ CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
if (g == NULL)
return cat_types_empty();
g->base.vtable = &g_generator_vtable;
g->base.refcnt = 1;
g->vm = vm;
g->cl = cl;
g->frame.fn = cl->proto;
@@ -76,6 +91,12 @@ CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
for (i = 0; i < nargs && i < 256; i++)
g->args[i] = args[i];
g->nargs = nargs;
/* Own references to the closure and the captured arguments: the
* generator keeps them alive across suspensions. */
if (cl != NULL)
cat_value_retain(&cl->base);
for (i = 0; i < nargs && i < 256; i++)
cat_value_retain(g->args[i]);
return &g->base;
}
+1
View File
@@ -39,6 +39,7 @@ CAT_VALUE_Value *cat_types_int_new(long long v)
if (n == NULL)
return NULL;
n->number.base.vtable = &g_int_vtable;
n->number.base.refcnt = 1;
n->number.is_float = 0;
n->number.i = v;
n->number.f = (double)v;
+7
View File
@@ -57,6 +57,8 @@ static int list_set_attribute(CAT_VALUE_Value *self, const char *name,
if (idx < 0 || idx >= l->n)
return (cat_error_raise(err,
"list index %ld out of range", idx), -1);
cat_value_retain(value);
cat_value_release(l->items[idx]);
l->items[idx] = value;
return 0;
}
@@ -66,7 +68,10 @@ static int list_set_attribute(CAT_VALUE_Value *self, const char *name,
static void list_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
int i;
for (i = 0; i < l->n; i++)
cat_value_release(l->items[i]);
free(l->items);
free(l);
}
@@ -97,6 +102,7 @@ CAT_VALUE_Value *cat_types_list_new(void)
if (l == NULL)
return NULL;
l->base.vtable = &g_list_vtable;
l->base.refcnt = 1;
return &l->base;
}
@@ -114,6 +120,7 @@ int cat_types_list_push(CAT_VALUE_Value *list, CAT_VALUE_Value *v)
l->cap = nc;
}
l->items[l->n++] = v;
cat_value_retain(v);
return 0;
}
+1
View File
@@ -275,6 +275,7 @@ CAT_VALUE_Value *cat_types_memory_new(size_t size)
if (m == NULL)
return NULL;
m->base.vtable = &g_memory_vtable;
m->base.refcnt = 1;
m->size = size;
m->data = calloc(1, size ? size : 1);
if (m->data == NULL) {
+1
View File
@@ -74,6 +74,7 @@ CAT_VALUE_Value *cat_types_native_new_doc(const char *name,
if (nf == NULL)
return NULL;
nf->base.vtable = &g_native_vtable;
nf->base.refcnt = 1;
nf->name = strdup(name ? name : "native");
nf->doc = doc ? strdup(doc) : NULL;
nf->cb = cb;
+4 -1
View File
@@ -102,8 +102,11 @@ CAT_VALUE_Value *cat_types_selector_lookup(const char *name)
return NULL;
/* accept both `_dot_` and `.` spellings of a selector */
for (i = 0; i < (int)(sizeof(g_sel) / sizeof(g_sel[0])); i++) {
if (g_sel[i].base.vtable == NULL)
if (g_sel[i].base.vtable == NULL) {
g_sel[i].base.vtable = &g_selector_vtable;
/* static singleton: immortal, never freed */
g_sel[i].base.refcnt = -1;
}
}
strncpy(key, name, sizeof(key) - 1);
key[sizeof(key) - 1] = '\0';
+13 -8
View File
@@ -39,7 +39,7 @@ static int table_get_attribute(CAT_VALUE_Value *self, const char *name,
return 0;
}
}
return (cat_error_raise(err, "table has no key '%s'", name), -1);
return (cat_error_raise(err, "object has no member '%s'", name), -1);
}
static int table_set_attribute(CAT_VALUE_Value *self, const char *name,
@@ -62,7 +62,7 @@ static int table_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs,
cat_error_clear(&e);
if (cat_value_get_attribute(self, "new", &ctor, &e) != 0 || ctor == NULL)
return (cat_error_raise(err,
"table is not callable (no 'new')"), -1);
"object is not callable (no 'new')"), -1);
callargs[0] = self;
for (i = 0; i < nargs && i < 257; i++)
callargs[i + 1] = args[i];
@@ -73,12 +73,13 @@ static void table_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)self;
int i;
/* Values are NOT destroyed: the same value object may be referenced
* from several tables (globals, constants, locals), so a recursive
* destroy would double-free. We only release the table's own keys
* and storage. */
for (i = 0; i < t->npairs; i++)
/* Release the values we own, then our own keys and storage. Values
* are shared, so we drop exactly one reference each; the last holder
* frees them. */
for (i = 0; i < t->npairs; i++) {
cat_value_release(t->pairs[i].value);
free(t->pairs[i].key);
}
free(t->pairs);
free(t);
}
@@ -104,6 +105,7 @@ CAT_VALUE_Value *cat_types_table_new(void)
if (t == NULL)
return NULL;
t->base.vtable = &g_table_vtable;
t->base.refcnt = 1;
return &t->base;
}
@@ -124,6 +126,8 @@ int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key,
(void)err;
if (idx >= 0) {
cat_value_retain(value);
cat_value_release(t->pairs[idx].value);
t->pairs[idx].value = value;
return 0;
}
@@ -137,6 +141,7 @@ int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key,
}
t->pairs[t->npairs].key = strdup(key);
t->pairs[t->npairs].value = value;
cat_value_retain(value);
t->npairs++;
return 0;
}
@@ -151,7 +156,7 @@ int cat_types_table_get(CAT_VALUE_Value *tbl, const char *key,
*out = t->pairs[idx].value;
return 0;
}
return (cat_error_raise(err, "table has no key '%s'", key), -1);
return (cat_error_raise(err, "object has no member '%s'", key), -1);
}
int cat_types_table_count(CAT_VALUE_Value *tbl)
+1
View File
@@ -69,6 +69,7 @@ CAT_VALUE_Value *cat_types_utf8_text_new(const char *s)
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_utf8_vtable;
t->text.base.refcnt = 1;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
+50
View File
@@ -25,6 +25,56 @@
#include <stdlib.h>
#include <string.h>
/* ---- reference counting (thread-safe) -------------------------------
*
* The count lives in the common value header. retain/release use atomic
* read-modify-write with acquire/release ordering, so the object graph
* can be shared across threads safely. Destroying the object runs on
* whichever thread drops the last reference.
*
* A negative count marks an immortal value (a singleton, or a wrapper
* whose storage lives on the C stack); retain/release ignore it. */
void cat_value_retain(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
if (atomic_load_explicit(&v->refcnt, memory_order_relaxed) < 0)
return;
atomic_fetch_add_explicit(&v->refcnt, 1, memory_order_relaxed);
}
void cat_value_release(CAT_VALUE_Value *v)
{
long prev;
if (v == NULL)
return;
prev = atomic_load_explicit(&v->refcnt, memory_order_relaxed);
if (prev < 0)
return;
if (atomic_fetch_sub_explicit(&v->refcnt, 1,
memory_order_acq_rel) == 1) {
/* Last reference: publish our writes, then destroy. */
atomic_thread_fence(memory_order_acquire);
if (v->vtable != NULL && v->vtable->destroy != NULL)
v->vtable->destroy(v);
}
}
long cat_value_refcount(CAT_VALUE_Value *v)
{
if (v == NULL)
return 0;
return atomic_load_explicit(&v->refcnt, memory_order_relaxed);
}
void cat_value_make_immortal(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
atomic_store_explicit(&v->refcnt, -1, memory_order_relaxed);
}
const char *cat_value_type_name(CAT_VALUE_Value *v)
{
if (v == NULL || v->vtable == NULL || v->vtable->type_name == NULL)
+32 -4
View File
@@ -70,6 +70,19 @@ int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v)
return cat_types_table_set(vm->globals, name, v, &e);
}
/* Set a global from a freshly-created value, transferring ownership to
* the globals table (the caller's reference is dropped). Use this when
* the value is created inline: `cat_vm_set_global_owned(vm, "x",
* cat_types_native_new(...))`. */
int cat_vm_set_global_owned(CAT_VM_State *vm, const char *name,
CAT_VALUE_Value *v)
{
int rc = cat_vm_set_global(vm, name, v);
cat_value_release(v);
return rc;
}
int cat_vm_register_native(CAT_VM_State *vm, const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int,
CAT_VALUE_Value **))
@@ -77,7 +90,7 @@ int cat_vm_register_native(CAT_VM_State *vm, const char *name,
/* A native function is a first-class value. Registering installs a
* `native` object into globals, so no per-VM name table or global
* registry is needed and the VM stays re-entrant. */
cat_vm_set_global(vm, name, cat_types_native_new(name, cb));
cat_vm_set_global_owned(vm, name, cat_types_native_new(name, cb));
return 0;
}
@@ -587,15 +600,30 @@ int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **ou
memset(&cl, 0, sizeof(cl));
cl.base.vtable = cat_types_function_vtable();
cl.proto = fn;
/* This closure lives on the C stack: mark it immortal so a stray
* release can never try to free it. */
cat_value_make_immortal(&cl.base);
return cat_vm_exec_closure(vm, &cl, NULL, 0, out);
}
void cat_vm_free(CAT_VM_State *vm)
{
int i;
if (vm == NULL)
return;
if (vm->globals != NULL && vm->globals->vtable &&
vm->globals->vtable->destroy)
vm->globals->vtable->destroy(vm->globals);
/* Release any module still saved on the stack (e.g. the initial
* `module` if the run never balanced enter/leave). */
while (vm->nmodule > 0) {
CAT_VALUE_Value *m = vm->module_stack[--vm->nmodule];
cat_value_release(m);
}
/* The globals table owns one reference per value it holds; releasing
* it cascades: each stored value's reference drops and the last
* holder frees it. */
if (vm->globals != NULL)
cat_value_release(vm->globals);
for (i = 0; i < vm->nnatives; i++)
(void)vm->natives[i];
free(vm);
}
+1 -1
View File
@@ -60,7 +60,7 @@ function chk_expr(e)
chk_expr(e.idx)
elseif t == "attr" then
chk_expr(e.obj)
elseif t == "table" then
elseif t == "object" then
local i = 1
while i <= len(e.fields) do
chk_expr(e.fields[i].v)
+1 -1
View File
@@ -145,7 +145,7 @@ function cmp_expr(e)
elseif t == "attr" then
cmp_expr(e.obj)
cmp_emit(22, cmp_addstr(e.name), 0, 0)
elseif t == "table" then
elseif t == "object" then
cmp_emit(24, 0, 0, 0)
local pos = 1
local i = 1
+2 -2
View File
@@ -11,7 +11,7 @@
-- { t="method", obj=O, name="m", args={...} }
-- { t="index", obj=O, idx=I }
-- { t="attr", obj=O, name="a" }
-- { t="table", fields={ {k=..., v=...}, ... } } -- positional k is empty
-- { t="object", fields={ {k=..., v=...}, ... } } -- positional k is empty
-- { t="func", name=..., params={...}, body={stats} }
--
-- Statements:
@@ -125,7 +125,7 @@ function par_table()
par_advance()
end
par_expect("}", "'}'")
return { t = "table", fields = fields }
return { t = "object", fields = fields }
end
function par_args()
+2 -2
View File
@@ -1,7 +1,7 @@
-- tests/functions_as_objects.cat -- functions are objects too.
--
-- A closure carries a member table, so it can hold `_doc_` (and any
-- other attribute) exactly like a table. `help()` reads it; a dotted
-- A closure carries a member object, so it can hold `_doc_` (and any
-- other attribute) exactly like an object. `help()` reads it; a dotted
-- assignment can reach an attribute of a nested object (a method).
local t = {x = 1, y = 2}
+2 -2
View File
@@ -1,6 +1,6 @@
-- tests/module.cat -- the `module` global reflects the current unit.
--
-- `module` is a global table: `name` is the basename of the running
-- `module` is a global object: `name` is the basename of the running
-- file, `path` its path and `dir` its directory. Importing another
-- file (use/dofile) swaps `module` for the duration of that file and
-- restores the caller's afterwards.
@@ -8,7 +8,7 @@
print("name:", module.name)
print("dir:", module.dir)
-- a user may mutate it like any table
-- a user may mutate it like any object
module.extra = "tagged"
print("extra:", module.extra)
+1 -1
View File
@@ -19,7 +19,7 @@ class Point
end
local p = Point(3, 4)
print("table:", tostring(t))
print("object:", tostring(t))
print("point:", tostring(p))
print("int:", tostring(42))
print("str:", tostring("hi"))
+1 -1
View File
@@ -162,7 +162,7 @@ check "fn-help" "add(a, b) -- soma dois numeros." "`echo "$out" | sed -n
# ---- _repr_ protocol -------------------------------------------------
out=`$BIN tests/repr.cat`
check "repr-value" "table: a custom point" "`echo "$out" | sed -n 1p`"
check "repr-value" "object: a custom point" "`echo "$out" | sed -n 1p`"
check "repr-method" "point: Point(3, 4)" "`echo "$out" | sed -n 2p`"
check "repr-int" "int: 42" "`echo "$out" | sed -n 3p`"
check "repr-str" "str: hi" "`echo "$out" | sed -n 4p`"
+1 -1
View File
@@ -17,7 +17,7 @@ counter.bump(3)
counter.bump(4)
print("with self:", counter.n)
-- a plain table field
-- a plain object field
local point = { x = 10, y = 20 }
print("field x:", point.x)