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.
This commit is contained in:
Minus committed 2026-11-18 17:18:58 +00:00
1 parent 95f3823acf
commit 70728093ef
6 files changed
+133 -9

No files matched your search

+1
View File
@@ -31,6 +31,7 @@ enum CAT_LEXER_Kind {
CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS, CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS,
CAT_LEXER_TOK_IS, CAT_LEXER_TOK_IS,
CAT_LEXER_TOK_COMPTIME, CAT_LEXER_TOK_COMPTIME,
CAT_LEXER_TOK_TRAIT,
/* symbols */ /* symbols */
CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR, CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR,
CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET, CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET,
+25 -8
View File
@@ -1006,8 +1006,17 @@ static void stat(Compiler *c)
expect(c, CAT_LEXER_TOK_END, "'end'"); expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line); emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
/* runtime assertion: the class must satisfy each declared interface /* 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++) { 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, emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, "__implements_check"), 0, line); add_string(c, "__implements_check"), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line); emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
@@ -1018,15 +1027,17 @@ static void stat(Compiler *c)
break; break;
} }
case CAT_LEXER_TOK_TRAIT:
case CAT_LEXER_TOK_INTERFACE: { case CAT_LEXER_TOK_INTERFACE: {
/* interface NAME [extends BASE] <function m(...) end> end /* interface|trait NAME [extends BASE] <function m(...) end> end
* *
* An interface is a table tagged `__interface`; its members name the * Both build a table tagged `__interface` so the `is` operator and
* required methods (a body is allowed and becomes a default method, * the runtime check work the same way. A `trait` is additionally
* shared through `__index`). The `is` operator checks satisfaction * tagged `__trait`: its methods carry default bodies, and a class
* structurally at runtime. */ * that `implements` it has those methods mixed in. */
char name[256]; char name[256];
char base[256]; char base[256];
int is_trait = (c->tok.kind == CAT_LEXER_TOK_TRAIT);
next(c); next(c);
name[0] = '\0'; name[0] = '\0';
base[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_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line); emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__interface"), 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') { if (base[0] != '\0') {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line); emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, base), 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)) { while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF)) {
if (!check(c, CAT_LEXER_TOK_FUNCTION)) { if (!check(c, CAT_LEXER_TOK_FUNCTION)) {
err_at(c, c->tok.line, err_at(c, c->tok.line,
"expected 'function' or 'end' in interface"); "expected 'function' or 'end' in %s",
is_trait ? "trait" : "interface");
break; break;
} }
next(c); next(c);
+2 -1
View File
@@ -28,6 +28,7 @@ static const struct kw g_keywords[] = {
{ "interface", CAT_LEXER_TOK_INTERFACE }, { "interface", CAT_LEXER_TOK_INTERFACE },
{ "is", CAT_LEXER_TOK_IS }, { "is", CAT_LEXER_TOK_IS },
{ "comptime", CAT_LEXER_TOK_COMPTIME }, { "comptime", CAT_LEXER_TOK_COMPTIME },
{ "trait", CAT_LEXER_TOK_TRAIT },
{ "false", CAT_LEXER_TOK_FALSE }, { "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR }, { "for", CAT_LEXER_TOK_FOR },
{ "function", CAT_LEXER_TOK_FUNCTION }, { "function", CAT_LEXER_TOK_FUNCTION },
@@ -291,7 +292,7 @@ const char *cat_lexer_kind_name(int kind)
"for", "function", "if", "in", "local", "nil", "not", "for", "function", "if", "in", "local", "nil", "not",
"or", "repeat", "return", "then", "true", "until", "while", "or", "repeat", "return", "then", "true", "until", "while",
"yield", "try", "except", "raise", "use", "class", "extends", "yield", "try", "except", "raise", "use", "class", "extends",
"interface", "implements", "is", "comptime", "interface", "implements", "is", "comptime", "trait",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=",
"<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",", "<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",",
".", ":", "::", "..", "->" ".", ":", "::", "..", "->"
+61
View File
@@ -655,6 +655,52 @@ static int lf_implements_check(CAT_VM_State *vm, CAT_VALUE_Value **args,
return 0; 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, static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out) CAT_VALUE_Value **out)
{ {
@@ -719,6 +765,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
std[i].doc)); std[i].doc));
cat_vm_register_native(vm, "__class_new", lf_class_new); 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, "__implements_check", lf_implements_check);
cat_vm_register_native(vm, "__trait_mixin", lf_trait_mixin);
cat_vm_set_global_owned(vm, "implements", cat_vm_set_global_owned(vm, "implements",
cat_types_native_new_doc("implements", lf_implements, cat_types_native_new_doc("implements", lf_implements,
"implements(obj, iface) -- teste estrutural: obj atende a interface?")); "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_vm_set_global_owned(vm, "memory",
cat_types_native_new_doc("memory", lf_memory, cat_types_native_new_doc("memory", lf_memory,
"memory(n) -- buffer de n bytes com limites verificados.")); "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) */ /* `module` reflects the unit currently executing (name/path/dir) */
cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL)); cat_vm_set_global_owned(vm, "module", cat_module_table("main", NULL));
return 0; return 0;
+9
View File
@@ -254,6 +254,15 @@ esac
# ---- self-hosted front-end (written in catscript) ------------------- # ---- 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` out=`$BIN tests/comptime.cat`
check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`" check "comptime-expr" "ct-expr: 42" "`echo "$out" | sed -n 1p`"
check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`" check "comptime-text" "ct-text: hi there" "`echo "$out" | sed -n 2p`"
+35
View File
@@ -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))