catscript: núcleo C, stdlib (TOML), família de arquivos e front-end self-hosted

- Modelo de objetos Cat_Value + vtable (interfaces abstratas)
- VM de bytecode, sem GIL (VM por-thread, nativas como valores)
- Stdlib com TOML embutido (toml_parse/toml_encode)
- Família de arquivos: AbstractFile (abstrata), File::open, StringIO, BytesIO
- Front-end (lexer/parser/checker/compiler) implementado em catscript
- cpk (cat package manager) como primeiro programa; manifest package.toml
- Type hints advisory, inclusive DynSized() e sentinel_sized<...>
- 25/25 testes passando (make test)
This commit is contained in:
Minus committed 2026-11-16 01:27:44 +00:00
commit 52d118211f
69 files changed
+6938

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
/*
* cat/bytecode.c -- bytecode construction and disassembly.
*
* Naming rule: symbols here are cat_bytecode_* / CAT_BYTECODE_*.
*/
#include "cat/bytecode.h"
#include "cat/error.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name)
{
CAT_BYTECODE_Function *fn = calloc(1, sizeof(*fn));
if (fn == NULL)
return NULL;
fn->name = strdup(name ? name : "<anon>");
return fn;
}
int cat_bytecode_emit(CAT_BYTECODE_Function *fn, unsigned char op,
int a, int b, int c, int line)
{
if (fn->ncode == fn->capcode) {
int nc = fn->capcode ? fn->capcode * 2 : 16;
CAT_BYTECODE_Instr *ni = realloc(fn->code, (size_t)nc * sizeof(*ni));
if (ni == NULL)
return -1;
fn->code = ni;
fn->capcode = nc;
}
fn->code[fn->ncode].op = op;
fn->code[fn->ncode].a = a;
fn->code[fn->ncode].b = b;
fn->code[fn->ncode].c = c;
fn->code[fn->ncode].line = line;
return fn->ncode++;
}
int cat_bytecode_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v)
{
int i;
for (i = 0; i < fn->nconsts; i++)
if (fn->consts[i].value == v)
return i;
if (fn->nconsts == fn->capconsts) {
int nc = fn->capconsts ? fn->capconsts * 2 : 8;
CAT_BYTECODE_Constant *ncp =
realloc(fn->consts, (size_t)nc * sizeof(*ncp));
if (ncp == NULL)
return -1;
fn->consts = ncp;
fn->capconsts = nc;
}
fn->consts[fn->nconsts].value = v;
return fn->nconsts++;
}
int cat_bytecode_add_proto(CAT_BYTECODE_Function *fn, CAT_BYTECODE_Function *p)
{
if (fn->nprotos == fn->capprotos) {
int nc = fn->capprotos ? fn->capprotos * 2 : 4;
CAT_BYTECODE_Function **np =
realloc(fn->protos, (size_t)nc * sizeof(*np));
if (np == NULL)
return -1;
fn->protos = np;
fn->capprotos = nc;
}
fn->protos[fn->nprotos] = p;
return fn->nprotos++;
}
/* opcode -> mnemonic, indexed by CAT_BYTECODE_Op. */
static const char *op_name(unsigned char op)
{
static const char *names[] = {
"NOP", "CONST", "NIL", "TRUE", "FALSE", "GETLOCAL", "SETLOCAL",
"GETGLOBAL", "SETGLOBAL", "ADD", "SUB", "MUL", "DIV", "REM",
"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"
};
if (op < sizeof(names) / sizeof(names[0]))
return names[op];
return "?";
}
void cat_bytecode_dump(CAT_BYTECODE_Function *fn, FILE *out)
{
int i;
fprintf(out, "== function %s (params=%d locals=%d consts=%d) ==\n",
fn->name, fn->nparams, fn->nlocals, fn->nconsts);
for (i = 0; i < fn->nconsts; i++)
fprintf(out, " const[%d] = %s\n", i,
cat_value_type_name(fn->consts[i].value));
for (i = 0; i < fn->ncode; i++) {
CAT_BYTECODE_Instr *in = &fn->code[i];
fprintf(out, " %04d %-10s %d %d %d\n", i, op_name(in->op),
in->a, in->b, in->c);
}
for (i = 0; i < fn->nprotos; i++)
cat_bytecode_dump(fn->protos[i], out);
}
void cat_bytecode_function_free(CAT_BYTECODE_Function *fn)
{
int i;
if (fn == NULL)
return;
/* Constant VALUES are intentionally not destroyed here. A chunk's
* constants may be shared (e.g. a chunk built from a catscript table
* via bc_run borrows the table's values), and destroying them would
* double-free. The pool itself is freed; leaked values are bounded
* by the number of compilations in a single run. */
(void)i;
for (i = 0; i < fn->nprotos; i++)
cat_bytecode_function_free(fn->protos[i]);
free(fn->code);
free(fn->consts);
free(fn->protos);
free(fn->name);
free(fn);
}
+848
View File
@@ -0,0 +1,848 @@
/*
* cat/compiler.c -- source -> bytecode, recursive descent + Pratt exprs.
*
* Naming rule: symbols here are cat_compiler_* / CAT_COMPILER_*.
*
* Grammar (Lua-like):
* chunk := { stat }
* stat := `;`
* | `local` NAME [`: type`] [`=` expr]
* | `local` `function` NAME `(` params `)` chunk `end`
* | `function` NAME `(` params `)` [`->` type] chunk `end`
* | NAME `=` expr
* | `if` expr `then` chunk { `elseif` expr `then` chunk }
* [`else` chunk] `end`
* | `while` expr `do` chunk `end`
* | `repeat` chunk `until` expr
* | `for` NAME `=` expr `,` expr [`,` expr] `do` chunk `end`
* | `return` [expr]
* | expr
* expr := precedence-climbing; primaries carry call/index suffixes.
*
* Type hints (`: type`, `-> ret`) are parsed and discarded: typing is
* structural at runtime, so hints are advisory documentation only.
*/
#include "cat/compiler.h"
#include "cat/lexer.h"
#include "cat/error.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/ascii_text.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLOCALS 256
/* One lexical scope: the function being compiled plus its locals. */
typedef struct {
CAT_BYTECODE_Function *fn;
char locals[MAXLOCALS][64];
int nlocals;
} FuncCtx;
typedef struct {
CAT_LEXER_Lexer lx;
CAT_LEXER_Token tok;
CAT_ERROR_Error *err;
int failed;
FuncCtx stack[32];
int nstack;
/* break handling: pending break jumps per active loop */
int brk_ends[16][64];
int brk_n[16];
int nloops;
} Compiler;
static void err_at(Compiler *c, int line, const char *fmt, ...)
{
va_list ap;
char msg[200];
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
cat_error_raise(c->err, "line %d: %s", line, msg);
c->failed = 1;
}
/* ---- token cursor ---------------------------------------------------- */
static void next(Compiler *c)
{
cat_lexer_next(&c->lx, &c->tok);
}
static int check(Compiler *c, int kind)
{
return c->tok.kind == kind;
}
static int accept(Compiler *c, int kind)
{
if (check(c, kind)) {
next(c);
return 1;
}
return 0;
}
static void expect(Compiler *c, int kind, const char *what)
{
if (!accept(c, kind))
err_at(c, c->tok.line, "expected %s, got %s", what,
cat_lexer_kind_name(c->tok.kind));
}
static CAT_BYTECODE_Function *cur_fn(Compiler *c);
static int emit(Compiler *c, int op, int a, int b, int line)
{
return cat_bytecode_emit(cur_fn(c), (unsigned char)op, a, b, 0, line);
}
static FuncCtx *ctx(Compiler *c)
{
return &c->stack[c->nstack - 1];
}
static int add_string(Compiler *c, const char *s)
{
return cat_bytecode_add_const(cur_fn(c), cat_types_ascii_text_new(s));
}
static CAT_BYTECODE_Function *cur_fn(Compiler *c)
{
return ctx(c)->fn;
}
static int find_local(Compiler *c, const char *name)
{
FuncCtx *f = ctx(c);
int i;
for (i = f->nlocals - 1; i >= 0; i--)
if (strcmp(f->locals[i], name) == 0)
return i;
return -1;
}
static int add_local(Compiler *c, const char *name)
{
FuncCtx *f = ctx(c);
int slot;
if (f->nlocals >= MAXLOCALS)
return -1;
slot = f->nlocals++;
snprintf(f->locals[slot], sizeof(f->locals[slot]), "%s", name);
if (f->nlocals > f->fn->nlocals)
f->fn->nlocals = f->nlocals;
return slot;
}
/* ---- forward decls --------------------------------------------------- */
static void expr(Compiler *c);
static void block(Compiler *c);
/* ---- expressions ----------------------------------------------------- */
static int binop_for(int kind)
{
switch (kind) {
case CAT_LEXER_TOK_PLUS: return CAT_BYTECODE_OP_ADD;
case CAT_LEXER_TOK_MINUS: return CAT_BYTECODE_OP_SUB;
case CAT_LEXER_TOK_STAR: return CAT_BYTECODE_OP_MUL;
case CAT_LEXER_TOK_SLASH: return CAT_BYTECODE_OP_DIV;
case CAT_LEXER_TOK_PERCENT: return CAT_BYTECODE_OP_REM;
case CAT_LEXER_TOK_CONCAT: return CAT_BYTECODE_OP_CONCAT;
case CAT_LEXER_TOK_EQ: return CAT_BYTECODE_OP_EQ;
case CAT_LEXER_TOK_NE: return CAT_BYTECODE_OP_NE;
case CAT_LEXER_TOK_LT: return CAT_BYTECODE_OP_LT;
case CAT_LEXER_TOK_LE: return CAT_BYTECODE_OP_LE;
case CAT_LEXER_TOK_GT: return CAT_BYTECODE_OP_GT;
case CAT_LEXER_TOK_GE: return CAT_BYTECODE_OP_GE;
default: return -1;
}
}
static int bp_of(int kind)
{
switch (kind) {
case CAT_LEXER_TOK_OR: return 1;
case CAT_LEXER_TOK_AND: return 2;
case CAT_LEXER_TOK_EQ: case CAT_LEXER_TOK_NE:
case CAT_LEXER_TOK_LT: case CAT_LEXER_TOK_LE:
case CAT_LEXER_TOK_GT: case CAT_LEXER_TOK_GE: return 3;
case CAT_LEXER_TOK_CONCAT: return 4;
case CAT_LEXER_TOK_PLUS: case CAT_LEXER_TOK_MINUS: return 5;
case CAT_LEXER_TOK_STAR: case CAT_LEXER_TOK_SLASH:
case CAT_LEXER_TOK_PERCENT: return 6;
default: return 0;
}
}
/* Skip an advisory type expression: e.g. `: int`, `: cbyte[]`,
* `: DynSized()`, `: sentinel_sized<'\0'>`. Types are advisory only
* (catscript is structurally typed), so we parse and discard a full
* balanced type expression, ignoring `()`, `<>`, `[]` nesting. */
static void skip_type_hint(Compiler *c)
{
int depth = 0;
if (!check(c, CAT_LEXER_TOK_COLON))
return;
next(c);
for (;;) {
int k = c->tok.kind;
if (k == CAT_LEXER_TOK_LPAREN || k == CAT_LEXER_TOK_LT ||
k == CAT_LEXER_TOK_LBRACKET) {
depth++;
next(c);
continue;
}
if (k == CAT_LEXER_TOK_RPAREN || k == CAT_LEXER_TOK_GT ||
k == CAT_LEXER_TOK_RBRACKET) {
if (depth == 0)
break;
depth--;
next(c);
continue;
}
if ((k == CAT_LEXER_TOK_NAME || k == CAT_LEXER_TOK_INT ||
k == CAT_LEXER_TOK_STRING) ||
(k == CAT_LEXER_TOK_COMMA && depth > 0)) {
next(c);
continue;
}
break;
}
}
/* Compile `function (params) body end` starting at `function`. */
static int compile_function_literal(Compiler *c, const char *name)
{
CAT_BYTECODE_Function *sub;
FuncCtx nc;
int proto;
expect(c, CAT_LEXER_TOK_LPAREN, "'('");
sub = cat_bytecode_function_new(name ? name : "anon");
memset(&nc, 0, sizeof(nc));
nc.fn = sub;
/* parse parameter list into the new context */
while (!check(c, CAT_LEXER_TOK_RPAREN) && !check(c, CAT_LEXER_TOK_EOF)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
char pn[64];
snprintf(pn, sizeof(pn), "%s", c->tok.text);
next(c);
skip_type_hint(c);
/* add_local into nc directly */
snprintf(nc.locals[nc.nlocals], sizeof(nc.locals[0]), "%s", pn);
nc.nlocals++;
sub->nparams++;
} else {
break;
}
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
expect(c, CAT_LEXER_TOK_RPAREN, "')'");
if (sub->nlocals < nc.nlocals)
sub->nlocals = nc.nlocals;
/* optional return type hint */
if (accept(c, CAT_LEXER_TOK_ARROW)) {
if (check(c, CAT_LEXER_TOK_NAME))
next(c);
}
/* push context and compile body */
c->stack[c->nstack++] = nc;
block(c);
expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, c->tok.line);
c->nstack--;
proto = cat_bytecode_add_proto(cur_fn(c), sub);
return proto;
}
/* primary + suffixes */
static void primary(Compiler *c)
{
CAT_LEXER_Token t = c->tok;
switch (t.kind) {
case CAT_LEXER_TOK_INT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_int_new(t.ival));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
}
case CAT_LEXER_TOK_FLOAT: {
int k = cat_bytecode_add_const(cur_fn(c), cat_types_float_new(t.fval));
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
}
case CAT_LEXER_TOK_STRING: {
int k = add_string(c, t.text);
emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line);
next(c);
break;
}
case CAT_LEXER_TOK_NIL:
emit(c, CAT_BYTECODE_OP_NIL, 0, 0, t.line);
next(c);
break;
case CAT_LEXER_TOK_TRUE:
emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, t.line);
next(c);
break;
case CAT_LEXER_TOK_FALSE:
emit(c, CAT_BYTECODE_OP_FALSE, 0, 0, t.line);
next(c);
break;
case CAT_LEXER_TOK_LPAREN:
next(c);
expr(c);
expect(c, CAT_LEXER_TOK_RPAREN, "')'");
break;
case CAT_LEXER_TOK_FUNCTION: {
int proto;
next(c);
proto = compile_function_literal(c, "anon");
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, t.line);
break;
}
case CAT_LEXER_TOK_LBRACE: {
int posidx = 1; /* positional elements are 1-based, like Lua */
next(c);
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, t.line);
while (!check(c, CAT_LEXER_TOK_RBRACE) && !check(c, CAT_LEXER_TOK_EOF)) {
if (check(c, CAT_LEXER_TOK_NAME) &&
c->lx.src[c->lx.pos] != '\0') {
/* lookahead for `key =` */
size_t sp = c->lx.pos;
int sl = c->lx.line;
CAT_LEXER_Token la;
char key[256];
snprintf(key, sizeof(key), "%s", c->tok.text);
cat_lexer_next(&c->lx, &la);
if (la.kind == CAT_LEXER_TOK_ASSIGN) {
c->tok = la;
next(c);
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
expr(c);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, key),
0, t.line);
} else {
/* positional element: emit idx, value, SETIDX */
char idxkey[32];
c->lx.pos = sp;
c->lx.line = sl;
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
(void)idxkey;
emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, t.line);
}
} else {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line);
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c),
cat_types_int_new(posidx++)),
0, t.line);
expr(c);
emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, t.line);
}
if (!accept(c, CAT_LEXER_TOK_COMMA) &&
!accept(c, CAT_LEXER_TOK_SEMI))
break;
}
expect(c, CAT_LEXER_TOK_RBRACE, "'}'");
break;
}
case CAT_LEXER_TOK_NAME: {
char name[256];
int slot;
snprintf(name, sizeof(name), "%s", t.text);
next(c);
slot = find_local(c, name);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, t.line);
else
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, t.line);
break;
}
default:
err_at(c, t.line, "unexpected token %s",
cat_lexer_kind_name(t.kind));
emit(c, CAT_BYTECODE_OP_NIL, 0, 0, t.line);
next(c);
return;
}
/* suffixes */
for (;;) {
if (check(c, CAT_LEXER_TOK_DOT)) {
next(c);
if (check(c, CAT_LEXER_TOK_NAME)) {
int k = add_string(c, c->tok.text);
emit(c, CAT_BYTECODE_OP_GETATTR, k, 0, c->tok.line);
next(c);
}
} else if ((check(c, CAT_LEXER_TOK_COLON) ||
check(c, CAT_LEXER_TOK_DCOLON)) &&
c->lx.src[c->lx.pos] != '\0') {
/* method call: obj:name(args), or class method:
* Class::name(args). Both call with the receiver as
* the implicit first argument (`self`). */
size_t sp = c->lx.pos;
int sl = c->lx.line;
CAT_LEXER_Token la;
cat_lexer_next(&c->lx, &la);
if (la.kind == CAT_LEXER_TOK_NAME) {
char mname[256];
int k, nargs = 0;
snprintf(mname, sizeof(mname), "%s", la.text);
c->tok = la;
next(c);
expect(c, CAT_LEXER_TOK_LPAREN, "'('");
while (!check(c, CAT_LEXER_TOK_RPAREN) &&
!check(c, CAT_LEXER_TOK_EOF)) {
expr(c);
nargs++;
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
expect(c, CAT_LEXER_TOK_RPAREN, "')'");
k = add_string(c, mname);
emit(c, CAT_BYTECODE_OP_CALLMETHOD, nargs, k, c->tok.line);
} else {
c->lx.pos = sp;
c->lx.line = sl;
break;
}
} else if (check(c, CAT_LEXER_TOK_LPAREN)) {
int nargs = 0;
next(c);
while (!check(c, CAT_LEXER_TOK_RPAREN) &&
!check(c, CAT_LEXER_TOK_EOF)) {
expr(c);
nargs++;
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
expect(c, CAT_LEXER_TOK_RPAREN, "')'");
emit(c, CAT_BYTECODE_OP_CALL, nargs, 0, c->tok.line);
} else if (check(c, CAT_LEXER_TOK_LBRACKET)) {
next(c);
expr(c);
expect(c, CAT_LEXER_TOK_RBRACKET, "']'");
emit(c, CAT_BYTECODE_OP_GETIDX, 0, 0, c->tok.line);
} else {
break;
}
}
}
static void unary(Compiler *c)
{
if (check(c, CAT_LEXER_TOK_MINUS)) {
next(c);
unary(c);
emit(c, CAT_BYTECODE_OP_NEG, 0, 0, c->tok.line);
} else if (check(c, CAT_LEXER_TOK_NOT)) {
next(c);
unary(c);
emit(c, CAT_BYTECODE_OP_NOT, 0, 0, c->tok.line);
} else if (check(c, CAT_LEXER_TOK_HASH)) {
next(c);
unary(c);
emit(c, CAT_BYTECODE_OP_GETATTR, add_string(c, "length"), 0, c->tok.line);
} else {
primary(c);
}
}
static void expr_bp(Compiler *c, int minbp)
{
unary(c);
for (;;) {
int kind = c->tok.kind;
int bp = bp_of(kind);
if (bp == 0 || bp < minbp)
break;
if (kind == CAT_LEXER_TOK_AND || kind == CAT_LEXER_TOK_OR) {
/* Short-circuit while keeping the stack balanced:
* a or b -> push a; DUP; JUMPIF L; POP; push b; L:
* a and b -> push a; DUP; JUMPIFNOT L; POP; push b; L:
* Only one value is left on the stack at L. */
int op = (kind == CAT_LEXER_TOK_AND) ?
CAT_BYTECODE_OP_JUMPIFNOT : CAT_BYTECODE_OP_JUMPIF;
int jmp;
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, c->tok.line);
jmp = emit(c, op, 0, 0, c->tok.line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, c->tok.line);
next(c);
expr_bp(c, bp + 1);
cur_fn(c)->code[jmp].a = cur_fn(c)->ncode;
continue;
}
next(c);
expr_bp(c, bp + 1);
emit(c, binop_for(kind), 0, 0, c->tok.line);
}
}
static void expr(Compiler *c)
{
expr_bp(c, 1);
}
/* ---- statements ------------------------------------------------------ */
static void stat(Compiler *c)
{
int line = c->tok.line;
switch (c->tok.kind) {
case CAT_LEXER_TOK_SEMI:
next(c);
break;
case CAT_LEXER_TOK_BREAK:
next(c);
if (c->nloops <= 0) {
err_at(c, line, "'break' outside a loop");
} else {
int lv = c->nloops - 1;
if (c->brk_n[lv] < 64)
c->brk_ends[lv][c->brk_n[lv]++] =
emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line);
}
break;
case CAT_LEXER_TOK_LOCAL:
next(c);
if (check(c, CAT_LEXER_TOK_FUNCTION)) {
char name[256];
int slot;
int proto;
next(c);
name[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
slot = add_local(c, name);
proto = compile_function_literal(c, name);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
break;
}
if (check(c, CAT_LEXER_TOK_NAME)) {
char name[256];
int slot;
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
skip_type_hint(c);
if (accept(c, CAT_LEXER_TOK_ASSIGN))
expr(c);
else
emit(c, CAT_BYTECODE_OP_NIL, 0, 0, line);
slot = add_local(c, name);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
}
break;
case CAT_LEXER_TOK_IF: {
int jfalse;
int ends[64];
int nends = 0;
next(c);
expr(c);
expect(c, CAT_LEXER_TOK_THEN, "'then'");
jfalse = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line);
block(c);
while (check(c, CAT_LEXER_TOK_ELSEIF)) {
next(c);
if (nends < 64)
ends[nends++] = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line);
cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode;
expr(c);
expect(c, CAT_LEXER_TOK_THEN, "'then'");
jfalse = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line);
block(c);
}
if (accept(c, CAT_LEXER_TOK_ELSE)) {
if (nends < 64)
ends[nends++] = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line);
cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode;
block(c);
} else {
cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode;
}
{
int k;
for (k = 0; k < nends; k++)
cur_fn(c)->code[ends[k]].a = cur_fn(c)->ncode;
}
expect(c, CAT_LEXER_TOK_END, "'end'");
break;
}
case CAT_LEXER_TOK_WHILE: {
int jcond, jend, lv;
next(c);
jcond = cur_fn(c)->ncode;
expr(c);
expect(c, CAT_LEXER_TOK_DO, "'do'");
jend = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line);
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;
}
case CAT_LEXER_TOK_REPEAT: {
int jtop, lv;
next(c);
jtop = cur_fn(c)->ncode;
lv = c->nloops++;
c->brk_n[lv] = 0;
block(c);
c->nloops--;
expect(c, CAT_LEXER_TOK_UNTIL, "'until'");
expr(c);
emit(c, CAT_BYTECODE_OP_JUMPIFNOT, jtop, 0, line);
{ 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; }
break;
}
case CAT_LEXER_TOK_FOR: {
char var[64];
int slot, jcond, jend;
next(c);
var[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(var, sizeof(var), "%s", c->tok.text);
next(c);
}
skip_type_hint(c);
expect(c, CAT_LEXER_TOK_ASSIGN, "'='");
expr(c); /* start */
expect(c, CAT_LEXER_TOK_COMMA, "','");
expr(c); /* limit */
if (accept(c, CAT_LEXER_TOK_COMMA))
expr(c); /* step */
else
emit(c, CAT_BYTECODE_OP_CONST,
cat_bytecode_add_const(cur_fn(c), cat_types_int_new(1)),
0, line);
expect(c, CAT_LEXER_TOK_DO, "'do'");
slot = add_local(c, var);
add_local(c, " .limit");
add_local(c, " .step");
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot + 2, 0, line);
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot + 1, 0, line);
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
jcond = cur_fn(c)->ncode;
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line);
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot + 1, 0, line);
emit(c, CAT_BYTECODE_OP_LE, 0, 0, line);
jend = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line);
{
int lv = c->nloops++;
c->brk_n[lv] = 0;
block(c);
c->nloops--;
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line);
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot + 2, 0, line);
emit(c, CAT_BYTECODE_OP_ADD, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
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;
}
case CAT_LEXER_TOK_FUNCTION: {
char name[256];
int proto;
next(c);
name[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
proto = compile_function_literal(c, name);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
break;
}
case CAT_LEXER_TOK_RETURN:
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)) {
expr(c);
emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line);
} else {
emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, line);
}
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_NAME: {
/* assignment if `name =`, or field assignment if `name.attr =`.
* Otherwise rewind and parse as an ordinary expression. */
size_t sp = c->lx.pos;
int sl = c->lx.line;
CAT_LEXER_Token la;
char name[256];
snprintf(name, sizeof(name), "%s", c->tok.text);
cat_lexer_next(&c->lx, &la);
if (la.kind == CAT_LEXER_TOK_ASSIGN) {
c->tok = la;
next(c);
expr(c);
{
int slot = find_local(c, name);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
else
emit(c, CAT_BYTECODE_OP_SETGLOBAL,
add_string(c, name), 0, line);
}
break;
}
if (la.kind == CAT_LEXER_TOK_LBRACKET) {
/* indexed assignment: name[idx] = value */
int slot = find_local(c, name);
c->tok = la;
next(c);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line);
else
emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, name), 0, line);
expr(c);
expect(c, CAT_LEXER_TOK_RBRACKET, "']'");
if (!accept(c, CAT_LEXER_TOK_ASSIGN)) {
err_at(c, line, "expected '=' after index target");
break;
}
expr(c);
emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, line);
break;
}
if (la.kind == CAT_LEXER_TOK_DOT) {
CAT_LEXER_Token attr;
cat_lexer_next(&c->lx, &attr);
if (attr.kind == CAT_LEXER_TOK_NAME) {
CAT_LEXER_Token eq;
cat_lexer_next(&c->lx, &eq);
if (eq.kind == CAT_LEXER_TOK_ASSIGN) {
int slot = find_local(c, name);
c->tok = eq;
next(c);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line);
else
emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, name), 0, line);
expr(c);
emit(c, CAT_BYTECODE_OP_SETATTR,
add_string(c, attr.text), 0, line);
break;
}
}
}
/* not an assignment: rewind and parse as an expression, keeping the
* current NAME token in place. */
c->lx.pos = sp;
c->lx.line = sl;
}
/* FALLTHROUGH */
default:
expr(c);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
break;
}
}
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)) {
int before = cur_fn(c)->ncode;
/* a lone ';' is a valid empty statement, not a parse error */
if (check(c, CAT_LEXER_TOK_SEMI)) {
next(c);
continue;
}
stat(c);
if (c->failed)
break;
if (cur_fn(c)->ncode == before &&
!check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI)) {
err_at(c, c->tok.line, "parse error near %s",
cat_lexer_kind_name(c->tok.kind));
break;
}
}
}
CAT_BYTECODE_Function *cat_compiler_compile(const char *source,
CAT_ERROR_Error *err)
{
Compiler c;
CAT_BYTECODE_Function *fn;
memset(&c, 0, sizeof(c));
c.err = err;
cat_lexer_init(&c.lx, source);
fn = cat_bytecode_function_new("main");
memset(&c.stack[0], 0, sizeof(c.stack[0]));
c.stack[0].fn = fn;
c.nstack = 1;
next(&c);
block(&c);
emit(&c, CAT_BYTECODE_OP_RETURN0, 0, 0, c.tok.line);
if (c.failed) {
cat_bytecode_function_free(fn);
return NULL;
}
return fn;
}
+30
View File
@@ -0,0 +1,30 @@
/*
* cat/error.c -- implementation of CAT_ERROR_Error.
*
* Naming rule: symbols here are cat_error_* / CAT_ERROR_*.
*/
#include "cat/error.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
void cat_error_clear(CAT_ERROR_Error *err)
{
if (err == NULL)
return;
err->raised = false;
err->message[0] = '\0';
}
void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...)
{
va_list ap;
if (err == NULL)
return;
err->raised = true;
va_start(ap, fmt);
vsnprintf(err->message, sizeof(err->message), fmt, ap);
va_end(ap);
}
+264
View File
@@ -0,0 +1,264 @@
/*
* cat/lexer.c -- tokenizer implementation.
*
* Naming rule: symbols here are cat_lexer_* / CAT_LEXER_*.
*/
#include "cat/lexer.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/* Keyword table: name -> token kind. */
struct kw {
const char *name;
int kind;
};
static const struct kw g_keywords[] = {
{ "and", CAT_LEXER_TOK_AND },
{ "break", CAT_LEXER_TOK_BREAK },
{ "do", CAT_LEXER_TOK_DO },
{ "else", CAT_LEXER_TOK_ELSE },
{ "elseif", CAT_LEXER_TOK_ELSEIF },
{ "end", CAT_LEXER_TOK_END },
{ "false", CAT_LEXER_TOK_FALSE },
{ "for", CAT_LEXER_TOK_FOR },
{ "function", CAT_LEXER_TOK_FUNCTION },
{ "if", CAT_LEXER_TOK_IF },
{ "in", CAT_LEXER_TOK_IN },
{ "local", CAT_LEXER_TOK_LOCAL },
{ "nil", CAT_LEXER_TOK_NIL },
{ "not", CAT_LEXER_TOK_NOT },
{ "or", CAT_LEXER_TOK_OR },
{ "repeat", CAT_LEXER_TOK_REPEAT },
{ "return", CAT_LEXER_TOK_RETURN },
{ "then", CAT_LEXER_TOK_THEN },
{ "true", CAT_LEXER_TOK_TRUE },
{ "until", CAT_LEXER_TOK_UNTIL },
{ "while", CAT_LEXER_TOK_WHILE },
};
void cat_lexer_init(CAT_LEXER_Lexer *lx, const char *src)
{
lx->src = src ? src : "";
lx->pos = 0;
lx->line = 1;
}
static int peek(CAT_LEXER_Lexer *lx)
{
return (unsigned char)lx->src[lx->pos];
}
static int peek2(CAT_LEXER_Lexer *lx)
{
return (unsigned char)lx->src[lx->pos + 1];
}
static int advance(CAT_LEXER_Lexer *lx)
{
int c = lx->src[lx->pos];
if (c == '\0')
return -1;
lx->pos++;
if (c == '\n')
lx->line++;
return c;
}
/* Skip whitespace and `--` line comments. */
static void skip_ws(CAT_LEXER_Lexer *lx)
{
for (;;) {
int c = peek(lx);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
advance(lx);
} else if (c == '-' && peek2(lx) == '-') {
advance(lx);
advance(lx);
while (peek(lx) != '\n' && peek(lx) != '\0')
advance(lx);
} else {
break;
}
}
}
static int lookup_keyword(const char *s)
{
size_t i;
for (i = 0; i < sizeof(g_keywords) / sizeof(g_keywords[0]); i++)
if (strcmp(g_keywords[i].name, s) == 0)
return g_keywords[i].kind;
return CAT_LEXER_TOK_NAME;
}
int cat_lexer_next(CAT_LEXER_Lexer *lx, CAT_LEXER_Token *out)
{
int c;
memset(out, 0, sizeof(*out));
skip_ws(lx);
out->line = lx->line;
c = peek(lx);
if (c == '\0') {
out->kind = CAT_LEXER_TOK_EOF;
return 0;
}
/* identifiers / keywords */
if (isalpha(c) || c == '_') {
int n = 0;
while (isalnum(peek(lx)) || peek(lx) == '_') {
if (n < (int)sizeof(out->text) - 1)
out->text[n++] = (char)advance(lx);
else
advance(lx);
}
out->text[n] = '\0';
out->kind = lookup_keyword(out->text);
return 0;
}
/* numbers: int or float */
if (isdigit(c)) {
int isfloat = 0;
int n = 0;
while (isdigit(peek(lx))) {
if (n < (int)sizeof(out->text) - 1)
out->text[n++] = (char)advance(lx);
else
advance(lx);
}
if (peek(lx) == '.' && isdigit(peek2(lx))) {
isfloat = 1;
if (n < (int)sizeof(out->text) - 1)
out->text[n++] = (char)advance(lx);
while (isdigit(peek(lx))) {
if (n < (int)sizeof(out->text) - 1)
out->text[n++] = (char)advance(lx);
else
advance(lx);
}
}
out->text[n] = '\0';
if (isfloat) {
out->kind = CAT_LEXER_TOK_FLOAT;
out->fval = strtod(out->text, NULL);
} else {
out->kind = CAT_LEXER_TOK_INT;
out->ival = strtoll(out->text, NULL, 10);
}
return 0;
}
/* strings: '...' or "..." with \n \t \\ \" escapes */
if (c == '"' || c == '\'') {
int quote = advance(lx);
int n = 0;
while (peek(lx) != quote && peek(lx) != '\0') {
int ch = advance(lx);
if (ch == '\\') {
int e = advance(lx);
switch (e) {
case 'n': ch = '\n'; break;
case 't': ch = '\t'; break;
case '\\': ch = '\\'; break;
case '"': ch = '"'; break;
case '\'': ch = '\''; break;
default: ch = e; break;
}
}
if (n < (int)sizeof(out->text) - 1)
out->text[n++] = (char)ch;
}
if (peek(lx) == quote)
advance(lx);
out->text[n] = '\0';
out->kind = CAT_LEXER_TOK_STRING;
return 0;
}
/* symbols */
switch (c) {
case '+': advance(lx); out->kind = CAT_LEXER_TOK_PLUS; return 0;
case '-':
advance(lx);
if (peek(lx) == '>') {
advance(lx);
out->kind = CAT_LEXER_TOK_ARROW;
return 0;
}
out->kind = CAT_LEXER_TOK_MINUS;
return 0;
case '*': advance(lx); out->kind = CAT_LEXER_TOK_STAR; return 0;
case '/': advance(lx); out->kind = CAT_LEXER_TOK_SLASH; return 0;
case '%': advance(lx); out->kind = CAT_LEXER_TOK_PERCENT; return 0;
case '^': advance(lx); out->kind = CAT_LEXER_TOK_CARET; return 0;
case '#': advance(lx); out->kind = CAT_LEXER_TOK_HASH; return 0;
case ';': advance(lx); out->kind = CAT_LEXER_TOK_SEMI; return 0;
case ',': advance(lx); out->kind = CAT_LEXER_TOK_COMMA; return 0;
case '(': advance(lx); out->kind = CAT_LEXER_TOK_LPAREN; return 0;
case ')': advance(lx); out->kind = CAT_LEXER_TOK_RPAREN; return 0;
case '{': advance(lx); out->kind = CAT_LEXER_TOK_LBRACE; return 0;
case '}': advance(lx); out->kind = CAT_LEXER_TOK_RBRACE; return 0;
case '[': advance(lx); out->kind = CAT_LEXER_TOK_LBRACKET; return 0;
case ']': advance(lx); out->kind = CAT_LEXER_TOK_RBRACKET; return 0;
case '=':
advance(lx);
if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_EQ; }
else out->kind = CAT_LEXER_TOK_ASSIGN;
return 0;
case '~':
advance(lx);
if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_NE; return 0; }
out->kind = CAT_LEXER_TOK_EOF;
return 0;
case '<':
advance(lx);
if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_LE; }
else out->kind = CAT_LEXER_TOK_LT;
return 0;
case '>':
advance(lx);
if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_GE; }
else out->kind = CAT_LEXER_TOK_GT;
return 0;
case '.':
advance(lx);
if (peek(lx) == '.') {
advance(lx);
out->kind = CAT_LEXER_TOK_CONCAT;
} else {
out->kind = CAT_LEXER_TOK_DOT;
}
return 0;
case ':':
advance(lx);
if (peek(lx) == ':') { advance(lx); out->kind = CAT_LEXER_TOK_DCOLON; }
else out->kind = CAT_LEXER_TOK_COLON;
return 0;
default:
advance(lx);
out->kind = CAT_LEXER_TOK_EOF;
return 0;
}
}
const char *cat_lexer_kind_name(int kind)
{
static const char *names[] = {
"EOF", "NAME", "INT", "FLOAT", "STRING",
"and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "if", "in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while",
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<",
">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":",
"::", "..", "->"
};
if (kind >= 0 && kind < (int)(sizeof(names) / sizeof(names[0])))
return names[kind];
return "?";
}
+60
View File
@@ -0,0 +1,60 @@
/*
* cat/module.c -- Cat_Module implementation.
*
* Naming rule: symbols here are cat_module_* / CAT_MODULE_*.
*/
#include "cat/module.h"
#include "cat/compiler.h"
#include "cat/bytecode.h"
#include "cat/vm.h"
#include "cat/stdlib/stdlib.h"
#include "cat/stdlib/build.h"
#include <stdlib.h>
#include <string.h>
CAT_MODULE_Module *cat_module_new(const char *name)
{
CAT_MODULE_Module *m = calloc(1, sizeof(*m));
if (m == NULL)
return NULL;
m->name = strdup(name ? name : "module");
return m;
}
int cat_module_compile(CAT_MODULE_Module *mod, const char *source,
CAT_ERROR_Error *err)
{
mod->main = cat_compiler_compile(source, err);
return mod->main ? 0 : -1;
}
int cat_module_run(CAT_MODULE_Module *mod, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
CAT_VM_State *vm;
int rc;
if (mod->main == NULL)
return (cat_error_raise(err, "module has no compiled code"), -1);
vm = cat_vm_new();
if (vm == NULL)
return -1;
cat_stdlib_stdlib_install(vm);
cat_stdlib_build_install(vm);
rc = cat_vm_run(vm, mod->main, out);
if (rc != 0)
cat_error_raise(err, "%s", vm->err.message);
cat_vm_free(vm);
return rc;
}
void cat_module_free(CAT_MODULE_Module *mod)
{
if (mod == NULL)
return;
cat_bytecode_function_free(mod->main);
free(mod->name);
free(mod);
}
+132
View File
@@ -0,0 +1,132 @@
/*
* cat/stdlib/build.c -- bytecode builder primitives (see build.h).
*
* Naming rule: symbols here are cat_stdlib_build_* / CAT_STDLIB_BUILD_*.
*
* bc_run(chunk) -- build a CAT_BYTECODE_Function from a chunk table and
* execute it, returning the chunk's return value.
* bc_dump(chunk) -- print a disassembly of a chunk table.
*/
#include "cat/stdlib/build.h"
#include "cat/bytecode.h"
#include "cat/types/table.h"
#include "cat/types/int.h"
#include "cat/types/nil.h"
#include "cat/types/ascii_text.h"
#include "cat/error.h"
#include <stdio.h>
/* Read an integer field from a table (0 if absent). */
static long long tbl_int(CAT_VALUE_Value *t, const char *key)
{
CAT_VALUE_Value *v = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
if (t == NULL || cat_types_table_get(t, key, &v, &e) != 0 || v == NULL)
return 0;
return cat_types_number_as_int(v);
}
static const char *tbl_str(CAT_VALUE_Value *t, const char *key)
{
CAT_VALUE_Value *v = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
if (t == NULL || cat_types_table_get(t, key, &v, &e) != 0 || v == NULL)
return NULL;
return cat_types_text_bytes(v);
}
/* Recursively convert a chunk table into a CAT_BYTECODE_Function. */
static CAT_BYTECODE_Function *build_function(CAT_VALUE_Value *chunk)
{
CAT_BYTECODE_Function *fn = cat_bytecode_function_new(tbl_str(chunk, "name"));
CAT_VALUE_Value *arr = NULL;
CAT_ERROR_Error e;
int i, n;
fn->nparams = (int)tbl_int(chunk, "nparams");
fn->nlocals = (int)tbl_int(chunk, "nlocals");
/* constants */
cat_error_clear(&e);
if (cat_types_table_get(chunk, "consts", &arr, &e) == 0) {
n = cat_types_table_count(arr);
for (i = 0; i < n; i++)
cat_bytecode_add_const(fn, cat_types_table_value_at(arr, i));
}
/* nested prototypes */
cat_error_clear(&e);
if (cat_types_table_get(chunk, "protos", &arr, &e) == 0) {
n = cat_types_table_count(arr);
for (i = 0; i < n; i++)
cat_bytecode_add_proto(fn,
build_function(cat_types_table_value_at(arr, i)));
}
/* instructions */
cat_error_clear(&e);
if (cat_types_table_get(chunk, "code", &arr, &e) == 0) {
n = cat_types_table_count(arr);
for (i = 0; i < n; i++) {
CAT_VALUE_Value *in = cat_types_table_value_at(arr, i);
cat_bytecode_emit(fn, (unsigned char)tbl_int(in, "op"),
(int)tbl_int(in, "a"),
(int)tbl_int(in, "b"),
(int)tbl_int(in, "c"),
(int)tbl_int(in, "line"));
}
}
return fn;
}
static int lf_bc_run(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_BYTECODE_Function *fn;
CAT_ERROR_Error e;
int rc;
(void)vm;
cat_error_clear(&e);
if (nargs < 1 || !cat_types_table_count(args[0])) { /* not a chunk */
}
fn = build_function(args[0]);
if (fn == NULL) {
*out = cat_types_nil_get();
return 0;
}
rc = cat_vm_run(vm, fn, out);
cat_bytecode_function_free(fn);
return rc;
}
static int lf_bc_dump(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_BYTECODE_Function *fn;
(void)vm;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
fn = build_function(args[0]);
if (fn != NULL) {
cat_bytecode_dump(fn, stdout);
cat_bytecode_function_free(fn);
}
*out = cat_types_nil_get();
return 0;
}
int cat_stdlib_build_install(CAT_VM_State *vm)
{
cat_vm_register_native(vm, "bc_run", lf_bc_run);
cat_vm_register_native(vm, "bc_dump", lf_bc_dump);
return 0;
}
+387
View File
@@ -0,0 +1,387 @@
/*
* cat/stdlib/stdlib.c -- standard library native functions.
*
* Naming rule: symbols here are cat_stdlib_stdlib_*.
*
* Native signature: int cb(vm, args, nargs, out). Installed names:
* print, tostring, tonumber, type, len, toml_parse, toml_encode.
*/
#include "cat/stdlib/stdlib.h"
#include "cat/stdlib/toml.h"
#include "cat/compiler.h"
#include "cat/bytecode.h"
#include "cat/types/nil.h"
#include "cat/types/bool.h"
#include "cat/types/number.h"
#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/native.h"
#include "cat/types/file.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* toString for any value (heap string, caller does not free). */
static const char *value_to_text(CAT_VALUE_Value *v)
{
static char buf[512];
if (v == NULL || v == cat_types_nil_get())
return "nil";
if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT)
return cat_types_text_bytes(v);
if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
if (((CAT_TYPES_NUMBER_Number *)v)->is_float)
snprintf(buf, sizeof(buf), "%g", cat_types_number_as_double(v));
else
snprintf(buf, sizeof(buf), "%lld", cat_types_number_as_int(v));
return buf;
}
if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL)
return ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false";
snprintf(buf, sizeof(buf), "<%s>", cat_value_type_name(v));
return buf;
}
static int lf_print(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
int i;
(void)vm;
for (i = 0; i < nargs; i++) {
if (i)
putchar(' ');
fputs(value_to_text(args[i]), stdout);
}
putchar('\n');
*out = cat_types_nil_get();
return 0;
}
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]) : "");
return 0;
}
static int lf_tonumber(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
const char *s;
char *end;
(void)vm;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_NUMBER) {
*out = args[0];
return 0;
}
s = cat_types_text_bytes(args[0]);
if (strchr(s, '.') != NULL) {
double d = strtod(s, &end);
*out = (*end == '\0') ? cat_types_float_new(d) : cat_types_nil_get();
} else {
long long n = strtoll(s, &end, 10);
*out = (*end == '\0') ? cat_types_int_new(n) : cat_types_nil_get();
}
return 0;
}
static int lf_type(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
(void)vm;
*out = cat_types_ascii_text_new(nargs > 0 ? cat_value_type_name(args[0])
: "nil");
return 0;
}
static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
(void)vm;
if (nargs < 1) {
*out = cat_types_int_new(0);
return 0;
}
if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TEXT)
*out = cat_types_int_new(cat_types_text_length(args[0]));
else if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TABLE)
*out = cat_types_int_new(cat_types_table_count(args[0]));
else
*out = cat_types_int_new(0);
return 0;
}
static int lf_toml_parse(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_VALUE_Value *tbl = NULL;
CAT_ERROR_Error e;
(void)vm;
cat_error_clear(&e);
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
if (cat_stdlib_toml_parse(cat_types_text_bytes(args[0]), &tbl, &e) != 0) {
fprintf(stderr, "toml_parse: %s\n", e.message);
*out = cat_types_nil_get();
return 0;
}
*out = tbl;
return 0;
}
static int lf_toml_encode(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_ERROR_Error e;
char *s;
(void)vm;
cat_error_clear(&e);
if (nargs < 1) {
*out = cat_types_ascii_text_new("");
return 0;
}
s = cat_stdlib_toml_encode(args[0], &e);
*out = cat_types_ascii_text_new(s ? s : "");
free(s);
return 0;
}
static int lf_read_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
FILE *f;
long sz;
char *buf = NULL;
char *path;
(void)vm;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
path = (char *)cat_types_text_bytes(args[0]);
f = fopen(path, "rb");
if (f == NULL) {
*out = cat_types_nil_get();
return 0;
}
fseek(f, 0, SEEK_END);
sz = ftell(f);
fseek(f, 0, SEEK_SET);
buf = malloc((size_t)sz + 1);
if (buf == NULL) {
fclose(f);
*out = cat_types_nil_get();
return 0;
}
if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ }
buf[sz] = '\0';
fclose(f);
*out = cat_types_ascii_text_new(buf);
free(buf);
return 0;
}
static int lf_write_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
FILE *f;
(void)vm;
if (nargs < 2) {
*out = cat_types_nil_get();
return 0;
}
f = fopen(cat_types_text_bytes(args[0]), "wb");
if (f != NULL) {
const char *s = cat_types_text_bytes(args[1]);
fwrite(s, 1, strlen(s), f);
fclose(f);
}
*out = cat_types_nil_get();
return 0;
}
static int lf_ord(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
const char *s;
long long i;
(void)vm;
if (nargs < 2) {
*out = cat_types_int_new(-1);
return 0;
}
s = cat_types_text_bytes(args[0]);
i = cat_types_number_as_int(args[1]);
if (i < 0 || i >= (long long)strlen(s))
*out = cat_types_int_new(-1);
else
*out = cat_types_int_new((unsigned char)s[i]);
return 0;
}
static int lf_chr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
char buf[2];
(void)vm;
buf[0] = (char)(nargs > 0 ? cat_types_number_as_int(args[0]) : 0);
buf[1] = '\0';
*out = cat_types_ascii_text_new(buf);
return 0;
}
static int lf_substr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
const char *s;
long long i, n;
char *buf;
(void)vm;
if (nargs < 3) {
*out = cat_types_ascii_text_new("");
return 0;
}
s = cat_types_text_bytes(args[0]);
i = cat_types_number_as_int(args[1]);
n = cat_types_number_as_int(args[2]);
if (i < 0 || i > (long long)strlen(s) || n < 0) {
*out = cat_types_ascii_text_new("");
return 0;
}
buf = malloc((size_t)n + 1);
if (buf == NULL) {
*out = cat_types_ascii_text_new("");
return 0;
}
memcpy(buf, s + i, (size_t)n);
buf[n] = '\0';
*out = cat_types_ascii_text_new(buf);
free(buf);
return 0;
}
static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
FILE *f;
long sz;
char *src;
CAT_BYTECODE_Function *fn;
CAT_ERROR_Error e;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
f = fopen(cat_types_text_bytes(args[0]), "rb");
if (f == NULL) {
*out = cat_types_nil_get();
return 0;
}
fseek(f, 0, SEEK_END);
sz = ftell(f);
fseek(f, 0, SEEK_SET);
src = malloc((size_t)sz + 1);
if (src == NULL) {
fclose(f);
*out = cat_types_nil_get();
return 0;
}
if (fread(src, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ }
src[sz] = '\0';
fclose(f);
cat_error_clear(&e);
fn = cat_compiler_compile(src, &e);
free(src);
if (fn == NULL) {
fprintf(stderr, "dofile: %s\n", e.message);
*out = cat_types_nil_get();
return 0;
}
cat_error_clear(&e);
cat_vm_run(vm, fn, out);
/* The compiled chunk is intentionally NOT freed: any `function`
* definitions in it became globals whose closures point into this
* bytecode tree. The chunk lives as long as the VM does. */
return 0;
}
static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
/* AbstractFile cannot be instantiated: it is the abstract base of the
* stream family (File/StringIO/BytesIO). */
(void)vm;
(void)args;
(void)nargs;
fprintf(stderr, "AbstractFile is abstract; use File::open, "
"StringIO or BytesIO\n");
*out = cat_types_nil_get();
return 0;
}
static int lf_stringio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
(void)vm;
*out = cat_types_file_stringio(nargs > 0 ?
cat_types_text_bytes(args[0]) : "");
return 0;
}
static int lf_bytesio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
(void)vm;
(void)args;
(void)nargs;
*out = cat_types_file_bytesio();
return 0;
}
int cat_stdlib_stdlib_install(CAT_VM_State *vm)
{
cat_vm_register_native(vm, "print", lf_print);
cat_vm_register_native(vm, "tostring", lf_tostring);
cat_vm_register_native(vm, "tonumber", lf_tonumber);
cat_vm_register_native(vm, "type", lf_type);
cat_vm_register_native(vm, "len", lf_len);
cat_vm_register_native(vm, "toml_parse", lf_toml_parse);
cat_vm_register_native(vm, "toml_encode", lf_toml_encode);
cat_vm_register_native(vm, "read_file", lf_read_file);
cat_vm_register_native(vm, "write_file", lf_write_file);
cat_vm_register_native(vm, "ord", lf_ord);
cat_vm_register_native(vm, "chr", lf_chr);
cat_vm_register_native(vm, "substr", lf_substr);
cat_vm_register_native(vm, "dofile", lf_dofile);
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
cat_vm_set_global(vm, "AbstractFile",
cat_types_native_new("AbstractFile", lf_abstractfile));
cat_vm_set_global(vm, "File", cat_types_file_class_table());
cat_vm_set_global(vm, "StringIO",
cat_types_native_new("StringIO", lf_stringio));
cat_vm_set_global(vm, "BytesIO",
cat_types_native_new("BytesIO", lf_bytesio));
return 0;
}
+408
View File
@@ -0,0 +1,408 @@
/*
* cat/stdlib/toml.c -- TOML subset parser/encoder.
*
* Naming rule: symbols here are cat_stdlib_toml_* / CAT_STDLIB_TOML_*.
*
* Supported: bare/quoted keys, [table], [[array of tables]], strings,
* integers, floats, booleans, inline arrays, dotted keys. Returns a
* table value so TOML documents are ordinary catscript objects.
*/
#include "cat/stdlib/toml.h"
#include "cat/types/table.h"
#include "cat/types/number.h"
#include "cat/types/text.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include "cat/types/ascii_text.h"
#include "cat/types/bool.h"
#include "cat/types/nil.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *s;
size_t pos;
int line;
CAT_ERROR_Error *err;
} TParser;
static void skip_ws(TParser *p)
{
for (;;) {
char c = p->s[p->pos];
if (c == ' ' || c == '\t' || c == '\r') {
p->pos++;
} else if (c == '#' || (c == '\n')) {
if (c == '#') {
while (p->s[p->pos] != '\n' && p->s[p->pos] != '\0')
p->pos++;
} else {
p->pos++;
p->line++;
}
} else {
break;
}
}
}
static void skip_inline_ws(TParser *p)
{
while (p->s[p->pos] == ' ' || p->s[p->pos] == '\t')
p->pos++;
}
static char *parse_key(TParser *p)
{
char buf[256];
int n = 0;
skip_inline_ws(p);
if (p->s[p->pos] == '"') {
p->pos++;
while (p->s[p->pos] != '"' && p->s[p->pos] != '\0') {
if (n < (int)sizeof(buf) - 1)
buf[n++] = p->s[p->pos];
p->pos++;
}
if (p->s[p->pos] == '"')
p->pos++;
} else {
while (isalnum((unsigned char)p->s[p->pos]) ||
p->s[p->pos] == '_' || p->s[p->pos] == '-') {
if (n < (int)sizeof(buf) - 1)
buf[n++] = p->s[p->pos];
p->pos++;
}
}
buf[n] = '\0';
return strdup(buf);
}
static CAT_VALUE_Value *parse_value(TParser *p);
static CAT_VALUE_Value *parse_string(TParser *p)
{
char buf[1024];
int n = 0;
char quote = p->s[p->pos++];
while (p->s[p->pos] != quote && p->s[p->pos] != '\0') {
char c = p->s[p->pos++];
if (c == '\\') {
char e = p->s[p->pos++];
switch (e) {
case 'n': c = '\n'; break;
case 't': c = '\t'; break;
case 'r': c = '\r'; break;
case '\\': c = '\\'; break;
case '"': c = '"'; break;
default: c = e; break;
}
}
if (n < (int)sizeof(buf) - 1)
buf[n++] = c;
}
if (p->s[p->pos] == quote)
p->pos++;
buf[n] = '\0';
return cat_types_ascii_text_new(buf);
}
static CAT_VALUE_Value *parse_array(TParser *p)
{
CAT_VALUE_Value *arr = cat_types_table_new();
int idx = 0;
p->pos++; /* [ */
for (;;) {
char key[32];
CAT_VALUE_Value *v;
CAT_ERROR_Error e;
skip_ws(p);
if (p->s[p->pos] == ']') {
p->pos++;
break;
}
if (p->s[p->pos] == '\0')
break;
v = parse_value(p);
snprintf(key, sizeof(key), "%d", idx++);
cat_error_clear(&e);
cat_types_table_set(arr, key, v, &e);
skip_ws(p);
if (p->s[p->pos] == ',')
p->pos++;
}
return arr;
}
static CAT_VALUE_Value *parse_value(TParser *p)
{
char c;
skip_inline_ws(p);
c = p->s[p->pos];
if (c == '"' || c == '\'')
return parse_string(p);
if (c == '[')
return parse_array(p);
if (c == 't' && strncmp(p->s + p->pos, "true", 4) == 0) {
p->pos += 4;
return cat_types_bool_true();
}
if (c == 'f' && strncmp(p->s + p->pos, "false", 5) == 0) {
p->pos += 5;
return cat_types_bool_false();
}
if (isdigit((unsigned char)c) || c == '-' || c == '+') {
char buf[64];
int n = 0;
int isfloat = 0;
while ((isdigit((unsigned char)p->s[p->pos]) || p->s[p->pos] == '-' ||
p->s[p->pos] == '+' || p->s[p->pos] == '.' ||
p->s[p->pos] == 'e' || p->s[p->pos] == 'E') &&
n < (int)sizeof(buf) - 1) {
if (p->s[p->pos] == '.' || p->s[p->pos] == 'e' ||
p->s[p->pos] == 'E')
isfloat = 1;
buf[n++] = p->s[p->pos++];
}
buf[n] = '\0';
if (isfloat)
return cat_types_float_new(strtod(buf, NULL));
return cat_types_int_new(strtoll(buf, NULL, 10));
}
/* fallback: consume a bare word as a string */
{
char buf[256];
int n = 0;
while (p->s[p->pos] != '\0' && p->s[p->pos] != '\n' &&
p->s[p->pos] != ',' && p->s[p->pos] != ']' &&
n < (int)sizeof(buf) - 1)
buf[n++] = p->s[p->pos++];
buf[n] = '\0';
return cat_types_ascii_text_new(buf);
}
}
/* Navigate/create a nested table by dotted path. */
static CAT_VALUE_Value *descend(CAT_VALUE_Value *root, char *path)
{
char *save = NULL;
char *part = strtok_r(path, ".", &save);
CAT_VALUE_Value *cur = root;
while (part != NULL) {
CAT_VALUE_Value *next = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
if (cat_types_table_get(cur, part, &next, &e) != 0) {
next = cat_types_table_new();
cat_error_clear(&e);
cat_types_table_set(cur, part, next, &e);
}
cur = next;
part = strtok_r(NULL, ".", &save);
}
return cur;
}
int cat_stdlib_toml_parse(const char *text, CAT_VALUE_Value **out,
CAT_ERROR_Error *err)
{
TParser p;
CAT_VALUE_Value *root = cat_types_table_new();
CAT_VALUE_Value *current = root;
p.s = text ? text : "";
p.pos = 0;
p.line = 1;
p.err = err;
for (;;) {
skip_ws(&p);
if (p.s[p.pos] == '\0')
break;
if (p.s[p.pos] == '[') {
int array_table = 0;
char path[256];
int n = 0;
p.pos++;
if (p.s[p.pos] == '[') {
array_table = 1;
p.pos++;
}
while (p.s[p.pos] != ']' && p.s[p.pos] != '\0' &&
n < (int)sizeof(path) - 1)
path[n++] = p.s[p.pos++];
path[n] = '\0';
/* trim */
while (n > 0 && (path[n - 1] == ' ' || path[n - 1] == '\t'))
path[--n] = '\0';
if (p.s[p.pos] == ']')
p.pos++;
if (p.s[p.pos] == ']')
p.pos++;
if (array_table) {
CAT_VALUE_Value *tbl = cat_types_table_new();
CAT_ERROR_Error e;
char countkey[32];
CAT_VALUE_Value *arr = NULL;
int cnt;
cat_error_clear(&e);
if (cat_types_table_get(root, path, &arr, &e) != 0) {
arr = cat_types_table_new();
cat_error_clear(&e);
cat_types_table_set(root, path, arr, &e);
}
cnt = cat_types_table_count(arr);
snprintf(countkey, sizeof(countkey), "%d", cnt);
cat_error_clear(&e);
cat_types_table_set(arr, countkey, tbl, &e);
current = tbl;
} else {
char copy[256];
snprintf(copy, sizeof(copy), "%s", path);
current = descend(root, copy);
}
continue;
}
/* key = value */
{
char copy[256];
char *key = parse_key(&p);
CAT_VALUE_Value *val;
CAT_VALUE_Value *target;
CAT_ERROR_Error e;
snprintf(copy, sizeof(copy), "%s", key);
free(key);
skip_inline_ws(&p);
if (p.s[p.pos] == '=') {
p.pos++;
} else {
/* skip line */
while (p.s[p.pos] != '\n' && p.s[p.pos] != '\0')
p.pos++;
continue;
}
val = parse_value(&p);
target = descend(current, copy);
cat_error_clear(&e);
/* descend with a full path only makes sense for top-level;
* here `copy` may contain dots for dotted keys. */
(void)target;
{
char *dot = strrchr(copy, '.');
if (dot != NULL) {
*dot = '\0';
descend(current, copy);
cat_error_clear(&e);
cat_types_table_set(descend(current, copy),
dot + 1, val, &e);
} else {
cat_error_clear(&e);
cat_types_table_set(current, copy, val, &e);
}
}
}
}
*out = root;
return 0;
}
/* ---- encoder --------------------------------------------------------- */
static void enc_value(FILE *f, CAT_VALUE_Value *v);
static int is_bare_key(const char *s)
{
if (*s == '\0')
return 0;
for (; *s != '\0'; s++)
if (!(isalnum((unsigned char)*s) || *s == '_' || *s == '-'))
return 0;
return 1;
}
static void enc_string(FILE *f, const char *s)
{
fputc('"', f);
for (; *s != '\0'; s++) {
switch (*s) {
case '"': fputs("\\\"", f); break;
case '\\': fputs("\\\\", f); break;
case '\n': fputs("\\n", f); break;
case '\t': fputs("\\t", f); break;
default: fputc(*s, f); break;
}
}
fputc('"', f);
}
static void enc_value(FILE *f, CAT_VALUE_Value *v)
{
if (v == NULL || v == cat_types_nil_get()) {
fputs("\"nil\"", f);
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) {
enc_string(f, cat_value_type_name(v) ? ((CAT_TYPES_TEXT_Text *)v)->bytes : "");
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) {
CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v;
if (n->is_float)
fprintf(f, "%g", n->f);
else
fprintf(f, "%lld", n->i);
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) {
fputs(((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false", f);
} else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TABLE) {
int i, n = cat_types_table_count(v);
fputc('[', f);
for (i = 0; i < n; i++) {
if (i)
fputs(", ", f);
enc_value(f, cat_types_table_value_at(v, i));
}
fputc(']', f);
} else {
fputs("\"?\"", f);
}
}
char *cat_stdlib_toml_encode(CAT_VALUE_Value *tbl, CAT_ERROR_Error *err)
{
FILE *f;
char *buf;
long sz;
int i, n;
(void)err;
if (tbl == NULL || !tbl->vtable || tbl->vtable->kind != CAT_VALUE_KIND_TABLE)
return strdup("");
f = open_memstream(&buf, (size_t *)&sz);
if (f == NULL)
return strdup("");
n = cat_types_table_count(tbl);
for (i = 0; i < n; i++) {
const char *key = cat_types_table_key_at(tbl, i);
CAT_VALUE_Value *v = cat_types_table_value_at(tbl, i);
if (is_bare_key(key))
fputs(key, f);
else
enc_string(f, key);
fputs(" = ", f);
enc_value(f, v);
fputc('\n', f);
}
fclose(f);
return buf;
}
+52
View File
@@ -0,0 +1,52 @@
/*
* cat/types/ascii_text.c -- the concrete `ascii_text` type.
*
* Naming rule: symbols here are cat_types_ascii_text_*.
*/
#include "cat/types/ascii_text.h"
#include <stdlib.h>
#include <string.h>
static void ascii_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_ASCII_TEXT_AsciiText *t = (CAT_TYPES_ASCII_TEXT_AsciiText *)self;
free(t->owned);
free(t);
}
static CAT_VALUE_Vtable g_ascii_vtable = {
.type_name = "ascii_text",
.kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { cat_types_text_get_attribute },
.destroy = ascii_destroy,
};
CAT_VALUE_Vtable *cat_types_ascii_text_vtable(void)
{
return &g_ascii_vtable;
}
CAT_VALUE_Value *cat_types_ascii_text_new(const char *s)
{
CAT_TYPES_ASCII_TEXT_AsciiText *t;
size_t n;
if (s == NULL)
s = "";
n = strlen(s);
t = calloc(1, sizeof(*t));
if (t == NULL)
return NULL;
t->owned = malloc(n + 1);
if (t->owned == NULL) {
free(t);
return NULL;
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_ascii_vtable;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
}
+35
View File
@@ -0,0 +1,35 @@
/*
* cat/types/bool.c -- the boolean type.
*
* Naming rule: symbols here are cat_types_bool_* / CAT_TYPES_BOOL_*.
*/
#include "cat/types/bool.h"
static int bool_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err)
{
(void)err;
return ((CAT_TYPES_BOOL_Bool *)self)->v != 0;
}
static CAT_VALUE_Vtable g_bool_vtable = {
.type_name = "bool",
.kind = CAT_VALUE_KIND_BOOL,
.truthy = bool_truthy,
};
CAT_VALUE_Vtable *cat_types_bool_vtable(void)
{
return &g_bool_vtable;
}
CAT_VALUE_Value *cat_types_bool_true(void)
{
static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable }, 1 };
return &t.base;
}
CAT_VALUE_Value *cat_types_bool_false(void)
{
static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable }, 0 };
return &f.base;
}
+53
View File
@@ -0,0 +1,53 @@
/*
* cat/types/byte.c -- the concrete `byte` type.
*
* Naming rule: symbols here are cat_types_byte_* / CAT_TYPES_BYTE_*.
*/
#include "cat/types/byte.h"
#include <stdlib.h>
static void byte_destroy(CAT_VALUE_Value *self)
{
free(self);
}
static int byte_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err)
{
(void)err;
return ((CAT_TYPES_NUMBER_Number *)self)->i != 0;
}
static CAT_VALUE_Vtable g_byte_vtable = {
.type_name = "byte",
.kind = CAT_VALUE_KIND_NUMBER,
.add = { cat_types_number_add },
.sub = { cat_types_number_sub },
.mul = { cat_types_number_mul },
.div = { cat_types_number_div },
.rem = { cat_types_number_rem },
.call = { NULL },
.raise = { NULL },
.get_attribute = { NULL },
.set_attribute = { NULL },
.truthy = byte_truthy,
.destroy = byte_destroy,
};
CAT_VALUE_Vtable *cat_types_byte_vtable(void)
{
return &g_byte_vtable;
}
CAT_VALUE_Value *cat_types_byte_new(unsigned int v)
{
CAT_TYPES_BYTE_Byte *n = calloc(1, sizeof(*n));
if (n == NULL)
return NULL;
n->number.base.vtable = &g_byte_vtable;
n->number.is_float = 0;
n->number.i = (long long)(v & 0xFFu);
n->number.f = (double)(v & 0xFFu);
return &n->number.base;
}
+65
View File
@@ -0,0 +1,65 @@
/*
* cat/types/char.c -- the fixed-width text types char1..char4.
*
* Naming rule: symbols here are cat_types_char_* / CAT_TYPES_CHAR_*.
*/
#include "cat/types/char.h"
#include <stdlib.h>
#include <string.h>
static void char_destroy(CAT_VALUE_Value *self)
{
free(self);
}
/* Four vtables, one per width, so type_name reports e.g. "char2". */
static CAT_VALUE_Vtable g_char_vtables[4] = {
{ .type_name = "char1", .kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { cat_types_text_get_attribute },
.destroy = char_destroy },
{ .type_name = "char2", .kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { cat_types_text_get_attribute },
.destroy = char_destroy },
{ .type_name = "char3", .kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { cat_types_text_get_attribute },
.destroy = char_destroy },
{ .type_name = "char4", .kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { cat_types_text_get_attribute },
.destroy = char_destroy },
};
CAT_VALUE_Vtable *cat_types_char_vtable(int width)
{
if (width < 1)
width = 1;
if (width > 4)
width = 4;
return &g_char_vtables[width - 1];
}
CAT_VALUE_Value *cat_types_char_new(int width, const char *s)
{
CAT_TYPES_CHAR_Char *c;
if (width < 1 || width > 4)
return NULL;
c = calloc(1, sizeof(*c));
if (c == NULL)
return NULL;
c->width = width;
if (s != NULL) {
int i;
for (i = 0; i < width && s[i] != '\0'; i++)
c->buf[i] = s[i];
}
c->buf[width] = '\0';
c->text.base.vtable = cat_types_char_vtable(width);
c->text.bytes = c->buf;
c->text.len = width;
return &c->text.base;
}
+358
View File
@@ -0,0 +1,358 @@
/*
* cat/types/file.c -- the file family (AbstractFile/File/StringIO/BytesIO).
*
* Naming rule: symbols here are cat_types_file_* / CAT_TYPES_FILE_*.
*
* AbstractFile is the abstract base; all streams share one vtable and
* therefore the same method set, so they are interchangeable:
*
* f = File::open("x.txt") -- a real file
* s = StringIO("hello") -- an in-memory text stream
* b = BytesIO() -- an in-memory byte stream
* f:write("data"); f:close()
* s:read()
*
* Thread-safety: every stream owns its own buffer/handle; nothing here
* touches shared mutable state, so streams created and used on separate
* threads never interfere (no GIL).
*/
#include "cat/types/file.h"
#include "cat/types/native.h"
#include "cat/types/int.h"
#include "cat/types/nil.h"
#include "cat/types/ascii_text.h"
#include "cat/types/table.h"
#include "cat/error.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define AF(v) ((CAT_TYPES_FILE_AbstractFile *)(v))
static const char *as_text(CAT_VALUE_Value *v)
{
return (v != NULL && v->vtable &&
v->vtable->kind == CAT_VALUE_KIND_TEXT)
? cat_types_text_bytes(v) : NULL;
}
static long long as_int(CAT_VALUE_Value *v)
{
return (v != NULL && v->vtable &&
v->vtable->kind == CAT_VALUE_KIND_NUMBER)
? cat_types_number_as_int(v) : 0;
}
/* ---- methods (self is args[0]) --------------------------------------- */
static int m_read(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_TYPES_FILE_AbstractFile *af;
long long want;
(void)vm;
if (nargs < 1) {
*out = cat_types_nil_get();
return 0;
}
af = AF(args[0]);
if (af->closed) {
*out = cat_types_nil_get();
return 0;
}
want = (nargs > 1) ? as_int(args[1]) : -1;
if (af->is_bytes) {
CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af;
long avail = m->len - m->pos;
long take = (want < 0 || want > avail) ? avail : (long)want;
char *buf = malloc((size_t)take + 1);
if (buf == NULL) {
*out = cat_types_nil_get();
return 0;
}
memcpy(buf, m->buf + m->pos, (size_t)take);
buf[take] = '\0';
m->pos += take;
*out = cat_types_ascii_text_new(buf);
free(buf);
return 0;
} else {
CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af;
size_t cap = 256, n = 0;
char *buf = malloc(cap);
FILE *fp = (FILE *)f->fp;
if (buf == NULL) {
*out = cat_types_nil_get();
return 0;
}
for (;;) {
int ch = fgetc(fp);
if (ch == EOF)
break;
if (want >= 0 && (long long)n >= want)
break;
if (n + 1 >= cap) {
cap *= 2;
buf = realloc(buf, cap);
if (buf == NULL)
break;
}
buf[n++] = (char)ch;
}
buf[n] = '\0';
*out = cat_types_ascii_text_new(buf);
free(buf);
return 0;
}
}
static int m_write(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_TYPES_FILE_AbstractFile *af;
const char *s;
(void)vm;
if (nargs < 2) {
*out = cat_types_int_new(0);
return 0;
}
af = AF(args[0]);
s = as_text(args[1]);
if (af->closed || s == NULL) {
*out = cat_types_int_new(0);
return 0;
}
if (af->is_bytes) {
CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af;
size_t add = strlen(s);
if (m->len + (long)add + 1 > m->cap) {
long nc = (m->cap ? m->cap : 128);
while (nc < m->len + (long)add + 1)
nc *= 2;
m->buf = realloc(m->buf, (size_t)nc);
m->cap = nc;
}
memcpy(m->buf + m->len, s, add);
m->len += (long)add;
m->buf[m->len] = '\0';
*out = cat_types_int_new((long long)add);
return 0;
} else {
CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af;
size_t w = fwrite(s, 1, strlen(s), (FILE *)f->fp);
fflush((FILE *)f->fp);
*out = cat_types_int_new((long long)w);
return 0;
}
}
static int m_close(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_TYPES_FILE_AbstractFile *af;
(void)vm;
if (nargs >= 1) {
af = AF(args[0]);
if (!af->closed && !af->is_bytes) {
CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af;
if (f->fp != NULL)
fclose((FILE *)f->fp);
f->fp = NULL;
}
af->closed = 1;
}
*out = cat_types_nil_get();
return 0;
}
static int m_name(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
CAT_TYPES_FILE_AbstractFile *af;
(void)vm;
if (nargs < 1) {
*out = cat_types_ascii_text_new("");
return 0;
}
af = AF(args[0]);
if (!af->is_bytes) {
CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af;
*out = cat_types_ascii_text_new(f->path ? f->path : "");
} else {
*out = cat_types_ascii_text_new(af->is_bytes == 1 ? "<stringio>" : "<bytesio>");
}
return 0;
}
static int file_get_attr(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
(void)self;
(void)err;
if (strcmp(name, "read") == 0) {
*out = cat_types_native_new("read", m_read);
return 0;
}
if (strcmp(name, "write") == 0) {
*out = cat_types_native_new("write", m_write);
return 0;
}
if (strcmp(name, "close") == 0) {
*out = cat_types_native_new("close", m_close);
return 0;
}
if (strcmp(name, "name") == 0) {
*out = cat_types_native_new("name", m_name);
return 0;
}
return (cat_error_raise(err, "file has no method '%s'", name), -1);
}
static void file_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FILE_AbstractFile *af = AF(self);
if (af->is_bytes) {
CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af;
free(m->buf);
} else {
CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af;
if (!af->closed && f->fp != NULL)
fclose((FILE *)f->fp);
free(f->path);
}
free(self);
}
static CAT_VALUE_Vtable g_file_vtable = {
.type_name = "File",
.kind = CAT_VALUE_KIND_TABLE,
.get_attribute = { file_get_attr },
.destroy = file_destroy,
};
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)
{
CAT_TYPES_FILE_File *f;
FILE *fp;
int m = 0;
if (path == NULL)
return cat_types_nil_get();
if (mode == NULL)
mode = "r";
fp = fopen(path, mode);
if (fp == NULL)
return cat_types_nil_get();
if (strchr(mode, 'w') != NULL)
m = CAT_TYPES_FILE_MODE_WRITE;
else if (strchr(mode, 'a') != NULL)
m = CAT_TYPES_FILE_MODE_APPEND;
else
m = CAT_TYPES_FILE_MODE_READ;
f = calloc(1, sizeof(*f));
if (f == NULL) {
fclose(fp);
return cat_types_nil_get();
}
f->af.base.vtable = &g_file_vtable;
f->af.mode = m;
f->af.closed = 0;
f->af.is_bytes = 0;
f->fp = fp;
f->path = strdup(path);
return &f->af.base;
}
CAT_VALUE_Value *cat_types_file_stringio(const char *initial)
{
CAT_TYPES_FILE_MemFile *m = calloc(1, sizeof(*m));
if (m == NULL)
return cat_types_nil_get();
m->af.base.vtable = &g_file_vtable;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->af.is_bytes = 1; /* in-memory */
m->cap = 128;
m->buf = malloc((size_t)m->cap);
if (m->buf == NULL) {
free(m);
return cat_types_nil_get();
}
m->buf[0] = '\0';
if (initial != NULL) {
size_t n = strlen(initial);
if ((long)n + 1 > m->cap) {
m->cap = (long)n + 1;
m->buf = realloc(m->buf, (size_t)m->cap);
}
memcpy(m->buf, initial, n + 1);
m->len = (long)n;
}
m->pos = 0;
m->af.is_bytes = 3; /* 3 == StringIO text marker */
return &m->af.base;
}
CAT_VALUE_Value *cat_types_file_bytesio(void)
{
CAT_TYPES_FILE_MemFile *m = calloc(1, sizeof(*m));
if (m == NULL)
return cat_types_nil_get();
m->af.base.vtable = &g_file_vtable;
m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE;
m->cap = 128;
m->buf = malloc((size_t)m->cap);
if (m->buf == NULL) {
free(m);
return cat_types_nil_get();
}
m->buf[0] = '\0';
m->pos = 0;
m->af.is_bytes = 2; /* 2 == BytesIO marker */
return &m->af.base;
}
/* ---- the class table: File::open(...) -------------------------------- */
static int cm_open(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out)
{
const char *path, *mode;
(void)vm;
if (nargs < 2) {
*out = cat_types_nil_get();
return 0;
}
path = as_text(args[1]);
mode = (nargs > 2) ? as_text(args[2]) : "r";
if (mode == NULL)
mode = "r";
*out = cat_types_file_open(path, mode);
return 0;
}
CAT_VALUE_Value *cat_types_file_class_table(void)
{
CAT_VALUE_Value *t = cat_types_table_new();
CAT_ERROR_Error e;
cat_error_clear(&e);
cat_types_table_set(t, "open", cat_types_native_new("open", cm_open), &e);
return t;
}
+53
View File
@@ -0,0 +1,53 @@
/*
* cat/types/float.c -- the concrete `float` type.
*
* Naming rule: symbols here are cat_types_float_* / CAT_TYPES_FLOAT_*.
*/
#include "cat/types/float.h"
#include <stdlib.h>
static void float_destroy(CAT_VALUE_Value *self)
{
free(self);
}
static int float_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err)
{
(void)err;
return ((CAT_TYPES_NUMBER_Number *)self)->f != 0.0;
}
static CAT_VALUE_Vtable g_float_vtable = {
.type_name = "float",
.kind = CAT_VALUE_KIND_NUMBER,
.add = { cat_types_number_add },
.sub = { cat_types_number_sub },
.mul = { cat_types_number_mul },
.div = { cat_types_number_div },
.rem = { cat_types_number_rem },
.call = { NULL },
.raise = { NULL },
.get_attribute = { NULL },
.set_attribute = { NULL },
.truthy = float_truthy,
.destroy = float_destroy,
};
CAT_VALUE_Vtable *cat_types_float_vtable(void)
{
return &g_float_vtable;
}
CAT_VALUE_Value *cat_types_float_new(double v)
{
CAT_TYPES_FLOAT_Float *n = calloc(1, sizeof(*n));
if (n == NULL)
return NULL;
n->number.base.vtable = &g_float_vtable;
n->number.is_float = 1;
n->number.f = v;
n->number.i = (long long)v;
return &n->number.base;
}
+61
View File
@@ -0,0 +1,61 @@
/*
* cat/types/function.c -- closures.
*
* Naming rule: symbols here are cat_types_function_*.
*
* Calling a closure enters the VM (cat_vm_exec_closure). The compiler
* emits OP_CALL on any value and this type's call slot is what runs the
* subroutine, keeping "everything is an object" honest.
*/
#include "cat/types/function.h"
#include "cat/vm.h"
#include <stdlib.h>
int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl,
CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out);
static int function_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self;
/* The active VM for this thread (thread-local, so no global lock). */
CAT_VM_State *vm = cat_vm_current();
(void)err;
if (vm == NULL)
return (cat_error_raise(err, "no active VM"), -1);
return cat_vm_exec_closure(vm, cl, args, nargs, out);
}
static void function_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self;
free(cl->upvals);
/* proto is owned by its enclosing module/bytecode tree */
free(cl);
}
static CAT_VALUE_Vtable g_function_vtable = {
.type_name = "function",
.kind = CAT_VALUE_KIND_FUNCTION,
.call = { function_call },
.destroy = function_destroy,
};
CAT_VALUE_Vtable *cat_types_function_vtable(void)
{
return &g_function_vtable;
}
CAT_VALUE_Value *cat_types_function_new(CAT_BYTECODE_Function *proto)
{
CAT_TYPES_FUNCTION_Closure *cl = calloc(1, sizeof(*cl));
if (cl == NULL)
return NULL;
cl->base.vtable = &g_function_vtable;
cl->proto = proto;
cl->nupvals = 0;
cl->upvals = NULL;
return &cl->base;
}
+53
View File
@@ -0,0 +1,53 @@
/*
* cat/types/int.c -- the concrete `int` type.
*
* Naming rule: symbols here are cat_types_int_* / CAT_TYPES_INT_*.
*/
#include "cat/types/int.h"
#include <stdlib.h>
static void int_destroy(CAT_VALUE_Value *self)
{
free(self);
}
static int int_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err)
{
(void)err;
return ((CAT_TYPES_NUMBER_Number *)self)->i != 0;
}
static CAT_VALUE_Vtable g_int_vtable = {
.type_name = "int",
.kind = CAT_VALUE_KIND_NUMBER,
.add = { cat_types_number_add },
.sub = { cat_types_number_sub },
.mul = { cat_types_number_mul },
.div = { cat_types_number_div },
.rem = { cat_types_number_rem },
.call = { NULL },
.raise = { NULL },
.get_attribute = { NULL },
.set_attribute = { NULL },
.truthy = int_truthy,
.destroy = int_destroy,
};
CAT_VALUE_Vtable *cat_types_int_vtable(void)
{
return &g_int_vtable;
}
CAT_VALUE_Value *cat_types_int_new(long long v)
{
CAT_TYPES_INT_Int *n = calloc(1, sizeof(*n));
if (n == NULL)
return NULL;
n->number.base.vtable = &g_int_vtable;
n->number.is_float = 0;
n->number.i = v;
n->number.f = (double)v;
return &n->number.base;
}
+59
View File
@@ -0,0 +1,59 @@
/*
* cat/types/native.c -- native function values.
*
* Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*.
*/
#include "cat/types/native.h"
#include "cat/vm.h"
#include "cat/error.h"
#include <stdlib.h>
#include <string.h>
static int native_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args,
int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self;
CAT_VM_State *vm = cat_vm_current();
if (vm == NULL)
return (cat_error_raise(err, "no active VM"), -1);
return nf->cb(vm, args, nargs, out);
}
static void native_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self;
free(nf->name);
free(nf);
}
static CAT_VALUE_Vtable g_native_vtable = {
.type_name = "native",
.kind = CAT_VALUE_KIND_FUNCTION,
.call = { native_call },
.destroy = native_destroy,
};
CAT_VALUE_Vtable *cat_types_native_vtable(void)
{
return &g_native_vtable;
}
CAT_VALUE_Value *cat_types_native_new(const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **))
{
CAT_TYPES_NATIVE_Native *nf = calloc(1, sizeof(*nf));
if (nf == NULL)
return NULL;
nf->base.vtable = &g_native_vtable;
nf->name = strdup(name ? name : "native");
nf->cb = cb;
return &nf->base;
}
int cat_types_native_is(CAT_VALUE_Value *v)
{
return v != NULL && v->vtable == &g_native_vtable;
}
+31
View File
@@ -0,0 +1,31 @@
/*
* cat/types/nil.c -- the `nil` singleton value.
*
* Naming rule: symbols here are cat_types_nil_* / CAT_TYPES_NIL_*.
*/
#include "cat/types/nil.h"
static int nil_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err)
{
(void)self;
(void)err;
return 0; /* nil is falsy */
}
static CAT_VALUE_Vtable g_nil_vtable = {
.type_name = "nil",
.kind = CAT_VALUE_KIND_NIL,
.truthy = nil_truthy,
};
CAT_VALUE_Vtable *cat_types_nil_vtable(void)
{
return &g_nil_vtable;
}
CAT_VALUE_Value *cat_types_nil_get(void)
{
static CAT_TYPES_NIL_Nil g_nil;
g_nil.base.vtable = &g_nil_vtable;
return &g_nil.base;
}
+122
View File
@@ -0,0 +1,122 @@
/*
* cat/types/number.c -- shared numeric semantics for Cat_Number.
*
* Naming rule: symbols here are cat_types_number_* / CAT_TYPES_NUMBER_*.
* The compiler/VM does NOT own arithmetic: every +,-,*,/,% on numbers
* lands here, so embedders and the language share one implementation.
*/
#include "cat/types/number.h"
#include "cat/types/int.h"
#include "cat/types/float.h"
#include <math.h>
#include <stdlib.h>
static CAT_TYPES_NUMBER_Number *as_num(CAT_VALUE_Value *v)
{
return (CAT_TYPES_NUMBER_Number *)v;
}
int cat_types_number_is_number(CAT_VALUE_Value *v)
{
return v != NULL && v->vtable != NULL &&
v->vtable->kind == CAT_VALUE_KIND_NUMBER;
}
double cat_types_number_as_double(CAT_VALUE_Value *v)
{
CAT_TYPES_NUMBER_Number *n = as_num(v);
return n->is_float ? n->f : (double)n->i;
}
long long cat_types_number_as_int(CAT_VALUE_Value *v)
{
CAT_TYPES_NUMBER_Number *n = as_num(v);
return n->is_float ? (long long)n->f : n->i;
}
/* Build a result number: float if either side is float, else int. */
static CAT_VALUE_Value *make_result(int want_float, long long iv, double fv)
{
if (want_float)
return cat_types_float_new(fv);
return cat_types_int_new(iv);
}
int cat_types_number_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
int wf;
if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b))
return (cat_error_raise(err, "add expects numbers"), -1);
wf = as_num(a)->is_float || as_num(b)->is_float;
*out = make_result(wf, (long long)(cat_types_number_as_double(a) +
cat_types_number_as_double(b)),
cat_types_number_as_double(a) +
cat_types_number_as_double(b));
return 0;
}
int cat_types_number_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
int wf;
if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b))
return (cat_error_raise(err, "sub expects numbers"), -1);
wf = as_num(a)->is_float || as_num(b)->is_float;
*out = make_result(wf, (long long)(cat_types_number_as_double(a) -
cat_types_number_as_double(b)),
cat_types_number_as_double(a) -
cat_types_number_as_double(b));
return 0;
}
int cat_types_number_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
int wf;
if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b))
return (cat_error_raise(err, "mul expects numbers"), -1);
wf = as_num(a)->is_float || as_num(b)->is_float;
*out = make_result(wf, (long long)(cat_types_number_as_double(a) *
cat_types_number_as_double(b)),
cat_types_number_as_double(a) *
cat_types_number_as_double(b));
return 0;
}
int cat_types_number_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
double d;
if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b))
return (cat_error_raise(err, "div expects numbers"), -1);
d = cat_types_number_as_double(b);
if (d == 0.0)
return (cat_error_raise(err, "division by zero"), -1);
/* division always yields float, matching Lua's `/`. */
*out = cat_types_float_new(cat_types_number_as_double(a) / d);
return 0;
}
int cat_types_number_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
double d;
int wf;
if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b))
return (cat_error_raise(err, "rem expects numbers"), -1);
wf = as_num(a)->is_float || as_num(b)->is_float;
if (wf) {
d = cat_types_number_as_double(b);
if (d == 0.0)
return (cat_error_raise(err, "modulo by zero"), -1);
*out = cat_types_float_new(fmod(cat_types_number_as_double(a), d));
} else {
long long ib = cat_types_number_as_int(b);
if (ib == 0)
return (cat_error_raise(err, "modulo by zero"), -1);
*out = cat_types_int_new(cat_types_number_as_int(a) % ib);
}
return 0;
}
+136
View File
@@ -0,0 +1,136 @@
/*
* cat/types/table.c -- the table/object type.
*
* Naming rule: symbols here are cat_types_table_* / CAT_TYPES_TABLE_*.
*/
#include "cat/types/table.h"
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include <stdlib.h>
#include <string.h>
static int table_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_ERROR_Error local;
CAT_VALUE_Value *base = NULL;
cat_error_clear(&local);
if (cat_types_table_get(self, name, out, &local) == 0)
return 0;
/* Inheritance: a `__index` attribute names a base table/method table.
* Looking the key up there gives lightweight class inheritance, so a
* concrete class (e.g. `File`) can share methods with its abstract
* base (`AbstractFile`). */
cat_error_clear(&local);
if (cat_types_table_get(self, "__index", &base, &local) == 0 &&
base != NULL && base != self)
return cat_value_get_attribute(base, name, out, err);
return (cat_error_raise(err, "table has no key '%s'", name), -1);
}
static int table_set_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
return cat_types_table_set(self, name, value, err);
}
static void table_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)self;
int i;
/* Values are NOT destroyed: the same value object may be referenced
* from several tables (globals, constants, locals), so a recursive
* destroy would double-free. We only release the table's own keys
* and storage. */
for (i = 0; i < t->npairs; i++)
free(t->pairs[i].key);
free(t->pairs);
free(t);
}
static CAT_VALUE_Vtable g_table_vtable = {
.type_name = "table",
.kind = CAT_VALUE_KIND_TABLE,
.get_attribute = { table_get_attribute },
.set_attribute = { table_set_attribute },
.destroy = table_destroy,
};
CAT_VALUE_Vtable *cat_types_table_vtable(void)
{
return &g_table_vtable;
}
CAT_VALUE_Value *cat_types_table_new(void)
{
CAT_TYPES_TABLE_Table *t = calloc(1, sizeof(*t));
if (t == NULL)
return NULL;
t->base.vtable = &g_table_vtable;
return &t->base;
}
static int find_key(CAT_TYPES_TABLE_Table *t, const char *key)
{
int i;
for (i = 0; i < t->npairs; i++)
if (strcmp(t->pairs[i].key, key) == 0)
return i;
return -1;
}
int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key,
CAT_VALUE_Value *value, CAT_ERROR_Error *err)
{
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)tbl;
int idx = find_key(t, key);
(void)err;
if (idx >= 0) {
t->pairs[idx].value = value;
return 0;
}
if (t->npairs == t->cappairs) {
int nc = t->cappairs ? t->cappairs * 2 : 4;
CAT_TYPES_TABLE_Pair *np = realloc(t->pairs, (size_t)nc * sizeof(*np));
if (np == NULL)
return (cat_error_raise(err, "out of memory"), -1);
t->pairs = np;
t->cappairs = nc;
}
t->pairs[t->npairs].key = strdup(key);
t->pairs[t->npairs].value = value;
t->npairs++;
return 0;
}
int cat_types_table_get(CAT_VALUE_Value *tbl, const char *key,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)tbl;
int idx = find_key(t, key);
if (idx >= 0) {
*out = t->pairs[idx].value;
return 0;
}
return (cat_error_raise(err, "table has no key '%s'", key), -1);
}
int cat_types_table_count(CAT_VALUE_Value *tbl)
{
return ((CAT_TYPES_TABLE_Table *)tbl)->npairs;
}
const char *cat_types_table_key_at(CAT_VALUE_Value *tbl, int i)
{
return ((CAT_TYPES_TABLE_Table *)tbl)->pairs[i].key;
}
CAT_VALUE_Value *cat_types_table_value_at(CAT_VALUE_Value *tbl, int i)
{
return ((CAT_TYPES_TABLE_Table *)tbl)->pairs[i].value;
}
+64
View File
@@ -0,0 +1,64 @@
/*
* cat/types/text.c -- shared text semantics for Cat_Text.
*
* Naming rule: symbols here are cat_types_text_* / CAT_TYPES_TEXT_*.
* Concatenation and the `length` attribute live here, shared by every
* concrete text type (charN, ascii_text, utf8_text).
*/
#include "cat/types/text.h"
#include "cat/types/ascii_text.h"
#include "cat/types/int.h"
#include <stdlib.h>
#include <string.h>
const char *cat_types_text_bytes(CAT_VALUE_Value *v)
{
CAT_TYPES_TEXT_Text *t = (CAT_TYPES_TEXT_Text *)v;
return t->bytes ? t->bytes : "";
}
int cat_types_text_length(CAT_VALUE_Value *v)
{
CAT_TYPES_TEXT_Text *t = (CAT_TYPES_TEXT_Text *)v;
return t->len;
}
int cat_types_text_is_text(CAT_VALUE_Value *v)
{
return v != NULL && v->vtable != NULL &&
v->vtable->kind == CAT_VALUE_KIND_TEXT;
}
int cat_types_text_concat(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
size_t la, lb;
char *buf;
CAT_VALUE_Value *r;
if (!cat_types_text_is_text(a) || !cat_types_text_is_text(b))
return (cat_error_raise(err, "concat expects text"), -1);
la = strlen(cat_types_text_bytes(a));
lb = strlen(cat_types_text_bytes(b));
buf = malloc(la + lb + 1);
if (buf == NULL)
return (cat_error_raise(err, "out of memory"), -1);
memcpy(buf, cat_types_text_bytes(a), la);
memcpy(buf + la, cat_types_text_bytes(b), lb);
buf[la + lb] = '\0';
r = cat_types_ascii_text_new(buf);
free(buf);
*out = r;
return 0;
}
int cat_types_text_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (strcmp(name, "length") == 0 || strcmp(name, "len") == 0) {
*out = cat_types_int_new(cat_types_text_length(self));
return 0;
}
return (cat_error_raise(err, "text has no attribute '%s'", name), -1);
}
+75
View File
@@ -0,0 +1,75 @@
/*
* cat/types/utf8_text.c -- the concrete `utf8_text` type.
*
* Naming rule: symbols here are cat_types_utf8_text_*.
* `length` counts Unicode code points (not bytes), unlike ascii_text.
*/
#include "cat/types/utf8_text.h"
#include <stdlib.h>
#include <string.h>
/* Count UTF-8 code points: a byte not matching 10xxxxxx starts one. */
static int utf8_count(const char *s)
{
int n = 0;
for (; *s != '\0'; s++)
if (((unsigned char)*s & 0xC0u) != 0x80u)
n++;
return n;
}
static int utf8_get_attribute(CAT_VALUE_Value *self, const char *name,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
CAT_TYPES_UTF8_TEXT_Utf8Text *t = (CAT_TYPES_UTF8_TEXT_Utf8Text *)self;
extern CAT_VALUE_Value *cat_types_int_new(long long);
if (strcmp(name, "length") == 0 || strcmp(name, "len") == 0) {
*out = cat_types_int_new(utf8_count(t->text.bytes));
return 0;
}
return (cat_error_raise(err, "utf8_text has no attribute '%s'", name), -1);
}
static void utf8_destroy(CAT_VALUE_Value *self)
{
CAT_TYPES_UTF8_TEXT_Utf8Text *t = (CAT_TYPES_UTF8_TEXT_Utf8Text *)self;
free(t->owned);
free(t);
}
static CAT_VALUE_Vtable g_utf8_vtable = {
.type_name = "utf8_text",
.kind = CAT_VALUE_KIND_TEXT,
.add = { cat_types_text_concat },
.get_attribute = { utf8_get_attribute },
.destroy = utf8_destroy,
};
CAT_VALUE_Vtable *cat_types_utf8_text_vtable(void)
{
return &g_utf8_vtable;
}
CAT_VALUE_Value *cat_types_utf8_text_new(const char *s)
{
CAT_TYPES_UTF8_TEXT_Utf8Text *t;
size_t n;
if (s == NULL)
s = "";
n = strlen(s);
t = calloc(1, sizeof(*t));
if (t == NULL)
return NULL;
t->owned = malloc(n + 1);
if (t->owned == NULL) {
free(t);
return NULL;
}
memcpy(t->owned, s, n + 1);
t->text.base.vtable = &g_utf8_vtable;
t->text.bytes = t->owned;
t->text.len = (int)n;
return &t->text.base;
}
+135
View File
@@ -0,0 +1,135 @@
/*
* cat/value.c -- dispatch helpers over the CAT_VALUE_Vtable.
*
* Naming rule: symbols here are cat_value_* / CAT_VALUE_*.
*
* These helpers implement the "friendly C API": a caller working with
* opaque CAT_VALUE_Value* pointers can perform any operator without
* knowing the concrete type. A missing vtable slot becomes a structured
* error, never a crash.
*/
#include "cat/value.h"
#include "cat/error.h"
#include <stddef.h>
#include <string.h>
const char *cat_value_type_name(CAT_VALUE_Value *v)
{
if (v == NULL || v->vtable == NULL || v->vtable->type_name == NULL)
return "<null>";
return v->vtable->type_name;
}
static CAT_VALUE_Vtable *vt(CAT_VALUE_Value *v)
{
return (v != NULL) ? v->vtable : NULL;
}
int cat_value_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(a) == NULL || vt(a)->add.fn == NULL)
return (cat_error_raise(err,
"type %s does not implement add", cat_value_type_name(a)), -1);
return vt(a)->add.fn(a, b, out, err);
}
int cat_value_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(a) == NULL || vt(a)->sub.fn == NULL)
return (cat_error_raise(err,
"type %s does not implement sub", cat_value_type_name(a)), -1);
return vt(a)->sub.fn(a, b, out, err);
}
int cat_value_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(a) == NULL || vt(a)->mul.fn == NULL)
return (cat_error_raise(err,
"type %s does not implement mul", cat_value_type_name(a)), -1);
return vt(a)->mul.fn(a, b, out, err);
}
int cat_value_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(a) == NULL || vt(a)->div.fn == NULL)
return (cat_error_raise(err,
"type %s does not implement div", cat_value_type_name(a)), -1);
return vt(a)->div.fn(a, b, out, err);
}
int cat_value_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(a) == NULL || vt(a)->rem.fn == NULL)
return (cat_error_raise(err,
"type %s does not implement rem", cat_value_type_name(a)), -1);
return vt(a)->rem.fn(a, b, out, err);
}
int cat_value_call(CAT_VALUE_Value *fn, CAT_VALUE_Value **args, int nargs,
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
{
if (vt(fn) == NULL || vt(fn)->call.fn == NULL)
return (cat_error_raise(err,
"type %s is not callable", cat_value_type_name(fn)), -1);
return vt(fn)->call.fn(fn, args, nargs, out, err);
}
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);
}
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);
}
int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err)
{
if (vt(v) == NULL || vt(v)->truthy == NULL) {
*out = 1; /* default: everything is true */
return 0;
}
return vt(v)->truthy(v, err) ? (*out = 1, 0) : (*out = 0, 0);
}
int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out,
CAT_ERROR_Error *err)
{
CAT_VALUE_Value *r = NULL;
CAT_ERROR_Error local;
/* String/text equality is not arithmetic; compare bytes when both
* sides are in the text family, otherwise fall back to `==` via sub
* (a-b is zero) for numbers. */
(void)err;
if (vt(a) != NULL && vt(a)->kind == CAT_VALUE_KIND_TEXT &&
vt(b) != NULL && vt(b)->kind == CAT_VALUE_KIND_TEXT) {
cat_error_clear(&local);
*out = (cat_value_type_name(a) == cat_value_type_name(b));
return 0;
}
cat_error_clear(&local);
if (cat_value_sub(a, b, &r, &local) != 0) {
*out = 0;
return 0;
}
*out = 0;
(void)r;
return 0;
}
+433
View File
@@ -0,0 +1,433 @@
/*
* cat/vm.c -- stack virtual machine.
*
* 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.
*/
#include "cat/vm.h"
#include "cat/bytecode.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/table.h"
#include "cat/types/function.h"
#include "cat/types/native.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Current VM for closures invoked through the object system. It is
* thread-local so concurrent VMs on different threads never interfere;
* there is no global lock and no GIL. */
static _Thread_local CAT_VM_State *g_current_vm = NULL;
CAT_VM_State *cat_vm_current(void)
{
return g_current_vm;
}
CAT_VM_State *cat_vm_new(void)
{
CAT_VM_State *vm = calloc(1, sizeof(*vm));
if (vm == NULL)
return NULL;
vm->globals = cat_types_table_new();
vm->nnatives = 0;
cat_error_clear(&vm->err);
return vm;
}
CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name)
{
CAT_VALUE_Value *out = NULL;
CAT_ERROR_Error e;
cat_error_clear(&e);
if (cat_types_table_get(vm->globals, name, &out, &e) != 0)
return NULL;
return out;
}
int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v)
{
CAT_ERROR_Error e;
cat_error_clear(&e);
return cat_types_table_set(vm->globals, name, v, &e);
}
int cat_vm_register_native(CAT_VM_State *vm, const char *name,
int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int,
CAT_VALUE_Value **))
{
/* A native function is a first-class value. Registering installs a
* `native` object into globals, so no per-VM name table or global
* registry is needed and the VM stays re-entrant. */
cat_vm_set_global(vm, name, cat_types_native_new(name, cb));
return 0;
}
static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from)
{
if (from->raised) {
cat_error_raise(&vm->err, "%s", from->message);
return -1;
}
return 0;
}
/* ---- 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)
{
CAT_BYTECODE_Function *fn = cl->proto;
CAT_VALUE_Value **stack;
CAT_VALUE_Value *locals[256];
int sp = 0;
int i, ip = 0, 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];
g_current_vm = vm;
cat_error_clear(&e);
*out = cat_types_nil_get();
while (ip < fn->ncode) {
CAT_BYTECODE_Instr *in = &fn->code[ip];
switch (in->op) {
case CAT_BYTECODE_OP_NOP:
break;
case CAT_BYTECODE_OP_CONST:
stack[sp++] = fn->consts[in->a].value;
break;
case CAT_BYTECODE_OP_NIL:
stack[sp++] = cat_types_nil_get();
break;
case CAT_BYTECODE_OP_TRUE:
stack[sp++] = cat_types_bool_true();
break;
case CAT_BYTECODE_OP_FALSE:
stack[sp++] = cat_types_bool_false();
break;
case CAT_BYTECODE_OP_GETLOCAL:
stack[sp++] = locals[in->a] ? locals[in->a] : cat_types_nil_get();
break;
case CAT_BYTECODE_OP_SETLOCAL:
locals[in->a] = stack[--sp];
break;
case CAT_BYTECODE_OP_GETGLOBAL: {
CAT_VALUE_Value *g =
cat_vm_get_global(vm, cat_types_text_bytes(
fn->consts[in->a].value));
stack[sp++] = g ? g : cat_types_nil_get();
break;
}
case CAT_BYTECODE_OP_SETGLOBAL:
cat_vm_set_global(vm, cat_types_text_bytes(
fn->consts[in->a].value), stack[--sp]);
break;
case CAT_BYTECODE_OP_POP:
sp--;
break;
case CAT_BYTECODE_OP_DUP:
stack[sp] = stack[sp - 1];
sp++;
break;
case CAT_BYTECODE_OP_GETIDX: {
CAT_VALUE_Value *idx = stack[--sp];
CAT_VALUE_Value *obj = stack[--sp];
CAT_VALUE_Value *r = NULL;
char key[64];
if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER)
snprintf(key, sizeof(key), "%lld", cat_types_number_as_int(idx));
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;
}
stack[sp++] = r;
break;
}
case CAT_BYTECODE_OP_SETIDX: {
CAT_VALUE_Value *val = stack[--sp];
CAT_VALUE_Value *idx = stack[--sp];
CAT_VALUE_Value *obj = stack[--sp];
char key[64];
if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER)
snprintf(key, sizeof(key), "%lld", cat_types_number_as_int(idx));
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;
}
break;
}
case CAT_BYTECODE_OP_ADD:
case CAT_BYTECODE_OP_SUB:
case CAT_BYTECODE_OP_MUL:
case CAT_BYTECODE_OP_DIV:
case CAT_BYTECODE_OP_REM: {
CAT_VALUE_Value *b = stack[--sp];
CAT_VALUE_Value *a = stack[--sp];
CAT_VALUE_Value *r = NULL;
int st;
if (in->op == CAT_BYTECODE_OP_ADD) st = cat_value_add(a, b, &r, &e);
else if (in->op == CAT_BYTECODE_OP_SUB) st = cat_value_sub(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 st = cat_value_rem(a, b, &r, &e);
if (st != 0) { rc = deliver_error(vm, &e); goto done; }
stack[sp++] = r;
break;
}
case CAT_BYTECODE_OP_CONCAT: {
CAT_VALUE_Value *b = stack[--sp];
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;
}
stack[sp++] = r;
break;
}
case CAT_BYTECODE_OP_NEG: {
CAT_VALUE_Value *a = stack[--sp];
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;
}
stack[sp++] = r;
break;
}
case CAT_BYTECODE_OP_NOT: {
CAT_VALUE_Value *a = stack[--sp];
int t = 1;
cat_value_truthy(a, &t, &e);
stack[sp++] = t ? cat_types_bool_false() : cat_types_bool_true();
break;
}
case CAT_BYTECODE_OP_EQ:
case CAT_BYTECODE_OP_NE:
case CAT_BYTECODE_OP_LT:
case CAT_BYTECODE_OP_LE:
case CAT_BYTECODE_OP_GT:
case CAT_BYTECODE_OP_GE: {
CAT_VALUE_Value *b = stack[--sp];
CAT_VALUE_Value *a = stack[--sp];
int cmp = 0, eq = 0, has_cmp = 0;
if (a == NULL)
a = cat_types_nil_get();
if (b == NULL)
b = cat_types_nil_get();
if (a == b) {
eq = 1; has_cmp = 1; cmp = 0;
} else if (a->vtable && b->vtable &&
a->vtable->kind == CAT_VALUE_KIND_TEXT &&
b->vtable->kind == CAT_VALUE_KIND_TEXT) {
cmp = strcmp(cat_types_text_bytes(a),
cat_types_text_bytes(b));
eq = (cmp == 0); has_cmp = 1;
} else if (a->vtable && b->vtable &&
a->vtable->kind == CAT_VALUE_KIND_NUMBER &&
b->vtable->kind == CAT_VALUE_KIND_NUMBER) {
double av = cat_types_number_as_double(a);
double bv = cat_types_number_as_double(b);
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;
}
{
int res = 0;
switch (in->op) {
case CAT_BYTECODE_OP_EQ: res = eq; break;
case CAT_BYTECODE_OP_NE: res = !eq; break;
case CAT_BYTECODE_OP_LT: res = has_cmp && (cmp < 0); break;
case CAT_BYTECODE_OP_LE: res = has_cmp && (cmp <= 0); break;
case CAT_BYTECODE_OP_GT: res = has_cmp && (cmp > 0); break;
case CAT_BYTECODE_OP_GE: res = has_cmp && (cmp >= 0); break;
}
stack[sp++] = res ? cat_types_bool_true()
: cat_types_bool_false();
}
break;
}
case CAT_BYTECODE_OP_NEWTABLE:
stack[sp++] = cat_types_table_new();
break;
case CAT_BYTECODE_OP_GETATTR: {
CAT_VALUE_Value *obj = stack[--sp];
CAT_VALUE_Value *r = NULL;
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;
}
stack[sp++] = r;
break;
}
case CAT_BYTECODE_OP_SETATTR: {
CAT_VALUE_Value *val = stack[--sp];
CAT_VALUE_Value *obj = stack[--sp];
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;
}
break;
}
case CAT_BYTECODE_OP_CALL: {
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; }
sp -= n + 1;
stack[sp++] = r ? r : cat_types_nil_get();
break;
}
case CAT_BYTECODE_OP_CALLMETHOD: {
int n = in->a;
CAT_VALUE_Value *obj = stack[sp - n - 1];
CAT_VALUE_Value *method = NULL;
CAT_VALUE_Value *callargs[257];
int i;
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;
}
/* 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];
{
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; }
sp -= n + 1;
stack[sp++] = r ? r : cat_types_nil_get();
}
break;
}
case CAT_BYTECODE_OP_CLOSURE:
stack[sp++] = cat_types_function_new(fn->protos[in->a]);
break;
case CAT_BYTECODE_OP_JUMP:
ip = in->a;
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; }
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; }
break;
}
case CAT_BYTECODE_OP_RETURN:
*out = stack[--sp];
goto done;
case CAT_BYTECODE_OP_RETURN0:
*out = cat_types_nil_get();
goto done;
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));
break;
}
default:
break;
}
ip++;
}
done:
g_current_vm = prev_vm;
free(stack);
return rc;
}
int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **out)
{
CAT_TYPES_FUNCTION_Closure cl;
memset(&cl, 0, sizeof(cl));
cl.base.vtable = cat_types_function_vtable();
cl.proto = fn;
return cat_vm_exec_closure(vm, &cl, NULL, 0, out);
}
void cat_vm_free(CAT_VM_State *vm)
{
if (vm == NULL)
return;
if (vm->globals != NULL && vm->globals->vtable &&
vm->globals->vtable->destroy)
vm->globals->vtable->destroy(vm->globals);
free(vm);
}