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

+98 -2
View File
@@ -41,6 +41,7 @@ typedef struct {
CAT_BYTECODE_Function *fn;
char locals[MAXLOCALS][64];
int nlocals;
int is_generator; /* body used `yield` */
} FuncCtx;
typedef struct {
@@ -265,6 +266,9 @@ static int compile_function_literal(Compiler *c, const char *name)
c->stack[c->nstack++] = nc;
block(c);
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);
c->nstack--;
@@ -648,6 +652,37 @@ static void stat(Compiler *c)
next(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, "'='");
expr(c); /* start */
expect(c, CAT_LEXER_TOK_COMMA, "','");
@@ -711,7 +746,8 @@ static void stat(Compiler *c)
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_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) &&
!check(c, CAT_LEXER_TOK_EXCEPT)) {
expr(c);
emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line);
} else {
@@ -720,6 +756,66 @@ static void stat(Compiler *c)
accept(c, CAT_LEXER_TOK_SEMI);
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: {
/* assignment if `name =`, or field assignment if `name.attr =`.
* 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) &&
!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;
/* a lone ';' is a valid empty statement, not a parse error */
if (check(c, CAT_LEXER_TOK_SEMI)) {
+17
View File
@@ -4,6 +4,7 @@
* Naming rule: symbols here are cat_error_* / CAT_ERROR_*.
*/
#include "cat/error.h"
#include "cat/value.h"
#include <stdarg.h>
#include <stdio.h>
@@ -15,6 +16,7 @@ void cat_error_clear(CAT_ERROR_Error *err)
return;
err->raised = false;
err->message[0] = '\0';
err->value = NULL;
}
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);
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 },
{ "else", CAT_LEXER_TOK_ELSE },
{ "elseif", CAT_LEXER_TOK_ELSEIF },
{ "except", CAT_LEXER_TOK_EXCEPT },
{ "end", CAT_LEXER_TOK_END },
{ "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR },
@@ -32,11 +33,14 @@ static const struct kw g_keywords[] = {
{ "not", CAT_LEXER_TOK_NOT },
{ "or", CAT_LEXER_TOK_OR },
{ "repeat", CAT_LEXER_TOK_REPEAT },
{ "raise", CAT_LEXER_TOK_RAISE },
{ "return", CAT_LEXER_TOK_RETURN },
{ "then", CAT_LEXER_TOK_THEN },
{ "true", CAT_LEXER_TOK_TRUE },
{ "try", CAT_LEXER_TOK_TRY },
{ "until", CAT_LEXER_TOK_UNTIL },
{ "while", CAT_LEXER_TOK_WHILE },
{ "yield", CAT_LEXER_TOK_YIELD },
};
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",
"function", "if", "in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while",
"yield", "try", "except", "raise",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<",
">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":",
"::", "..", "->"
+31 -3
View File
@@ -24,6 +24,7 @@
#include "cat/types/table.h"
#include "cat/error.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -230,10 +231,38 @@ static void file_destroy(CAT_VALUE_Value *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 = {
.type_name = "File",
.kind = CAT_VALUE_KIND_TABLE,
.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,
};
@@ -241,7 +270,6 @@ CAT_VALUE_Vtable *cat_types_file_abstract_vtable(void)
{
return &g_file_vtable;
}
/* ---- constructors ---------------------------------------------------- */
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)
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.is_bytes = 1; /* in-memory */
m->cap = 128;
@@ -313,7 +341,7 @@ CAT_VALUE_Value *cat_types_file_bytesio(void)
if (m == NULL)
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->cap = 128;
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/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 <stdlib.h>
#include <string.h>
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,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(self) == NULL || vt(self)->get_attribute.fn == NULL)
return (cat_error_raise(err,
"type %s has no attributes", cat_value_type_name(self)), -1);
return vt(self)->get_attribute.fn(self, name, out, err);
const CAT_VALUE_Slot *s;
if (vt(self) != NULL && vt(self)->get_attribute.fn != NULL &&
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,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
if (vt(self) == NULL || vt(self)->set_attribute.fn == NULL)
return (cat_error_raise(err,
"type %s has no settable attributes",
cat_value_type_name(self)), -1);
return vt(self)->set_attribute.fn(self, name, value, err);
const CAT_VALUE_Slot *s;
if (vt(self) != NULL && vt(self)->set_attribute.fn != NULL &&
vt(self)->set_attribute.fn(self, name, value, err) == 0)
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)
@@ -133,3 +164,93 @@ int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
(void)r;
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_*.
*
* The VM is a simple stack machine. It 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.
* Execution happens inside a CAT_VM_Frame, which holds the instruction
* pointer, operand stack, locals and active `try` handlers. Because a
* 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/bytecode.h"
@@ -14,9 +19,11 @@
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/table.h"
#include "cat/types/function.h"
#include "cat/types/native.h"
#include "cat/types/generator.h"
#include <stdio.h>
#include <stdlib.h>
@@ -78,42 +85,65 @@ static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from)
{
if (from->raised) {
cat_error_raise(&vm->err, "%s", from->message);
vm->err.value = from->value;
return -1;
}
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 -------------------------------------------- */
/* Frames are implemented as recursion over cat_vm_exec_closure so that
* closures can call each other through the object system naturally. */
int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out)
/* Run (or resume) a frame until it returns, yields, or raises. Returns:
* 0 the frame returned; *out = return value, frame not resumable
* 1 the frame yielded; *out = yielded value, frame resumable
* -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_VALUE_Value **stack;
CAT_BYTECODE_Function *fn = f->fn;
CAT_VALUE_Value **stack = f->stack;
CAT_VALUE_Value *locals[256];
int sp = 0;
int i, ip = 0, rc = 0;
int sp = f->sp;
int rc = 0;
CAT_ERROR_Error e;
CAT_VM_State *prev_vm = g_current_vm;
stack = calloc((size_t)(fn->ncode + 64), sizeof(*stack));
if (stack == NULL) {
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];
/* locals are part of the frame (persist across yields) */
memcpy(locals, f->locals, sizeof(locals));
g_current_vm = vm;
cat_error_clear(&e);
*out = cat_types_nil_get();
while (ip < fn->ncode) {
CAT_BYTECODE_Instr *in = &fn->code[ip];
while (f->ip < fn->ncode) {
CAT_BYTECODE_Instr *in = &fn->code[f->ip];
int ip = f->ip;
switch (in->op) {
case CAT_BYTECODE_OP_NOP:
break;
@@ -163,7 +193,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
else
snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx));
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;
break;
@@ -178,7 +208,7 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
else
snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx));
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;
}
@@ -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_DIV) st = cat_value_div(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;
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 *r = NULL;
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;
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 *r = NULL;
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;
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;
eq = (cmp == 0); has_cmp = 1;
} else {
/* Values of different kinds are never equal and never
* ordered; distinct objects compare unequal. */
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,
cat_types_text_bytes(fn->consts[in->a].value),
&r, &e) != 0) {
rc = deliver_error(vm, &e); goto done;
deliver_error(vm, &e); goto on_error;
}
stack[sp++] = r;
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,
cat_types_text_bytes(fn->consts[in->a].value),
val, &e) != 0) {
rc = deliver_error(vm, &e); goto done;
deliver_error(vm, &e); goto on_error;
}
break;
}
@@ -303,22 +331,9 @@ int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
int n = in->a;
CAT_VALUE_Value *fnv = stack[sp - n - 1];
CAT_VALUE_Value *r = NULL;
int st = 0;
/* native? */
if (fnv != NULL && fnv->vtable &&
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; }
int st;
st = call_value(vm, fnv, &stack[sp - n], n, &r, &e);
if (st != 0) { deliver_error(vm, &e); goto on_error; }
sp -= n + 1;
stack[sp++] = r ? r : cat_types_nil_get();
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 *method = NULL;
CAT_VALUE_Value *callargs[257];
int i;
int j;
if (cat_value_get_attribute(obj,
cat_types_text_bytes(fn->consts[in->b].value),
&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;
for (i = 0; i < n && i < 256; i++)
callargs[i + 1] = stack[sp - n + i];
for (j = 0; j < n && j < 256; j++)
callargs[j + 1] = stack[sp - n + j];
{
CAT_VALUE_Value *r = NULL;
int st = 0;
int j;
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; }
int st = call_value(vm, method, callargs, n + 1, &r, &e);
if (st != 0) { deliver_error(vm, &e); goto on_error; }
sp -= n + 1;
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]);
break;
case CAT_BYTECODE_OP_JUMP:
ip = in->a;
f->ip = in->a;
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
continue;
case CAT_BYTECODE_OP_JUMPIF: {
CAT_VALUE_Value *c = stack[--sp];
int t = 1;
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;
}
case CAT_BYTECODE_OP_JUMPIFNOT: {
CAT_VALUE_Value *c = stack[--sp];
int t = 1;
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;
}
case CAT_BYTECODE_OP_RETURN:
*out = stack[--sp];
rc = 0;
goto done;
case CAT_BYTECODE_OP_RETURN0:
*out = cat_types_nil_get();
rc = 0;
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: {
CAT_VALUE_Value *v = stack[--sp];
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));
print_value(v);
break;
}
default:
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:
/* Persist frame state so a generator can resume exactly here. */
f->sp = sp;
memcpy(f->locals, locals, sizeof(locals));
g_current_vm = prev_vm;
free(stack);
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)
{
CAT_TYPES_FUNCTION_Closure cl;