generators/iterators, raise/try/except, and slot-based object layout

- VM refactor: resumable CAT_VM_Frame (ip/sp/locals/handlers)
- yield/next/generators: calling a yield-function returns a generator
- for..in over any iterator, ends on explicit exhaustion status
- raise/try/except: structured error values, nearest-handler unwinding
- slots: C-declared member layout (offsetof), PyTypeObject/tp_members style
- File now exposes path/mode/closed via slots
- examples: generators.cat, errors.cat, slots.cat; 40/40 tests
This commit is contained in:
Minus committed 2026-11-16 01:48:47 +00:00
1 parent 52d118211f
commit 3c20496c78
19 files changed
+978 -99

No files matched your search

+1
View File
@@ -45,6 +45,7 @@ SRCS := \
src/cat/types/function.c \ src/cat/types/function.c \
src/cat/types/native.c \ src/cat/types/native.c \
src/cat/types/file.c \ src/cat/types/file.c \
src/cat/types/generator.c \
src/cat/stdlib/stdlib.c \ src/cat/stdlib/stdlib.c \
src/cat/stdlib/toml.c \ src/cat/stdlib/toml.c \
src/cat/stdlib/build.c src/cat/stdlib/build.c
+62
View File
@@ -142,6 +142,68 @@ end
se conhece na compilação; `sentinel_sized<'\0'>` marca arrays terminados se conhece na compilação; `sentinel_sized<'\0'>` marca arrays terminados
por um valor sentinela. por um valor sentinela.
## Layout de objetos com slots (estilo PyTypeObject)
Cada tipo C declara seu layout **uma vez** como um array fixo de
`CAT_VALUE_Slot` (nome, `offsetof`, tipo, readonly). O dispatcher de
atributos então lê/escreve membros por offset, sem código C por
atributo — exatamente como `tp_members`/`__slots__` do CPython. Assim o
layout é conhecido pelos módulos C que incluem o header do tipo:
```c
static const CAT_VALUE_Slot g_file_slots[] = {
{ "path", offsetof(CAT_TYPES_FILE_File, path), CAT_VALUE_SLOT_TEXT, 1 },
{ "mode", offsetof(CAT_TYPES_FILE_File, af)
+ offsetof(CAT_TYPES_FILE_AbstractFile, mode), CAT_VALUE_SLOT_NUMBER, 1 },
{ "closed", offsetof(CAT_TYPES_FILE_File, af)
+ offsetof(CAT_TYPES_FILE_AbstractFile, closed), CAT_VALUE_SLOT_BOOL, 1 },
};
```
Do lado catscript: `f.path`, `f.mode`, `f.closed` funcionam sem nenhum
accessor escrito à mão.
## Geradores, iteradores e `yield`
Uma função cujo corpo usa `yield` **não roda ao ser chamada**: ela
produz um **generator**. `next()` retoma a execução até o próximo
`yield` (ou o `return`, que encerra a iteração). O mesmo protocolo
(`next` na vtable) é o iterador geral, e `for x in it do ... end`
consome qualquer iterador, terminando por **status de exaustão** — então
geradores podem produzir `nil`, `false` ou `0` sem encerrar o loop:
```lua
function count_up(n)
local i = 1
while i <= n do
yield i
i = i + 1
end
end
local g = count_up(3)
print(g:next()) -- 1
for x in count_up(5) do -- iteração automática
print(x)
end
```
## Erros: `raise`, `try`, `except`
`raise expr` lança um valor; `try ... except [NAME] ... end` captura o
erro mais próximo (inclusive erros estruturados, não só strings), e o
valor capturado é ligado ao nome do `except`. Erros propagam por
chamadas aninhadas até o handler mais próximo:
```lua
try
raise { code = 42, what = "custom" }
except e
print(e.code, e.what)
end
```
## cpk — Cat Package Manager ## cpk — Cat Package Manager
O primeiro programa em catscript. Lê o `package.toml` de um pacote O primeiro programa em catscript. Lê o `package.toml` de um pacote
+38
View File
@@ -0,0 +1,38 @@
-- examples/errors.cat -- raise, try, except.
function risky(n)
if n < 0 then
raise "negative not allowed"
end
return n * 2
end
-- raise is caught by try/except
try
print("ok:", risky(21))
raise "boom"
print("unreachable")
except e
print("caught:", e)
end
-- a structured (non-string) error value can be caught too
try
raise { code = 42, what = "custom" }
except e
print("code:", e.code)
print("what:", e.what)
end
-- errors propagate out of nested calls to the nearest handler
function outer()
return risky(-1)
end
try
outer()
except e
print("propagated:", e)
end
print("still running")
+44
View File
@@ -0,0 +1,44 @@
-- examples/generators.cat -- generators, iterators, yield, for..in.
-- a generator: calling it returns a generator, not a value
function count_up(n)
local i = 1
while i <= n do
yield i
i = i + 1
end
end
print("type:", type(count_up(3)))
-- manual iteration with next
local g = count_up(3)
print("next:", g:next())
print("next:", g:next())
print("next:", g:next())
print("next:", g:next()) -- nil: exhausted
-- for..in drives any iterator automatically
local sum = 0
for x in count_up(5) do
sum = sum + x
end
print("sum 1..5 =", sum)
-- infinite generator + take: lazy, stopped by break
function naturals()
local i = 0
while true do
yield i
i = i + 1
end
end
local taken = 0
for x in naturals() do
if x >= 3 then
break
end
taken = taken + 1
end
print("taken < 3:", taken)
+14
View File
@@ -0,0 +1,14 @@
-- examples/slots.cat -- the slot-based object layout.
--
-- A C module declares its concrete layout once (a fixed array of
-- CAT_VALUE_Slot). The attribute dispatcher then reads members by
-- offset, so `f.path` / `f.mode` / `f.closed` need no per-attribute C
-- code. This is the analogue of CPython's tp_members / __slots__.
local f = File::open("/tmp/catscript_slots_demo.txt", "w")
print("path:", f.path)
print("mode:", f.mode)
print("closed:", f.closed)
f:write("slots")
f:close()
print("closed:", f.closed)
+7
View File
@@ -58,6 +58,12 @@ enum CAT_BYTECODE_Op {
CAT_BYTECODE_OP_DUP, /* duplicate top of stack */ CAT_BYTECODE_OP_DUP, /* duplicate top of stack */
CAT_BYTECODE_OP_GETIDX, /* pop idx, obj -> push obj[idx] */ CAT_BYTECODE_OP_GETIDX, /* pop idx, obj -> push obj[idx] */
CAT_BYTECODE_OP_SETIDX, /* pop val, idx, obj -> obj[idx]=val */ CAT_BYTECODE_OP_SETIDX, /* pop val, idx, obj -> obj[idx]=val */
CAT_BYTECODE_OP_YIELD, /* suspend a generator, yielding top */
CAT_BYTECODE_OP_NEXT, /* pop it -> push next(it) or nil */
CAT_BYTECODE_OP_TRYSETUP, /* A: handler target addr */
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 */
}; };
/* One instruction: opcode + three integer operands. */ /* One instruction: opcode + three integer operands. */
@@ -88,6 +94,7 @@ typedef struct CAT_BYTECODE_Function {
int nprotos, capprotos; int nprotos, capprotos;
int nlocals; /* number of local slots */ int nlocals; /* number of local slots */
int nparams; /* number of parameters */ int nparams; /* number of parameters */
int is_generator; /* contains yield: calls produce a generator */
} CAT_BYTECODE_Function; } CAT_BYTECODE_Function;
CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name); CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name);
+9
View File
@@ -12,12 +12,17 @@
#include <stdbool.h> #include <stdbool.h>
struct CAT_VALUE_Value;
/* CAT_ERROR_Error -- an error slot passed into API calls. */ /* CAT_ERROR_Error -- an error slot passed into API calls. */
/* `raised` becomes true when an operation fails; `message` is a */ /* `raised` becomes true when an operation fails; `message` is a */
/* human-readable description (always NUL terminated when raised). */ /* human-readable description (always NUL terminated when raised). */
/* `value` optionally carries a catscript value (what `raise` was */
/* given, or the message as text), which `try/except` binds. */
typedef struct CAT_ERROR_Error { typedef struct CAT_ERROR_Error {
bool raised; bool raised;
char message[256]; char message[256];
struct CAT_VALUE_Value *value;
} CAT_ERROR_Error; } CAT_ERROR_Error;
/* Clear an error slot back to the "no error" state. */ /* Clear an error slot back to the "no error" state. */
@@ -26,4 +31,8 @@ void cat_error_clear(CAT_ERROR_Error *err);
/* Raise (fill) an error slot with a printf-style message. */ /* Raise (fill) an error slot with a printf-style message. */
void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...); void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...);
/* Raise with a carried catscript value (what `raise v` was given). */
void cat_error_raise_value(CAT_ERROR_Error *err, struct CAT_VALUE_Value *v,
const char *fmt, ...);
#endif /* CAT_ERROR_H */ #endif /* CAT_ERROR_H */
+2
View File
@@ -26,6 +26,8 @@ enum CAT_LEXER_Kind {
CAT_LEXER_TOK_NIL, CAT_LEXER_TOK_NOT, CAT_LEXER_TOK_OR, CAT_LEXER_TOK_NIL, CAT_LEXER_TOK_NOT, CAT_LEXER_TOK_OR,
CAT_LEXER_TOK_REPEAT, CAT_LEXER_TOK_RETURN, CAT_LEXER_TOK_THEN, CAT_LEXER_TOK_REPEAT, CAT_LEXER_TOK_RETURN, CAT_LEXER_TOK_THEN,
CAT_LEXER_TOK_TRUE, CAT_LEXER_TOK_UNTIL, CAT_LEXER_TOK_WHILE, 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,
/* symbols */ /* symbols */
CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR, CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR,
CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET, CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET,
+42
View File
@@ -0,0 +1,42 @@
/*
* cat/types/generator.h -- generators / iterators.
*
* Naming rule: symbols here are cat_types_generator_* / CAT_TYPES_GENERATOR_*.
*
* A generator wraps a suspended CAT_VM_Frame. Calling a function whose
* body contains `yield` does not run it: it produces a generator whose
* `next()` resumes the frame until the next `yield` (or the function's
* return, which ends iteration). The same type is the general iterator
* protocol: `cat_value_next` on anything with a `next` slot advances it.
*/
#ifndef CAT_TYPES_GENERATOR_H
#define CAT_TYPES_GENERATOR_H
#include "cat/value.h"
#include "cat/vm.h"
/* CAT_TYPES_GENERATOR_Generator -- a resumable suspended frame. */
typedef struct CAT_TYPES_GENERATOR_Generator {
CAT_VALUE_Value base;
CAT_VM_State *vm;
CAT_TYPES_FUNCTION_Closure *cl;
CAT_VM_Frame frame; /* ip/sp/locals/handlers of the paused call */
CAT_VALUE_Value **stack; /* operand stack (lives across resumes) */
int started;
int done;
/* arguments captured for the first resume */
CAT_VALUE_Value *args[256];
int nargs;
} CAT_TYPES_GENERATOR_Generator;
/* Create a generator for `cl` invoked with `args`; nothing runs yet. */
CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs);
CAT_VALUE_Vtable *cat_types_generator_vtable(void);
/* True if v is a generator. */
int cat_types_generator_is(CAT_VALUE_Value *v);
#endif /* CAT_TYPES_GENERATOR_H */
+53 -1
View File
@@ -17,6 +17,7 @@
#define CAT_VALUE_H #define CAT_VALUE_H
#include <stdbool.h> #include <stdbool.h>
#include <stddef.h>
struct CAT_ERROR_Error; struct CAT_ERROR_Error;
struct CAT_VALUE_Value; struct CAT_VALUE_Value;
@@ -82,6 +83,37 @@ typedef struct CAT_IMPL_SetAttribute {
CAT_ERROR_Error *err); CAT_ERROR_Error *err);
} CAT_IMPL_SetAttribute; } CAT_IMPL_SetAttribute;
/* Cat_ImplementsNext -- advance an iterator/generator: -> *out (nil ends). */
typedef struct CAT_IMPL_Next {
int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
} CAT_IMPL_Next;
/* ---- slots: a C-known object layout (PyTypeObject / tp_members) ----
*
* A C module declares its concrete layout once, as a fixed array of
* CAT_VALUE_Slot descriptors. The VM and the attribute dispatcher then
* read/write members by name with no per-access C code, and the layout
* is known to every C module that includes the type's header (the
* offsets come from offsetof). This is the analogue of CPython's
* `tp_members` / `__slots__`.
*/
typedef struct CAT_VALUE_Slot {
const char *name; /* attribute name */
size_t offset; /* byte offset from the value base pointer */
int kind; /* one of CAT_VALUE_SLOT_* */
int readonly; /* 1 => assign raises */
} CAT_VALUE_Slot;
enum {
CAT_VALUE_SLOT_VALUE, /* CAT_VALUE_Value * member */
CAT_VALUE_SLOT_NUMBER, /* long long member */
CAT_VALUE_SLOT_DOUBLE, /* double member */
CAT_VALUE_SLOT_TEXT, /* char * member */
CAT_VALUE_SLOT_BOOL, /* int/bool member */
CAT_VALUE_SLOT_NIL /* no storage; always reads nil */
};
/* Runtime kind tag: structural families the VM can test cheaply. */ /* Runtime kind tag: structural families the VM can test cheaply. */
enum { enum {
CAT_VALUE_KIND_NIL, CAT_VALUE_KIND_NIL,
@@ -89,7 +121,8 @@ enum {
CAT_VALUE_KIND_NUMBER, /* Cat_Number family */ CAT_VALUE_KIND_NUMBER, /* Cat_Number family */
CAT_VALUE_KIND_TEXT, /* Cat_Text family */ CAT_VALUE_KIND_TEXT, /* Cat_Text family */
CAT_VALUE_KIND_TABLE, /* table / object */ CAT_VALUE_KIND_TABLE, /* table / object */
CAT_VALUE_KIND_FUNCTION /* closure */ CAT_VALUE_KIND_FUNCTION, /* closure */
CAT_VALUE_KIND_GENERATOR /* suspended generator / iterator */
}; };
/* ---- the vtable every value type fills in ---- */ /* ---- the vtable every value type fills in ---- */
@@ -109,6 +142,10 @@ struct CAT_VALUE_Vtable {
CAT_IMPL_Raise raise; CAT_IMPL_Raise raise;
CAT_IMPL_GetAttribute get_attribute; CAT_IMPL_GetAttribute get_attribute;
CAT_IMPL_SetAttribute set_attribute; CAT_IMPL_SetAttribute set_attribute;
CAT_IMPL_Next next;
/* fixed member layout, when this type has one (may be NULL) */
const CAT_VALUE_Slot *slots;
int nslots;
/* truthiness for control flow (NULL => everything is true) */ /* truthiness for control flow (NULL => everything is true) */
int (*truthy)(CAT_VALUE_Value *self, CAT_ERROR_Error *err); int (*truthy)(CAT_VALUE_Value *self, CAT_ERROR_Error *err);
/* release the object's own storage (shallow) */ /* release the object's own storage (shallow) */
@@ -142,6 +179,21 @@ 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, int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
CAT_ERROR_Error *err); 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 a nil/sentinel
* value) lets generators yield nil, false or 0 without ending the loop. */
int cat_value_next(CAT_VALUE_Value *v, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
/* Slot-based member access. `cat_value_slot_find` returns the Slot or
* NULL; get/set read or write the member through its offset. */
const CAT_VALUE_Slot *cat_value_slot_find(CAT_VALUE_Value *v, const char *name);
int cat_value_slot_get(CAT_VALUE_Value *v, const CAT_VALUE_Slot *s,
CAT_VALUE_Value **out, CAT_ERROR_Error *err);
int cat_value_slot_set(CAT_VALUE_Value *v, const CAT_VALUE_Slot *s,
CAT_VALUE_Value *value, CAT_ERROR_Error *err);
const char *cat_value_type_name(CAT_VALUE_Value *v); const char *cat_value_type_name(CAT_VALUE_Value *v);
#endif /* CAT_VALUE_H */ #endif /* CAT_VALUE_H */
+32 -1
View File
@@ -10,9 +10,10 @@
#include "cat/error.h" #include "cat/error.h"
#include "cat/bytecode.h" #include "cat/bytecode.h"
/* Forward declaration so the native-callback signature below refers to /* Forward declarations so the native-callback signature below refers to
* the real CAT_VM_State type, not a parameter-list-scoped struct. */ * the real CAT_VM_State type, not a parameter-list-scoped struct. */
typedef struct CAT_VM_State CAT_VM_State; typedef struct CAT_VM_State CAT_VM_State;
typedef struct CAT_TYPES_FUNCTION_Closure CAT_TYPES_FUNCTION_Closure;
/* One registered native function. Natives live in the VM (not in a /* One registered native function. Natives live in the VM (not in a
* process-global list) so distinct VMs never share mutable state and can * process-global list) so distinct VMs never share mutable state and can
@@ -24,6 +25,30 @@ typedef struct CAT_VM_Native {
#define CAT_VM_MAXNATIVE 128 #define CAT_VM_MAXNATIVE 128
/* An active `try` handler: where to jump and the stack height to
* restore when an error is caught. */
typedef struct CAT_VM_Handler {
int target; /* instruction index of the handler */
int sp; /* stack height to restore */
} CAT_VM_Handler;
#define CAT_VM_MAXHANDLER 64
/* CAT_VM_Frame -- one function activation. A frame holds everything
* needed to suspend and resume execution (ip, operand stack, locals and
* active handlers), so the same interpreter drives both ordinary calls
* and generators that yield in the middle. */
typedef struct CAT_VM_Frame {
CAT_BYTECODE_Function *fn;
CAT_TYPES_FUNCTION_Closure *cl;
CAT_VALUE_Value **stack; /* operand stack (owned by the caller) */
CAT_VALUE_Value *locals[256];
int sp;
int ip;
CAT_VM_Handler handlers[CAT_VM_MAXHANDLER];
int nhandlers;
} CAT_VM_Frame;
/* CAT_VM_State -- globals + a call stack. Fully self-contained: two VMs /* CAT_VM_State -- globals + a call stack. Fully self-contained: two VMs
* share no mutable state, so they may execute on separate threads. */ * share no mutable state, so they may execute on separate threads. */
typedef struct CAT_VM_State { typedef struct CAT_VM_State {
@@ -50,6 +75,12 @@ int cat_vm_register_native(CAT_VM_State *vm, const char *name,
* closures/natives invoked through the object system. */ * closures/natives invoked through the object system. */
CAT_VM_State *cat_vm_current(void); CAT_VM_State *cat_vm_current(void);
/* Run (or resume) a frame. Returns 0 when the frame returns (*out set),
* 1 when it yields (*out set, frame left resumable), or -1 on error
* (vm->err set). The frame owns neither its operand stack nor its
* handlers' lifetime; the caller keeps the stack alive across resumes. */
int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out);
/* Convenience: get/set a global. */ /* Convenience: get/set a global. */
CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name); CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name);
int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v); int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v);
+98 -2
View File
@@ -41,6 +41,7 @@ typedef struct {
CAT_BYTECODE_Function *fn; CAT_BYTECODE_Function *fn;
char locals[MAXLOCALS][64]; char locals[MAXLOCALS][64];
int nlocals; int nlocals;
int is_generator; /* body used `yield` */
} FuncCtx; } FuncCtx;
typedef struct { typedef struct {
@@ -265,6 +266,9 @@ static int compile_function_literal(Compiler *c, const char *name)
c->stack[c->nstack++] = nc; c->stack[c->nstack++] = nc;
block(c); block(c);
expect(c, CAT_LEXER_TOK_END, "'end'"); expect(c, CAT_LEXER_TOK_END, "'end'");
/* A body that used `yield` makes this a generator. */
if (c->stack[c->nstack - 1].is_generator)
sub->is_generator = 1;
emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, c->tok.line); emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, c->tok.line);
c->nstack--; c->nstack--;
@@ -648,6 +652,37 @@ static void stat(Compiler *c)
next(c); next(c);
} }
skip_type_hint(c); skip_type_hint(c);
if (check(c, CAT_LEXER_TOK_IN)) {
/* for NAME in expr do <body> end -- iterate any iterator
* (generator). Each round calls NEXT; nil ends the loop. */
int islot;
next(c);
expr(c); /* the iterable */
expect(c, CAT_LEXER_TOK_DO, "'do'");
slot = add_local(c, var);
islot = add_local(c, " .it");
emit(c, CAT_BYTECODE_OP_SETLOCAL, islot, 0, line);
jcond = cur_fn(c)->ncode;
emit(c, CAT_BYTECODE_OP_GETLOCAL, islot, 0, line);
jend = emit(c, CAT_BYTECODE_OP_FORNEXT, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
{
int lv = c->nloops++;
c->brk_n[lv] = 0;
block(c);
c->nloops--;
emit(c, CAT_BYTECODE_OP_JUMP, jcond, 0, line);
cur_fn(c)->code[jend].a = cur_fn(c)->ncode;
{
int k;
for (k = 0; k < c->brk_n[lv]; k++)
cur_fn(c)->code[c->brk_ends[lv][k]].a =
cur_fn(c)->ncode;
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
break;
}
expect(c, CAT_LEXER_TOK_ASSIGN, "'='"); expect(c, CAT_LEXER_TOK_ASSIGN, "'='");
expr(c); /* start */ expr(c); /* start */
expect(c, CAT_LEXER_TOK_COMMA, "','"); expect(c, CAT_LEXER_TOK_COMMA, "','");
@@ -711,7 +746,8 @@ static void stat(Compiler *c)
next(c); next(c);
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) && if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) && !check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) &&
!check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL)) { !check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) &&
!check(c, CAT_LEXER_TOK_EXCEPT)) {
expr(c); expr(c);
emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line); emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line);
} else { } else {
@@ -720,6 +756,66 @@ static void stat(Compiler *c)
accept(c, CAT_LEXER_TOK_SEMI); accept(c, CAT_LEXER_TOK_SEMI);
break; break;
case CAT_LEXER_TOK_YIELD:
/* `yield [expr]` suspends the enclosing function; its body now
* marks the function as a generator (calls return a generator). */
next(c);
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) &&
!check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) &&
!check(c, CAT_LEXER_TOK_EXCEPT))
expr(c);
else
emit(c, CAT_BYTECODE_OP_NIL, 0, 0, line);
emit(c, CAT_BYTECODE_OP_YIELD, 0, 0, line);
ctx(c)->is_generator = 1;
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_RAISE:
/* `raise expr` throws the value; caught by an enclosing try. */
next(c);
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI))
expr(c);
else
emit(c, CAT_BYTECODE_OP_NIL, 0, 0, line);
emit(c, CAT_BYTECODE_OP_RAISE, 0, 0, line);
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_TRY: {
/* try <block> except [NAME] <block> end. On error the VM
* unwinds to the handler with the error value on the stack. */
int setup, jend;
next(c);
setup = emit(c, CAT_BYTECODE_OP_TRYSETUP, 0, 0, line);
block(c);
emit(c, CAT_BYTECODE_OP_TRYEND, 0, 0, line);
jend = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line);
/* handler entry */
cur_fn(c)->code[setup].a = cur_fn(c)->ncode;
if (accept(c, CAT_LEXER_TOK_EXCEPT)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
char vn[64];
int slot;
snprintf(vn, sizeof(vn), "%s", c->tok.text);
next(c);
slot = add_local(c, vn);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
else
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
} else {
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
}
block(c);
}
cur_fn(c)->code[jend].a = cur_fn(c)->ncode;
expect(c, CAT_LEXER_TOK_END, "'end'");
break;
}
case CAT_LEXER_TOK_NAME: { case CAT_LEXER_TOK_NAME: {
/* assignment if `name =`, or field assignment if `name.attr =`. /* assignment if `name =`, or field assignment if `name.attr =`.
* Otherwise rewind and parse as an ordinary expression. */ * Otherwise rewind and parse as an ordinary expression. */
@@ -802,7 +898,7 @@ static void block(Compiler *c)
{ {
while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) && while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_ELSE) && !check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_ELSE) && !check(c, CAT_LEXER_TOK_ELSEIF) &&
!check(c, CAT_LEXER_TOK_UNTIL)) { !check(c, CAT_LEXER_TOK_UNTIL) && !check(c, CAT_LEXER_TOK_EXCEPT)) {
int before = cur_fn(c)->ncode; int before = cur_fn(c)->ncode;
/* a lone ';' is a valid empty statement, not a parse error */ /* a lone ';' is a valid empty statement, not a parse error */
if (check(c, CAT_LEXER_TOK_SEMI)) { if (check(c, CAT_LEXER_TOK_SEMI)) {
+17
View File
@@ -4,6 +4,7 @@
* Naming rule: symbols here are cat_error_* / CAT_ERROR_*. * Naming rule: symbols here are cat_error_* / CAT_ERROR_*.
*/ */
#include "cat/error.h" #include "cat/error.h"
#include "cat/value.h"
#include <stdarg.h> #include <stdarg.h>
#include <stdio.h> #include <stdio.h>
@@ -15,6 +16,7 @@ void cat_error_clear(CAT_ERROR_Error *err)
return; return;
err->raised = false; err->raised = false;
err->message[0] = '\0'; err->message[0] = '\0';
err->value = NULL;
} }
void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...) void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...)
@@ -28,3 +30,18 @@ void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...)
vsnprintf(err->message, sizeof(err->message), fmt, ap); vsnprintf(err->message, sizeof(err->message), fmt, ap);
va_end(ap); va_end(ap);
} }
void cat_error_raise_value(CAT_ERROR_Error *err, struct CAT_VALUE_Value *v,
const char *fmt, ...)
{
va_list ap;
if (err == NULL)
return;
cat_error_raise(err, "%s", "");
err->raised = true;
va_start(ap, fmt);
vsnprintf(err->message, sizeof(err->message), fmt, ap);
va_end(ap);
err->value = v;
}
+5
View File
@@ -21,6 +21,7 @@ static const struct kw g_keywords[] = {
{ "do", CAT_LEXER_TOK_DO }, { "do", CAT_LEXER_TOK_DO },
{ "else", CAT_LEXER_TOK_ELSE }, { "else", CAT_LEXER_TOK_ELSE },
{ "elseif", CAT_LEXER_TOK_ELSEIF }, { "elseif", CAT_LEXER_TOK_ELSEIF },
{ "except", CAT_LEXER_TOK_EXCEPT },
{ "end", CAT_LEXER_TOK_END }, { "end", CAT_LEXER_TOK_END },
{ "false", CAT_LEXER_TOK_FALSE }, { "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR }, { "for", CAT_LEXER_TOK_FOR },
@@ -32,11 +33,14 @@ static const struct kw g_keywords[] = {
{ "not", CAT_LEXER_TOK_NOT }, { "not", CAT_LEXER_TOK_NOT },
{ "or", CAT_LEXER_TOK_OR }, { "or", CAT_LEXER_TOK_OR },
{ "repeat", CAT_LEXER_TOK_REPEAT }, { "repeat", CAT_LEXER_TOK_REPEAT },
{ "raise", CAT_LEXER_TOK_RAISE },
{ "return", CAT_LEXER_TOK_RETURN }, { "return", CAT_LEXER_TOK_RETURN },
{ "then", CAT_LEXER_TOK_THEN }, { "then", CAT_LEXER_TOK_THEN },
{ "true", CAT_LEXER_TOK_TRUE }, { "true", CAT_LEXER_TOK_TRUE },
{ "try", CAT_LEXER_TOK_TRY },
{ "until", CAT_LEXER_TOK_UNTIL }, { "until", CAT_LEXER_TOK_UNTIL },
{ "while", CAT_LEXER_TOK_WHILE }, { "while", CAT_LEXER_TOK_WHILE },
{ "yield", CAT_LEXER_TOK_YIELD },
}; };
void cat_lexer_init(CAT_LEXER_Lexer *lx, const char *src) void cat_lexer_init(CAT_LEXER_Lexer *lx, const char *src)
@@ -254,6 +258,7 @@ const char *cat_lexer_kind_name(int kind)
"and", "break", "do", "else", "elseif", "end", "false", "for", "and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "if", "in", "local", "nil", "not", "or", "repeat", "function", "if", "in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while", "return", "then", "true", "until", "while",
"yield", "try", "except", "raise",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<", "+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<",
">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":", ">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":",
"::", "..", "->" "::", "..", "->"
+31 -3
View File
@@ -24,6 +24,7 @@
#include "cat/types/table.h" #include "cat/types/table.h"
#include "cat/error.h" #include "cat/error.h"
#include <stddef.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -230,10 +231,38 @@ static void file_destroy(CAT_VALUE_Value *self)
free(self); free(self);
} }
/* ---- slots: the C-known layout of a real File ----------------------
*
* The File struct is fixed and known to any C module that includes
* cat/types/file.h, so it declares its members once as slots. The
* attribute dispatcher then reads/writes path/mode/closed by offset,
* with no per-attribute C code (the analogue of CPython's tp_members). */
static const CAT_VALUE_Slot g_file_slots[] = {
{ "path", offsetof(CAT_TYPES_FILE_File, path),
CAT_VALUE_SLOT_TEXT, 1 },
{ "mode", offsetof(CAT_TYPES_FILE_File, af) +
offsetof(CAT_TYPES_FILE_AbstractFile, mode),
CAT_VALUE_SLOT_NUMBER, 1 },
{ "closed", offsetof(CAT_TYPES_FILE_File, af) +
offsetof(CAT_TYPES_FILE_AbstractFile, closed),
CAT_VALUE_SLOT_BOOL, 1 },
};
static CAT_VALUE_Vtable g_file_vtable = { static CAT_VALUE_Vtable g_file_vtable = {
.type_name = "File", .type_name = "File",
.kind = CAT_VALUE_KIND_TABLE, .kind = CAT_VALUE_KIND_TABLE,
.get_attribute = { file_get_attr }, .get_attribute = { file_get_attr },
.slots = g_file_slots,
.nslots = (int)(sizeof(g_file_slots) / sizeof(g_file_slots[0])),
.destroy = file_destroy,
};
/* StringIO/BytesIO share the methods but not the layout of a real File,
* so they get their own vtable (no slots). */
static CAT_VALUE_Vtable g_memfile_vtable = {
.type_name = "StringIO",
.kind = CAT_VALUE_KIND_TABLE,
.get_attribute = { file_get_attr },
.destroy = file_destroy, .destroy = file_destroy,
}; };
@@ -241,7 +270,6 @@ CAT_VALUE_Vtable *cat_types_file_abstract_vtable(void)
{ {
return &g_file_vtable; return &g_file_vtable;
} }
/* ---- constructors ---------------------------------------------------- */ /* ---- constructors ---------------------------------------------------- */
CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode) CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode)
@@ -283,7 +311,7 @@ CAT_VALUE_Value *cat_types_file_stringio(const char *initial)
if (m == NULL) if (m == NULL)
return cat_types_nil_get(); return cat_types_nil_get();
m->af.base.vtable = &g_file_vtable; m->af.base.vtable = &g_memfile_vtable;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE; m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->af.is_bytes = 1; /* in-memory */ m->af.is_bytes = 1; /* in-memory */
m->cap = 128; m->cap = 128;
@@ -313,7 +341,7 @@ CAT_VALUE_Value *cat_types_file_bytesio(void)
if (m == NULL) if (m == NULL)
return cat_types_nil_get(); return cat_types_nil_get();
m->af.base.vtable = &g_file_vtable; m->af.base.vtable = &g_memfile_vtable;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE; m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->cap = 128; m->cap = 128;
m->buf = malloc((size_t)m->cap); m->buf = malloc((size_t)m->cap);
+133
View File
@@ -0,0 +1,133 @@
/*
* cat/types/generator.c -- generators / iterators.
*
* Naming rule: symbols here are cat_types_generator_* / CAT_TYPES_GENERATOR_*.
*/
#include "cat/types/generator.h"
#include "cat/types/native.h"
#include "cat/types/nil.h"
#include "cat/types/function.h"
#include "cat/bytecode.h"
#include "cat/error.h"
#include <stdlib.h>
#include <string.h>
static int generator_next(CAT_VALUE_Value *self, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
/* `it:next()` method form: receiver is args[0]. */
static int gen_method_next(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out);
static int generator_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
(void)self;
if (strcmp(name, "next") == 0) {
*out = cat_types_native_new("next", gen_method_next);
return 0;
}
return (cat_error_raise(err, "generator has no method '%s'", name), -1);
}
static CAT_VALUE_Vtable g_generator_vtable = {
.type_name = "generator",
.kind = CAT_VALUE_KIND_GENERATOR,
.next = { generator_next },
.get_attribute = { generator_get_attribute },
};
CAT_VALUE_Vtable *cat_types_generator_vtable(void)
{
return &g_generator_vtable;
}
int cat_types_generator_is(CAT_VALUE_Value *v)
{
return v != NULL && v->vtable == &g_generator_vtable;
}
CAT_VALUE_Value *cat_types_generator_new(CAT_VM_State *vm,
CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs)
{
CAT_TYPES_GENERATOR_Generator *g = calloc(1, sizeof(*g));
int i;
if (g == NULL)
return cat_types_nil_get();
g->base.vtable = &g_generator_vtable;
g->vm = vm;
g->cl = cl;
g->frame.fn = cl->proto;
g->frame.cl = cl;
g->frame.ip = 0;
g->frame.sp = 0;
g->frame.nhandlers = 0;
g->stack = calloc((size_t)(g->frame.fn->ncode + 64), sizeof(*g->stack));
if (g->stack == NULL) {
free(g);
return cat_types_nil_get();
}
g->frame.stack = g->stack;
g->started = 0;
g->done = 0;
for (i = 0; i < nargs && i < 256; i++)
g->args[i] = args[i];
g->nargs = nargs;
return &g->base;
}
static int generator_next(CAT_VALUE_Value *self, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
CAT_TYPES_GENERATOR_Generator *g = (CAT_TYPES_GENERATOR_Generator *)self;
CAT_VALUE_Value *val = NULL;
int rc, i;
if (g->done)
return 1; /* exhausted */
if (!g->started) {
g->frame.ip = 0;
g->frame.sp = 0;
for (i = 0; i < 256; i++)
g->frame.locals[i] = NULL;
for (i = 0; i < g->nargs && i < g->frame.fn->nparams && i < 256; i++)
g->frame.locals[i] = g->args[i];
g->started = 1;
}
rc = cat_vm_frame_run(g->vm, &g->frame, &val);
if (rc < 0) {
*out = NULL;
cat_error_raise(err, "%s", g->vm->err.message);
err->value = g->vm->err.value;
return -1;
}
if (rc == 1) { /* yielded */
*out = val ? val : cat_types_nil_get();
return 0;
}
/* function returned: iteration ends */
g->done = 1;
return 1; /* exhausted */
}
/* `it:next()` -- returns the next value, or nil when exhausted. */
static int gen_method_next(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_ERROR_Error e;
int rc;
(void)vm;
cat_error_clear(&e);
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
rc = cat_value_next(args[0], out, &e);
if (rc != 0)
*out = cat_types_nil_get(); /* exhausted or error -> nil */
return 0;
}
+130 -9
View File
@@ -10,8 +10,15 @@
*/ */
#include "cat/value.h" #include "cat/value.h"
#include "cat/error.h" #include "cat/error.h"
#include "cat/types/nil.h"
#include "cat/types/bool.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include <stddef.h> #include <stddef.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
const char *cat_value_type_name(CAT_VALUE_Value *v) const char *cat_value_type_name(CAT_VALUE_Value *v)
@@ -83,20 +90,44 @@ int cat_value_call(CAT_VALUE_Value *fn, CAT_VALUE_Value **args, int nargs,
int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name, int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err) CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{ {
if (vt(self) == NULL || vt(self)->get_attribute.fn == NULL) const CAT_VALUE_Slot *s;
return (cat_error_raise(err,
"type %s has no attributes", cat_value_type_name(self)), -1); if (vt(self) != NULL && vt(self)->get_attribute.fn != NULL &&
return vt(self)->get_attribute.fn(self, name, out, err); vt(self)->get_attribute.fn(self, name, out, err) == 0)
return 0;
/* The type's own handler declined; clear any error it left behind
* before trying the C-known member layout (slots). */
if (err != NULL)
cat_error_clear(err);
s = cat_value_slot_find(self, name);
if (s != NULL && cat_value_slot_get(self, s, out, err) == 0) {
if (err != NULL)
cat_error_clear(err);
return 0;
}
return (cat_error_raise(err,
"type %s has no attribute '%s'", cat_value_type_name(self), name), -1);
} }
int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name, int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value *value, CAT_ERROR_Error *err) CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{ {
if (vt(self) == NULL || vt(self)->set_attribute.fn == NULL) const CAT_VALUE_Slot *s;
return (cat_error_raise(err,
"type %s has no settable attributes", if (vt(self) != NULL && vt(self)->set_attribute.fn != NULL &&
cat_value_type_name(self)), -1); vt(self)->set_attribute.fn(self, name, value, err) == 0)
return vt(self)->set_attribute.fn(self, name, value, err); return 0;
if (err != NULL)
cat_error_clear(err);
s = cat_value_slot_find(self, name);
if (s != NULL && cat_value_slot_set(self, s, value, err) == 0) {
if (err != NULL)
cat_error_clear(err);
return 0;
}
return (cat_error_raise(err,
"type %s has no settable attribute '%s'",
cat_value_type_name(self), name), -1);
} }
int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err) int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err)
@@ -133,3 +164,93 @@ int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
(void)r; (void)r;
return 0; return 0;
} }
int cat_value_next(CAT_VALUE_Value *v, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
if (vt(v) == NULL || vt(v)->next.fn == NULL)
return (cat_error_raise(err,
"type %s is not iterable", cat_value_type_name(v)), -1);
return vt(v)->next.fn(v, out, err);
}
const CAT_VALUE_Slot *cat_value_slot_find(CAT_VALUE_Value *v, const char *name)
{
int i;
if (vt(v) == NULL || vt(v)->slots == NULL)
return NULL;
for (i = 0; i < vt(v)->nslots; i++)
if (strcmp(vt(v)->slots[i].name, name) == 0)
return &vt(v)->slots[i];
return NULL;
}
int cat_value_slot_get(CAT_VALUE_Value *v, const CAT_VALUE_Slot *s,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
char *base = (char *)v;
switch (s->kind) {
case CAT_VALUE_SLOT_VALUE:
*out = *(CAT_VALUE_Value **)(base + s->offset);
break;
case CAT_VALUE_SLOT_NUMBER:
*out = cat_types_int_new(*(long long *)(base + s->offset));
break;
case CAT_VALUE_SLOT_DOUBLE:
*out = cat_types_float_new(*(double *)(base + s->offset));
break;
case CAT_VALUE_SLOT_TEXT: {
char *p = *(char **)(base + s->offset);
*out = cat_types_ascii_text_new(p ? p : "");
break;
}
case CAT_VALUE_SLOT_BOOL:
*out = (*(int *)(base + s->offset)) ? cat_types_bool_true()
: cat_types_bool_false();
break;
default:
*out = cat_types_nil_get();
break;
}
if (*out == NULL)
return (cat_error_raise(err, "slot '%s' unreadable", s->name), -1);
return 0;
}
int cat_value_slot_set(CAT_VALUE_Value *v, const CAT_VALUE_Slot *s,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
char *base = (char *)v;
if (s->readonly)
return (cat_error_raise(err, "slot '%s' is read-only", s->name), -1);
switch (s->kind) {
case CAT_VALUE_SLOT_VALUE:
*(CAT_VALUE_Value **)(base + s->offset) = value;
break;
case CAT_VALUE_SLOT_NUMBER:
*(long long *)(base + s->offset) = cat_types_number_as_int(value);
break;
case CAT_VALUE_SLOT_DOUBLE:
*(double *)(base + s->offset) = cat_types_number_as_double(value);
break;
case CAT_VALUE_SLOT_TEXT: {
const char *p = cat_types_text_bytes(value);
char **dst = (char **)(base + s->offset);
free(*dst);
*dst = p ? strdup(p) : NULL;
break;
}
case CAT_VALUE_SLOT_BOOL: {
int t = 1;
cat_value_truthy(value, &t, err);
*(int *)(base + s->offset) = t;
break;
}
default:
break;
}
return 0;
}
+233 -83
View File
@@ -1,11 +1,16 @@
/* /*
* cat/vm.c -- stack virtual machine. * cat/vm.c -- stack virtual machine with resumable frames.
* *
* Naming rule: symbols here are cat_vm_* / CAT_VM_*. * Naming rule: symbols here are cat_vm_* / CAT_VM_*.
* *
* The VM is a simple stack machine. It knows nothing about concrete * Execution happens inside a CAT_VM_Frame, which holds the instruction
* types: every operator goes through cat_value_* dispatch, so new value * pointer, operand stack, locals and active `try` handlers. Because a
* types added purely through the C API work without touching the VM. * frame is a plain struct, a generator is simply a frame that suspended
* at `yield` and can be resumed later.
*
* The VM knows nothing about concrete types: every operator goes through
* cat_value_* dispatch, so new value types added purely through the C API
* work without touching the VM.
*/ */
#include "cat/vm.h" #include "cat/vm.h"
#include "cat/bytecode.h" #include "cat/bytecode.h"
@@ -14,9 +19,11 @@
#include "cat/types/int.h" #include "cat/types/int.h"
#include "cat/types/float.h" #include "cat/types/float.h"
#include "cat/types/text.h" #include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/table.h" #include "cat/types/table.h"
#include "cat/types/function.h" #include "cat/types/function.h"
#include "cat/types/native.h" #include "cat/types/native.h"
#include "cat/types/generator.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@@ -78,42 +85,65 @@ static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from)
{ {
if (from->raised) { if (from->raised) {
cat_error_raise(&vm->err, "%s", from->message); cat_error_raise(&vm->err, "%s", from->message);
vm->err.value = from->value;
return -1; return -1;
} }
return 0; return 0;
} }
/* Call any callable value: native, closure, or generator factory. A
* closure whose prototype contains `yield` is not executed here; it
* produces a generator (lazy). */
static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out,
CAT_ERROR_Error *err);
static void print_value(CAT_VALUE_Value *v)
{
if (v == NULL)
printf("nil\n");
else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT)
printf("%s\n", cat_types_text_bytes(v));
else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
if (((CAT_TYPES_NUMBER_Number *)v)->is_float)
printf("%g\n", cat_types_number_as_double(v));
else
printf("%lld\n", cat_types_number_as_int(v));
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL)
printf("%s\n", ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false");
else if (v == cat_types_nil_get())
printf("nil\n");
else
printf("<%s>\n", cat_value_type_name(v));
}
/* ---- the interpreter loop -------------------------------------------- */ /* ---- the interpreter loop -------------------------------------------- */
/* Frames are implemented as recursion over cat_vm_exec_closure so that /* Run (or resume) a frame until it returns, yields, or raises. Returns:
* closures can call each other through the object system naturally. */ * 0 the frame returned; *out = return value, frame not resumable
int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, * 1 the frame yielded; *out = yielded value, frame resumable
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) * -1 the frame raised; vm->err set
*/
int cat_vm_frame_run(CAT_VM_State *vm, CAT_VM_Frame *f, CAT_VALUE_Value **out)
{ {
CAT_BYTECODE_Function *fn = cl->proto; CAT_BYTECODE_Function *fn = f->fn;
CAT_VALUE_Value **stack; CAT_VALUE_Value **stack = f->stack;
CAT_VALUE_Value *locals[256]; CAT_VALUE_Value *locals[256];
int sp = 0; int sp = f->sp;
int i, ip = 0, rc = 0; int rc = 0;
CAT_ERROR_Error e; CAT_ERROR_Error e;
CAT_VM_State *prev_vm = g_current_vm; CAT_VM_State *prev_vm = g_current_vm;
stack = calloc((size_t)(fn->ncode + 64), sizeof(*stack)); /* locals are part of the frame (persist across yields) */
if (stack == NULL) { memcpy(locals, f->locals, sizeof(locals));
cat_error_raise(&vm->err, "out of memory");
return -1;
}
for (i = 0; i < 256; i++)
locals[i] = NULL;
for (i = 0; i < nargs && i < fn->nparams && i < 256; i++)
locals[i] = args[i];
g_current_vm = vm; g_current_vm = vm;
cat_error_clear(&e); cat_error_clear(&e);
*out = cat_types_nil_get(); *out = cat_types_nil_get();
while (ip < fn->ncode) { while (f->ip < fn->ncode) {
CAT_BYTECODE_Instr *in = &fn->code[ip]; CAT_BYTECODE_Instr *in = &fn->code[f->ip];
int ip = f->ip;
switch (in->op) { switch (in->op) {
case CAT_BYTECODE_OP_NOP: case CAT_BYTECODE_OP_NOP:
break; break;
@@ -163,7 +193,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
else else
snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx)); snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx));
if (cat_value_get_attribute(obj, key, &r, &e) != 0) { if (cat_value_get_attribute(obj, key, &r, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
stack[sp++] = r; stack[sp++] = r;
break; break;
@@ -178,7 +208,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
else else
snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx)); snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx));
if (cat_value_set_attribute(obj, key, val, &e) != 0) { if (cat_value_set_attribute(obj, key, val, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
break; break;
} }
@@ -196,7 +226,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
else if (in->op == CAT_BYTECODE_OP_MUL) st = cat_value_mul(a, b, &r, &e); else if (in->op == CAT_BYTECODE_OP_MUL) st = cat_value_mul(a, b, &r, &e);
else if (in->op == CAT_BYTECODE_OP_DIV) st = cat_value_div(a, b, &r, &e); else if (in->op == CAT_BYTECODE_OP_DIV) st = cat_value_div(a, b, &r, &e);
else st = cat_value_rem(a, b, &r, &e); else st = cat_value_rem(a, b, &r, &e);
if (st != 0) { rc = deliver_error(vm, &e); goto done; } if (st != 0) { deliver_error(vm, &e); goto on_error; }
stack[sp++] = r; stack[sp++] = r;
break; break;
} }
@@ -205,7 +235,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value *a = stack[--sp]; CAT_VALUE_Value *a = stack[--sp];
CAT_VALUE_Value *r = NULL; CAT_VALUE_Value *r = NULL;
if (cat_types_text_concat(a, b, &r, &e) != 0) { if (cat_types_text_concat(a, b, &r, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
stack[sp++] = r; stack[sp++] = r;
break; break;
@@ -215,7 +245,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value *zero = cat_types_int_new(0); CAT_VALUE_Value *zero = cat_types_int_new(0);
CAT_VALUE_Value *r = NULL; CAT_VALUE_Value *r = NULL;
if (cat_value_sub(zero, a, &r, &e) != 0) { if (cat_value_sub(zero, a, &r, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
stack[sp++] = r; stack[sp++] = r;
break; break;
@@ -256,8 +286,6 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
cmp = (av < bv) ? -1 : (av > bv) ? 1 : 0; cmp = (av < bv) ? -1 : (av > bv) ? 1 : 0;
eq = (cmp == 0); has_cmp = 1; eq = (cmp == 0); has_cmp = 1;
} else { } else {
/* Values of different kinds are never equal and never
* ordered; distinct objects compare unequal. */
eq = 0; has_cmp = 0; cmp = 0; eq = 0; has_cmp = 0; cmp = 0;
} }
{ {
@@ -284,7 +312,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
if (cat_value_get_attribute(obj, if (cat_value_get_attribute(obj,
cat_types_text_bytes(fn->consts[in->a].value), cat_types_text_bytes(fn->consts[in->a].value),
&r, &e) != 0) { &r, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
stack[sp++] = r; stack[sp++] = r;
break; break;
@@ -295,7 +323,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
if (cat_value_set_attribute(obj, if (cat_value_set_attribute(obj,
cat_types_text_bytes(fn->consts[in->a].value), cat_types_text_bytes(fn->consts[in->a].value),
val, &e) != 0) { val, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
break; break;
} }
@@ -303,22 +331,9 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
int n = in->a; int n = in->a;
CAT_VALUE_Value *fnv = stack[sp - n - 1]; CAT_VALUE_Value *fnv = stack[sp - n - 1];
CAT_VALUE_Value *r = NULL; CAT_VALUE_Value *r = NULL;
int st = 0; int st;
/* native? */ st = call_value(vm, fnv, &stack[sp - n], n, &r, &e);
if (fnv != NULL && fnv->vtable && if (st != 0) { deliver_error(vm, &e); goto on_error; }
fnv->vtable->kind == CAT_VALUE_KIND_TABLE) {
int j;
for (j = 0; j < vm->nnatives; j++) {
CAT_VALUE_Value *g = cat_vm_get_global(vm, vm->natives[j].name);
if (g == fnv) {
st = vm->natives[j].cb(vm, &stack[sp - n], n, &r);
break;
}
}
} else {
st = cat_value_call(fnv, &stack[sp - n], n, &r, &e);
}
if (st != 0) { rc = deliver_error(vm, &e); goto done; }
sp -= n + 1; sp -= n + 1;
stack[sp++] = r ? r : cat_types_nil_get(); stack[sp++] = r ? r : cat_types_nil_get();
break; break;
@@ -328,30 +343,19 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value *obj = stack[sp - n - 1]; CAT_VALUE_Value *obj = stack[sp - n - 1];
CAT_VALUE_Value *method = NULL; CAT_VALUE_Value *method = NULL;
CAT_VALUE_Value *callargs[257]; CAT_VALUE_Value *callargs[257];
int i; int j;
if (cat_value_get_attribute(obj, if (cat_value_get_attribute(obj,
cat_types_text_bytes(fn->consts[in->b].value), cat_types_text_bytes(fn->consts[in->b].value),
&method, &e) != 0) { &method, &e) != 0) {
rc = deliver_error(vm, &e); goto done; deliver_error(vm, &e); goto on_error;
} }
/* A method is called with the receiver as its first argument. */
callargs[0] = obj; callargs[0] = obj;
for (i = 0; i < n && i < 256; i++) for (j = 0; j < n && j < 256; j++)
callargs[i + 1] = stack[sp - n + i]; callargs[j + 1] = stack[sp - n + j];
{ {
CAT_VALUE_Value *r = NULL; CAT_VALUE_Value *r = NULL;
int st = 0; int st = call_value(vm, method, callargs, n + 1, &r, &e);
int j; if (st != 0) { deliver_error(vm, &e); goto on_error; }
for (j = 0; j < vm->nnatives; j++) {
CAT_VALUE_Value *g = cat_vm_get_global(vm, vm->natives[j].name);
if (g == method) {
st = vm->natives[j].cb(vm, callargs, n + 1, &r);
break;
}
}
if (st == 0 && j == vm->nnatives)
st = cat_value_call(method, callargs, n + 1, &r, &e);
if (st != 0) { rc = deliver_error(vm, &e); goto done; }
sp -= n + 1; sp -= n + 1;
stack[sp++] = r ? r : cat_types_nil_get(); stack[sp++] = r ? r : cat_types_nil_get();
} }
@@ -361,57 +365,203 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
stack[sp++] = cat_types_function_new(fn->protos[in->a]); stack[sp++] = cat_types_function_new(fn->protos[in->a]);
break; break;
case CAT_BYTECODE_OP_JUMP: case CAT_BYTECODE_OP_JUMP:
ip = in->a; f->ip = in->a;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
continue; continue;
case CAT_BYTECODE_OP_JUMPIF: { case CAT_BYTECODE_OP_JUMPIF: {
CAT_VALUE_Value *c = stack[--sp]; CAT_VALUE_Value *c = stack[--sp];
int t = 1; int t = 1;
cat_value_truthy(c, &t, &e); cat_value_truthy(c, &t, &e);
if (t) { ip = in->a; continue; } if (t) {
f->ip = in->a;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
continue;
}
break; break;
} }
case CAT_BYTECODE_OP_JUMPIFNOT: { case CAT_BYTECODE_OP_JUMPIFNOT: {
CAT_VALUE_Value *c = stack[--sp]; CAT_VALUE_Value *c = stack[--sp];
int t = 1; int t = 1;
cat_value_truthy(c, &t, &e); cat_value_truthy(c, &t, &e);
if (!t) { ip = in->a; continue; } if (!t) {
f->ip = in->a;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
continue;
}
break; break;
} }
case CAT_BYTECODE_OP_RETURN: case CAT_BYTECODE_OP_RETURN:
*out = stack[--sp]; *out = stack[--sp];
rc = 0;
goto done; goto done;
case CAT_BYTECODE_OP_RETURN0: case CAT_BYTECODE_OP_RETURN0:
*out = cat_types_nil_get(); *out = cat_types_nil_get();
rc = 0;
goto done; goto done;
case CAT_BYTECODE_OP_YIELD: {
/* suspend: value on top is the yielded value */
*out = stack[--sp];
f->ip = ip + 1;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
rc = 1; /* yielded */
goto done;
}
case CAT_BYTECODE_OP_NEXT: {
CAT_VALUE_Value *it = stack[--sp];
CAT_VALUE_Value *r = NULL;
int nr = cat_value_next(it, &r, &e);
if (nr < 0) {
deliver_error(vm, &e); goto on_error;
}
/* NEXT yields nil when exhausted (method-style use). */
stack[sp++] = (nr == 0 && r) ? r : cat_types_nil_get();
break;
}
case CAT_BYTECODE_OP_FORNEXT: {
/* pop iterator; push next value, or jump to A when exhausted */
CAT_VALUE_Value *it = stack[--sp];
CAT_VALUE_Value *r = NULL;
int nr = cat_value_next(it, &r, &e);
if (nr < 0) {
deliver_error(vm, &e); goto on_error;
}
if (nr == 1) {
f->ip = in->a;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
continue;
}
stack[sp++] = r ? r : cat_types_nil_get();
break;
}
case CAT_BYTECODE_OP_TRYSETUP:
if (f->nhandlers < CAT_VM_MAXHANDLER) {
f->handlers[f->nhandlers].target = in->a;
f->handlers[f->nhandlers].sp = sp;
f->nhandlers++;
}
break;
case CAT_BYTECODE_OP_TRYEND:
if (f->nhandlers > 0)
f->nhandlers--;
break;
case CAT_BYTECODE_OP_RAISE: {
CAT_VALUE_Value *v = stack[--sp];
const char *msg = (v && v->vtable &&
v->vtable->kind == CAT_VALUE_KIND_TEXT)
? cat_types_text_bytes(v) : "raised";
cat_error_raise_value(&vm->err, v, "%s", msg);
goto on_error;
}
case CAT_BYTECODE_OP_PRINT: { case CAT_BYTECODE_OP_PRINT: {
CAT_VALUE_Value *v = stack[--sp]; CAT_VALUE_Value *v = stack[--sp];
if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) print_value(v);
printf("%s\n", cat_types_text_bytes(v));
else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
if (((CAT_TYPES_NUMBER_Number *)v)->is_float)
printf("%g\n", cat_types_number_as_double(v));
else
printf("%lld\n", cat_types_number_as_int(v));
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL)
printf("%s\n", ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false");
else if (v == cat_types_nil_get())
printf("nil\n");
else
printf("<%s>\n", cat_value_type_name(v));
break; break;
} }
default: default:
break; break;
} }
ip++; (void)ip;
f->ip++;
continue;
on_error:
/* An error occurred. If a `try` handler is active, unwind to it:
* restore the stack, push the error value, and continue at the
* handler. Otherwise the frame fails and the error propagates. */
if (f->nhandlers > 0) {
CAT_VM_Handler *h = &f->handlers[--f->nhandlers];
sp = h->sp;
if (vm->err.value != NULL)
stack[sp++] = vm->err.value;
else
stack[sp++] = cat_types_ascii_text_new(vm->err.message);
f->ip = h->target;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
cat_error_clear(&vm->err);
continue;
}
rc = -1;
goto done;
} }
/* fell off the end */
*out = cat_types_nil_get();
rc = 0;
done: done:
/* Persist frame state so a generator can resume exactly here. */
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
g_current_vm = prev_vm; g_current_vm = prev_vm;
free(stack);
return rc; return rc;
} }
/* ---- calling a closure from C ---------------------------------------- */
int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out)
{
CAT_VM_Frame f;
CAT_VALUE_Value **stack;
CAT_VALUE_Value *val = NULL;
int rc, i;
/* A generator function does not run on call: it yields a generator. */
if (cl->proto != NULL && cl->proto->is_generator) {
*out = cat_types_generator_new(vm, cl, args, nargs);
return 0;
}
memset(&f, 0, sizeof(f));
f.fn = cl->proto;
f.cl = cl;
stack = calloc((size_t)(f.fn->ncode + 64), sizeof(*stack));
if (stack == NULL)
return (cat_error_raise(&vm->err, "out of memory"), -1);
f.stack = stack;
f.ip = 0;
f.sp = 0;
f.nhandlers = 0;
for (i = 0; i < 256; i++)
f.locals[i] = NULL;
for (i = 0; i < nargs && i < f.fn->nparams && i < 256; i++)
f.locals[i] = args[i];
rc = cat_vm_frame_run(vm, &f, &val);
free(stack);
if (rc < 0)
return -1;
*out = val ? val : cat_types_nil_get();
return 0;
}
static int call_value(CAT_VM_State *vm, CAT_VALUE_Value *fnv,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
if (fnv != NULL && fnv->vtable &&
fnv->vtable->kind == CAT_VALUE_KIND_FUNCTION &&
fnv->vtable == cat_types_function_vtable()) {
CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)fnv;
int st;
/* generator factory */
if (cl->proto != NULL && cl->proto->is_generator) {
*out = cat_types_generator_new(vm, cl, args, nargs);
return 0;
}
st = cat_vm_exec_closure(vm, cl, args, nargs, out);
if (st != 0 && vm->err.raised)
cat_error_raise(err, "%s", vm->err.message);
return st;
}
return cat_value_call(fnv, args, nargs, out, err);
}
int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **out) int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **out)
{ {
CAT_TYPES_FUNCTION_Closure cl; CAT_TYPES_FUNCTION_Closure cl;
+27
View File
@@ -63,6 +63,33 @@ check "file-stringio" "stringio: hello, catscript" "`echo "$out" | sed -n 1p`"
check "file-bytesio" "bytesio: bytes io" "`echo "$out" | sed -n 2p`" check "file-bytesio" "bytesio: bytes io" "`echo "$out" | sed -n 2p`"
check "file-open" "file: line one" "`echo "$out" | sed -n 3p`" check "file-open" "file: line one" "`echo "$out" | sed -n 3p`"
check "file-hints" "n=3 buf=abc" "`echo "$out" | sed -n 5p`" check "file-hints" "n=3 buf=abc" "`echo "$out" | sed -n 5p`"
# ---- generators / iterators (yield, next, for..in) ------------------
out=`$BIN examples/generators.cat`
check "gen-type" "type: generator" "`echo "$out" | sed -n 1p`"
check "gen-next-1" "next: 1" "`echo "$out" | sed -n 2p`"
check "gen-next-nil" "next: nil" "`echo "$out" | sed -n 5p`"
check "gen-forin-sum" "sum 1..5 = 15" "`echo "$out" | sed -n 6p`"
check "gen-break-lazy" "taken < 3: 3" "`echo "$out" | sed -n 7p`"
# ---- errors (raise, try, except) ------------------------------------
out=`$BIN examples/errors.cat`
check "err-ok" "ok: 42" "`echo "$out" | sed -n 1p`"
check "err-catch" "caught: boom" "`echo "$out" | sed -n 2p`"
check "err-struct-code" "code: 42" "`echo "$out" | sed -n 3p`"
check "err-struct-what" "what: custom" "`echo "$out" | sed -n 4p`"
check "err-propagate" "propagated: negative not allowed" "`echo "$out" | sed -n 5p`"
check "err-survive" "still running" "`echo "$out" | sed -n 6p`"
# ---- slots: C-known object layout -----------------------------------
out=`$BIN examples/slots.cat`
check "slot-path" "path: /tmp/catscript_slots_demo.txt" "`echo "$out" | sed -n 1p`"
check "slot-mode" "mode: 2" "`echo "$out" | sed -n 2p`"
check "slot-closed" "closed: false" "`echo "$out" | sed -n 3p`"
check "slot-closed-2" "closed: true" "`echo "$out" | sed -n 4p`"
# ---- bytecode dump --------------------------------------------------- # ---- bytecode dump ---------------------------------------------------
out=`$BIN --dump examples/hello.cat` out=`$BIN --dump examples/hello.cat`