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.
48 lines
1.2 KiB
Plaintext
48 lines
1.2 KiB
Plaintext
-- 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))
|