From e0bf102f2a3bd0976ce98b7ae68abe096f6e5d82 Mon Sep 17 00:00:00 2001 From: Minus Date: Mon, 16 Nov 2026 03:50:54 +0000 Subject: [PATCH] functions are objects: closures carry a member table (_doc_) - CAT_TYPES_FUNCTION_Closure gains an attrs table; get/set_attribute give closures real members, so a function can hold _doc_ and any other attribute like a table - cat_types_function_attrs() accessor; attributes() enumerates a closure's members; help() reads a function's _doc_ - compiler: generalise dotted assignment to chains (name.a.b = v), so a method can be documented (Calc.add._doc_ = ...) - tests/functions_as_objects.cat + 7 assertions (84 total, all green) - README: 'funcoes tambem sao objetos' + reflection sections --- README.md | 31 ++++++++++++++++++ include/cat/types/function.h | 4 +++ src/cat/compiler.c | 57 ++++++++++++++++++++++++---------- src/cat/stdlib/stdlib.c | 22 ++++++++++++- src/cat/types/function.c | 48 ++++++++++++++++++++++++++++ tests/functions_as_objects.cat | 28 +++++++++++++++++ tests/run_tests.sh | 11 +++++++ 7 files changed, 183 insertions(+), 18 deletions(-) create mode 100644 tests/functions_as_objects.cat diff --git a/README.md b/README.md index d9ed1b0..0569d50 100644 --- a/README.md +++ b/README.md @@ -275,6 +275,37 @@ Gramática da assinatura: `RET(ARG,ARG,...)`, com tipos `void`, `bool`, Requer `-lffi -ldl` (já no Makefile). +## 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: + +```lua +function add(a, b) return a + b end +add._doc_ = "add(a, b) -- soma dois numeros." +help(add) -- lê a doc da função + +-- documentando um método (atribuição encadeada) +class Calc + function add(self, a, b) return a + b end +end +Calc.add._doc_ = "add(a, b) on Calc." +``` + +## Reflection: `attributes()` e `help()` + +`attributes(obj)` lista os nomes dos membros de um objeto (como o `dir()` +do Python), seguindo a herança via `__index`; devolve uma **lista** +iterável. `help(obj)` imprime a documentação de um valor, lida do seu +atributo `_doc_`: + +```lua +local p = {x = 0, y = 0} +p._doc_ = "A 2D point." +for a in attributes(p) do print(a) end -- x, y, _doc_ +help(p) -- A 2D point. +``` + ## cpk — Cat Package Manager O primeiro programa em catscript. Lê o `package.toml` de um pacote diff --git a/include/cat/types/function.h b/include/cat/types/function.h index be31613..2b45452 100644 --- a/include/cat/types/function.h +++ b/include/cat/types/function.h @@ -17,11 +17,15 @@ typedef struct CAT_TYPES_FUNCTION_Closure { struct CAT_BYTECODE_Function *proto; CAT_VALUE_Value **upvals; /* captured values */ int nupvals; + CAT_VALUE_Value *attrs; /* optional member table (e.g. `_doc_`) */ } CAT_TYPES_FUNCTION_Closure; /* Wrap a prototype as a callable closure. */ CAT_VALUE_Value *cat_types_function_new(struct CAT_BYTECODE_Function *proto); +/* The closure's own member table (created lazily; may be NULL). */ +CAT_VALUE_Value *cat_types_function_attrs(CAT_VALUE_Value *fn); + CAT_VALUE_Vtable *cat_types_function_vtable(void); #endif /* CAT_TYPES_FUNCTION_H */ diff --git a/src/cat/compiler.c b/src/cat/compiler.c index d5931ce..cb4103d 100644 --- a/src/cat/compiler.c +++ b/src/cat/compiler.c @@ -933,25 +933,48 @@ static void stat(Compiler *c) break; } if (la.kind == CAT_LEXER_TOK_DOT) { - CAT_LEXER_Token attr; - cat_lexer_next(&c->lx, &attr); - if (attr.kind == CAT_LEXER_TOK_NAME) { - CAT_LEXER_Token eq; - cat_lexer_next(&c->lx, &eq); - if (eq.kind == CAT_LEXER_TOK_ASSIGN) { - int slot = find_local(c, name); - c->tok = eq; - next(c); - if (slot >= 0) - emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); - else - emit(c, CAT_BYTECODE_OP_GETGLOBAL, - add_string(c, name), 0, line); - expr(c); - emit(c, CAT_BYTECODE_OP_SETATTR, - add_string(c, attr.text), 0, line); + /* dotted assignment, possibly chained: name.a.b = value. + * Collect the attribute chain; if it ends in '=', emit the + * object expression followed by a final SETATTR. Otherwise + * rewind and parse as an ordinary expression. */ + char chain[16][256]; + int nchain = 0; + int is_assign = 0; + for (;;) { + CAT_LEXER_Token attr, nx; + cat_lexer_next(&c->lx, &attr); + if (attr.kind != CAT_LEXER_TOK_NAME) break; + if (nchain < 16) + snprintf(chain[nchain], sizeof(chain[0]), + "%s", attr.text); + nchain++; + cat_lexer_next(&c->lx, &nx); + if (nx.kind == CAT_LEXER_TOK_DOT) + continue; + if (nx.kind == CAT_LEXER_TOK_ASSIGN) { + c->tok = nx; + is_assign = 1; } + break; + } + if (is_assign && nchain > 0 && nchain <= 16) { + int slot = find_local(c, name); + int k; + next(c); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); + else + emit(c, CAT_BYTECODE_OP_GETGLOBAL, + add_string(c, name), 0, line); + /* walk to the object that owns the final attribute */ + for (k = 0; k < nchain - 1; k++) + emit(c, CAT_BYTECODE_OP_GETATTR, + add_string(c, chain[k]), 0, line); + expr(c); + emit(c, CAT_BYTECODE_OP_SETATTR, + add_string(c, chain[nchain - 1]), 0, line); + break; } } /* not an assignment: rewind and parse as an expression, keeping the diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index e3111ba..eb03caf 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -180,7 +180,7 @@ static int lf_attributes(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value *list = cat_types_list_new(); CAT_VALUE_Value *seen[8]; int nseen = 0; - int i; + int i, j; (void)vm; if (obj == NULL || obj->vtable == NULL) { @@ -193,6 +193,26 @@ static int lf_attributes(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, cat_types_list_push(list, cat_types_ascii_text_new("name")); cat_types_list_push(list, cat_types_ascii_text_new("_doc_")); } + /* a closure's member table (functions are objects too) */ + { + CAT_VALUE_Value *fattrs = cat_types_function_attrs(obj); + if (fattrs != NULL && fattrs->vtable == cat_types_table_vtable()) { + for (i = 0; i < cat_types_table_count(fattrs); i++) { + const char *k = cat_types_table_key_at(fattrs, i); + int dup = 0; + for (j = 0; j < cat_types_list_count(list); j++) { + CAT_VALUE_Value *n = cat_types_list_at(list, j); + if (n != NULL && n->vtable && + n->vtable->kind == CAT_VALUE_KIND_TEXT && + strcmp(cat_types_text_bytes(n), k) == 0) + dup = 1; + } + if (!dup) + cat_types_list_push(list, + cat_types_ascii_text_new(k)); + } + } + } /* fixed members from the type's slot layout */ if (obj->vtable->slots != NULL) { for (i = 0; i < obj->vtable->nslots; i++) diff --git a/src/cat/types/function.c b/src/cat/types/function.c index 56e5829..a0d940c 100644 --- a/src/cat/types/function.c +++ b/src/cat/types/function.c @@ -8,9 +8,12 @@ * subroutine, keeping "everything is an object" honest. */ #include "cat/types/function.h" +#include "cat/types/table.h" +#include "cat/types/ascii_text.h" #include "cat/vm.h" #include +#include int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out); @@ -27,6 +30,40 @@ static int function_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, return cat_vm_exec_closure(vm, cl, args, nargs, out); } +/* Functions are objects too: they carry a member table so a closure can + * hold `_doc_` (and any other attribute), just like a table. */ +static CAT_VALUE_Value *function_attrs(CAT_TYPES_FUNCTION_Closure *cl) +{ + if (cl->attrs == NULL) + cl->attrs = cat_types_table_new(); + return cl->attrs; +} + +static int function_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self; + CAT_VALUE_Value *attrs = function_attrs(cl); + + if (cat_types_table_get(attrs, name, out, err) == 0) + return 0; + /* built-ins any function answers */ + if (strcmp(name, "name") == 0) { + *out = cat_types_ascii_text_new(cl->proto && cl->proto->name ? + cl->proto->name : "function"); + return 0; + } + return (cat_error_raise(err, "function has no attribute '%s'", name), -1); +} + +static int function_set_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value *value, CAT_ERROR_Error *err) +{ + CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self; + + return cat_types_table_set(function_attrs(cl), name, value, err); +} + static void function_destroy(CAT_VALUE_Value *self) { CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self; @@ -39,9 +76,20 @@ static CAT_VALUE_Vtable g_function_vtable = { .type_name = "function", .kind = CAT_VALUE_KIND_FUNCTION, .call = { function_call }, + .get_attribute = { function_get_attribute }, + .set_attribute = { function_set_attribute }, .destroy = function_destroy, }; +CAT_VALUE_Value *cat_types_function_attrs(CAT_VALUE_Value *fn) +{ + CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)fn; + + if (cl == NULL || cl->base.vtable != &g_function_vtable) + return NULL; + return cl->attrs; +} + CAT_VALUE_Vtable *cat_types_function_vtable(void) { return &g_function_vtable; diff --git a/tests/functions_as_objects.cat b/tests/functions_as_objects.cat new file mode 100644 index 0000000..2448cec --- /dev/null +++ b/tests/functions_as_objects.cat @@ -0,0 +1,28 @@ +-- 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 +-- assignment can reach an attribute of a nested object (a method). + +local t = {x = 1, y = 2} +t._doc_ = "A point." + +function add(a, b) return a + b end +add._doc_ = "add(a, b) -- soma dois numeros." +print("call:", add(2, 3)) +print("name:", add.name) +print("doc:", add._doc_) + +for a in attributes(add) do print("attr:", a) end + +-- documenting a method: nested (chained) attribute assignment +class Calc + function add(self, a, b) return a + b end +end +Calc.add._doc_ = "add(a, b) on Calc." +print("method doc:", Calc.add._doc_) +local c = Calc() +print("method call:", c:add(4, 5)) + +-- help() reads a function's _doc_ +help(add) diff --git a/tests/run_tests.sh b/tests/run_tests.sh index d7b0fec..9c7b88e 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -147,6 +147,17 @@ check "attr-doc" " - _doc_" "`echo "$out" | sed -n 5p`" check "attr-method" "animal has speak: true" "`echo "$out" | sed -n 6p`" check "help-doc" "A 2D point with x, y coordinates." "`echo "$out" | sed -n 8p`" check "help-native" "print(a, ...) -- escreve os argumentos em stdout." "`echo "$out" | sed -n 10p`" + +# ---- functions are objects too (member table, _doc_) ---------------- + +out=`$BIN tests/functions_as_objects.cat` +check "fn-call" "call: 5" "`echo "$out" | sed -n 1p`" +check "fn-name" "name: add" "`echo "$out" | sed -n 2p`" +check "fn-doc" "doc: add(a, b) -- soma dois numeros." "`echo "$out" | sed -n 3p`" +check "fn-attr" "attr: _doc_" "`echo "$out" | sed -n 4p`" +check "fn-method-doc" "method doc: add(a, b) on Calc." "`echo "$out" | sed -n 5p`" +check "fn-method-call" "method call: 9" "`echo "$out" | sed -n 6p`" +check "fn-help" "add(a, b) -- soma dois numeros." "`echo "$out" | sed -n 7p`" # ---- bytecode dump --------------------------------------------------- out=`$BIN --dump examples/hello.cat`