From 70728093ef43bb3aa87c44fceabddf222b882bc4 Mon Sep 17 00:00:00 2001 From: Minus Date: Wed, 18 Nov 2026 17:18:58 +0000 Subject: [PATCH] traits + Sized(): default methods and the sized marker - `trait` keyword: like `interface`, but tagged `__trait`; its methods carry default bodies. A class that `implements` a trait has those bodies mixed in (a class's own method wins), then is checked structurally -- so the mix-in runs BEFORE `__implements_check`. - runtime `__trait_mixin(cls, trait)`: copies a trait's default methods into the class (skipping `__*` meta keys and existing members). - `Sized` -- the marker object for "layout known at compile time"; every concrete value satisfies it, so `x is Sized` / `implements(x, Sized)` hold and signatures can name it (`buf : Sized()`). - tests/traits.cat + suite: default method, override, `is`, and Sized. Suite 144 -> 151. --- include/cat/lexer.h | 1 + src/cat/compiler.c | 33 ++++++++++++++++------ src/cat/lexer.c | 3 +- src/cat/stdlib/stdlib.c | 61 +++++++++++++++++++++++++++++++++++++++++ tests/run_tests.sh | 9 ++++++ tests/traits.cat | 35 +++++++++++++++++++++++ 6 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 tests/traits.cat diff --git a/include/cat/lexer.h b/include/cat/lexer.h index 25332fb..29648b0 100644 --- a/include/cat/lexer.h +++ b/include/cat/lexer.h @@ -31,6 +31,7 @@ enum CAT_LEXER_Kind { CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS, CAT_LEXER_TOK_IS, CAT_LEXER_TOK_COMPTIME, + CAT_LEXER_TOK_TRAIT, /* symbols */ CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR, CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET, diff --git a/src/cat/compiler.c b/src/cat/compiler.c index d272b6e..63d72d6 100644 --- a/src/cat/compiler.c +++ b/src/cat/compiler.c @@ -1006,8 +1006,17 @@ static void stat(Compiler *c) expect(c, CAT_LEXER_TOK_END, "'end'"); emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line); /* runtime assertion: the class must satisfy each declared interface - * (structural check, performed by __implements_check). */ + * (structural check, performed by __implements_check), and gets any + * trait's default methods mixed in (a no-op for plain interfaces). */ for (i = 0; i < nimpl && i < 8; i++) { + /* mix a trait's defaults in FIRST, then assert the class + * satisfies the contract (a plain interface adds nothing). */ + emit(c, CAT_BYTECODE_OP_GETGLOBAL, + add_string(c, "__trait_mixin"), 0, line); + emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line); + emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, impl[i]), 0, line); + emit(c, CAT_BYTECODE_OP_CALL, 2, 0, line); + emit(c, CAT_BYTECODE_OP_POP, 0, 0, line); emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, "__implements_check"), 0, line); emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line); @@ -1018,15 +1027,17 @@ static void stat(Compiler *c) break; } + case CAT_LEXER_TOK_TRAIT: case CAT_LEXER_TOK_INTERFACE: { - /* interface NAME [extends BASE] end + /* interface|trait NAME [extends BASE] end * - * An interface is a table tagged `__interface`; its members name the - * required methods (a body is allowed and becomes a default method, - * shared through `__index`). The `is` operator checks satisfaction - * structurally at runtime. */ + * Both build a table tagged `__interface` so the `is` operator and + * the runtime check work the same way. A `trait` is additionally + * tagged `__trait`: its methods carry default bodies, and a class + * that `implements` it has those methods mixed in. */ char name[256]; char base[256]; + int is_trait = (c->tok.kind == CAT_LEXER_TOK_TRAIT); next(c); name[0] = '\0'; base[0] = '\0'; @@ -1045,7 +1056,12 @@ static void stat(Compiler *c) emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line); emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line); emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__interface"), 0, line); - /* interface inheritance */ + if (is_trait) { + emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line); + emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line); + emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__trait"), 0, line); + } + /* interface/trait inheritance */ if (base[0] != '\0') { emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line); emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, base), 0, line); @@ -1054,7 +1070,8 @@ static void stat(Compiler *c) while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF)) { if (!check(c, CAT_LEXER_TOK_FUNCTION)) { err_at(c, c->tok.line, - "expected 'function' or 'end' in interface"); + "expected 'function' or 'end' in %s", + is_trait ? "trait" : "interface"); break; } next(c); diff --git a/src/cat/lexer.c b/src/cat/lexer.c index 5f7325a..24396b8 100644 --- a/src/cat/lexer.c +++ b/src/cat/lexer.c @@ -28,6 +28,7 @@ static const struct kw g_keywords[] = { { "interface", CAT_LEXER_TOK_INTERFACE }, { "is", CAT_LEXER_TOK_IS }, { "comptime", CAT_LEXER_TOK_COMPTIME }, + { "trait", CAT_LEXER_TOK_TRAIT }, { "false", CAT_LEXER_TOK_FALSE }, { "for", CAT_LEXER_TOK_FOR }, { "function", CAT_LEXER_TOK_FUNCTION }, @@ -291,7 +292,7 @@ const char *cat_lexer_kind_name(int kind) "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "yield", "try", "except", "raise", "use", "class", "extends", - "interface", "implements", "is", "comptime", + "interface", "implements", "is", "comptime", "trait", "+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":", "::", "..", "->" diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index 2a56a39..b46e88c 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -655,6 +655,52 @@ static int lf_implements_check(CAT_VM_State *vm, CAT_VALUE_Value **args, return 0; } +/* `__trait_mixin(cls, trait)` -- copy a trait's default methods into a + * class that implements it (a mix-in). Existing class members win. */ +static int lf_trait_mixin(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_VALUE_Value *cls; + CAT_VALUE_Value *tr; + CAT_VALUE_Value *marker = NULL; + CAT_ERROR_Error e; + int i; + + if (nargs < 2 || args[0] == NULL || args[1] == NULL) { + *out = cat_types_empty(); + return 0; + } + cls = args[0]; + tr = args[1]; + cat_error_clear(&e); + if (cat_value_get_attribute(tr, "__trait", &marker, &e) != 0 || + marker == NULL) { + *out = cat_types_empty(); + return 0; /* not a trait: nothing to mix in */ + } + if (tr->vtable != cat_types_table_vtable() || + cls->vtable != cat_types_table_vtable()) { + *out = cat_types_empty(); + return 0; + } + for (i = 0; i < cat_types_table_count(tr); i++) { + const char *k = cat_types_table_key_at(tr, i); + CAT_VALUE_Value *v; + CAT_VALUE_Value *existing = NULL; + + if (strncmp(k, "__", 2) == 0) + continue; + cat_error_clear(&e); + if (cat_types_table_get(cls, k, &existing, &e) == 0) + continue; /* the class already provides it */ + v = cat_types_table_value_at(tr, i); + cat_error_clear(&e); + cat_types_table_set(cls, k, v, &e); + } + *out = cat_types_empty(); + return 0; +} + static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { @@ -719,6 +765,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm) std[i].doc)); cat_vm_register_native(vm, "__class_new", lf_class_new); cat_vm_register_native(vm, "__implements_check", lf_implements_check); + cat_vm_register_native(vm, "__trait_mixin", lf_trait_mixin); cat_vm_set_global_owned(vm, "implements", cat_types_native_new_doc("implements", lf_implements, "implements(obj, iface) -- teste estrutural: obj atende a interface?")); @@ -738,6 +785,20 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm) cat_vm_set_global_owned(vm, "memory", cat_types_native_new_doc("memory", lf_memory, "memory(n) -- buffer de n bytes com limites verificados.")); + /* `Sized` -- the marker interface for "layout known at compile time". + * Every concrete catscript value has a known layout, so every value + * satisfies it; it exists so signatures can express the bound + * (`buf : Sized()`) and the checker can reason about it. */ + { + CAT_VALUE_Value *sized = cat_types_table_new(); + CAT_ERROR_Error e; + + cat_error_clear(&e); + cat_types_table_set(sized, "__interface", cat_types_bool_true(), &e); + cat_error_clear(&e); + cat_types_table_set(sized, "__sized", cat_types_bool_true(), &e); + cat_vm_set_global_owned(vm, "Sized", sized); + } /* `module` reflects the unit currently executing (name/path/dir) */ cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL)); return 0; diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 08660c5..803e6c0 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -254,6 +254,15 @@ esac # ---- self-hosted front-end (written in catscript) ------------------- +out=`$BIN tests/traits.cat` +check "trait-default" "hello, Marcel" "`echo "$out" | sed -n 1p`" +check "trait-second" "HELLO, Marcel" "`echo "$out" | sed -n 2p`" +check "trait-is" "person is Greeter: true" "`echo "$out" | sed -n 3p`" +check "trait-override" "beep R2" "`echo "$out" | sed -n 4p`" +check "trait-robot" "robot is Greeter: true" "`echo "$out" | sed -n 6p`" +check "trait-sized" "sized: true" "`echo "$out" | sed -n 7p`" +check "trait-sized-fn" "implements Sized: true" "`echo "$out" | sed -n 8p`" + out=`$BIN tests/comptime.cat` check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`" check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`" diff --git a/tests/traits.cat b/tests/traits.cat new file mode 100644 index 0000000..345d971 --- /dev/null +++ b/tests/traits.cat @@ -0,0 +1,35 @@ +-- tests/traits.cat -- traits: interfaces with default methods (mix-in). +-- +-- A `trait` is an interface whose methods carry default bodies. A class +-- that `implements` it gets those bodies mixed in (unless it defines its +-- own), and satisfies the trait structurally. Methods take explicit +-- `self`, like every method in catscript. + +trait Greeter + function greet(self) return "hello, " .. self.name end + function loud(self) return "HELLO, " .. self.name end +end + +class Person implements Greeter + function init(self, n) self.name = n end +end + +-- a class may override a trait's default method +class Robot implements Greeter + function init(self, n) self.name = n end + function greet(self) return "beep " .. self.name end +end + +local p = Person("Marcel") +print(p.greet()) +print(p.loud()) +print("person is Greeter:", p is Greeter) + +local r = Robot("R2") +print(r.greet()) +print(r.loud()) +print("robot is Greeter:", r is Greeter) + +-- Sized(): every concrete value has a known layout, so it is satisfied +print("sized:", p is Sized) +print("implements Sized:", implements(p, Sized))