/* * cat/stdlib/stdlib.c -- standard library native functions. * * Naming rule: symbols here are cat_stdlib_stdlib_*. * * Native signature: int cb(vm, args, nargs, out). Installed names: * print, tostring, tonumber, type, len, toml_parse, toml_encode. */ #include "cat/stdlib/stdlib.h" #include "cat/stdlib/toml.h" #include "cat/compiler.h" #include "cat/bytecode.h" #include "cat/module.h" #include "cat/types/empty.h" #include "cat/types/bool.h" #include "cat/types/number.h" #include "cat/types/int.h" #include "cat/types/float.h" #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" #include "cat/types/empty.h" #include #include #include /* toString for any value (heap string, caller does not free). */ static const char *value_to_text(CAT_VALUE_Value *v) { static char buf[512]; if (v == NULL || v == cat_types_empty()) return "empty"; if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) return cat_types_text_bytes(v); if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { if (((CAT_TYPES_NUMBER_Number *)v)->is_float) snprintf(buf, sizeof(buf), "%g", cat_types_number_as_double(v)); else snprintf(buf, sizeof(buf), "%lld", cat_types_number_as_int(v)); return buf; } if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) return ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false"; snprintf(buf, sizeof(buf), "<%s>", cat_value_type_name(v)); return buf; } static int lf_print(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { int i; (void)vm; for (i = 0; i < nargs; i++) { if (i) putchar(' '); fputs(value_to_text(args[i]), stdout); } putchar('\n'); *out = cat_types_empty(); return 0; } static int lf_tostring(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { (void)vm; /* `tostring` is the display form (no quotes); the REPL echo uses the * repr form. Both honour `_repr_`. */ *out = (nargs > 0) ? cat_types_ascii_text_new(cat_value_str_text(args[0])) : cat_types_ascii_text_new(""); return 0; } static int lf_tonumber(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { const char *s; char *end; (void)vm; if (nargs < 1) { *out = cat_types_empty(); return 0; } if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_NUMBER) { *out = args[0]; return 0; } s = cat_types_text_bytes(args[0]); if (strchr(s, '.') != NULL) { double d = strtod(s, &end); *out = (*end == '\0') ? cat_types_float_new(d) : cat_types_empty(); } else { long long n = strtoll(s, &end, 10); *out = (*end == '\0') ? cat_types_int_new(n) : cat_types_empty(); } return 0; } static int lf_type(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { CAT_VALUE_Value *v = nargs > 0 ? args[0] : NULL; (void)vm; /* Structural typing: the type of an object IS its structure, so an * object with no members has the empty type. That covers both the * canonical `empty` and a freshly built `{}`. */ if (v != NULL && v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TABLE && (v->vtable == cat_types_table_vtable() || v->vtable == cat_types_empty_vtable())) { int members = (v->vtable == cat_types_table_vtable()) ? cat_types_table_count(v) : 0; if (members == 0) { *out = cat_types_ascii_text_new("empty"); return 0; } } *out = cat_types_ascii_text_new(v != NULL ? cat_value_type_name(v) : "empty"); return 0; } static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { (void)vm; if (nargs < 1) { *out = cat_types_int_new(0); return 0; } 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 *out = cat_types_int_new(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, j; (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_")); } /* 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++) 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_empty(); 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_empty(); 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_empty(); return 0; } static int lf_toml_parse(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { CAT_VALUE_Value *tbl = NULL; CAT_ERROR_Error e; (void)vm; cat_error_clear(&e); if (nargs < 1) { *out = cat_types_empty(); return 0; } if (cat_stdlib_toml_parse(cat_types_text_bytes(args[0]), &tbl, &e) != 0) { fprintf(stderr, "toml_parse: %s\n", e.message); *out = cat_types_empty(); return 0; } *out = tbl; return 0; } static int lf_toml_encode(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { CAT_ERROR_Error e; char *s; (void)vm; cat_error_clear(&e); if (nargs < 1) { *out = cat_types_ascii_text_new(""); return 0; } s = cat_stdlib_toml_encode(args[0], &e); *out = cat_types_ascii_text_new(s ? s : ""); free(s); return 0; } static int lf_read_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { FILE *f; long sz; char *buf = NULL; char *path; (void)vm; if (nargs < 1) { *out = cat_types_empty(); return 0; } path = (char *)cat_types_text_bytes(args[0]); f = fopen(path, "rb"); if (f == NULL) { *out = cat_types_empty(); return 0; } fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); buf = malloc((size_t)sz + 1); if (buf == NULL) { fclose(f); *out = cat_types_empty(); return 0; } if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ } buf[sz] = '\0'; fclose(f); *out = cat_types_ascii_text_new(buf); free(buf); return 0; } static int lf_write_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { FILE *f; (void)vm; if (nargs < 2) { *out = cat_types_empty(); return 0; } f = fopen(cat_types_text_bytes(args[0]), "wb"); if (f != NULL) { const char *s = cat_types_text_bytes(args[1]); fwrite(s, 1, strlen(s), f); fclose(f); } *out = cat_types_empty(); return 0; } static int lf_ord(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { const char *s; long long i; (void)vm; if (nargs < 2) { *out = cat_types_int_new(-1); return 0; } s = cat_types_text_bytes(args[0]); i = cat_types_number_as_int(args[1]); if (i < 0 || i >= (long long)strlen(s)) *out = cat_types_int_new(-1); else *out = cat_types_int_new((unsigned char)s[i]); return 0; } static int lf_chr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { char buf[2]; (void)vm; buf[0] = (char)(nargs > 0 ? cat_types_number_as_int(args[0]) : 0); buf[1] = '\0'; *out = cat_types_ascii_text_new(buf); return 0; } static int lf_substr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { const char *s; long long i, n; char *buf; (void)vm; if (nargs < 3) { *out = cat_types_ascii_text_new(""); return 0; } s = cat_types_text_bytes(args[0]); i = cat_types_number_as_int(args[1]); n = cat_types_number_as_int(args[2]); if (i < 0 || i > (long long)strlen(s) || n < 0) { *out = cat_types_ascii_text_new(""); return 0; } buf = malloc((size_t)n + 1); if (buf == NULL) { *out = cat_types_ascii_text_new(""); return 0; } memcpy(buf, s + i, (size_t)n); buf[n] = '\0'; *out = cat_types_ascii_text_new(buf); free(buf); return 0; } /* Resolve a `use` operand to a readable path. A name like `math` * resolves (in order) to: the name itself, `.cat`, `std//\ * .cat`, `/.cat`, and `std/.cat`. A path that * already contains a `.cat` or a `/` is used as-is. Returns a malloc'd * path, or NULL when nothing matches. */ static char *use_resolve(const char *name) { static const char *fmts[] = { "%s", "%s.cat", "std/%s/%s.cat", "%s/%s.cat", "std/%s.cat", }; char buf[1024]; int i; if (strstr(name, ".cat") != NULL || strchr(name, '/') != NULL) { FILE *f = fopen(name, "rb"); if (f != NULL) { fclose(f); return strdup(name); } return NULL; } for (i = 0; i < (int)(sizeof(fmts) / sizeof(fmts[0])); i++) { FILE *f; snprintf(buf, sizeof(buf), fmts[i], name, name); f = fopen(buf, "rb"); if (f != NULL) { fclose(f); return strdup(buf); } } return NULL; } static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { FILE *f; long sz; char *src; char *resolved = NULL; const char *path; CAT_BYTECODE_Function *fn; CAT_ERROR_Error e; if (nargs < 1) { *out = cat_types_empty(); return 0; } /* Resolve a module name (`math`) to a path; a path is used as-is. */ resolved = use_resolve(cat_types_text_bytes(args[0])); path = (resolved != NULL) ? resolved : cat_types_text_bytes(args[0]); f = fopen(path, "rb"); if (f == NULL) { free(resolved); return (cat_error_raise(&vm->err, "cannot import module '%s'", cat_types_text_bytes(args[0])), -1); } fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); src = malloc((size_t)sz + 1); if (src == NULL) { fclose(f); *out = cat_types_empty(); return 0; } if (fread(src, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ } src[sz] = '\0'; fclose(f); cat_error_clear(&e); fn = cat_compiler_compile(src, &e); if (fn == NULL) { fprintf(stderr, "dofile: %s\n", e.message); free(src); *out = cat_types_empty(); return 0; } /* `module` reflects the imported unit while it runs, then the * caller's `module` is restored. The name is the basename. */ { const char *p = path; const char *base = strrchr(p, '/'); base = (base != NULL) ? base + 1 : p; cat_module_enter(vm, base, p); } cat_error_clear(&e); cat_vm_run(vm, fn, out); cat_module_leave(vm); free(src); free(resolved); /* The compiled chunk is intentionally NOT freed: any `function` * definitions in it became globals whose closures point into this * bytecode tree. The chunk lives as long as the VM does. */ return 0; } /* `use expr` -- import another catscript source file (alias of dofile), * so `use "std/io/file.cat"` pulls its definitions into this unit. */ static int lf_use(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { return lf_dofile(vm, args, nargs, out); } /* `__class_new(cls, ...)` -- default constructor installed on every * class as `new`. Copies the class into a fresh instance and runs the * class's `init` method (if any) with the given arguments. */ static int lf_class_new(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { CAT_VALUE_Value *cls; CAT_VALUE_Value *inst; CAT_VALUE_Value *init = NULL; CAT_ERROR_Error e; int i; (void)vm; if (nargs < 1) { *out = cat_types_empty(); return 0; } cls = args[0]; inst = cat_types_table_new(); /* share the class's methods/layout with the instance */ cat_error_clear(&e); cat_types_table_set(inst, "__index", cls, &e); cat_error_clear(&e); cat_types_table_set(inst, "__class", cls, &e); /* run init(args...) if the class defines it */ cat_error_clear(&e); if (cat_value_get_attribute(cls, "init", &init, &e) == 0 && init != NULL) { CAT_VALUE_Value *r = NULL; CAT_VALUE_Value *callargs[258]; callargs[0] = inst; for (i = 1; i < nargs && i < 257; i++) callargs[i] = args[i]; cat_error_clear(&e); cat_value_call(init, callargs, nargs, &r, &e); } *out = inst; return 0; } static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { /* AbstractFile cannot be instantiated: it is the abstract base of the * stream family (File/StringIO/BytesIO). */ (void)vm; (void)args; (void)nargs; fprintf(stderr, "AbstractFile is abstract; use File::open, " "StringIO or BytesIO\n"); *out = cat_types_empty(); return 0; } static int lf_stringio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { (void)vm; *out = cat_types_file_stringio(nargs > 0 ? cat_types_text_bytes(args[0]) : ""); return 0; } static int lf_bytesio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { (void)vm; (void)args; (void)nargs; *out = cat_types_file_bytesio(); return 0; } int cat_stdlib_stdlib_install(CAT_VM_State *vm) { 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 (usa `_repr_` se houver)." }, { "tonumber", lf_tonumber, "tonumber(s) -- converte texto em n\u00famero (ou vazio se inv\u00e1lido)." }, { "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", 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_types_native_new("StringIO", lf_stringio)); cat_vm_set_global(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()); /* the empty object: the value for "no value" (catscript has no nil) */ cat_vm_set_global(vm, "empty", cat_types_empty()); /* `module` reflects the unit currently executing (name/path/dir) */ cat_vm_set_global(vm, "module", cat_module_table("main", NULL)); return 0; }