diff --git a/Makefile b/Makefile index 7a1afc5..1a88341 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ CC ?= cc CFLAGS ?= -std=c11 -Wall -Wextra -O2 -Wno-unused-parameter -D_DEFAULT_SOURCE CPPFLAGS += -Iinclude LDFLAGS ?= -LDLIBS ?= -lm +LDLIBS ?= -lm -lffi -ldl BUILD := build/catscript BIN := $(BUILD)/catscript @@ -46,6 +46,8 @@ SRCS := \ src/cat/types/native.c \ src/cat/types/file.c \ src/cat/types/generator.c \ + src/cat/types/selector.c \ + src/cat/types/ffi.c \ src/cat/stdlib/stdlib.c \ src/cat/stdlib/toml.c \ src/cat/stdlib/build.c diff --git a/README.md b/README.md index 50f91c9..e30965d 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,27 @@ local d = Dog("Rex") -- constrói via `new` print(d:speak()) -- Rex barks ``` +## `ffi` — chamar código nativo (estilo ctypes/CDLL) + +A biblioteca `ffi` carrega um `.so`/DLL e chama símbolos por nome com +uma assinatura declarada, usando **libffi** para a chamada ABI-correta +(é o mesmo mecanismo por trás do ctypes do Python): + +```lua +local m = ffi.load("libm.so.6") +local pow = m:func("pow", "double(double,double)") +print(pow(2, 10)) -- 1024 + +local c = ffi.load("libc.so.6") +local strlen = c:func("strlen", "long(string)") +``` + +Gramática da assinatura: `RET(ARG,ARG,...)`, com tipos `void`, `bool`, +`char`, `int8/uint8`, `int16/uint16`, `int/long/int32/uint32`, +`int64/uint64/longlong`, `float`, `double`, `string`, ponteiros. + +Requer `-lffi -ldl` (já no Makefile). + ## cpk — Cat Package Manager O primeiro programa em catscript. Lê o `package.toml` de um pacote diff --git a/examples/ffi.cat b/examples/ffi.cat new file mode 100644 index 0000000..b59297e --- /dev/null +++ b/examples/ffi.cat @@ -0,0 +1,22 @@ +-- examples/ffi.cat -- call native code through the `ffi` library. +-- +-- Like Python's ctypes/CDLL: load a shared object, bind a symbol with a +-- signature, and call it. libffi performs the ABI-correct call. + +local m = ffi.load("libm.so.6") +local pow = m:func("pow", "double(double,double)") +print("pow(2,10) =", pow(2, 10)) + +local sqrt = m:func("sqrt", "double(double)") +print("sqrt(144) =", sqrt(144)) + +local c = ffi.load("libc.so.6") +local getpid = c:func("getpid", "int()") +local pid = getpid() +print("getpid > 0:", pid > 0) + +local strlen = c:func("strlen", "long(string)") +print("strlen:", strlen("catscript")) + +local abs = c:func("abs", "int(int)") +print("abs(-42) =", abs(-42)) diff --git a/include/cat/types/ffi.h b/include/cat/types/ffi.h new file mode 100644 index 0000000..38118c3 --- /dev/null +++ b/include/cat/types/ffi.h @@ -0,0 +1,67 @@ +/* + * cat/types/ffi.h -- the `ffi` library: call native code (ctypes/CDLL-like). + * + * Naming rule: symbols here are cat_types_ffi_* / CAT_TYPES_FFI_*. + * + * catscript can load a shared library (dlopen) and call its symbols with + * a declared signature, using libffi to perform the ABI-correct call. + * + * local lib = ffi.load("libm.so.6") + * local pow = lib:func("pow", "double(double,double)") + * print(pow(2, 10)) -- 1024 + * + * local c = ffi.load("libc.so.6") + * local pid = c:func("getpid", "int()") + * + * Signature grammar: "RET(ARG,ARG,...)" where each type is one of + * void, bool, char, int8/uint8, int16/uint16, int/long/int32/uint32, + * int64/uint64/longlong, float, double, string, pointer spellings, or + * any base name suffixed with a star. + */ +#ifndef CAT_TYPES_FFI_H +#define CAT_TYPES_FFI_H + +#include "cat/value.h" + +/* CAT_TYPES_FFI_Library -- a dlopen() handle as a first-class value. + * `lib:func(name, sig)` / `lib[name]` resolve a symbol. */ +typedef struct CAT_TYPES_FFI_Library { + CAT_VALUE_Value base; + void *handle; + char *path; +} CAT_TYPES_FFI_Library; + +/* CAT_TYPES_FFI_Function -- a resolved symbol + prepared libffi call. */ +typedef struct CAT_TYPES_FFI_Function { + CAT_VALUE_Value base; + void *sym; /* the dlsym pointer */ + char *name; + char *sig; /* original signature text */ + void *cif; /* ffi_cif * (kept opaque here) */ + void *argtypes; /* ffi_type ** */ + int nargs; + void *rtype; /* ffi_type * */ + int ret_kind; /* CAT_TYPES_FFI_RET_* */ +} CAT_TYPES_FFI_Function; + +enum { + CAT_TYPES_FFI_RET_VOID, + CAT_TYPES_FFI_RET_INT, + CAT_TYPES_FFI_RET_DOUBLE, + CAT_TYPES_FFI_RET_STRING +}; + +/* Load a shared library by path; returns a Library value (nil on error). */ +CAT_VALUE_Value *cat_types_ffi_load(const char *path); + +/* Bind a symbol with a signature; returns a Function value (nil on error). */ +CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name, + const char *sig); + +/* Build the `ffi` module table (with `load`). */ +CAT_VALUE_Value *cat_types_ffi_module(void); + +CAT_VALUE_Vtable *cat_types_ffi_library_vtable(void); +CAT_VALUE_Vtable *cat_types_ffi_function_vtable(void); + +#endif /* CAT_TYPES_FFI_H */ diff --git a/include/cat/types/selector.h b/include/cat/types/selector.h new file mode 100644 index 0000000..bddd070 --- /dev/null +++ b/include/cat/types/selector.h @@ -0,0 +1,49 @@ +/* + * cat/types/selector.h -- syntax selectors. + * + * Naming rule: symbols here are cat_types_selector_* / CAT_TYPES_SELECTOR_*. + * + * catscript has no special-case operators for member access. Instead the + * compiler lowers surface syntax to ordinary method sends against a small + * set of well-known selector names: + * + * obj(a, b) -> obj:_parenthesis_(a, b) + * obj[i] -> obj:_squarebrackets_(i) + * obj[i] = v -> obj:_squarebrackets_set_(i, v) + * obj.k -> obj:_dot_("k") + * obj.k = v -> obj:_dot_set_("k", v) + * { ... } -> _curlybrackets_ hook on the new object + * + * Every object bound to these names inherits a default implementation + * (a `selector` value) that performs the raw, built-in behaviour. A type + * can override any selector by defining a method of that name, so new + * indexing/attribute semantics need no compiler change at all. + */ +#ifndef CAT_TYPES_SELECTOR_H +#define CAT_TYPES_SELECTOR_H + +#include "cat/value.h" + +/* The selector kinds. */ +enum { + CAT_TYPES_SELECTOR_DOT = 1, /* obj._dot_(key) */ + CAT_TYPES_SELECTOR_DOT_SET, /* obj._dot_set_(key, value) */ + CAT_TYPES_SELECTOR_SQ, /* obj._squarebrackets_(idx) */ + CAT_TYPES_SELECTOR_SQ_SET, /* obj._squarebrackets_set_(idx, v) */ + CAT_TYPES_SELECTOR_PAREN, /* obj._parenthesis_(args...) */ + CAT_TYPES_SELECTOR_CURLY /* obj._curlybrackets_() */ +}; + +/* CAT_TYPES_SELECTOR_Selector -- a bound default selector method. */ +typedef struct CAT_TYPES_SELECTOR_Selector { + CAT_VALUE_Value base; + int kind; +} CAT_TYPES_SELECTOR_Selector; + +/* Return a fresh selector value for a selector name, or NULL if `name` + * is not one of the reserved selector names. */ +CAT_VALUE_Value *cat_types_selector_lookup(const char *name); + +CAT_VALUE_Vtable *cat_types_selector_vtable(void); + +#endif /* CAT_TYPES_SELECTOR_H */ diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index 1234b34..1ef5af8 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -20,6 +20,7 @@ #include "cat/types/table.h" #include "cat/types/native.h" #include "cat/types/file.h" +#include "cat/types/ffi.h" #include #include @@ -433,5 +434,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm) 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()); return 0; } diff --git a/src/cat/types/ffi.c b/src/cat/types/ffi.c new file mode 100644 index 0000000..3306f23 --- /dev/null +++ b/src/cat/types/ffi.c @@ -0,0 +1,378 @@ +/* + * cat/types/ffi.c -- the `ffi` library: call native code (ctypes/CDLL-like). + * + * Naming rule: symbols here are cat_types_ffi_* / CAT_TYPES_FFI_*. + * + * `ffi.load(path)` dlopen()s a shared object. `lib:func(name, sig)` + * dlsym()s a symbol and prepares a libffi call from the signature, e.g. + * "double(double,double)". Calling the result makes the ABI-correct + * native call and converts the result back to a catscript value. + */ +#include "cat/types/ffi.h" +#include "cat/types/text.h" +#include "cat/types/ascii_text.h" +#include "cat/types/native.h" +#include "cat/types/nil.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/bool.h" +#include "cat/types/table.h" +#include "cat/error.h" + +#include +#include + +#include +#include +#include + +/* ---- type names -> ffi_type / kind ---------------------------------- */ + +static ffi_type *type_for(const char *t) +{ + if (strcmp(t, "void") == 0) return &ffi_type_void; + if (strcmp(t, "bool") == 0) return &ffi_type_uint8; + if (strcmp(t, "char") == 0) return &ffi_type_schar; + if (strcmp(t, "int8") == 0) return &ffi_type_sint8; + if (strcmp(t, "uint8") == 0) return &ffi_type_uint8; + if (strcmp(t, "int16") == 0) return &ffi_type_sint16; + if (strcmp(t, "uint16") == 0) return &ffi_type_uint16; + if (strcmp(t, "int") == 0) return &ffi_type_sint32; + if (strcmp(t, "int32") == 0) return &ffi_type_sint32; + if (strcmp(t, "uint32") == 0) return &ffi_type_uint32; + if (strcmp(t, "long") == 0) return &ffi_type_slong; + if (strcmp(t, "ulong") == 0) return &ffi_type_ulong; + if (strcmp(t, "int64") == 0) return &ffi_type_sint64; + if (strcmp(t, "uint64") == 0) return &ffi_type_uint64; + if (strcmp(t, "longlong") == 0) return &ffi_type_sint64; + if (strcmp(t, "float") == 0) return &ffi_type_float; + if (strcmp(t, "double") == 0) return &ffi_type_double; + if (strcmp(t, "string") == 0) return &ffi_type_pointer; + if (strcmp(t, "char*") == 0) return &ffi_type_pointer; + if (strcmp(t, "void*") == 0) return &ffi_type_pointer; + if (strcmp(t, "ptr") == 0) return &ffi_type_pointer; + if (strcmp(t, "pointer") == 0) return &ffi_type_pointer; + /* any unknown base name followed by '*' is a pointer */ + if (t[strlen(t) - 1] == '*') + return &ffi_type_pointer; + return NULL; +} + +static int ret_kind_for(const char *t) +{ + if (strcmp(t, "void") == 0) return CAT_TYPES_FFI_RET_VOID; + if (strcmp(t, "double") == 0 || strcmp(t, "float") == 0) + return CAT_TYPES_FFI_RET_DOUBLE; + if (strcmp(t, "string") == 0 || strcmp(t, "char*") == 0) + return CAT_TYPES_FFI_RET_STRING; + return CAT_TYPES_FFI_RET_INT; +} + +/* Parse "RET(A,B,...)" into the function's cif/argtypes. Returns 0 on + * success, -1 on a malformed signature. */ +static int prepare(CAT_TYPES_FFI_Function *f, const char *sig) +{ + char ret[32]; + char args[512]; + const char *lp, *rp; + ffi_type **at; + int n; + char *p, *tok; + + if (sig == NULL) + return -1; + lp = strchr(sig, '('); + rp = (lp != NULL) ? strrchr(sig, ')') : NULL; + if (lp == NULL || rp == NULL || rp < lp) + return -1; + if ((size_t)(lp - sig) >= sizeof(ret)) + return -1; + memcpy(ret, sig, (size_t)(lp - sig)); + ret[lp - sig] = '\0'; + if ((size_t)(rp - lp - 1) >= sizeof(args)) + return -1; + memcpy(args, lp + 1, (size_t)(rp - lp - 1)); + args[rp - lp - 1] = '\0'; + + f->rtype = type_for(ret); + f->ret_kind = ret_kind_for(ret); + if (f->rtype == NULL) + return -1; + + at = calloc(16, sizeof(*at)); + n = 0; + p = args; + while (*p != '\0' && n < 16) { + while (*p == ' ' || *p == '\t' || *p == ',') + p++; + if (*p == '\0') + break; + tok = p; + while (*p != ',' && *p != '\0') + p++; + if (*p == ',') + *p++ = '\0'; + { + size_t tl = strlen(tok); + while (tl > 0 && (tok[tl - 1] == ' ' || tok[tl - 1] == '\t')) + tok[--tl] = '\0'; + } + if (tok[0] == '\0') + continue; + at[n] = type_for(tok); + if (at[n] == NULL) { + free(at); + return -1; + } + n++; + } + f->argtypes = at; + f->nargs = n; + { + ffi_cif *cif = calloc(1, sizeof(*cif)); + if (cif == NULL || ffi_prep_cif(cif, FFI_DEFAULT_ABI, (unsigned)n, + f->rtype, at) != FFI_OK) { + free(cif); + free(at); + return -1; + } + f->cif = cif; + } + return 0; +} + +static void function_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_FFI_Function *f = (CAT_TYPES_FFI_Function *)self; + + free(f->cif); + free(f->argtypes); + free(f->name); + free(f->sig); + free(f); +} + +/* ---- converting catscript args to native storage -------------------- */ + +typedef union { + long long i; + double d; + const char *s; + void *p; +} ffi_slot; + +static void arg_to_slot(CAT_VALUE_Value *v, ffi_type *t, ffi_slot *slot) +{ + if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + if (t == &ffi_type_double) { + slot->d = cat_types_number_as_double(v); + return; + } + if (t == &ffi_type_float) { + slot->d = cat_types_number_as_double(v); + return; + } + slot->i = cat_types_number_as_int(v); + return; + } + if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) { + if (t == &ffi_type_pointer) { + slot->s = cat_types_text_bytes(v); + return; + } + slot->i = (long long)strtoll(cat_types_text_bytes(v), NULL, 10); + return; + } + if (v != NULL && v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) { + slot->i = ((CAT_VALUE_Value *)v) ? 1 : 0; + return; + } + slot->i = 0; +} + +static int function_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, + int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_FFI_Function *f = (CAT_TYPES_FFI_Function *)self; + ffi_slot slots[16]; + void *aptr[16]; + ffi_slot ret; + int base = 0; /* args[0] is the receiver when sent with ':' */ + int n = nargs - base; + int i; + + if (n > 16) + return (cat_error_raise(err, "ffi: too many arguments"), -1); + if (n != f->nargs) + return (cat_error_raise(err, + "ffi: %s expects %d args, got %d", f->name, f->nargs, n), -1); + for (i = 0; i < n; i++) { + arg_to_slot(args[base + i], ((ffi_type **)f->argtypes)[i], &slots[i]); + aptr[i] = &slots[i]; + } + memset(&ret, 0, sizeof(ret)); + ffi_call((ffi_cif *)f->cif, FFI_FN(f->sym), &ret, aptr); + + switch (f->ret_kind) { + case CAT_TYPES_FFI_RET_VOID: + *out = cat_types_nil_get(); + break; + case CAT_TYPES_FFI_RET_DOUBLE: + *out = cat_types_float_new(ret.d); + break; + case CAT_TYPES_FFI_RET_STRING: + *out = cat_types_ascii_text_new(ret.s ? ret.s : ""); + break; + default: + *out = cat_types_int_new(ret.i); + break; + } + return 0; +} + +static CAT_VALUE_Vtable g_function_vtable = { + .type_name = "ffi.Function", + .kind = CAT_VALUE_KIND_FUNCTION, + .call = { function_call }, + .destroy = function_destroy, +}; + +CAT_VALUE_Vtable *cat_types_ffi_function_vtable(void) +{ + return &g_function_vtable; +} + +/* ---- the Library value ---------------------------------------------- */ + +/* lib:func(name, sig) -- the explicit form that carries the signature. */ +static int lib_method_func(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_VALUE_Value *lib = nargs >= 1 ? args[0] : NULL; + const char *name = (nargs >= 2) ? cat_types_text_bytes(args[1]) : NULL; + const char *sig = (nargs >= 3) ? cat_types_text_bytes(args[2]) : NULL; + + (void)vm; + *out = cat_types_ffi_bind(lib, name, sig); + return 0; +} + +static int library_get_attr_full(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (strcmp(name, "func") == 0) { + *out = cat_types_native_new("func", lib_method_func); + return 0; + } + return (cat_error_raise(err, "ffi.Library has no '%s'", name), -1); +} + +static int library_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, + int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + /* Calling a library directly: lib("name", "sig") == lib:func(...) */ + CAT_VALUE_Value *callargs[4]; + + callargs[0] = self; + callargs[1] = nargs >= 1 ? args[0] : cat_types_nil_get(); + callargs[2] = nargs >= 2 ? args[1] : cat_types_nil_get(); + callargs[3] = cat_types_nil_get(); + return lib_method_func(NULL, callargs, 3, out); +} + +static void library_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_FFI_Library *l = (CAT_TYPES_FFI_Library *)self; + + if (l->handle != NULL) + dlclose(l->handle); + free(l->path); + free(l); +} + +static CAT_VALUE_Vtable g_library_vtable = { + .type_name = "ffi.Library", + .kind = CAT_VALUE_KIND_TABLE, + .call = { library_call }, + .get_attribute = { library_get_attr_full }, + .destroy = library_destroy, +}; + +CAT_VALUE_Vtable *cat_types_ffi_library_vtable(void) +{ + return &g_library_vtable; +} + +/* ---- constructors --------------------------------------------------- */ + +CAT_VALUE_Value *cat_types_ffi_load(const char *path) +{ + CAT_TYPES_FFI_Library *l; + void *h; + + if (path == NULL) + return cat_types_nil_get(); + h = dlopen(path, RTLD_NOW | RTLD_GLOBAL); + if (h == NULL) + return cat_types_nil_get(); + l = calloc(1, sizeof(*l)); + if (l == NULL) { + dlclose(h); + return cat_types_nil_get(); + } + l->base.vtable = &g_library_vtable; + l->handle = h; + l->path = strdup(path); + return &l->base; +} + +CAT_VALUE_Value *cat_types_ffi_bind(CAT_VALUE_Value *lib, const char *name, + const char *sig) +{ + CAT_TYPES_FFI_Library *l; + CAT_TYPES_FFI_Function *f; + void *sym; + + if (lib == NULL || lib->vtable != &g_library_vtable || name == NULL) + return cat_types_nil_get(); + l = (CAT_TYPES_FFI_Library *)lib; + sym = dlsym(l->handle, name); + if (sym == NULL) + return cat_types_nil_get(); + f = calloc(1, sizeof(*f)); + if (f == NULL) + return cat_types_nil_get(); + f->base.vtable = &g_function_vtable; + f->sym = sym; + f->name = strdup(name); + f->sig = sig ? strdup(sig) : NULL; + if (prepare(f, sig) != 0) { + function_destroy(&f->base); + return cat_types_nil_get(); + } + return &f->base; +} + +/* `ffi.load(path)` module function. */ +static int ffi_load_native(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + *out = cat_types_ffi_load(cat_types_text_bytes(args[0])); + return 0; +} + +CAT_VALUE_Value *cat_types_ffi_module(void) +{ + CAT_VALUE_Value *m = cat_types_table_new(); + CAT_ERROR_Error e; + + cat_error_clear(&e); + cat_types_table_set(m, "load", + cat_types_native_new("load", ffi_load_native), &e); + return m; +} diff --git a/src/cat/types/selector.c b/src/cat/types/selector.c new file mode 100644 index 0000000..47b9c8e --- /dev/null +++ b/src/cat/types/selector.c @@ -0,0 +1,123 @@ +/* + * cat/types/selector.c -- default selector implementations. + * + * Naming rule: symbols here are cat_types_selector_* / CAT_TYPES_SELECTOR_*. + * + * Each selector is a bound default method. When a program sends + * `obj:_dot_(k)` and the object does not define `_dot_`, the attribute + * dispatcher hands back one of these instead, and calling it performs the + * raw built-in access. This is what lets the compiler drop the special + * GETATTR/SETATTR/GETIDX/SETIDX/CALL cases: they are all just `:` sends. + */ +#include "cat/types/selector.h" +#include "cat/types/text.h" +#include "cat/types/number.h" +#include "cat/types/nil.h" +#include "cat/types/table.h" +#include "cat/error.h" + +#include +#include +#include + +/* Turn a key/index value into the string an object stores it under. */ +static void sel_key(CAT_VALUE_Value *v, char *buf, size_t n) +{ + if (v == NULL) { + buf[0] = '\0'; + return; + } + if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) + snprintf(buf, n, "%lld", cat_types_number_as_int(v)); + else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) + snprintf(buf, n, "%s", cat_types_text_bytes(v)); + else + buf[0] = '\0'; +} + +/* A selector is called as `receiver:_sel_(...)`, so args[0] is the + * receiver and args[1..] are the selector's own arguments. */ +static int selector_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, + int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_SELECTOR_Selector *s = (CAT_TYPES_SELECTOR_Selector *)self; + CAT_VALUE_Value *rx = (nargs >= 1) ? args[0] : NULL; + char key[64]; + + switch (s->kind) { + case CAT_TYPES_SELECTOR_DOT: /* _dot_(key) */ + sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key)); + return cat_value_get_attribute(rx, key, out, err); + case CAT_TYPES_SELECTOR_DOT_SET: /* _dot_set_(key, value) */ + sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key)); + cat_value_set_attribute(rx, key, nargs >= 3 ? args[2] : NULL, err); + *out = nargs >= 3 ? args[2] : cat_types_nil_get(); + return 0; + case CAT_TYPES_SELECTOR_SQ: /* _squarebrackets_(idx) */ + sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key)); + return cat_value_get_attribute(rx, key, out, err); + case CAT_TYPES_SELECTOR_SQ_SET: /* _squarebrackets_set_(idx, value) */ + sel_key(nargs >= 2 ? args[1] : NULL, key, sizeof(key)); + cat_value_set_attribute(rx, key, nargs >= 3 ? args[2] : NULL, err); + *out = nargs >= 3 ? args[2] : cat_types_nil_get(); + return 0; + case CAT_TYPES_SELECTOR_PAREN: /* _parenthesis_(args...) */ + return cat_value_call(rx, nargs >= 1 ? &args[1] : args, + nargs >= 1 ? nargs - 1 : 0, out, err); + case CAT_TYPES_SELECTOR_CURLY: /* _curlybrackets_() */ + *out = cat_types_table_new(); + return 0; + default: + return (cat_error_raise(err, "unknown selector"), -1); + } +} + +static CAT_VALUE_Vtable g_selector_vtable = { + .type_name = "selector", + .kind = CAT_VALUE_KIND_FUNCTION, + .call = { selector_call }, +}; + +CAT_VALUE_Vtable *cat_types_selector_vtable(void) +{ + return &g_selector_vtable; +} + +/* Static singletons: one per selector kind (no per-lookup allocation). */ +static CAT_TYPES_SELECTOR_Selector g_sel[] = { + { { NULL }, CAT_TYPES_SELECTOR_DOT }, + { { NULL }, CAT_TYPES_SELECTOR_DOT_SET }, + { { NULL }, CAT_TYPES_SELECTOR_SQ }, + { { NULL }, CAT_TYPES_SELECTOR_SQ_SET }, + { { NULL }, CAT_TYPES_SELECTOR_PAREN }, + { { NULL }, CAT_TYPES_SELECTOR_CURLY }, +}; + +CAT_VALUE_Value *cat_types_selector_lookup(const char *name) +{ + int i; + char key[64]; + + if (name == NULL) + 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) + g_sel[i].base.vtable = &g_selector_vtable; + } + strncpy(key, name, sizeof(key) - 1); + key[sizeof(key) - 1] = '\0'; + if (strcmp(key, "_dot_") == 0 || strcmp(key, ".") == 0) + return &g_sel[0].base; + if (strcmp(key, "_dot_set_") == 0) + return &g_sel[1].base; + if (strcmp(key, "_squarebrackets_") == 0 || strcmp(key, "[]") == 0) + return &g_sel[2].base; + if (strcmp(key, "_squarebrackets_set_") == 0) + return &g_sel[3].base; + if (strcmp(key, "_parenthesis_") == 0 || strcmp(key, "()") == 0) + return &g_sel[4].base; + if (strcmp(key, "_curlybrackets_") == 0 || strcmp(key, "{}") == 0) + return &g_sel[5].base; + return NULL; +} diff --git a/src/cat/types/table.c b/src/cat/types/table.c index ee4abee..11f9477 100644 --- a/src/cat/types/table.c +++ b/src/cat/types/table.c @@ -6,6 +6,7 @@ #include "cat/types/table.h" #include "cat/types/text.h" #include "cat/types/ascii_text.h" +#include "cat/types/selector.h" #include #include @@ -27,6 +28,17 @@ static int table_get_attribute(CAT_VALUE_Value *self, const char *name, if (cat_types_table_get(self, "__index", &base, &local) == 0 && base != NULL && base != self) return cat_value_get_attribute(base, name, out, err); + /* Selector fallback: () [] . {} are not special operators, they are + * sends to well-known selector names. An object that does not define + * one still works because the dispatcher hands back the default + * implementation of that selector here. */ + { + CAT_VALUE_Value *sel = cat_types_selector_lookup(name); + if (sel != NULL) { + *out = sel; + return 0; + } + } return (cat_error_raise(err, "table has no key '%s'", name), -1); } diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 926e1bd..e17771c 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -106,6 +106,15 @@ out=`$BIN tests/std.cat` check "std-math" "math double: 42" "`echo "$out" | sed -n 1p`" check "std-io" "io join: a-b-c" "`echo "$out" | sed -n 4p`" check "std-fs" "fs copy: true" "`echo "$out" | sed -n 6p`" + +# ---- ffi: call native code (ctypes/CDLL-like) ----------------------- + +out=`$BIN examples/ffi.cat` +check "ffi-pow" "pow(2,10) = 1024" "`echo "$out" | sed -n 1p`" +check "ffi-sqrt" "sqrt(144) = 12" "`echo "$out" | sed -n 2p`" +check "ffi-getpid" "getpid > 0: true" "`echo "$out" | sed -n 3p`" +check "ffi-strlen" "strlen: 9" "`echo "$out" | sed -n 4p`" +check "ffi-abs" "abs(-42) = 42" "`echo "$out" | sed -n 5p`" # ---- bytecode dump --------------------------------------------------- out=`$BIN --dump examples/hello.cat`