REPL: persistent state + echo; add the _repr_ protocol

- REPL now runs every line on the SAME vm, so 'x = 50' then 'x'
  persists across lines (was re-creating a vm per line)
- a lone expression echoes its value (new PRINTEXPR opcode), and a
  call yielding no value (the empty object) is not echoed
- compiler: cat_compiler_compile_mode(src, err, repl) emits PRINTEXPR
  for a lone expression in REPL mode
- _repr_ protocol: cat_value_repr honours a  member (text value
  used verbatim, or a callable invoked with the value as self); a
  default by family otherwise.  tostring is the display form (text
  unquoted); the REPL echo is the repr form (text quoted)
- list/object default representations ([a, b], {k = v})
- tests: tests/repr.cat + REPL checks (92 total, all green)
This commit is contained in:
Minus committed 2026-11-17 13:14:05 +00:00
1 parent c7a87d05e2
commit de847e7793
11 files changed
+268 -5

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
-- tests/repr.cat -- the `_repr_` protocol.
--
-- `tostring` and the REPL echo honour a `_repr_` member: a text value is
-- used verbatim, and a callable is invoked with the value as `self`.
-- `tostring` is the display form (text unquoted); the REPL echo is the
-- repr form (text quoted, unless it came from `_repr_`).
local t = {a = 1, b = "x"}
t._repr_ = "a custom point"
class Point
function init(self, x, y)
self.x = x
self.y = y
end
function _repr_(self)
return "Point(" .. tostring(self.x) .. ", " .. tostring(self.y) .. ")"
end
end
local p = Point(3, 4)
print("table:", tostring(t))
print("point:", tostring(p))
print("int:", tostring(42))
print("str:", tostring("hi"))
print("bool:", tostring(true))
print("list:", tostring(attributes(t)))
+16
View File
@@ -158,6 +158,22 @@ 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`"
# ---- _repr_ protocol -------------------------------------------------
out=`$BIN tests/repr.cat`
check "repr-value" "table: a custom point" "`echo "$out" | sed -n 1p`"
check "repr-method" "point: Point(3, 4)" "`echo "$out" | sed -n 2p`"
check "repr-int" "int: 42" "`echo "$out" | sed -n 3p`"
check "repr-str" "str: hi" "`echo "$out" | sed -n 4p`"
check "repr-bool" "bool: true" "`echo "$out" | sed -n 5p`"
check "repr-list" "list: [a, b, _repr_]" "`echo "$out" | sed -n 6p`"
# ---- REPL: persistent state + echo ----------------------------------
out=`printf 'x = 50\nx\nx + 5\n' | $BIN | tr '>' '\n' | grep -oE '[0-9]+'`
check "repl-echo" "50" "`echo "$out" | sed -n 1p`"
check "repl-state" "55" "`echo "$out" | sed -n 2p`"
# ---- bytecode dump ---------------------------------------------------
out=`$BIN --dump examples/hello.cat`