diff --git a/Makefile b/Makefile index 1a88341..c23b922 100644 --- a/Makefile +++ b/Makefile @@ -47,6 +47,7 @@ SRCS := \ src/cat/types/file.c \ src/cat/types/generator.c \ src/cat/types/selector.c \ + src/cat/types/list.c \ src/cat/types/ffi.c \ src/cat/stdlib/stdlib.c \ src/cat/stdlib/toml.c \ diff --git a/examples/reflect.cat b/examples/reflect.cat new file mode 100644 index 0000000..8d8e523 --- /dev/null +++ b/examples/reflect.cat @@ -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) diff --git a/include/cat/types/list.h b/include/cat/types/list.h new file mode 100644 index 0000000..423affd --- /dev/null +++ b/include/cat/types/list.h @@ -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 */ diff --git a/include/cat/types/native.h b/include/cat/types/native.h index 215d67d..6464c26 100644 --- a/include/cat/types/native.h +++ b/include/cat/types/native.h @@ -21,12 +21,18 @@ typedef struct CAT_VM_State CAT_VM_State; typedef struct CAT_TYPES_NATIVE_Native { CAT_VALUE_Value base; char *name; + char *doc; /* optional `_doc_` documentation string */ int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); } CAT_TYPES_NATIVE_Native; CAT_VALUE_Value *cat_types_native_new(const char *name, 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); /* True if v is a native function value. */ diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index 1ef5af8..e3111ba 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -18,7 +18,9 @@ #include "cat/types/text.h" #include "cat/types/ascii_text.h" #include "cat/types/table.h" +#include "cat/types/list.h" #include "cat/types/native.h" +#include "cat/types/function.h" #include "cat/types/file.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) *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) *out = cat_types_int_new(cat_types_table_count(args[0])); else @@ -124,6 +128,125 @@ static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, 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, 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) { - cat_vm_register_native(vm, "print", lf_print); - cat_vm_register_native(vm, "tostring", lf_tostring); - cat_vm_register_native(vm, "tonumber", lf_tonumber); - cat_vm_register_native(vm, "type", lf_type); - cat_vm_register_native(vm, "len", lf_len); - cat_vm_register_native(vm, "toml_parse", lf_toml_parse); - cat_vm_register_native(vm, "toml_encode", lf_toml_encode); - cat_vm_register_native(vm, "read_file", lf_read_file); - cat_vm_register_native(vm, "write_file", lf_write_file); - cat_vm_register_native(vm, "ord", lf_ord); - cat_vm_register_native(vm, "chr", lf_chr); - cat_vm_register_native(vm, "substr", lf_substr); - cat_vm_register_native(vm, "dofile", lf_dofile); - cat_vm_register_native(vm, "use", lf_use); + struct { const char *name; + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); + const char *doc; } std[] = { + { "print", lf_print, "print(a, ...) -- escreve os argumentos em stdout." }, + { "tostring", lf_tostring, "tostring(v) -- representa\u00e7\u00e3o textual de v." }, + { "tonumber", lf_tonumber, "tonumber(s) -- converte texto em n\u00famero (ou nil)." }, + { "type", lf_type, "type(v) -- nome do tipo de v." }, + { "len", lf_len, "len(v) -- tamanho de texto ou n\u00famero de membros de um objeto." }, + { "attributes", lf_attributes, "attributes(obj) -- nomes dos membros de obj (lista), incluindo heran\u00e7a (como dir())." }, + { "help", lf_help, "help(obj) -- mostra a documenta\u00e7\u00e3o (`_doc_`) de obj ou lista seus atributos." }, + { "toml_parse", lf_toml_parse, "toml_parse(text) -- analisa TOML e devolve um objeto." }, + { "toml_encode", lf_toml_encode, "toml_encode(obj) -- serializa um objeto em TOML." }, + { "read_file", lf_read_file, "read_file(path) -- l\u00ea o conte\u00fado de um arquivo como texto." }, + { "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); /* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */ cat_vm_set_global(vm, "AbstractFile", diff --git a/src/cat/types/list.c b/src/cat/types/list.c new file mode 100644 index 0000000..a054975 --- /dev/null +++ b/src/cat/types/list.c @@ -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 +#include + +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]; +} diff --git a/src/cat/types/native.c b/src/cat/types/native.c index 1e7fe17..bbb0a93 100644 --- a/src/cat/types/native.c +++ b/src/cat/types/native.c @@ -4,6 +4,7 @@ * Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*. */ #include "cat/types/native.h" +#include "cat/types/ascii_text.h" #include "cat/vm.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); } +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) { CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self; free(nf->name); + free(nf->doc); free(nf); } @@ -32,6 +50,7 @@ static CAT_VALUE_Vtable g_native_vtable = { .type_name = "native", .kind = CAT_VALUE_KIND_FUNCTION, .call = { native_call }, + .get_attribute = { native_get_attribute }, .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, 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)); @@ -49,6 +75,7 @@ CAT_VALUE_Value *cat_types_native_new(const char *name, return NULL; nf->base.vtable = &g_native_vtable; nf->name = strdup(name ? name : "native"); + nf->doc = doc ? strdup(doc) : NULL; nf->cb = cb; return &nf->base; } diff --git a/tests/run_tests.sh b/tests/run_tests.sh index ee1a167..d7b0fec 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -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-strchr-bound" "strchr bound: true" "`echo "$out" | sed -n 15p`" 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 --------------------------------------------------- out=`$BIN --dump examples/hello.cat`