reflection: attributes() (dir-like) and help() with _doc_

- new list type (iterable, indexable) backing attributes()
- attributes(obj): member names of a table/object, follows __index
  inheritance, includes native and slot members (like Python dir())
- help(obj): prints the value's _doc_ documentation, else its type
  and attributes
- natives carry an optional _doc_ string (cat_types_native_new_doc);
  stdlib builtins documented
- len() handles lists
- examples/reflect.cat + 8 assertions wired into run_tests.sh (77 total)
This commit is contained in:
Minus committed 2026-11-16 03:48:44 +00:00
1 parent 4dae4ee1cd
commit 1203acd64b
8 files changed
+381 -14

No files matched your search

+1
View File
@@ -47,6 +47,7 @@ SRCS := \
src/cat/types/file.c \ src/cat/types/file.c \
src/cat/types/generator.c \ src/cat/types/generator.c \
src/cat/types/selector.c \ src/cat/types/selector.c \
src/cat/types/list.c \
src/cat/types/ffi.c \ src/cat/types/ffi.c \
src/cat/stdlib/stdlib.c \ src/cat/stdlib/stdlib.c \
src/cat/stdlib/toml.c \ src/cat/stdlib/toml.c \
+23
View File
@@ -0,0 +1,23 @@
-- examples/reflect.cat -- reflection: attributes() and help().
--
-- `attributes(obj)` lists an object's members (like Python's dir()),
-- following inheritance via `__index`. `help(obj)` prints an object's
-- documentation, read from its `_doc_` attribute.
local point = {x = 0, y = 0, name = "origin"}
point._doc_ = "A 2D point with x, y coordinates."
print("point attrs:", len(attributes(point)))
for a in attributes(point) do print(" -", a) end
class Animal
function speak(self) print("...") end
function name(self) return "animal" end
end
local a = Animal()
print("animal has speak:", len(attributes(a)) > 0)
print("--- help(point) ---")
help(point)
print("--- help(print) ---")
help(print)
+30
View File
@@ -0,0 +1,30 @@
/*
* cat/types/list.h -- a growable, iterable list of values.
*
* Naming rule: symbols here are cat_types_list_* / CAT_TYPES_LIST_*.
*
* `attributes(obj)` returns a List of member names, and `for name in
* attributes(obj)` iterates it. A List is a concrete iterator: its
* `next` advances an internal cursor over the stored items.
*/
#ifndef CAT_TYPES_LIST_H
#define CAT_TYPES_LIST_H
#include "cat/value.h"
/* CAT_TYPES_LIST_List -- ordered, iterable sequence of values. */
typedef struct CAT_TYPES_LIST_List {
CAT_VALUE_Value base;
CAT_VALUE_Value **items;
int n, cap;
int cursor; /* iteration state for `next` */
} CAT_TYPES_LIST_List;
CAT_VALUE_Value *cat_types_list_new(void);
int cat_types_list_push(CAT_VALUE_Value *list, CAT_VALUE_Value *v);
int cat_types_list_count(CAT_VALUE_Value *list);
CAT_VALUE_Value *cat_types_list_at(CAT_VALUE_Value *list, int i);
CAT_VALUE_Vtable *cat_types_list_vtable(void);
int cat_types_list_is(CAT_VALUE_Value *v);
#endif /* CAT_TYPES_LIST_H */
+6
View File
@@ -21,12 +21,18 @@ typedef struct CAT_VM_State CAT_VM_State;
typedef struct CAT_TYPES_NATIVE_Native { typedef struct CAT_TYPES_NATIVE_Native {
CAT_VALUE_Value base; CAT_VALUE_Value base;
char *name; char *name;
char *doc; /* optional `_doc_` documentation string */
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **);
} CAT_TYPES_NATIVE_Native; } CAT_TYPES_NATIVE_Native;
CAT_VALUE_Value *cat_types_native_new(const char *name, CAT_VALUE_Value *cat_types_native_new(const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **)); int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **));
/* Like cat_types_native_new, but with an attached `_doc_` string. */
CAT_VALUE_Value *cat_types_native_new_doc(const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **),
const char *doc);
CAT_VALUE_Vtable *cat_types_native_vtable(void); CAT_VALUE_Vtable *cat_types_native_vtable(void);
/* True if v is a native function value. */ /* True if v is a native function value. */
+150 -14
View File
@@ -18,7 +18,9 @@
#include "cat/types/text.h" #include "cat/types/text.h"
#include "cat/types/ascii_text.h" #include "cat/types/ascii_text.h"
#include "cat/types/table.h" #include "cat/types/table.h"
#include "cat/types/list.h"
#include "cat/types/native.h" #include "cat/types/native.h"
#include "cat/types/function.h"
#include "cat/types/file.h" #include "cat/types/file.h"
#include "cat/types/ffi.h" #include "cat/types/ffi.h"
@@ -117,6 +119,8 @@ static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
} }
if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TEXT) if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TEXT)
*out = cat_types_int_new(cat_types_text_length(args[0])); *out = cat_types_int_new(cat_types_text_length(args[0]));
else if (cat_types_list_is(args[0]))
*out = cat_types_int_new(cat_types_list_count(args[0]));
else if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TABLE) else if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TABLE)
*out = cat_types_int_new(cat_types_table_count(args[0])); *out = cat_types_int_new(cat_types_table_count(args[0]));
else else
@@ -124,6 +128,125 @@ static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
return 0; return 0;
} }
/* attributes(obj) -- the member names of an object (like Python dir()):
* a table's keys, plus inherited keys reachable through `__index`, plus
* any fixed slots its type exposes, in a List. */
static void collect_attributes(CAT_VALUE_Value *obj, CAT_VALUE_Value *list,
CAT_VALUE_Value **seen, int *nseen)
{
CAT_VALUE_Value *base = NULL;
int i, j;
if (obj == NULL || obj->vtable == NULL)
return;
/* skip a table we have already visited (classes point __index at
* themselves, so the chain can be cyclic) */
for (i = 0; i < *nseen; i++)
if (seen[i] == obj)
return;
if (*nseen < 8)
seen[(*nseen)++] = obj;
/* a table/object's own keys */
if (obj->vtable == cat_types_table_vtable()) {
for (i = 0; i < cat_types_table_count(obj); i++) {
const char *k = cat_types_table_key_at(obj, 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));
}
}
/* follow inheritance */
if (obj->vtable == cat_types_table_vtable()) {
CAT_ERROR_Error e2;
cat_error_clear(&e2);
if (cat_value_get_attribute(obj, "__index", &base, &e2) == 0 &&
base != NULL && base != obj)
collect_attributes(base, list, seen, nseen);
}
}
static int lf_attributes(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_VALUE_Value *obj = nargs > 0 ? args[0] : NULL;
CAT_VALUE_Value *list = cat_types_list_new();
CAT_VALUE_Value *seen[8];
int nseen = 0;
int i;
(void)vm;
if (obj == NULL || obj->vtable == NULL) {
*out = list;
return 0;
}
collect_attributes(obj, list, seen, &nseen);
/* a native's own members, so attributes(print) is not empty */
if (cat_types_native_is(obj)) {
cat_types_list_push(list, cat_types_ascii_text_new("name"));
cat_types_list_push(list, cat_types_ascii_text_new("_doc_"));
}
/* fixed members from the type's slot layout */
if (obj->vtable->slots != NULL) {
for (i = 0; i < obj->vtable->nslots; i++)
cat_types_list_push(list, cat_types_ascii_text_new(
obj->vtable->slots[i].name));
}
*out = list;
return 0;
}
/* help(obj) -- print a value's documentation. Looks up its `_doc_`
* attribute (an internal docstring) and otherwise lists what it offers. */
static int lf_help(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_VALUE_Value *obj = nargs > 0 ? args[0] : NULL;
CAT_ERROR_Error e;
CAT_VALUE_Value *doc = NULL;
(void)vm;
if (obj == NULL) {
printf("help(value) -- show documentation for any value.\n");
*out = cat_types_nil_get();
return 0;
}
cat_error_clear(&e);
if (cat_value_get_attribute(obj, "_doc_", &doc, &e) == 0 &&
doc != NULL && doc->vtable != NULL &&
doc->vtable->kind == CAT_VALUE_KIND_TEXT) {
printf("%s\n", cat_types_text_bytes(doc));
*out = cat_types_nil_get();
return 0;
}
/* no `_doc_`: describe the type and its members */
printf("%s\n", cat_value_type_name(obj));
cat_error_clear(&e);
{
CAT_VALUE_Value *names = NULL;
lf_attributes(vm, args, nargs, &names);
if (names != NULL && cat_types_list_count(names) > 0) {
int i;
printf("attributes:\n");
for (i = 0; i < cat_types_list_count(names); i++) {
CAT_VALUE_Value *n = cat_types_list_at(names, i);
if (n != NULL && n->vtable &&
n->vtable->kind == CAT_VALUE_KIND_TEXT)
printf(" %s\n", cat_types_text_bytes(n));
}
}
}
*out = cat_types_nil_get();
return 0;
}
static int lf_toml_parse(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, static int lf_toml_parse(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out) CAT_VALUE_Value **out)
{ {
@@ -411,20 +534,33 @@ static int lf_bytesio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
int cat_stdlib_stdlib_install(CAT_VM_State *vm) int cat_stdlib_stdlib_install(CAT_VM_State *vm)
{ {
cat_vm_register_native(vm, "print", lf_print); struct { const char *name;
cat_vm_register_native(vm, "tostring", lf_tostring); int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **);
cat_vm_register_native(vm, "tonumber", lf_tonumber); const char *doc; } std[] = {
cat_vm_register_native(vm, "type", lf_type); { "print", lf_print, "print(a, ...) -- escreve os argumentos em stdout." },
cat_vm_register_native(vm, "len", lf_len); { "tostring", lf_tostring, "tostring(v) -- representa\u00e7\u00e3o textual de v." },
cat_vm_register_native(vm, "toml_parse", lf_toml_parse); { "tonumber", lf_tonumber, "tonumber(s) -- converte texto em n\u00famero (ou nil)." },
cat_vm_register_native(vm, "toml_encode", lf_toml_encode); { "type", lf_type, "type(v) -- nome do tipo de v." },
cat_vm_register_native(vm, "read_file", lf_read_file); { "len", lf_len, "len(v) -- tamanho de texto ou n\u00famero de membros de um objeto." },
cat_vm_register_native(vm, "write_file", lf_write_file); { "attributes", lf_attributes, "attributes(obj) -- nomes dos membros de obj (lista), incluindo heran\u00e7a (como dir())." },
cat_vm_register_native(vm, "ord", lf_ord); { "help", lf_help, "help(obj) -- mostra a documenta\u00e7\u00e3o (`_doc_`) de obj ou lista seus atributos." },
cat_vm_register_native(vm, "chr", lf_chr); { "toml_parse", lf_toml_parse, "toml_parse(text) -- analisa TOML e devolve um objeto." },
cat_vm_register_native(vm, "substr", lf_substr); { "toml_encode", lf_toml_encode, "toml_encode(obj) -- serializa um objeto em TOML." },
cat_vm_register_native(vm, "dofile", lf_dofile); { "read_file", lf_read_file, "read_file(path) -- l\u00ea o conte\u00fado de um arquivo como texto." },
cat_vm_register_native(vm, "use", lf_use); { "write_file", lf_write_file, "write_file(path, text) -- escreve texto em um arquivo." },
{ "ord", lf_ord, "ord(s) -- c\u00f3digo do primeiro caractere de s." },
{ "chr", lf_chr, "chr(n) -- caractere com c\u00f3digo n." },
{ "substr", lf_substr, "substr(s, i, n) -- fatia de s a partir de i com n caracteres." },
{ "dofile", lf_dofile, "dofile(path) -- compila e executa outro arquivo catscript." },
{ "use", lf_use, "use(path) -- importa outro arquivo catscript (alias de dofile)." },
{ NULL, NULL, NULL }
};
int i;
for (i = 0; std[i].name != NULL; i++)
cat_vm_set_global(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); cat_vm_register_native(vm, "__class_new", lf_class_new);
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */ /* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
cat_vm_set_global(vm, "AbstractFile", cat_vm_set_global(vm, "AbstractFile",
+132
View File
@@ -0,0 +1,132 @@
/*
* cat/types/list.c -- a growable, iterable list of values.
*
* Naming rule: symbols here are cat_types_list_* / CAT_TYPES_LIST_*.
*/
#include "cat/types/list.h"
#include "cat/types/text.h"
#include "cat/types/int.h"
#include "cat/types/nil.h"
#include "cat/error.h"
#include <stdlib.h>
#include <string.h>
static int list_next(CAT_VALUE_Value *self, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
(void)err;
if (l->cursor >= l->n)
return 1; /* exhausted */
*out = l->items[l->cursor++];
return 0;
}
/* list[i] / list:get(i) -- 0-based indexing. */
static int list_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
char *end = NULL;
long idx = strtol(name, &end, 10);
if (end != NULL && *end == '\0' && name[0] != '\0') {
if (idx < 0 || idx >= l->n)
return (cat_error_raise(err,
"list index %ld out of range", idx), -1);
*out = l->items[idx];
return 0;
}
if (strcmp(name, "count") == 0) {
*out = cat_types_int_new(l->n);
return 0;
}
return (cat_error_raise(err, "list has no attribute '%s'", name), -1);
}
static int list_set_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
char *end = NULL;
long idx = strtol(name, &end, 10);
if (end != NULL && *end == '\0' && name[0] != '\0') {
if (idx < 0 || idx >= l->n)
return (cat_error_raise(err,
"list index %ld out of range", idx), -1);
l->items[idx] = value;
return 0;
}
return (cat_error_raise(err, "list has no attribute '%s'", name), -1);
}
static void list_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)self;
free(l->items);
free(l);
}
static CAT_VALUE_Vtable g_list_vtable = {
.type_name = "list",
.kind = CAT_VALUE_KIND_TABLE,
.next = { list_next },
.get_attribute = { list_get_attribute },
.set_attribute = { list_set_attribute },
.destroy = list_destroy,
};
CAT_VALUE_Vtable *cat_types_list_vtable(void)
{
return &g_list_vtable;
}
int cat_types_list_is(CAT_VALUE_Value *v)
{
return v != NULL && v->vtable == &g_list_vtable;
}
CAT_VALUE_Value *cat_types_list_new(void)
{
CAT_TYPES_LIST_List *l = calloc(1, sizeof(*l));
if (l == NULL)
return NULL;
l->base.vtable = &g_list_vtable;
return &l->base;
}
int cat_types_list_push(CAT_VALUE_Value *list, CAT_VALUE_Value *v)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)list;
if (l->n == l->cap) {
int nc = l->cap ? l->cap * 2 : 4;
CAT_VALUE_Value **ni = realloc(l->items,
(size_t)nc * sizeof(*ni));
if (ni == NULL)
return -1;
l->items = ni;
l->cap = nc;
}
l->items[l->n++] = v;
return 0;
}
int cat_types_list_count(CAT_VALUE_Value *list)
{
return ((CAT_TYPES_LIST_List *)list)->n;
}
CAT_VALUE_Value *cat_types_list_at(CAT_VALUE_Value *list, int i)
{
CAT_TYPES_LIST_List *l = (CAT_TYPES_LIST_List *)list;
if (i < 0 || i >= l->n)
return NULL;
return l->items[i];
}
+27
View File
@@ -4,6 +4,7 @@
* Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*. * Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*.
*/ */
#include "cat/types/native.h" #include "cat/types/native.h"
#include "cat/types/ascii_text.h"
#include "cat/vm.h" #include "cat/vm.h"
#include "cat/error.h" #include "cat/error.h"
@@ -21,10 +22,27 @@ static int native_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
return nf->cb(vm, args, nargs, out); return nf->cb(vm, args, nargs, out);
} }
static int native_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self;
if (strcmp(name, "_doc_") == 0) {
*out = cat_types_ascii_text_new(nf->doc ? nf->doc : "");
return 0;
}
if (strcmp(name, "name") == 0) {
*out = cat_types_ascii_text_new(nf->name ? nf->name : "native");
return 0;
}
return (cat_error_raise(err, "native has no attribute '%s'", name), -1);
}
static void native_destroy(CAT_VALUE_Value *self) static void native_destroy(CAT_VALUE_Value *self)
{ {
CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self; CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self;
free(nf->name); free(nf->name);
free(nf->doc);
free(nf); free(nf);
} }
@@ -32,6 +50,7 @@ static CAT_VALUE_Vtable g_native_vtable = {
.type_name = "native", .type_name = "native",
.kind = CAT_VALUE_KIND_FUNCTION, .kind = CAT_VALUE_KIND_FUNCTION,
.call = { native_call }, .call = { native_call },
.get_attribute = { native_get_attribute },
.destroy = native_destroy, .destroy = native_destroy,
}; };
@@ -42,6 +61,13 @@ CAT_VALUE_Vtable *cat_types_native_vtable(void)
CAT_VALUE_Value *cat_types_native_new(const char *name, CAT_VALUE_Value *cat_types_native_new(const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **)) int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **))
{
return cat_types_native_new_doc(name, cb, NULL);
}
CAT_VALUE_Value *cat_types_native_new_doc(const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **),
const char *doc)
{ {
CAT_TYPES_NATIVE_Native *nf = calloc(1, sizeof(*nf)); CAT_TYPES_NATIVE_Native *nf = calloc(1, sizeof(*nf));
@@ -49,6 +75,7 @@ CAT_VALUE_Value *cat_types_native_new(const char *name,
return NULL; return NULL;
nf->base.vtable = &g_native_vtable; nf->base.vtable = &g_native_vtable;
nf->name = strdup(name ? name : "native"); nf->name = strdup(name ? name : "native");
nf->doc = doc ? strdup(doc) : NULL;
nf->cb = cb; nf->cb = cb;
return &nf->base; return &nf->base;
} }
+12
View File
@@ -135,6 +135,18 @@ check "ffi-strlen-empty" "strlen empty: 0" "`echo "$out" | sed -n 13p
check "ffi-void-nil" "void ret nil: true" "`echo "$out" | sed -n 14p`" check "ffi-void-nil" "void ret nil: true" "`echo "$out" | sed -n 14p`"
check "ffi-strchr-bound" "strchr bound: true" "`echo "$out" | sed -n 15p`" check "ffi-strchr-bound" "strchr bound: true" "`echo "$out" | sed -n 15p`"
check "ffi-lib-callable" "cos 0: 1" "`echo "$out" | sed -n 16p`" check "ffi-lib-callable" "cos 0: 1" "`echo "$out" | sed -n 16p`"
# ---- reflection: attributes() / help() ------------------------------
out=`$BIN examples/reflect.cat`
check "attr-count" "point attrs: 4" "`echo "$out" | sed -n 1p`"
check "attr-x" " - x" "`echo "$out" | sed -n 2p`"
check "attr-y" " - y" "`echo "$out" | sed -n 3p`"
check "attr-name" " - name" "`echo "$out" | sed -n 4p`"
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`"
# ---- bytecode dump --------------------------------------------------- # ---- bytecode dump ---------------------------------------------------
out=`$BIN --dump examples/hello.cat` out=`$BIN --dump examples/hello.cat`