functions are objects: closures carry a member table (_doc_)

- CAT_TYPES_FUNCTION_Closure gains an attrs table; get/set_attribute
  give closures real members, so a function can hold _doc_ and any other
  attribute like a table
- cat_types_function_attrs() accessor; attributes() enumerates a
  closure's members; help() reads a function's _doc_
- compiler: generalise dotted assignment to chains (name.a.b = v), so a
  method can be documented (Calc.add._doc_ = ...)
- tests/functions_as_objects.cat + 7 assertions (84 total, all green)
- README: 'funcoes tambem sao objetos' + reflection sections
This commit is contained in:
Minus committed 2026-11-16 03:50:54 +00:00
1 parent 1203acd64b
commit e0bf102f2a
7 files changed
+183 -18

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
-- tests/functions_as_objects.cat -- functions are objects too.
--
-- A closure carries a member table, so it can hold `_doc_` (and any
-- other attribute) exactly like a table. `help()` reads it; a dotted
-- assignment can reach an attribute of a nested object (a method).
local t = {x = 1, y = 2}
t._doc_ = "A point."
function add(a, b) return a + b end
add._doc_ = "add(a, b) -- soma dois numeros."
print("call:", add(2, 3))
print("name:", add.name)
print("doc:", add._doc_)
for a in attributes(add) do print("attr:", a) end
-- documenting a method: nested (chained) attribute assignment
class Calc
function add(self, a, b) return a + b end
end
Calc.add._doc_ = "add(a, b) on Calc."
print("method doc:", Calc.add._doc_)
local c = Calc()
print("method call:", c:add(4, 5))
-- help() reads a function's _doc_
help(add)
+11
View File
@@ -147,6 +147,17 @@ check "attr-doc" " - _doc_" "`echo "$out" | sed -n 5p`"
check "attr-method" "animal has speak: true" "`echo "$out" | sed -n 6p`"
check "help-doc" "A 2D point with x, y coordinates." "`echo "$out" | sed -n 8p`"
check "help-native" "print(a, ...) -- escreve os argumentos em stdout." "`echo "$out" | sed -n 10p`"
# ---- functions are objects too (member table, _doc_) ----------------
out=`$BIN tests/functions_as_objects.cat`
check "fn-call" "call: 5" "`echo "$out" | sed -n 1p`"
check "fn-name" "name: add" "`echo "$out" | sed -n 2p`"
check "fn-doc" "doc: add(a, b) -- soma dois numeros." "`echo "$out" | sed -n 3p`"
check "fn-attr" "attr: _doc_" "`echo "$out" | sed -n 4p`"
check "fn-method-doc" "method doc: add(a, b) on Calc." "`echo "$out" | sed -n 5p`"
check "fn-method-call" "method call: 9" "`echo "$out" | sed -n 6p`"
check "fn-help" "add(a, b) -- soma dois numeros." "`echo "$out" | sed -n 7p`"
# ---- bytecode dump ---------------------------------------------------
out=`$BIN --dump examples/hello.cat`