interface + structural is: runtime-checked interfaces

Add nominal interface declarations with structural, runtime checking
(the owner asked for the operator AND the runtime check).

- lexer: `interface` and `is` are keywords; `implements` is a soft
  keyword (matched by text in the class clause) so the `implements()`
  stdlib function is not shadowed.
- `interface NAME [extends BASE] <function m() end> end` builds a table
  tagged `__interface`; members name the required methods (with an
  optional default body, shared via `__index`). Interface inheritance
  follows `__index`.
- class: `class C [extends B] [implements I, ...]` -- after the class
  global is set, `__implements_check` runs and raises if the class does
  not satisfy each declared interface.
- new opcode `IS` (`obj is iface`): structural membership test, and it
  degrades to an exact type (vtable) match when the right side is not an
  interface, so `x is SomeClass` reads naturally. Backed by
  `cat_value_is()`.
- stdlib: `implements(obj, iface)` (the same test as a function).
- tests/interface.cat + suite block: interface satisfaction, interface
  inheritance, duck typing (no `implements` needed), and a missing
  method failing. Suite 130 -> 136, all green.
This commit is contained in:
Minus committed 2026-11-18 15:56:10 +00:00
1 parent 7cdf388bf4
commit b945182739
11 files changed
+299 -2

No files matched your search

+1
View File
@@ -65,6 +65,7 @@ enum CAT_BYTECODE_Op {
CAT_BYTECODE_OP_RAISE, /* pop value -> raise it */
CAT_BYTECODE_OP_FORNEXT, /* A: exit target; pop it -> push next or jump */
CAT_BYTECODE_OP_PRINTEXPR, /* pop, print its repr (REPL echo) */
CAT_BYTECODE_OP_IS, /* pop iface, obj -> push obj is iface (structural) */
};
/* One instruction: opcode + three integer operands. */
+2 -1
View File
@@ -28,7 +28,8 @@ enum CAT_LEXER_Kind {
CAT_LEXER_TOK_TRUE, CAT_LEXER_TOK_UNTIL, CAT_LEXER_TOK_WHILE,
CAT_LEXER_TOK_YIELD, CAT_LEXER_TOK_TRY, CAT_LEXER_TOK_EXCEPT,
CAT_LEXER_TOK_RAISE, CAT_LEXER_TOK_USE, CAT_LEXER_TOK_CLASS,
CAT_LEXER_TOK_EXTENDS,
CAT_LEXER_TOK_EXTENDS, CAT_LEXER_TOK_INTERFACE, CAT_LEXER_TOK_IMPLEMENTS,
CAT_LEXER_TOK_IS,
/* 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,
+8
View File
@@ -208,6 +208,14 @@ int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err);
int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
CAT_ERROR_Error *err);
/* Structural `is`: is `obj` a member-wise implementation of the interface
* `iface`? An interface is a table carrying a `__interface` member whose
* other members name the required methods; inheritance (`__index`) is
* followed. When `iface` is not an interface, the test degrades to an
* exact type (vtable) match. Sets *out to 0/1. */
int cat_value_is(CAT_VALUE_Value *obj, CAT_VALUE_Value *iface, int *out,
CAT_ERROR_Error *err);
/* Advance an iterator/generator. Returns 0 and sets *out to the next
* value, 1 when the iterator is exhausted (*out untouched), or -1 on
* error. A separate exhaustion status (rather than an empty/sentinel
+1 -1
View File
@@ -88,7 +88,7 @@ static const char *op_name(unsigned char op)
"SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF",
"JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE",
"GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT",
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR"
"TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR", "IS"
};
if (op < sizeof(names) / sizeof(names[0]))
return names[op];
+91
View File
@@ -191,6 +191,7 @@ static int bp_of(int kind)
case CAT_LEXER_TOK_EQ: case CAT_LEXER_TOK_NE:
case CAT_LEXER_TOK_LT: case CAT_LEXER_TOK_LE:
case CAT_LEXER_TOK_GT: case CAT_LEXER_TOK_GE: return 3;
case CAT_LEXER_TOK_IS: return 3;
case CAT_LEXER_TOK_CONCAT: return 4;
case CAT_LEXER_TOK_PLUS: case CAT_LEXER_TOK_MINUS: return 5;
case CAT_LEXER_TOK_STAR: case CAT_LEXER_TOK_SLASH:
@@ -560,6 +561,9 @@ static void expr_bp(Compiler *c, int minbp)
}
next(c);
expr_bp(c, bp + 1);
if (kind == CAT_LEXER_TOK_IS)
emit(c, CAT_BYTECODE_OP_IS, 0, 0, c->tok.line);
else
emit(c, binop_for(kind), 0, 0, c->tok.line);
}
}
@@ -826,6 +830,9 @@ static void stat(Compiler *c)
* class's `init` if present. The table is bound to a global NAME. */
char name[256];
char base[256];
char impl[8][256];
int nimpl = 0;
int i;
next(c);
name[0] = '\0';
base[0] = '\0';
@@ -839,6 +846,21 @@ static void stat(Compiler *c)
next(c);
}
}
if (check(c, CAT_LEXER_TOK_NAME) &&
strcmp(c->tok.text, "implements") == 0) {
next(c);
for (;;) {
if (check(c, CAT_LEXER_TOK_NAME)) {
if (nimpl < 8)
snprintf(impl[nimpl], sizeof(impl[0]),
"%s", c->tok.text);
nimpl++;
next(c);
}
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* __index: base (inheritance) or the class itself */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
@@ -875,6 +897,75 @@ 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). */
for (i = 0; i < nimpl && i < 8; i++) {
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);
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);
}
break;
}
case CAT_LEXER_TOK_INTERFACE: {
/* interface NAME [extends BASE] <function m(...) end> 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. */
char name[256];
char base[256];
next(c);
name[0] = '\0';
base[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
if (accept(c, CAT_LEXER_TOK_EXTENDS)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(base, sizeof(base), "%s", c->tok.text);
next(c);
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* the interface marker, so `is` knows to check structurally */
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 (base[0] != '\0') {
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_SETATTR, add_string(c, "__index"), 0, line);
}
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");
break;
}
next(c);
{
char mname[256];
int proto;
mname[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
}
proto = compile_function_literal(c, mname);
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, mname), 0, line);
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
break;
}
+3
View File
@@ -25,6 +25,8 @@ static const struct kw g_keywords[] = {
{ "except", CAT_LEXER_TOK_EXCEPT },
{ "end", CAT_LEXER_TOK_END },
{ "extends", CAT_LEXER_TOK_EXTENDS },
{ "interface", CAT_LEXER_TOK_INTERFACE },
{ "is", CAT_LEXER_TOK_IS },
{ "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR },
{ "function", CAT_LEXER_TOK_FUNCTION },
@@ -288,6 +290,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",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=",
"<", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",",
".", ":", "::", "..", "->"
+53
View File
@@ -606,6 +606,55 @@ static int lf_class_new(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
return 0;
}
/* `implements(obj, iface)` -- structural runtime test: does `obj` answer
* every method the interface `iface` requires? Mirrors the `is`
* operator. */
static int lf_implements(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
int r = 0;
if (nargs < 2 || args[0] == NULL || args[1] == NULL) {
*out = cat_types_bool_false();
return 0;
}
if (cat_value_is(args[0], args[1], &r, &vm->err) != 0)
return -1;
*out = r ? cat_types_bool_true() : cat_types_bool_false();
return 0;
}
/* `__implements_check(cls, iface)` -- emitted after a class that declares
* `implements I`: raises unless the class satisfies the interface. */
static int lf_implements_check(CAT_VM_State *vm, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out)
{
int r = 0;
if (nargs < 2 || args[0] == NULL || args[1] == NULL) {
*out = cat_types_empty();
return 0;
}
if (cat_value_is(args[0], args[1], &r, &vm->err) != 0)
return -1;
if (!r) {
CAT_VALUE_Value *nm = NULL;
CAT_ERROR_Error e;
const char *iname = "interface";
cat_error_clear(&e);
if (cat_value_get_attribute(args[1], "name", &nm, &e) == 0 &&
nm != NULL && nm->vtable &&
nm->vtable->kind == CAT_VALUE_KIND_TEXT)
iname = cat_types_text_bytes(nm);
return (cat_error_raise(&vm->err,
"class %s does not implement %s",
cat_value_type_name(args[0]), iname), -1);
}
*out = cat_types_empty();
return 0;
}
static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
@@ -669,6 +718,10 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
cat_types_native_new_doc(std[i].name, std[i].cb,
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_set_global_owned(vm, "implements",
cat_types_native_new_doc("implements", lf_implements,
"implements(obj, iface) -- teste estrutural: obj atende a interface?"));
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
cat_vm_set_global_owned(vm, "AbstractFile",
cat_types_native_new("AbstractFile", lf_abstractfile));
+73
View File
@@ -306,6 +306,79 @@ int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name,
"type %s has no attribute '%s'", cat_value_type_name(self), name), -1);
}
/* Does `obj` answer member `name`? Used by the structural `is` test. */
static int obj_has_member(CAT_VALUE_Value *obj, const char *name)
{
CAT_VALUE_Value *tmp = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
return cat_value_get_attribute(obj, name, &tmp, &e) == 0;
}
int cat_value_is(CAT_VALUE_Value *obj, CAT_VALUE_Value *iface, int *out,
CAT_ERROR_Error *err)
{
CAT_ERROR_Error e;
CAT_VALUE_Value *marker = NULL;
int is_iface = 0;
if (out != NULL)
*out = 0;
if (obj == NULL || iface == NULL)
return 0;
/* An interface is a table tagged with `__interface`; follow interface
* inheritance (`__index`) too. Anything else degrades to an exact
* type (vtable) match, so `x is SomeClass` still reads naturally. */
cat_error_clear(&e);
if (cat_value_get_attribute(iface, "__interface", &marker, &e) == 0 &&
marker != NULL)
is_iface = 1;
if (!is_iface) {
if (out != NULL)
*out = (obj->vtable == iface->vtable);
return 0;
}
if (iface->vtable != cat_types_table_vtable()) {
if (out != NULL)
*out = 0;
return 0;
}
{
int i, ok = 1;
/* every required method (a key not starting with `__`) must be
* answered by the object: this is structural typing at runtime. */
for (i = 0; i < cat_types_table_count(iface) && ok; i++) {
const char *k = cat_types_table_key_at(iface, i);
if (strncmp(k, "__", 2) == 0)
continue;
if (!obj_has_member(obj, k))
ok = 0;
}
if (ok) {
CAT_VALUE_Value *base = NULL;
cat_error_clear(&e);
if (cat_value_get_attribute(iface, "__index", &base, &e) == 0 &&
base != NULL && base != iface) {
int sub = 0;
if (cat_value_is(obj, base, &sub, err) != 0 || !sub)
ok = 0;
}
}
if (out != NULL)
*out = ok;
}
return 0;
}
int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
+12
View File
@@ -493,6 +493,18 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
printf("%s\n", cat_types_text_bytes(s));
break;
}
case CAT_BYTECODE_OP_IS: {
/* pop iface, pop obj -> push (obj is iface), structural */
CAT_VALUE_Value *iface = stack[--sp];
CAT_VALUE_Value *obj = stack[--sp];
int r = 0;
if (cat_value_is(obj, iface, &r, &e) != 0) {
deliver_error(vm, &e); goto on_error;
}
stack[sp++] = r ? cat_types_bool_true()
: cat_types_bool_false();
break;
}
default:
break;
}
+47
View File
@@ -0,0 +1,47 @@
-- tests/interface.cat -- interfaces: structural typing at runtime.
--
-- `interface` declares a named contract; a class may declare
-- `implements I` (checked at class definition) and any object answers
-- the structural `is` operator, so a duck-typed object satisfies an
-- interface too.
interface Drawable
function draw() print("default draw") end
end
interface Shape extends Drawable
function area() return 0 end
end
class Circle implements Shape
function draw() print("draw circle") end
function area() return 3 end
end
local c = Circle()
print("circle is Drawable:", c is Drawable)
print("circle is Shape:", c is Shape)
c.draw()
print("circle area:", c.area())
-- a duck-typed object (no `implements`) still satisfies structurally
class Blob
function draw() print("blob draw") end
function area() return 1 end
end
local b = Blob()
print("blob is Drawable:", b is Drawable)
print("blob is Shape:", b is Shape)
-- an object missing a required method does not satisfy
class Line
function draw() print("line draw") end
end
local l = Line()
print("line is Drawable:", l is Drawable)
print("line is Shape:", l is Shape)
print("implements(c, Shape):", implements(c, Shape))
print("implements(l, Shape):", implements(l, Shape))
+8
View File
@@ -254,6 +254,14 @@ esac
# ---- self-hosted front-end (written in catscript) -------------------
out=`$BIN tests/interface.cat`
check "iface-is-sub" "circle is Drawable: true" "`echo "$out" | sed -n 1p`"
check "iface-is-inherited" "circle is Shape: true" "`echo "$out" | sed -n 2p`"
check "iface-method" "draw circle" "`echo "$out" | sed -n 3p`"
check "iface-duck" "blob is Shape: true" "`echo "$out" | sed -n 6p`"
check "iface-missing" "line is Shape: false" "`echo "$out" | sed -n 8p`"
check "iface-fn" "implements(c, Shape): true" "`echo "$out" | sed -n 9p`"
out=`$BIN tests/selfhost_lexer.cat`
case "$out" in
*"NAME [x]"*) check "selfhost-lexer" "yes" "yes" ;;