From de847e779346014d9fcbc56f7ed933536a1c1944 Mon Sep 17 00:00:00 2001 From: Minus Date: Tue, 17 Nov 2026 13:14:05 +0000 Subject: [PATCH] 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) --- include/cat/bytecode.h | 1 + include/cat/compiler.h | 5 ++ include/cat/value.h | 8 +++ src/cat/bytecode.c | 3 +- src/cat/compiler.c | 11 ++- src/cat/stdlib/stdlib.c | 7 +- src/cat/value.c | 147 ++++++++++++++++++++++++++++++++++++++++ src/cat/vm.c | 12 ++++ src/main.c | 36 +++++++++- tests/repr.cat | 27 ++++++++ tests/run_tests.sh | 16 +++++ 11 files changed, 268 insertions(+), 5 deletions(-) create mode 100644 tests/repr.cat diff --git a/include/cat/bytecode.h b/include/cat/bytecode.h index 9cdbb86..a755f55 100644 --- a/include/cat/bytecode.h +++ b/include/cat/bytecode.h @@ -64,6 +64,7 @@ enum CAT_BYTECODE_Op { CAT_BYTECODE_OP_TRYEND, /* pop the innermost handler */ 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) */ }; /* One instruction: opcode + three integer operands. */ diff --git a/include/cat/compiler.h b/include/cat/compiler.h index 8f96c67..56f49fb 100644 --- a/include/cat/compiler.h +++ b/include/cat/compiler.h @@ -17,4 +17,9 @@ CAT_BYTECODE_Function *cat_compiler_compile(const char *source, CAT_ERROR_Error *err); +/* Like cat_compiler_compile, but a lone expression statement is echoed + * (emits PRINTEXPR). Used by the REPL. */ +CAT_BYTECODE_Function *cat_compiler_compile_mode(const char *source, + CAT_ERROR_Error *err, int repl); + #endif /* CAT_COMPILER_H */ diff --git a/include/cat/value.h b/include/cat/value.h index 9bb518a..f8fea66 100644 --- a/include/cat/value.h +++ b/include/cat/value.h @@ -195,4 +195,12 @@ int cat_value_slot_set(CAT_VALUE_Value *v, const CAT_VALUE_Slot *s, const char *cat_value_type_name(CAT_VALUE_Value *v); +/* Textual representation. `cat_value_repr` honours a `_repr_` member + * (callable or value); `cat_value_repr_text` is the default by family. + * The bytes from repr_text are static; repr returns an ascii_text value. */ +CAT_VALUE_Value *cat_value_repr(CAT_VALUE_Value *v); +const char *cat_value_repr_text(CAT_VALUE_Value *v); +/* Display form: like repr_text but text values are not quoted. */ +const char *cat_value_str_text(CAT_VALUE_Value *v); + #endif /* CAT_VALUE_H */ diff --git a/src/cat/bytecode.c b/src/cat/bytecode.c index b078884..3a181a4 100644 --- a/src/cat/bytecode.c +++ b/src/cat/bytecode.c @@ -83,7 +83,8 @@ static const char *op_name(unsigned char op) "NEG", "NOT", "EQ", "NE", "LT", "LE", "GT", "GE", "GETATTR", "SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF", "JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE", - "GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX" + "GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT", + "TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR" }; if (op < sizeof(names) / sizeof(names[0])) return names[op]; diff --git a/src/cat/compiler.c b/src/cat/compiler.c index 0bc38f4..c83371b 100644 --- a/src/cat/compiler.c +++ b/src/cat/compiler.c @@ -55,6 +55,7 @@ typedef struct { int brk_ends[16][64]; int brk_n[16]; int nloops; + int repl; /* REPL mode: a lone expression is echoed */ } Compiler; static void err_at(Compiler *c, int line, const char *fmt, ...) @@ -985,7 +986,8 @@ static void stat(Compiler *c) /* FALLTHROUGH */ default: expr(c); - emit(c, CAT_BYTECODE_OP_POP, 0, 0, line); + emit(c, c->repl ? CAT_BYTECODE_OP_PRINTEXPR : CAT_BYTECODE_OP_POP, + 0, 0, line); break; } } @@ -1016,12 +1018,19 @@ static void block(Compiler *c) CAT_BYTECODE_Function *cat_compiler_compile(const char *source, CAT_ERROR_Error *err) +{ + return cat_compiler_compile_mode(source, err, 0); +} + +CAT_BYTECODE_Function *cat_compiler_compile_mode(const char *source, + CAT_ERROR_Error *err, int repl) { Compiler c; CAT_BYTECODE_Function *fn; memset(&c, 0, sizeof(c)); c.err = err; + c.repl = repl; cat_lexer_init(&c.lx, source); fn = cat_bytecode_function_new("main"); memset(&c.stack[0], 0, sizeof(c.stack[0])); diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index fef3808..785aa60 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -71,7 +71,10 @@ static int lf_tostring(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) { (void)vm; - *out = cat_types_ascii_text_new(nargs > 0 ? value_to_text(args[0]) : ""); + /* `tostring` is the display form (no quotes); the REPL echo uses the + * repr form. Both honour `_repr_`. */ + *out = (nargs > 0) ? cat_types_ascii_text_new(cat_value_str_text(args[0])) + : cat_types_ascii_text_new(""); return 0; } @@ -575,7 +578,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm) int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); const char *doc; } std[] = { { "print", lf_print, "print(a, ...) -- escreve os argumentos em stdout." }, - { "tostring", lf_tostring, "tostring(v) -- representa\u00e7\u00e3o textual de v." }, + { "tostring", lf_tostring, "tostring(v) -- representa\u00e7\u00e3o textual de v (usa `_repr_` se houver)." }, { "tonumber", lf_tonumber, "tonumber(s) -- converte texto em n\u00famero (ou vazio se inv\u00e1lido)." }, { "type", lf_type, "type(v) -- nome do tipo de v." }, { "len", lf_len, "len(v) -- tamanho de texto ou n\u00famero de membros de um objeto." }, diff --git a/src/cat/value.c b/src/cat/value.c index 1032014..a21b88b 100644 --- a/src/cat/value.c +++ b/src/cat/value.c @@ -14,10 +14,14 @@ #include "cat/types/bool.h" #include "cat/types/int.h" #include "cat/types/float.h" +#include "cat/types/number.h" +#include "cat/types/list.h" +#include "cat/types/table.h" #include "cat/types/text.h" #include "cat/types/ascii_text.h" #include +#include #include #include @@ -27,6 +31,149 @@ const char *cat_value_type_name(CAT_VALUE_Value *v) return ""; return v->vtable->type_name; } +/* Default representation by family (no `_repr_` lookup). Caller does + * not free the returned bytes. Uses a ring of static buffers so nested + * calls (an object's fields) do not clobber each other. */ +static size_t repr_into(char *out, size_t cap, CAT_VALUE_Value *v, + int quote_text); + +/* Resolve `_repr_` if present: returns the value to format (a text + * result from a callable/value `_repr_`), or `v` itself otherwise. + * Never returns NULL. */ +static CAT_VALUE_Value *repr_resolve(CAT_VALUE_Value *v) +{ + CAT_ERROR_Error e; + CAT_VALUE_Value *r = NULL; + + if (v == NULL) + return NULL; + cat_error_clear(&e); + if (cat_value_get_attribute(v, "_repr_", &r, &e) == 0 && r != NULL && + r != v) { + if (r->vtable != NULL && + r->vtable->kind == CAT_VALUE_KIND_FUNCTION) { + CAT_VALUE_Value *out = NULL; + CAT_VALUE_Value *callargs[1]; + callargs[0] = v; + cat_error_clear(&e); + if (cat_value_call(r, callargs, 1, &out, &e) == 0 && + out != NULL && out != v) + return out; + return NULL; + } + return r; + } + return v; +} + +const char *cat_value_repr_text(CAT_VALUE_Value *v) +{ + static char ring[8][512]; + static int slot = 0; + char *buf = ring[slot]; + + slot = (slot + 1) % 8; + repr_into(buf, sizeof(ring[0]), v, 1); + return buf; +} + +/* Display form (no quoting of text): what `tostring` produces. */ +const char *cat_value_str_text(CAT_VALUE_Value *v) +{ + static char ring[8][512]; + static int slot = 0; + char *buf = ring[slot]; + + slot = (slot + 1) % 8; + repr_into(buf, sizeof(ring[0]), v, 0); + return buf; +} + +static size_t repr_into(char *out, size_t cap, CAT_VALUE_Value *v, + int quote_text) +{ + if (cap == 0) + return 0; + /* Honour `_repr_` first: its text result is used verbatim (no + * quotes); a non-text result is formatted normally. */ + if (v != NULL) { + CAT_VALUE_Value *r = repr_resolve(v); + if (r != NULL && r != v) { + if (r->vtable != NULL && + r->vtable->kind == CAT_VALUE_KIND_TEXT) { + snprintf(out, cap, "%s", cat_types_text_bytes(r)); + return strlen(out); + } + v = r; + } else if (r == NULL) { + out[0] = '\0'; + return 0; + } + } + if (v == NULL || v == cat_types_empty()) { + snprintf(out, cap, "empty"); + return strlen(out); + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) { + if (quote_text) + snprintf(out, cap, "\"%s\"", cat_types_text_bytes(v)); + else + snprintf(out, cap, "%s", cat_types_text_bytes(v)); + return strlen(out); + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + if (((CAT_TYPES_NUMBER_Number *)v)->is_float) + snprintf(out, cap, "%g", cat_types_number_as_double(v)); + else + snprintf(out, cap, "%lld", cat_types_number_as_int(v)); + return strlen(out); + } + if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) { + snprintf(out, cap, "%s", ((CAT_TYPES_BOOL_Bool *)v)->v + ? "true" : "false"); + return strlen(out); + } + if (cat_types_list_is(v)) { + int i, n = cat_types_list_count(v); + size_t off = 0; + if (off < cap - 1) out[off++] = '['; + for (i = 0; i < n && off < cap - 24; i++) { + char item[256]; + repr_into(item, sizeof(item), cat_types_list_at(v, i), quote_text); + int w = snprintf(out + off, cap - off, "%s%s", + i ? ", " : "", item); + if (w > 0) off += (size_t)w; + } + if (off < cap - 1) out[off++] = ']'; + out[off] = '\0'; + return off; + } + if (v->vtable != NULL && v->vtable == cat_types_table_vtable()) { + int i, n = cat_types_table_count(v); + size_t off = 0; + if (off < cap - 1) out[off++] = '{'; + for (i = 0; i < n && off < cap - 40; i++) { + char item[256]; + repr_into(item, sizeof(item), cat_types_table_value_at(v, i), + quote_text); + int w = snprintf(out + off, cap - off, "%s%s = %s", + i ? ", " : "", cat_types_table_key_at(v, i), item); + if (w > 0) off += (size_t)w; + } + if (off < cap - 1) out[off++] = '}'; + out[off] = '\0'; + return off; + } + snprintf(out, cap, "<%s>", cat_value_type_name(v)); + return strlen(out); +} + +/* The textual representation of a value, as an ascii_text value: + * the repr form (text quoted). Honours `_repr_`. */ +CAT_VALUE_Value *cat_value_repr(CAT_VALUE_Value *v) +{ + return cat_types_ascii_text_new(cat_value_repr_text(v)); +} static CAT_VALUE_Vtable *vt(CAT_VALUE_Value *v) { diff --git a/src/cat/vm.c b/src/cat/vm.c index 133360c..2664cb5 100644 --- a/src/cat/vm.c +++ b/src/cat/vm.c @@ -468,6 +468,18 @@ int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out) print_value(v); break; } + case CAT_BYTECODE_OP_PRINTEXPR: { + /* REPL echo: show the value's representation. A call that + * yields no value (prints, mutators) returns the empty + * object, which is not echoed. */ + CAT_VALUE_Value *v = stack[--sp]; + CAT_VALUE_Value *s; + if (v == NULL || cat_types_empty_is(v)) + break; + s = cat_value_repr(v); + printf("%s\n", cat_types_text_bytes(s)); + break; + } default: break; } diff --git a/src/main.c b/src/main.c index 34165d8..e2f19d7 100644 --- a/src/main.c +++ b/src/main.c @@ -81,18 +81,52 @@ static int main_run_source(const char *source, int dump) return rc != 0; } +/* Compile one REPL line in repl mode and run it on the SAME vm, so + * assignments to globals (x = 50) persist across lines, and a lone + * expression is echoed. */ +static int main_repl_line(CAT_VM_State *vm, const char *source) +{ + CAT_ERROR_Error err; + CAT_BYTECODE_Function *fn; + CAT_VALUE_Value *out = NULL; + int rc; + + cat_error_clear(&err); + fn = cat_compiler_compile_mode(source, &err, 1); + if (fn == NULL) { + fprintf(stderr, "catscript: %s\n", err.message); + return 1; + } + rc = cat_vm_run(vm, fn, &out); + if (rc != 0) + fprintf(stderr, "catscript: %s\n", vm->err.message); + /* keep the chunk alive: any `function` defined becomes a global whose + * closure points into this bytecode tree. */ + if (rc != 0) + cat_bytecode_function_free(fn); + return rc != 0; +} + static void main_repl(void) { char line[1024]; + CAT_VM_State *vm = cat_vm_new(); + if (vm == NULL) { + fprintf(stderr, "catscript: cannot start REPL\n"); + return; + } + cat_stdlib_stdlib_install(vm); + cat_stdlib_build_install(vm); printf("catscript REPL -- type an expression; EOF to exit.\n"); for (;;) { printf("> "); fflush(stdout); if (fgets(line, sizeof(line), stdin) == NULL) break; - main_run_source(line, 0); + main_repl_line(vm, line); } + cat_vm_free(vm); } static void main_usage(void) diff --git a/tests/repr.cat b/tests/repr.cat new file mode 100644 index 0000000..ae2f242 --- /dev/null +++ b/tests/repr.cat @@ -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))) diff --git a/tests/run_tests.sh b/tests/run_tests.sh index ea98abe..585dd39 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -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`